# page_content

c2: SQLite Pro Support
c5: prosupport.html
c4:
Professional Support &amp; Extension Products




Support
(details below)



1.Public Forum. 
  Help and advice from a world-wide community of experts.

Free
More Info
Recent Posts

2.Annual Maintenance Subscription. 
  Private, expert email advice from the developers of SQLite.

$1500/year
More Info
Purchase

3.Technical Support. 
  High-priority email and phone support directly from the SQLite developers.
  Guaranteed response time available as an option.

$8K-85K/year
More Info
Request A Quote

4.SQLite Consortium Membership. 
  Premium enterprise support including on-site visits and
  access to all proprietary extensions and test suites.

$120K/year
More Info
Request A Quote





Public Forum. 
  Help and advice from a world-wide community of experts.

Cost: Free
More Info
Recent Posts


Annual Maintenance Subscription. 
  Private, expert email advice from the developers of SQLite.

Cost: $1500/year
More Info
Purchase


Technical Support. 
  High-priority email and phone support directly from the SQLite developers.
  Guaranteed response time available as an option.

Cost: $8K-85K/year
More Info
Request A Quote


SQLite Consortium Membership. 
  Premium enterprise support including on-site visits and
  access to all proprietary extensions and test suites.

Cost: $120K/year
More Info
Request A Quote




Licenses
(details below)



5.SQLite License. 
  Warranty of title and perpetual right-to-use for the SQLite source code. 

$6000 one time fee
More Info
Purchase

6.SQLite Encryption Extension (SEE). 
   A drop-in replacement for public-domain SQLite source code that has 
   the added ability to read/write AES-encrypted databases. 

$2000 one time fee
More Info
Purchase

7.Compressed And Encrypted Read-Only Database (CEROD). 
   A drop-in replacement for public-domain SQLite source code
   that has the added ability to read database that has been both 
   compressed and encrypted. 

$2000 one time fee
More Info
Buy Now!

8.The ZIPVFS Read/Write Compressed Database Extension. 
   The ZIPVFS extension automatically compresses and encrypts
   your data as it is written to disk, and decompressed and decrypts
   it while reading.

$4000 one time fee
More Info
Buy Now!





SQLite License. 
  Warranty of title and perpetual right-to-use for the SQLite source code. 

Cost: $6000 one time fee
More Info
Purchase


SQLite Encryption Extension (SEE). 
   A drop-in replacement for public-domain SQLite source code that has 
   the added ability to read/write AES-encrypted databases. 

Cost: $2000 one time fee
More Info
Purchase


Compressed And Encrypted Read-Only Database (CEROD). 
   A drop-in replacement for public-domain SQLite source code
   that has the added ability to read database that has been both 
   compressed and encrypted. 

Cost: $2000 one time fee
More Info
Buy Now!


The ZIPVFS Read/Write Compressed Database Extension. 
   The ZIPVFS extension automatically compresses and encrypts
   your data as it is written to disk, and decompressed and decrypts
   it while reading.

Cost: $4000 one time fee
More Info
Buy Now!




Special Services
(details below)



9.TH3 Testing Support. 
  The TH3 test harness
  is an aviation-grade test suite for SQLite. SQLite developers 
  can run TH3 on specialized hardware and/or using specialized
  compile-time options, according to customer specification, 
  either remotely or on customer premises. Pricing for this 
  services is on a case-by-case basis depending on requirements.

call
More Info
Request A Quote





TH3 Testing Support. 
  The TH3 test harness
  is an aviation-grade test suite for SQLite. SQLite developers 
  can run TH3 on specialized hardware and/or using specialized
  compile-time options, according to customer specification, 
  either remotely or on customer premises. Pricing for this 
  services is on a case-by-case basis depending on requirements.

Cost: call
More Info
Request A Quote





Further Information

SQLite is free and works great.
Most people use SQLite without
any kind of license or support.

Free support for SQLite is available on the public
SQLite Forum.
The forum is monitored by a large
community of experts, including the core SQLite development team,
who are able to resolve just about
any problems with SQLite that you are likely to have.

If you do not want to discuss your issues on a public and open forum, an
Annual Maintenance 
Subscription or "AMS" might
serve your needs better.
An AMS entitles you to private email support directly from the developers of
SQLite.  The level of support with an AMS is similar to the support one
gets from the public forum except that an AMS includes a unilateral 
promise of non-disclosure, so with an AMS you can discuss your issues
with the SQLite developers in private, without the whole world watching.
An AMS costs $1500 per year.

Users with more advanced support needs can opt for a
Technical Support
Agreement.
Technical support agreements are customized to the needs of each
individual client, but generally include direct telephone support
and priority handling of issues and bugs.  Guaranteed response time
is available as an option.  The cost of
technical support varies but is generally
in the range of $8000 to $35000 per year.

If SQLite is "mission critical" to your company, then you may
want to become an 
SQLite Consortium 
Member.  The SQLite
Consortium is a collaboration of companies who sponsor ongoing development
of SQLite in exchange for enterprise-level technical support, on-site
visits from the SQLite developers, unlimited access to all licensed
products, and strong guarantees that SQLite will remain in the public
domain, free and independent, and will not come under the control of
a competitor.


Software Licenses

The SQLite source code is in the 
public domain,
and is free for use
by anyone and for any purpose.  No license is required.  However, some
users desire a license so that they can have warranty of title, or just
because their company lawyers say they need one.  A
perpetual license
and warranty of title
for the core SQLite source code is available for this purpose.

The 
SQLite Encryption
Extension (SEE),
the ZIPVFS Extension,
and the Compressed and
Encrypted ReadOnly Database (CEROD) extension are enhanced versions 
of SQLite that handle encrypted
and/or compressed databases.  SEE can read and write encrypted databases.
SEE encrypts all database content, including metadata, so that the database
file appears as white noise.  ZIPVFS 
compresses the database on-the-fly using application-supplied 
compression and decompression functions.
CEROD reads a compressed database that is
also optionally encrypted.  All of SEE, ZIPVFS, and CEROD are 
supplied in source code form only; the licensee is responsible for 
compiling the products for their chosen platform.  It is not difficult 
to compile any of these extension.  All products come in the form of an
amalgamated source file
named "sqlite3.c".  So compiling SEE, ZIPVFS, or CEROD into an application 
is simply a matter of substituting the SEE-, ZIPVFS-, or CEROD-enabled sqlite3.c 
source file in place of the public-domain sqlite3.c source file and recompiling.
Licenses for SEE, ZIPVFS, and CEROD are perpetual.
All three extension can read and write ordinary,
uncompressed and unencrypted database files.


Testing Services

The Test Harness #3 (TH3) is 
a suite of test cases for SQLite that provide 100% branch test coverage
(and 100% modified condition/decision coverage) for the core SQLite in
an as-deployed configuration using only published and documented interfaces.
TH3 is designed for use with embedded devices, and is compatible with
DO-178B.  Every release of the public-domain SQLite is tested using TH3,
and so all users benefit from the TH3 tests.  But the TH3 tests are not
themselves public.  Hardware or system manufactures who want to have
TH3 test run on their systems can negotiate a service agreement to have
the SQLite Developers run those tests.

About The SQLite Team

Paid support options and products are provided by
Hipp, Wyrick &amp; Company, Inc., (Hwaci), a 
Georgia
corporation 
with headquarters in

Charlotte, North Carolina and has been in business since
1992.
Hwaci has an international team of
employees and associates representing the best available talent.  
We are a 100% engineering company.  There is
no sales staff.
Our goal is to provide outstanding service and honest advice
without spin or sales-talk.

Hwaci is a small company but it is
also closely held and debt-free and has low
fixed costs, which means that it is largely immune to buy-outs,
take-overs, and market down-turns.  Hwaci intends to 
continue operating in its current form, and at roughly its current 
size until at least the year 2050.
We expect to be here when you need us,
even if that need is many years in the future.


c2: JSON Functions And Operators
c5: json1.html
c4:
1. Overview

By default, SQLite supports fifteen functions and two operators for
dealing with JSON values.  There are also two table-valued functions
that can be used to decompose a JSON string.


There are 15 scalar functions and operators:



json(json)



json_array(value1,value2,...)



json_array_length(json)json_array_length(json,path)



json_extract(json,path,...)



json -> path



json ->> path



json_insert(json,path,value,...)



json_object(label1,value1,...)



json_patch(json1,json2)



json_remove(json,path,...)



json_replace(json,path,value,...)



json_set(json,path,value,...)



json_type(json)json_type(json,path)



json_valid(json)



json_quote(value)





There are two aggregate SQL functions:



json_group_array(value)



json_group_object(name,value)





The two table-valued functions are:



json_each(json)json_each(json,path)



json_tree(json)json_tree(json,path)












2. Compiling in JSON Support


The JSON functions and operators are built into SQLite by default,
as of SQLite version 3.38.0 (2022-02-22).  They can be omitted
by adding the -DSQLITE_OMIT_JSON compile-time option.  Prior to
version 3.38.0, the JSON functions were an extension that would only
be included in builds if the -DSQLITE_ENABLE_JSON1 compile-time option
was included.  In other words, the JSON functions went from being
opt-in with SQLite version 3.37.2 and earlier to opt-out with
SQLite version 3.38.0 and later.

3. Interface Overview


SQLite stores JSON as ordinary text.
Backwards compatibility constraints mean that SQLite is only able to
store values that are NULL, integers, floating-point numbers, text,
and BLOBs.  It is not possible to add a sixth "JSON" type.


SQLite does not (currently) support a binary encoding
of JSON.  Experiments have been unable to find a binary encoding
that is significantly smaller or faster than a plain text encoding.
(The present implementation parses JSON text at over 1 GB/s.)
All JSON functions currently throw an error if any of their
arguments are BLOBs because BLOBs are reserved
for a future enhancement in which BLOBs will store the binary encoding
for JSON.

3.1. JSON arguments


For functions that accept JSON as their first argument, that argument
can be a JSON object, array, number, string, or null.  SQLite numeric
values and NULL values are interpreted as JSON numbers and nulls, respectively.
SQLite text values can be understood as JSON objects, arrays, or strings.
If an SQLite text value that is not a well-formed JSON object, array, or
string is passed into JSON function, that function will usually throw
an error.  (Exceptions to this rule are json_valid() and
json_quote().)


For the purposes of determining validity, leading and trailing whitespace
on JSON inputs is ignored.  Interior whitespace is also ignored, in accordance
with the JSON spec.  These routines accept exactly the 
rfc-7159 JSON syntax
&mdash; no more and no less.



3.2. PATH arguments


For functions that accept PATH arguments, that PATH must be well-formed or
else the function will throw an error.
A well-formed PATH is a text value that begins with exactly one
'$' character followed by zero or more instances
of ".objectlabel" or "&#91;arrayindex&#93;".


The arrayindex is usually a non-negative integer N.  In
that case, the array element selected is the N-th element
of the array, starting with zero on the left.
The arrayindex can also be of the form "#-N"
in which case the element selected is the N-th from the
right.  The last element of the array is "#-1".  Think of
the "#" characters as the "number of elements in the array".  Then
the expression "#-1" evaluates to the integer that corresponds to 
the last entry in the array.  It is sometimes useful for the array
index to be just the # character, for example when appending
a value to an existing JSON array:


json_set('[0,1,2]','$[#]','new')
&rarr; '[0,1,2,"new"]'






3.3. VALUE arguments


For functions that accept "value" arguments (also shown as
"value1" and "value2"),
those arguments are usually understood
to be literal strings that are quoted and become JSON string values
in the result.  Even if the input value strings look like 
well-formed JSON, they are still interpreted as literal strings in the
result.


However, if a value argument comes directly from the result of another
JSON function or from the -> operator (but not the ->> operator),
then the argument is understood to be actual JSON and
the complete JSON is inserted rather than a quoted string.


For example, in the following call to json_object(), the value
argument looks like a well-formed JSON array.  However, because it is just
ordinary SQL text, it is interpreted as a literal string and added to the
result as a quoted string:


json_object('ex','[52,3.14159]')
&rarr; '{"ex":"[52,3.14159]"}'

json_object('ex',('52,3.14159]'->>'$'))
&rarr; '{"ex":"[52,3.14159]"}'





But if the value argument in the outer json_object() call is the
result of another JSON function like json() or json_array(), then
the value is understood to be actual JSON and is inserted as such:


json_object('ex',json('[52,3.14159]'))
&rarr; '{"ex":[52,3.14159]}'

json_object('ex',json_array(52,3.14159))
&rarr; '{"ex":[52,3.14159]}'

json_object('ex','[52,3.14159]'->'$')
&rarr; '{"ex":[52,3.14159]}'





To be clear: "json" arguments are always interpreted as JSON
regardless of where the value for that argument comes from.  But
"value" arguments are only interpreted as JSON if those arguments
come directly from another JSON function or the -> operator.

3.4. Compatibility


The current implementation of this JSON library uses a recursive descent
parser.  In order to avoid using excess stack space, any JSON input that has
more than 2000 levels of nesting is considered invalid.   Limits on nesting
depth are allowed for compatible implementations of JSON by
RFC-7159 section 9.


4. Function Details

The following sections provide additional detail on the operation of
the various JSON functions and operators:



4.1. The json() function

The json(X) function verifies that its argument X is a valid
JSON string and returns a minified version of that JSON string
(with all unnecessary whitespace removed).  If X is not a well-formed
JSON string, then this routine throws an error.

In other words, this function converts raw text that looks like
JSON into actual JSON so that it may be passed into the value argument
of some other json function and will be interpreted as JSON rather than
a string.  This function is not appropriate for testing whether or not
a particular string is well-formed JSON - use the json_valid() routine
below for that task.

If the argument X to json(X) contains JSON objects with duplicate
labels, then it is undefined whether or not the duplicates are
preserved.  The current implementation preserves duplicates.
However, future enhancements
to this routine may choose to silently remove duplicates.


Example:


json(' { "this" : "is", "a": [ "test" ] } ')
&rarr; '{"this":"is","a":["test"]}'






4.2. The json_array() function

The json_array() SQL function accepts zero or more arguments and
returns a well-formed JSON array that is composed from those arguments.
If any argument to json_array() is a BLOB then an error is thrown.

An argument with SQL type TEXT is normally converted into a quoted 
JSON string.  However, if the argument is the output from another json1
function, then it is stored as JSON.  This allows calls to json_array()
and json_object() to be nested.  The json() function can also
be used to force strings to be recognized as JSON.

Examples:


json_array(1,2,'3',4)
&rarr; '[1,2,"3",4]'

json_array('[1,2]')
&rarr; '["[1,2]"]'

json_array(json_array(1,2))
&rarr; '[[1,2]]'

json_array(1,null,'3','[4,5]','{"six":7.7}')
&rarr; '[1,null,"3","[4,5]","{\"six\":7.7}"]'

json_array(1,null,'3',json('[4,5]'),json('{"six":7.7}'))
&rarr; '[1,null,"3",[4,5],{"six":7.7}]'







4.3. The json_array_length() function

The json_array_length(X) function returns the number of elements
in the JSON array X, or 0 if X is some kind of JSON value other
than an array.  The json_array_length(X,P) locates the array at path P
within X and returns the length of that array, or 0 if path P locates
an element or X other than a JSON array, and NULL if path P does not
locate any element of X.  Errors are thrown if either X is not 
well-formed JSON or if P is not a well-formed path.

Examples:


json_array_length('[1,2,3,4]')
&rarr; 4

json_array_length('[1,2,3,4]', '$')
&rarr; 4

json_array_length('[1,2,3,4]', '$[2]')
&rarr; 0

json_array_length('{"one":[1,2,3]}')
&rarr; 0

json_array_length('{"one":[1,2,3]}', '$.one')
&rarr; 3

json_array_length('{"one":[1,2,3]}', '$.two')
&rarr; NULL







4.4. The json_extract() function

The json_extract(X,P1,P2,...) extracts and returns one or more 
values from the
well-formed JSON at X.  If only a single path P1 is provided, then the
SQL datatype of the result is NULL for a JSON null, INTEGER or REAL
for a JSON numeric value, an INTEGER zero for a JSON false value,
an INTEGER one for a JSON true value, the dequoted text for a 
JSON string value, and a text representation for JSON object and array values.
If there are multiple path arguments (P1, P2, and so forth) then this
routine returns SQLite text which is a well-formed JSON array holding
the various values.

Examples:


json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$')
&rarr; '{"a":2,"c":[4,5,{"f":7}]}'

json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c')
&rarr; '[4,5,{"f":7}]'

json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2]')
&rarr; '{"f":7}'

json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.c[2].f')
&rarr; 7

json_extract('{"a":2,"c":[4,5],"f":7}','$.c','$.a')
&rarr; '[[4,5],2]'

json_extract('{"a":2,"c":[4,5],"f":7}','$.c[#-1]')
&rarr; 5

json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x')
&rarr; NULL

json_extract('{"a":2,"c":[4,5,{"f":7}]}', '$.x', '$.a')
&rarr; '[null,2]'

json_extract('{"a":"xyz"}', '$.a')
&rarr; 'xyz'

json_extract('{"a":null}', '$.a')
&rarr; NULL




There is a subtle incompatibility between the json_extract() function
in SQLite and the json_extract() function in MySQL.  The MySQL version
of json_extract() always returns JSON.  The SQLite version of
json_extract() only returns JSON if there are two or more PATH arguments
(because the result is then a JSON array) or if the single PATH argument
references an array or object.  In SQLite, if json_extract() has only
a single PATH argument and that PATH references a JSON null or a string
or a numeric value, then json_extract() returns the corresponding SQL
NULL, TEXT, INTEGER, or REAL value.

The difference between MySQL json_extract() and SQLite json_extract()
really only stands out when accessing individual values within the JSON
that are strings or NULLs.  The following table demonstrates the difference:



OperationSQLite ResultMySQL Result
json_extract('{"a":null,"b":"xyz"}','$.a')NULL'null'
json_extract('{"a":null,"b":"xyz"}','$.b')'xyz''"xyz"'




4.5. The -> and ->> operators

Beginning with SQLite version 3.38.0 (2022-02-22), the ->
and ->> operators are available for extracting subcomponents of JSON.
The SQLite implementation of the -> and ->> operators strive to be
compatible with both MySQL and PostgreSQL.
The -> and ->> operators take a JSON string
as their left operand and a PATH expression or object field
label or array index as their right operand.  The -> operator
returns a JSON representation of the selected subcomponent or NULL if that
subcomponent does not exist.  The ->> operator returns an SQL TEXT,
INTEGER, REAL, or NULL value that represents the selected subcomponent,
or NULL if the subcomponent does not exist.

Both the -> and ->> operators select the same subcomponent
of the JSON to their left.  The difference is that -> always returns a
JSON representation of that subcomponent and the ->> operator always
returns an SQL representation of that subcomponent.  Thus, these operators
are subtly different from a two-argument json_extract() function call.
A call to json_extract() with two arguments will return a JSON representation
of the subcomponent if and only if the subcomponent is a JSON array or
object, and will return an SQL representation of the subcomponent if the
subcomponent is a JSON null, string, or numeric value.

The right-hand operand to the -> and ->> operators can
be a well-formed JSON path expression.  This is the form used by MySQL.
For compatibility with PostgreSQL,
the -> and ->> operators also accept a text label or
integer as their right-hand operand.  If the right operand is a text
label X, then it is interpreted as the JSON path '$.X'.  If the right
operand is an integer value N, then it is interpreted as the JSON path '$[N]'.

Examples:


'{"a":2,"c":[4,5,{"f":7}]}' -> '$'
&rarr; '{"a":2,"c":[4,5,{"f":7}]}'

'{"a":2,"c":[4,5,{"f":7}]}' -> '$.c'
&rarr; '[4,5,{"f":7}]'

'{"a":2,"c":[4,5,{"f":7}]}' -> 'c'
&rarr; '[4,5,{"f":7}]'

'{"a":2,"c":[4,5,{"f":7}]}' -> '$.c[2]'
&rarr; '{"f":7}'

'{"a":2,"c":[4,5,{"f":7}]}' -> '$.c[2].f'
&rarr; '7'

'{"a":2,"c":[4,5],"f":7}' -> '$.c[#-1]'
&rarr; '5'

'{"a":2,"c":[4,5,{"f":7}]}' -> '$.x'
&rarr; NULL

'[11,22,33,44]' -> 3
&rarr; '44'

'[11,22,33,44]' ->> 3
&rarr; 44

'{"a":"xyz"}' -> '$.a'
&rarr; '"xyz"'

'{"a":"xyz"}' ->> '$.a'
&rarr; 'xyz'

'{"a":null}' -> '$.a'
&rarr; 'null'

'{"a":null}' ->> '$.a'
&rarr; NULL










4.6. The json_insert(), json_replace, and json_set() functions

The json_insert(), json_replace, and json_set() functions all take
a single JSON value as their first argument followed by zero or more
pairs of path and value arguments, and return a new JSON string formed
by updating the input JSON by the path/value pairs.  The functions
differ only in how they deal with creating new values and overwriting
preexisting values.




FunctionOverwrite if already exists?Create if does not exist?

json_insert()NoYes

json_replace()YesNo

json_set()YesYes


The json_insert(), json_replace(), and json_set() functions always
take an odd number of arguments.  The first argument is always the original
JSON to be edited.  Subsequent arguments occur in pairs with the first
element of each pair being a path and the second element being the value
to insert or replace or set on that path.

Edits occur sequentially from left to right.  Changes caused by
prior edits can affect the path search for subsequent edits.

If the value of a path/value pair is an SQLite TEXT value, then it
is normally inserted as a quoted JSON string, even if the string looks
like valid JSON.  However, if the value is the result of another
json1 function (such as json() or json_array() or json_object())
or if it is the result of the -> operator,
then it is interpreted as JSON and is inserted as JSON retaining all
of its substructure.  Values that are the result of the ->> operator
are always interpreted as TEXT and are inserted as a JSON string even
if they look like valid JSON.

These routines throw an error if the first JSON argument is not
well-formed or if any PATH argument is not well-formed or if any
argument is a BLOB.

To append an element onto the end of an array, using json_insert()
with an array index of "#".  Examples:


json_insert('[1,2,3,4]','$[#]',99)
&rarr; '[1,2,3,4,99]'

json_insert('[1,[2,3],4]','$[1][#]',99)
&rarr; '[1,[2,3,99],4]'




Other examples:


json_insert('{"a":2,"c":4}', '$.a', 99)
&rarr; '{"a":2,"c":4}'

json_insert('{"a":2,"c":4}', '$.e', 99)
&rarr; '{"a":2,"c":4,"e":99}'

json_replace('{"a":2,"c":4}', '$.a', 99)
&rarr; '{"a":99,"c":4}'

json_replace('{"a":2,"c":4}', '$.e', 99)
&rarr; '{"a":2,"c":4}'

json_set('{"a":2,"c":4}', '$.a', 99)
&rarr; '{"a":99,"c":4}'

json_set('{"a":2,"c":4}', '$.e', 99)
&rarr; '{"a":2,"c":4,"e":99}'

json_set('{"a":2,"c":4}', '$.c', '[97,96]')
&rarr; '{"a":2,"c":"[97,96]"}'

json_set('{"a":2,"c":4}', '$.c', json('[97,96]'))
&rarr; '{"a":2,"c":[97,96]}'

json_set('{"a":2,"c":4}', '$.c', json_array(97,96))
&rarr; '{"a":2,"c":[97,96]}'






4.7. The json_object() function

The json_object() SQL function accepts zero or more pairs of arguments
and returns a well-formed JSON object that is composed from those arguments.
The first argument of each pair is the label and the second argument of
each pair is the value.
If any argument to json_object() is a BLOB then an error is thrown.

The json_object() function currently allows duplicate labels without
complaint, though this might change in a future enhancement.

An argument with SQL type TEXT it is normally converted into a quoted 
JSON string even if the input text is well-formed JSON.  
However, if the argument is the direct result from another JSON
function or the -> operator (but not the ->> operator), 
then it is treated as JSON and all of its JSON type information
and substructure is preserved.  This allows calls to json_object()
and json_array() to be nested.  The json() function can also
be used to force strings to be recognized as JSON.

Examples:


json_object('a',2,'c',4)
&rarr; '{"a":2,"c":4}'

json_object('a',2,'c','{e:5}')
&rarr; '{"a":2,"c":"{e:5}"}'

json_object('a',2,'c',json_object('e',5))
&rarr; '{"a":2,"c":{"e":5}}'






4.8. The json_patch() function

The json_patch(T,P) SQL function runs the
RFC-7396 MergePatch algorithm
to apply patch P against input T.  The patched copy of T is returned.

MergePatch can add, modify, or delete elements of a JSON Object,
and so for JSON Objects, the json_patch() routine is a generalized
replacement for json_set() and json_remove().  However, MergePatch
treats JSON Array objects as atomic.  MergePatch cannot append to an
Array nor modify individual elements of an Array.  It can only insert,
replace, or delete the whole Array as a single unit.  Hence, json_patch()
is not as useful when dealing with JSON that includes Arrays,
especially Arrays with lots of substructure.

Examples:


json_patch('{"a":1,"b":2}','{"c":3,"d":4}')
&rarr; '{"a":1,"b":2,"c":3,"d":4}'

json_patch('{"a":[1,2],"b":2}','{"a":9}')
&rarr; '{"a":9,"b":2}'

json_patch('{"a":[1,2],"b":2}','{"a":null}')
&rarr; '{"b":2}'

json_patch('{"a":1,"b":2}','{"a":9,"b":null,"c":8}')
&rarr; '{"a":9,"c":8}'

json_patch('{"a":{"x":1,"y":2},"b":3}','{"a":{"y":9},"c":8}')
&rarr; '{"a":{"x":1,"y":9},"b":3,"c":8}'






4.9. The json_remove() function

The json_remove(X,P,...) function takes a single JSON value as its
first argument followed by zero or more path arguments.
The json_remove(X,P,...) function returns
a copy of the X parameter with all the elements 
identified by path arguments removed.  Paths that select elements
not found in X are silently ignored.

Removals occurs sequentially from left to right.  Changes caused by
prior removals can affect the path search for subsequent arguments.

If the json_remove(X) function is called with no path arguments,
then it returns the input X reformatted, with excess whitespace
removed.

The json_remove() function throws an error if the first argument
is not well-formed JSON or if any later argument is not a well-formed
path, or if any argument is a BLOB.

Examples:


json_remove('[0,1,2,3,4]','$[2]')
&rarr; '[0,1,3,4]'

json_remove('[0,1,2,3,4]','$[2]','$[0]')
&rarr; '[1,3,4]'

json_remove('[0,1,2,3,4]','$[0]','$[2]')
&rarr; '[1,2,4]'

json_remove('[0,1,2,3,4]','$[#-1]','$[0]')
&rarr; '[1,2,3]'

json_remove('{"x":25,"y":42}')
&rarr; '{"x":25,"y":42}'

json_remove('{"x":25,"y":42}','$.z')
&rarr; '{"x":25,"y":42}'

json_remove('{"x":25,"y":42}','$.y')
&rarr; '{"x":25}'

json_remove('{"x":25,"y":42}','$')
&rarr; NULL






4.10. The json_type() function

The json_type(X) function returns the "type" of the outermost element
of X.  The json_type(X,P) function returns the "type" of the element
in X that is selected by path P.  The "type" returned by json_type() is
one of the following SQL text values:
'null', 'true', 'false', 'integer', 'real', 'text', 'array', or 'object'.
If the path P in json_type(X,P) selects an element that does not exist
in X, then this function returns NULL.

The json_type() function throws an error if any of its arguments is
not well-formed or is a BLOB.

Examples:


json_type('{"a":[2,3.5,true,false,null,"x"]}')
&rarr; 'object'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$')
&rarr; 'object'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a')
&rarr; 'array'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[0]')
&rarr; 'integer'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[1]')
&rarr; 'real'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[2]')
&rarr; 'true'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[3]')
&rarr; 'false'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[4]')
&rarr; 'null'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[5]')
&rarr; 'text'

json_type('{"a":[2,3.5,true,false,null,"x"]}','$.a[6]')
&rarr; NULL






4.11. The json_valid() function

The json_valid(X) function return 1 if the argument X is well-formed
JSON and return 0 if the argument X is not well-formed JSON.

Examples:


json_valid('{"x":35}')
&rarr; 1

json_valid('{"x":35')
&rarr; 0






4.12. The json_quote() function

The json_quote(X) function converts the SQL value X (a number or a
string) into its corresponding JSON representation.  If X is a JSON value
returned by another JSON function, then this function is a no-op.

Examples:


json_quote(3.14159)
&rarr; 3.14159

json_quote('verdant')
&rarr; '"verdant"'

json_quote('[1]')
&rarr; '"[1]"'

json_quote(json('[1]'))
&rarr; '[1]'

json_quote('[1,')
&rarr; '"[1"'







4.13. The json_group_array() and json_group_object()
aggregate SQL functions

The json_group_array(X) function is an 
aggregate SQL function that returns a JSON array
comprised of all X values in the aggregation.
Similarly, the json_group_object(NAME,VALUE) function returns a JSON object
comprised of all NAME/VALUE pairs in the aggregation.






4.14. The json_each() and json_tree() table-valued functions

The json_each(X) and json_tree(X) table-valued functions walk the
JSON value provided as their first argument and return one row for each
element.  The json_each(X) function only walks the immediate children
of the top-level array or object,
or just the top-level element itself if the top-level
element is a primitive value.
The json_tree(X) function recursively walks through the
JSON substructure starting with the top-level element.  

The json_each(X,P) and json_tree(X,P) functions work just like
their one-argument counterparts except that they treat the element
identified by path P as the top-level element.

The schema for the table returned by json_each() and json_tree() is
as follows:


CREATE TABLE json_tree(
    key ANY,             -- key for current element relative to its parent
    value ANY,           -- value for the current element
    type TEXT,           -- 'object','array','string','integer', etc.
    atom ANY,            -- value for primitive types, null for array & object
    id INTEGER,          -- integer ID for this element
    parent INTEGER,      -- integer ID for the parent of this element
    fullkey TEXT,        -- full path describing the current element
    path TEXT,           -- path to the container of the current row
    json JSON HIDDEN,    -- 1st input parameter: the raw JSON
    root TEXT HIDDEN     -- 2nd input parameter: the PATH at which to start
);



The "key" column is the integer array index for elements of a JSON array 
and the text label for elements of a JSON object.  The key column is
NULL in all other cases.


The "atom" column is the SQL value corresponding to primitive elements - 
elements other than JSON arrays and objects.  The "atom" column is NULL
for a JSON array or object.  The "value" column is the same as the
"atom" column for primitive JSON elements but takes on the text JSON value
for arrays and objects.


The "type" column is an SQL text value taken from ('null', 'true', 'false',
'integer', 'real', 'text', 'array', 'object') according to the type of
the current JSON element.


The "id" column is an integer that identifies a specific JSON element
within the complete JSON string.  The "id" integer is an internal housekeeping
number, the computation of which might change in future releases.  The
only guarantee is that the "id" column will be different for every row.


The "parent" column is always NULL for json_each().
For json_tree(),
the "parent" column is the "id" integer for the parent of the current
element, or NULL for the top-level JSON element or the element identified
by the root path in the second argument.


The "fullkey" column is a text path that uniquely identifies the current
row element within the original JSON string.  The complete key to the
true top-level element is returned even if an alternative starting point
is provided by the "root" argument.


The "path" column is the path to the array or object container that holds 
the current row, or the path to the current row in the case where the 
iteration starts on a primitive type and thus only provides a single
row of output.

4.14.1. Examples using json_each() and json_tree()

Suppose the table "CREATE TABLE user(name,phone)" stores zero or
more phone numbers as a JSON array object in the user.phone field.
To find all users who have any phone number with a 704 area code:


SELECT DISTINCT user.name
  FROM user, json_each(user.phone)
 WHERE json_each.value LIKE '704-%';


Now suppose the user.phone field contains plain text if the user
has only a single phone number and a JSON array if the user has multiple
phone numbers.  The same question is posed: "Which users have a phone number
in the 704 area code?"  But now the json_each() function can only be called
for those users that have two or more phone numbers since json_each()
requires well-formed JSON as its first argument:


SELECT name FROM user WHERE phone LIKE '704-%'
UNION
SELECT user.name
  FROM user, json_each(user.phone)
 WHERE json_valid(user.phone)
   AND json_each.value LIKE '704-%';


Consider a different database with "CREATE TABLE big(json JSON)".
To see a complete line-by-line decomposition of the data:


SELECT big.rowid, fullkey, value
  FROM big, json_tree(big.json)
 WHERE json_tree.type NOT IN ('object','array');


In the previous, the "type NOT IN ('object','array')" term of the
WHERE clause suppresses containers and only lets through leaf elements.
The same effect could be achieved this way:


SELECT big.rowid, fullkey, atom
  FROM big, json_tree(big.json)
 WHERE atom IS NOT NULL;


Suppose each entry in the BIG table is a JSON object 
with a '$.id' field that is a unique identifier
and a '$.partlist' field that can be a deeply nested object.
You want to find the id of every entry that contains one
or more references to uuid '6fa5181e-5721-11e5-a04e-57f3d7b32808' anywhere
in its '$.partlist'.


SELECT DISTINCT json_extract(big.json,'$.id')
  FROM big, json_tree(big.json, '$.partlist')
 WHERE json_tree.key='uuid'
   AND json_tree.value='6fa5181e-5721-11e5-a04e-57f3d7b32808';


c2: The SQLite Bytecode Engine
c5: opcode.html
c4:
1. Executive Summary

SQLite works by translating SQL statements into bytecode and
then running that bytecode in a virtual machine.  This document
describes how the bytecode engine works.

This document describes SQLite internals.  The information provided
here is not needed for routine application development using SQLite.
This document is intended for people who want to delve more deeply into
the internal operation of SQLite.

The bytecode engine is not an API of SQLite.  Details
about the bytecode engine change from one release of SQLite to the next.
Applications that use SQLite should not depend on any of the details
found in this document.



2. Introduction

SQLite works by translating each SQL statement into bytecode and
then running that bytecode.
A prepared statement in SQLite is mostly just the bytecode needed to
implement the corresponding SQL.  The sqlite3_prepare_v2() interface
is a compiler that translates SQL into bytecode.
The sqlite3_step() interface is the virtual machine that runs the
bytecode contained within the prepared statement.

The bytecode virtual machine is the heart of SQLite.
Programmers who want to understand how SQLite operates internally
must be familiar with the bytecode engine.

Historically, the bytecode engine in SQLite is called the
"Virtual DataBase Engine" or "VDBE".  This website uses the terms
"bytecode engine", "VDBE", "virtual machine", and "bytecode virtual
machine" interchangeably, as they all mean the same thing.


This article also uses the terms "bytecode program" and
"prepared statement" interchangeably, as they are mostly the same thing.

2.1. VDBE Source Code

The source code to the bytecode engine is in the 
vdbe.c source
file.  The opcode definitions in this document are derived
from comments in that source file. The 
source code comments are the canonical source of information
about the bytecode engine.  When in doubt, refer to the source code.

In addition to the primary vdbe.c source code file, there are 
other helper code files in the source tree, all of whose names
begin with "vdbe" - short for "Virtual DataBase Engine".

Remember that the names and meanings of opcodes often change from
one release of SQLite to the next.  So if you are studying the EXPLAIN
output from SQLite, you should reference the version of this document
(or the vdbe.c source code)
that corresponds to the version of SQLite that ran the EXPLAIN.
Otherwise, the description of the opcodes may not be accurate.
This document is derived from SQLite
 version 3.39.3 check-in
4635f4a69c8c2 dated 2022-09-05.




2.2. Instruction Format


A bytecoded program in SQLite consists of one or more instructions.
Each instruction has an opcode and
five operands named P1, P2  P3, P4, and P5.  The P1, P2, and P3 
operands are 32-bit signed integers.  These operands often refer to 
registers.  For instructions that operate on b-tree cursors,
the P1 operand is usually the cursor number.
For jump instructions, P2 is usually the jump destination.
P4 may be a 32-bit signed integer, a 64-bit signed integer, a
64-bit floating point value, a string literal, a Blob literal,
a pointer to a collating sequence comparison function, or a
pointer to the implementation of an application-defined SQL
function, or various other things.  P5 is an 16-bit unsigned integer
normally used to hold flags.  Bits of the P5 flag can sometimes affect
the opcode in subtle ways.  For example, if the 
SQLITE_NULLEQ (0x0080) bit of the P5 operand
is set on the Eq opcode, then the NULL values compare
equal to one another.  Otherwise NULL values compare different
from one another.


Some opcodes use all five operands.  Some opcodes use
one or two.  Some opcodes use none of the operands.


The bytecode engine begins execution on instruction number 0.
Execution continues until a Halt instruction is seen, or until
the program counter becomes greater than the address of
last instruction, or until there is an error.
When the bytecode engine halts, all memory
that it allocated is released and all database cursors it may
have had open are closed.  If the execution stopped due to an
error, any pending transactions are terminated and changes made
to the database are rolled back.



The ResultRow opcode causes the
bytecode engine to pause and the corresponding sqlite3_step()
call to return SQLITE_ROW.  Before invoking
ResultRow, the bytecoded program will
have loaded the results for a single row of a query into a series
of registers.  C-language APIs such as sqlite3_column_int()
or sqlite3_column_text() extract the query results from those
registers.  The bytecode engine resumes with the next instruction
after the ResultRow on the next call
to sqlite3_step().


2.3. Registers


Every bytecode program has a fixed (but potentially large) number of
registers.  A single register can hold a variety of objects:

 A NULL value
 A signed 64-bit integer
 An IEEE double-precision (64-bit) floating point number
 An arbitrary length strings
 An arbitrary length BLOB
 A RowSet object (See the RowSetAdd, RowSetRead, and
                      RowSetTest opcodes)
 A Frame object (Used by subprograms - see Program)



A register can also be "Undefined" meaning that it holds no value
at all.  Undefined is different from NULL.  Depending on compile-time
options, an attempt to read an undefined register will usually cause
a run-time error.  If the code generator (sqlite3_prepare_v2())
ever generates a prepared statement that reads an Undefined register,
that is a bug in the code generator.


Registers are numbered beginning with 0.
Most opcodes refer to at least one register.

The number of registers in a single prepared statement is fixed
at compile-time.  The content of all registers is cleared when
a prepared statement is reset or
finalized.

The internal Mem object stores the value for a single register.
The abstract sqlite3_value object that is exposed in the API is really
just a Mem object or register.

2.4. B-Tree Cursors


A prepared statement can have
zero or more open cursors.  Each cursor is identified by a
small integer, which is usually the P1 parameter to the opcode
that uses the cursor.
There can be multiple cursors open on the same index or table.
All cursors operate independently, even cursors pointing to the same
indices or tables.
The only way for the virtual machine to interact with a database
file is through a cursor.
Instructions in the virtual machine can create a new cursor 
(ex: OpenRead or OpenWrite),
read data from a cursor (Column),
advance the cursor to the next entry in the table
(ex: Next or Prev), and so forth.
All cursors are automatically
closed when the prepared statement is reset or
finalized.




2.5. Subroutines, Coroutines, and Subprograms

The bytecode engine has no stack on which to store the return address
of a subroutine.  Return addresses must be stored in registers.
Hence, bytecode subroutines are not reentrant.


The Gosub opcode stores the current program counter into
register P1 then jumps to address P2.  The Return opcode jumps
to address P1+1.  Hence, every subroutine is associated with two integers:
the address of the entry point in the subroutine and the register number
that is used to hold the return address.

The Yield opcode swaps the value of the program counter with
the integer value in register P1.  This opcode is used to implement
coroutines.  Coroutines are often used to implement subqueries from
which content is pulled on an as-needed basis.


Triggers need to be reentrant.


Since bytecode
subroutines are not reentrant a different mechanism must be used to
implement triggers.  Each trigger is implemented using a separate bytecode
program with its own opcodes, program counter, and register set.  The
Program opcode invokes the trigger subprogram.  The Program instruction
allocates and initializes a fresh register set for each invocation of the
subprogram, so subprograms can be reentrant and recursive.  The
Param opcode is used by subprograms to access content in registers
of the calling bytecode program.


2.6. Self-Altering Code


Some opcodes are self-altering.
For example, the Init opcode (which is always the first opcode
in every bytecode program) increments its P1 operand.  Subsequent
Once opcodes compare their P1 operands to the P1 value for
the Init opcode in order to determine if the one-time initialization
code that follows should be skipped.
Another example is the String8 opcode which converts its P4
operand from UTF-8 into the correct database string encoding, then
converts itself into a String opcode.



3. Viewing The Bytecode

Every SQL statement that SQLite interprets results in a program
for the virtual machine.  But if the SQL statement begins with
the keyword EXPLAIN the virtual machine will not execute the
program.  Instead, the instructions of the program will be returned,
one instruction per row,
like a query result.  This feature is useful for debugging and
for learning how the virtual machine operates.  For example:


$&nbsp;sqlite3&nbsp;ex1.db
sqlite&gt;&nbsp;explain&nbsp;delete&nbsp;from&nbsp;tbl1&nbsp;where&nbsp;two&lt;20;
addr&nbsp;&nbsp;opcode&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;p1&nbsp;&nbsp;&nbsp;&nbsp;p2&nbsp;&nbsp;&nbsp;&nbsp;p3&nbsp;&nbsp;&nbsp;&nbsp;p4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;p5&nbsp;&nbsp;comment&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
----&nbsp;&nbsp;-------------&nbsp;&nbsp;----&nbsp;&nbsp;----&nbsp;&nbsp;----&nbsp;&nbsp;-------------&nbsp;&nbsp;--&nbsp;&nbsp;-------------
0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Init&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;Start&nbsp;at&nbsp;12&nbsp;&nbsp;
1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Null&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;r[1]=NULL&nbsp;&nbsp;&nbsp;&nbsp;
2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;OpenWrite&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;root=2&nbsp;iDb=0;&nbsp;tbl1
3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Rewind&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;10&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Column&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;r[2]=tbl1.two
5&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Ge&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(BINARY)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;51&nbsp;&nbsp;if&nbsp;r[2]&gt;=r[3]&nbsp;goto&nbsp;9
6&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Rowid&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;r[4]=rowid&nbsp;&nbsp;&nbsp;
7&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Once&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
8&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Delete&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;tbl1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;02&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
9&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Next&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;4&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;01&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
10&nbsp;&nbsp;&nbsp;&nbsp;Noop&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
11&nbsp;&nbsp;&nbsp;&nbsp;Halt&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
12&nbsp;&nbsp;&nbsp;&nbsp;Transaction&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;01&nbsp;&nbsp;usesStmtJournal=0
13&nbsp;&nbsp;&nbsp;&nbsp;TableLock&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;2&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;tbl1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;iDb=0&nbsp;root=2&nbsp;write=1
14&nbsp;&nbsp;&nbsp;&nbsp;Integer&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;20&nbsp;&nbsp;&nbsp;&nbsp;3&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00&nbsp;&nbsp;r[3]=20&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
15&nbsp;&nbsp;&nbsp;&nbsp;Goto&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;0&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;00

Any application can run an EXPLAIN query to get output similar to 
the above.
However, indentation to show the loop structure is not generated
by the SQLite core.  The command-line shell contains extra logic
for indenting loops.
Also, the "comment" column in the EXPLAIN output
is only provided if SQLite is compiled with the
-DSQLITE_ENABLE_EXPLAIN_COMMENTS options.

When SQLite is compiled with the SQLITE_DEBUG compile-time option,
extra PRAGMA commands are available that are useful for debugging and
for exploring the operation of the VDBE.  For example the vdbe_trace
pragma can be enabled to cause a disassembly of each VDBE opcode to be
printed on standard output as the opcode is executed.  These debugging
pragmas include:

 PRAGMA parser_trace
 PRAGMA vdbe_addoptrace
 PRAGMA vdbe_debug
 PRAGMA vdbe_listing
 PRAGMA vdbe_trace



4. The Opcodes

There are currently 186
opcodes defined by the virtual machine.
All currently defined opcodes are described in the table below.
This table was generated automatically by scanning the source code
from the file
vdbe.c.


Remember: The VDBE opcodes are not part of the interface 
definition for SQLite.  The number of opcodes and their names and meanings
change from one release of SQLite to the next.
The opcodes shown in the table below are valid for SQLite
 version 3.39.3 check-in
4635f4a69c8c2 dated 2022-09-05.



  
  
  
  
  Opcode NameDescription

Abortable
Verify that an Abort can happen.  Assert if an Abort at this point
might cause database corruption.  This opcode only appears in debugging
builds.

An Abort is safe if either there have been no writes, or if there is
an active statement journal.

Add
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.

AddImm
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.

Affinity
Apply affinities to a range of P2 registers starting with P1.

P4 is a string that is P2 characters long. The N-th character of the
string indicates the column affinity that should be used for the N-th
memory cell in the range.

AggFinal
P1 is the memory location that is the accumulator for an aggregate
or window function.  Execute the finalizer function
for an aggregate and store the result in P1.

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 case where
the step function was not previously called.

AggInverse
Execute the xInverse function for an aggregate.
The function has P5 arguments.  P4 is a pointer to the
FuncDef structure that specifies the function.  Register P3 is the
accumulator.

The P5 arguments are taken from register P2 and its
successors.

AggStep
Execute the xStep function for an aggregate.
The function has P5 arguments.  P4 is a pointer to the
FuncDef structure that specifies the function.  Register P3 is the
accumulator.

The P5 arguments are taken from register P2 and its
successors.

AggStep1
Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
aggregate.  The function has P5 arguments.  P4 is a pointer to the
FuncDef structure that specifies the function.  Register P3 is the
accumulator.

The P5 arguments are taken from register P2 and its
successors.

This opcode is initially coded as OP_AggStep0.  On first evaluation,
the FuncDef stored in P4 is converted into an sqlite3_context and
the opcode is changed.  In this way, the initialization of the
sqlite3_context only happens once, instead of on each call to the
step function.

AggValue
Invoke the xValue() function and store the result in register P3.

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 case where
the step function was not previously called.

And
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.

AutoCommit
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.

BeginSubrtn
Mark the beginning of a subroutine that can be entered in-line
or that can be called using Gosub.  The subroutine should
be terminated by an Return instruction that has a P1 operand that
is the same as the P2 operand to this opcode and that has P3 set to 1.
If the subroutine is entered in-line, then the Return will simply
fall through.  But if the subroutine is entered using Gosub, then
the Return will jump back to the first instruction after the Gosub.

This routine works by loading a NULL into the P2 register.  When the
return address register contains a NULL, the Return instruction is
a no-op that simply falls through to the next instruction (assuming that
the Return opcode has a P3 value of 1).  Thus if the subroutine is
entered in-line, then the Return will cause in-line execution to
continue.  But if the subroutine is entered via Gosub, then the
Return will cause a return to the address following the Gosub.

This opcode is identical to Null.  It has a different name
only to make the byte code easier to read and verify.

BitAnd
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.

BitNot
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.

BitOr
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.

Blob
P4 points to a blob of data P1 bytes long.  Store this
blob in register P2.  If P4 is a NULL pointer, then construct
a zero-filled blob that is P1 bytes long in P2.

Cast
Force the value in register P1 to be the type defined by P2.


 P2=='A' &rarr; BLOB
 P2=='B' &rarr; TEXT
 P2=='C' &rarr; NUMERIC
 P2=='D' &rarr; INTEGER
 P2=='E' &rarr; REAL


A NULL value is not changed by this routine.  It remains NULL.

Checkpoint
Checkpoint database P1. This is a no-op if P1 is not currently in
WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
RESTART, or TRUNCATE.  Write 1 or 0 into mem&#91;P3&#93; if the checkpoint returns
SQLITE_BUSY or not, respectively.  Write the number of pages in the
WAL after the checkpoint into mem&#91;P3+1&#93; and the number of pages
in the WAL that have been checkpointed after the checkpoint
completes into mem&#91;P3+2&#93;.  However on an error, mem&#91;P3+1&#93; and
mem&#91;P3+2&#93; are initialized to -1.

Clear
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 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

Close
Close a cursor previously opened as P1.  If P1 is not
currently open, this instruction is a no-op.

ClrSubtype
Clear the subtype from register P1.

CollSeq
P4 is a pointer to a CollSeq object. 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.

If P1 is not zero, then it is a register that a subsequent min() or
max() aggregate will set to 1 if the current row is not the minimum or
maximum.  The P1 register is initialized to 0 by this instruction.

The interface used by the implementation of the aforementioned functions
to retrieve the collation sequence set by this opcode is not available
publicly.  Only built-in functions have access to this feature.

Column
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 record 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_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 then
the result is guaranteed to only be used as the argument of a length()
or typeof() function, respectively.  The loading of large blobs can be
skipped for length() and all content loading can be skipped for typeof().

ColumnsUsed
This opcode (which only exists if SQLite was compiled with
SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
table or index for cursor P1 are used.  P4 is a 64-bit integer
(P4_INT64) in which the first 63 bits are one for each of the
first 63 columns of the table or index that are actually used
by the cursor.  The high-order bit is set if any column after
the 64th is used.

Compare
Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
the comparison for use by the next Jump instruct.

If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
determined by the most recent Permutation operator.  If the
OPFLAG_PERMUTE bit is clear, then register are compared in sequential
order.

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.

This opcode must be immediately followed by an Jump opcode.

Concat
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().

Copy
Make a copy of registers P1..P1+P3 into registers P2..P2+P3.

If the 0x0002 bit of P5 is set then also clear the MEM_Subtype flag in the
destination.  The 0x0001 bit of P5 indicates that this Copy opcode cannot
be merged.  The 0x0001 bit is used by the query planner and does not
come into play during query execution.

This instruction makes a deep copy of the value.  A duplicate
is made of any string or blob constant.  See also SCopy.

Count
Store the number of entries (an integer value) in the table or index
opened by cursor P1 in register P2.

If P3==0, then an exact count is obtained, which involves visiting
every btree page of the table.  But if P3 is non-zero, an estimate
is returned based on the current cursor position.

CreateBtree
Allocate a new b-tree in the main database file if P1==0 or in the
TEMP database file if P1==1 or in an attached database if
P1&gt;1.  The P3 argument must be 1 (BTREE_INTKEY) for a rowid table
it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
The root page number of the new b-tree is stored in register P2.

CursorHint
Provide a hint to cursor P1 that it only needs to return rows that
satisfy the Expr in P4.  TK_REGISTER terms in the P4 expression refer
to values currently held in registers.  TK_COLUMN terms in the P4
expression refer to columns in the b-tree to which cursor P1 is pointing.

CursorLock
Lock the btree to which cursor P1 is pointing so that the btree cannot be
written by an other cursor.

CursorUnlock
Unlock the btree to which cursor P1 is pointing so that it can be
written by other cursors.

DecrJumpZero
Register P1 must hold an integer.  Decrement the value in P1
and jump to P2 if the new value is exactly zero.

DeferredSeek
P1 is an open index cursor and P3 is a cursor on the corresponding
table.  This opcode does a deferred seek of the P3 table cursor
to the row that corresponds to the current row of P1.

This is 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.

P4 may be an array of integers (type P4_INTARRAY) containing
one entry for each column in the P3 table.  If array entry a(i)
is non-zero, then reading column a(i)-1 from cursor P3 is
equivalent to performing the deferred seek and then reading column i
from P1.  This information is stored in P3 and used to redirect
reads against P3 over to P1, thus possibly avoiding the need to
seek and read cursor P3.

Delete
Delete the record at which the P1 cursor is currently pointing.

If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
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. As a result, in this case
it is ok to delete a record from within a Next loop. If
OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
left in an undefined state.

If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
delete one of several associated with deleting a table row and all its
associated index entries.  Exactly one of those deletes is the "primary"
delete.  The others are all on OPFLAG_FORDELETE cursors or else are
marked with the AUXDELETE flag.

If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) 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 points to a Table object. In this case either
the update or pre-update hook, or both, may be invoked. The P1 cursor must
have been positioned using NotFound prior to invoking this opcode in
this case. Specifically, if one is configured, the pre-update hook is
invoked if P4 is not NULL. The update-hook is invoked if one is configured,
P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.

If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
of the memory cell that contains the value that the rowid of the row will
be set to by the update.

Destroy
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.

This opcode throws an error if there are any active reader VMs when
it is invoked. This is done to avoid the difficulty associated with
updating existing cursors when a root page is moved in an AUTOVACUUM
database. This error is thrown even if the database is not an AUTOVACUUM
db in order to avoid introducing an incompatibility between autovacuum
and non-autovacuum modes.

See also: Clear

Divide
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.

DropIndex
Remove the internal (in-memory) data structures that describe
the index named P4 in database P1.  This is called after an index
is dropped from disk (using the Destroy opcode)
in order to keep the internal representation of the
schema consistent with what is on disk.

DropTable
Remove the internal (in-memory) data structures that describe
the table named P4 in database P1.  This is called after a table
is dropped from disk (using the Destroy opcode) in order to keep
the internal representation of the
schema consistent with what is on disk.

DropTrigger
Remove the internal (in-memory) data structures that describe
the trigger named P4 in database P1.  This is called after a trigger
is dropped from disk (using the Destroy opcode) in order to keep
the internal representation of the
schema consistent with what is on disk.

ElseEq
This opcode must follow an Lt or Gt comparison operator.  There
can be zero or more OP_ReleaseReg opcodes intervening, but no other
opcodes are allowed to occur between this instruction and the previous
Lt or Gt.

If result of an Eq comparison on the same two operands as the
prior Lt or Gt would have been true, then jump to P2.
If the result of an Eq comparison on the two previous
operands would have been false or NULL, then fall through.

EndCoroutine
The instruction at the address in register P1 is a Yield.
Jump to the P2 parameter of that Yield.
After the jump, register P1 becomes undefined.

See also: InitCoroutine

Eq
Compare the values in register P1 and P3.  If reg(P3)==reg(P1) then
jump to address P2.

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 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 result is the same as it would be if
the SQLITE_NULLEQ flag were omitted from P5.

This opcode saves the result of comparison for use by the new
Jump opcode.

Expire
Cause precompiled statements to expire.  When an expired statement
is executed using sqlite3_step() it will either automatically
reprepare itself (if it was originally created using sqlite3_prepare_v2())
or it will fail with SQLITE_SCHEMA.

If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
then only the currently executing statement is expired.

If P2 is 0, then SQL statements are expired immediately.  If P2 is 1,
then running SQL statements are allowed to continue to run to completion.
The P2==1 case occurs when a CREATE INDEX or similar schema change happens
that might help the statement run faster but which does not affect the
correctness of operation.

Filter
Compute a hash on the key contained in the P4 registers starting
with r&#91;P3&#93;.  Check to see if that hash is found in the
bloom filter hosted by register P1.  If it is not present then
maybe jump to P2.  Otherwise fall through.

False negatives are harmless.  It is always safe to fall through,
even if the value is in the bloom filter.  A false negative causes
more CPU cycles to be used, but it should still yield the correct
answer.  However, an incorrect answer may well arise from a
false positive - if the jump is taken when it should fall through.

FilterAdd
Compute a hash on the P4 registers starting with r&#91;P3&#93; and
add that hash to the bloom filter contained in r&#91;P1&#93;.

FinishSeek
If cursor P1 was previously moved via DeferredSeek, complete that
seek operation now, without further delay.  If the cursor seek has
already occurred, this instruction is a no-op.

FkCheck
Halt with an SQLITE_CONSTRAINT error if there are any unresolved
foreign key constraint violations.  If there are no foreign key
constraint violations, this is a no-op.

FK constraint violations are also checked when the prepared statement
exits.  This opcode is used to raise foreign key constraint errors prior
to returning results such as a row change count or the result of a
RETURNING clause.

FkCounter
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).

FkIfZero
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).

Found
If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
P4&gt;0 then register P3 is the first of P4 registers that form an unpacked
record.

Cursor P1 is on an index btree.  If the record identified by P3 and P4
is a prefix of any entry in P1 then a jump is made to P2 and
P1 is left pointing at the matching entry.

This operation leaves the cursor in a state where it can be
advanced in the forward direction.  The Next instruction will work,
but not the Prev instruction.

See also: NotFound, NoConflict, NotExists. SeekGe

Function
Invoke a user function (P4 is a pointer to an sqlite3_context object that
contains a pointer to the function to be run) with arguments taken
from register P2 and successors.  The number of arguments is in
the sqlite3_context object that P4 points to.
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, AggFinal, PureFunc

Ge
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.

Gosub
Write the current address onto register P1
and then jump to address P2.

Goto
An unconditional jump to address P2.
The next instruction executed will be
the one at index P2 from the beginning of
the program.

The P1 parameter is not actually used by this opcode.  However, it
is sometimes set to 1 instead of 0 as a hint to the command-line shell
that this Goto is the bottom of a loop and that the lines from P2 down
to the current line should be indented for EXPLAIN output.

Gt
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.

Halt
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.

P5 is a value between 0 and 4, inclusive, that modifies the P4 string.

0:  (no change)
1:  NOT NULL contraint failed: P4
2:  UNIQUE constraint failed: P4
3:  CHECK constraint failed: P4
4:  FOREIGN KEY constraint failed: P4

If P5 is not zero and P4 is NULL, then everything after the ":" is
omitted.

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.

HaltIfNull
Check the value in register P3.  If it 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.
The P5 parameter should be 1.

IdxDelete
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.

If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
if no matching index entry is found.  This happens when running
an UPDATE or DELETE statement and the index entry to be updated
or deleted is not found.  For some uses of IdxDelete
(example:  the EXCEPT operator) it does not matter that no matching
entry is found.  For those cases, P5 is zero.  Also, do not raise
this (self-correcting and non-critical) error if in writable_schema mode.

IdxGE
The P4 register values beginning with P3 form an unpacked index
key that omits the PRIMARY KEY.  Compare this key value against the index
that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
fields at the end.

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.

IdxGT
The P4 register values beginning with P3 form an unpacked index
key that omits the PRIMARY KEY.  Compare this key value against the index
that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
fields at the end.

If the P1 index entry is greater than the key value
then jump to P2.  Otherwise fall through to the next instruction.

IdxInsert
Register P2 holds an SQL index key made using the
MakeRecord instructions.  This opcode writes that key
into the index P1.  Data for the entry is nil.

If P4 is not zero, then it is the number of values in the unpacked
key of reg(P2).  In that case, P3 is the index of the first register
for the unpacked key.  The availability of the unpacked key can sometimes
be an optimization.

If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
that this insert is likely to be an append.

If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
then the change counter is unchanged.

If the OPFLAG_USESEEKRESULT flag of P5 is set, the implementation might
run faster by avoiding an unnecessary seek on cursor P1.  However,
the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
seeks on the cursor or if the most recent seek used a key equivalent
to P2.

This instruction only works for indices.  The equivalent instruction
for tables is Insert.

IdxLE
The P4 register values beginning with P3 form an unpacked index
key that omits the PRIMARY KEY or ROWID.  Compare this key value against
the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
ROWID on the P1 index.

If the P1 index entry is less than or equal to the key value then jump
to P2. Otherwise fall through to the next instruction.

IdxLT
The P4 register values beginning with P3 form an unpacked index
key that omits the PRIMARY KEY or ROWID.  Compare this key value against
the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
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.

IdxRowid
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.

If
Jump to P2 if the value in register P1 is true.  The value
is considered true if it is numeric and non-zero.  If the value
in P1 is NULL then take the jump if and only if P3 is non-zero.

IfNoHope
Register P3 is the first of P4 registers that form an unpacked
record.  Cursor P1 is an index btree.  P2 is a jump destination.
In other words, the operands to this opcode are the same as the
operands to NotFound and IdxGT.

This opcode is an optimization attempt only.  If this opcode always
falls through, the correct answer is still obtained, but extra works
is performed.

A value of N in the seekHit flag of cursor P1 means that there exists
a key P3:N that will match some record in the index.  We want to know
if it is possible for a record P3:P4 to match some record in the
index.  If it is not possible, we can skips some work.  So if seekHit
is less than P4, attempt to find out if a match is possible by running
NotFound.

This opcode is used in IN clause processing for a multi-column key.
If an IN clause is attached to an element of the key other than the
left-most element, and if there are no matches on the most recent
seek over the whole key, then it might be that one of the key element
to the left is prohibiting a match, and hence there is "no hope" of
any match regardless of how many IN clause elements are checked.
In such a case, we abandon the IN clause search early, using this
opcode.  The opcode name comes from the fact that the
jump is taken if there is "no hope" of achieving a match.

See also: NotFound, SeekHit

IfNot
Jump to P2 if the value in register P1 is False.  The value
is considered false if it has a numeric value of zero.  If the value
in P1 is NULL then take the jump if and only if P3 is non-zero.

IfNotOpen
If cursor P1 is not open, jump to instruction P2. Otherwise, fall through.

IfNotZero
Register P1 must contain an integer.  If the content of register P1 is
initially greater than zero, then decrement the value in register P1.
If it is non-zero (negative or positive) and then also jump to P2.
If register P1 is initially zero, leave it unchanged and fall through.

IfNullRow
Check the cursor P1 to see if it is currently pointing at a NULL row.
If it is, then set register P3 to NULL and jump immediately to P2.
If P1 is not on a NULL row, then fall through without making any
changes.

IfPos
Register P1 must contain an integer.
If the value of register P1 is 1 or greater, subtract P3 from the
value in P1 and jump to P2.

If the initial value of register P1 is less than 1, then the
value is unchanged and control passes through to the next instruction.

IfSmaller
Estimate the number of rows in the table P1.  Jump to P2 if that
estimate is less than approximately 2**(0.1*P3).

IncrVacuum
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.

Init
Programs contain a single instance of this opcode as the very first
opcode.

If tracing is enabled (by the sqlite3_trace()) interface, then
the UTF-8 string contained in P4 is emitted on the trace callback.
Or if P4 is blank, use the string returned by sqlite3_sql().

If P2 is not zero, jump to instruction P2.

Increment the value of P1 so that Once opcodes will jump the
first time they are evaluated for this run.

If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
error is encountered.

InitCoroutine
Set up register P1 so that it will Yield to the coroutine
located at address P3.

If P2!=0 then the coroutine implementation immediately follows
this opcode.  So jump over the coroutine implementation to
address P2.

See also: EndCoroutine

Insert
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, the implementation might
run faster by avoiding an unnecessary seek on cursor P1.  However,
the OPFLAG_USESEEKRESULT flag must only be set if there have been no prior
seeks on the cursor or if the most recent seek used a key equal to P3.

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 Table structure, 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 IdxInsert.

Int64
P4 is a pointer to a 64-bit integer value.
Write that value into register P2.

IntCopy
Transfer the integer value held in register P1 into register P2.

This is an optimized version of SCopy that works only for integer
values.

Integer
The 32-bit integer value P1 is written into register P2.

IntegrityCk
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 one less than 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 integers
stored in P4_INTARRAY argument.

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.

IsNull
Jump to P2 if the value in register P1 is NULL.

IsNullOrType
Jump to P2 if the value in register P1 is NULL or has a datatype P3.
P3 is an integer which should be one of SQLITE_INTEGER, SQLITE_FLOAT,
SQLITE_BLOB, SQLITE_NULL, or SQLITE_TEXT.

IsTrue
This opcode implements the IS TRUE, IS FALSE, IS NOT TRUE, and
IS NOT FALSE operators.

Interpret the value in register P1 as a boolean value.  Store that
boolean (a 0 or 1) in register P2.  Or if the value in register P1 is
NULL, then the P3 is stored in register P2.  Invert the answer if P4
is 1.

The logic is summarized like this:


 If P3==0 and P4==0  then  r&#91;P2&#93; := r&#91;P1&#93; IS TRUE
 If P3==1 and P4==1  then  r&#91;P2&#93; := r&#91;P1&#93; IS FALSE
 If P3==0 and P4==1  then  r&#91;P2&#93; := r&#91;P1&#93; IS NOT TRUE
 If P3==1 and P4==0  then  r&#91;P2&#93; := r&#91;P1&#93; IS NOT FALSE


JournalMode
Change the journal mode of database P1 to P3. P3 must be one of the
PAGER_JOURNALMODE_XXX values. If changing between the various rollback
modes (delete, truncate, persist, off and memory), this is a simple
operation. No IO is required.

If changing into or out of WAL mode the procedure is more complicated.

Write a string containing the final journal-mode to register P2.

Jump
Jump to the instruction at address P1, P2, or P3 depending on whether
in the most recent Compare instruction the P1 vector was less than
equal to, or greater than the P2 vector, respectively.

This opcode must immediately follow an Compare opcode.

Last
The next use of the Rowid or Column or Prev instruction for P1
will refer to the last entry in the database table or index.
If the table or index is empty and P2&gt;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.

This opcode leaves the cursor configured to move in reverse order,
from the end toward the beginning.  In other words, the cursor is
configured to use Prev, not Next.

Le
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.

LoadAnalysis
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.

Lt
Compare the values in register P1 and P3.  If reg(P3)&lt;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 the take the jump.  If the SQLITE_JUMPIFNULL
bit is clear then fall through 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.

This opcode saves the result of comparison for use by the new
Jump opcode.

MakeRecord
Convert P2 registers beginning with P1 into the record format
use as a data record in a database table or as a key
in an index.  The Column opcode can decode the record later.

P4 may be a string that is P2 characters long.  The N-th character of the
string indicates the column affinity that should be used for the N-th
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 BLOB.

The meaning of P5 depends on whether or not the SQLITE_ENABLE_NULL_TRIM
compile-time option is enabled:

* If SQLITE_ENABLE_NULL_TRIM is enabled, then the P5 is the index
of the right-most table that can be null-trimmed.

* If SQLITE_ENABLE_NULL_TRIM is omitted, then P5 has the value
OPFLAG_NOCHNG_MAGIC if the MakeRecord opcode is allowed to
accept no-change records with serial_type 10.  This value is
only used inside an assert() and does not affect the end result.

MaxPgcnt
Try to set the maximum page count for database P1 to the value in P3.
Do not let the maximum page count fall below the current page count and
do not change the maximum page count value if P3==0.

Store the maximum page count after the change in register P2.

MemMax
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.

Move
Move the P3 values in register P1..P1+P3-1 over into
registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
left holding a NULL.  It is an error for register ranges
P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
for P3 to be less than 1.

Multiply
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.

MustBeInt
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.

Ne
This works just like the Eq opcode except that the jump is taken if
the operands in registers P1 and P3 are not equal.  See the Eq opcode for
additional information.

NewRowid
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&gt;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,
an 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.

Next
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 Next opcode is only valid following an SeekGT, SeekGE, or
Rewind opcode used to position the cursor.  Next is not allowed
to follow SeekLT, SeekLE, or Last.

The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
been opened prior to this opcode or the program will segfault.

The P3 value is a hint to the btree implementation. If P3==1, that
means P1 is an SQL index and that this instruction could have been
omitted if that index had been unique.  P3 is usually 0.  P3 is
always either 0 or 1.

If P5 is positive and the jump is taken, then event counter
number P5-1 in the prepared statement is incremented.

See also: Prev

NoConflict
If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
P4&gt;0 then register P3 is the first of P4 registers that form an unpacked
record.

Cursor P1 is on an index btree.  If the record identified by P3 and P4
contains any NULL value, jump immediately to P2.  If all terms of the
record are not-NULL then a check is done to determine if any row in the
P1 index btree has a matching key prefix.  If there are no matches, jump
immediately to P2.  If there is a match, fall through and leave the P1
cursor pointing to the matching row.

This opcode is similar to NotFound with the exceptions that the
branch is always taken if any part of the search key input is NULL.

This operation leaves the cursor in a state where it cannot be
advanced in either direction.  In other words, the Next and Prev
opcodes do not work after this operation.

See also: NotFound, Found, NotExists

Noop
Do nothing.  This instruction is often useful as a jump
destination.

Not
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.

NotExists
P1 is the index of a cursor open on an SQL table btree (with integer
keys).  P3 is an integer rowid.  If P1 does not contain a record with
rowid P3 then jump immediately to P2.  Or, if P2 is 0, raise an
SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
leave the cursor pointing at that record and fall through to the next
instruction.

The SeekRowid opcode performs the same operation but also allows the
P3 register to contain a non-integer value, in which case the jump is
always taken.  This opcode requires that P3 always contain an integer.

The NotFound opcode performs the same operation on index btrees
(with arbitrary multi-value keys).

This opcode leaves the cursor in a state where it cannot be advanced
in either direction.  In other words, the Next and Prev opcodes will
not work following this opcode.

See also: Found, NotFound, NoConflict, SeekRowid

NotFound
If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
P4&gt;0 then register P3 is the first of P4 registers that form an unpacked
record.

Cursor P1 is on an index btree.  If the record identified by P3 and P4
is not the prefix of any entry in P1 then a jump is made to P2.  If P1
does contain an entry whose prefix matches the P3/P4 record then control
falls through to the next instruction and P1 is left pointing at the
matching entry.

This operation leaves the cursor in a state where it cannot be
advanced in either direction.  In other words, the Next and Prev
opcodes do not work after this operation.

See also: Found, NotExists, NoConflict, IfNoHope

NotNull
Jump to P2 if the value in register P1 is not NULL.

Null
Write a NULL into registers P2.  If P3 greater than P2, then also write
NULL into register P3 and every register in between P2 and P3.  If P3
is less than P2 (typically P3 is zero) then only register P2 is
set to NULL.

If the P1 value is non-zero, then also set the MEM_Cleared flag so that
NULL values will not compare equal even if SQLITE_NULLEQ is set on
Ne or Eq.

NullRow
Move the cursor P1 to a null row.  Any Column operations
that occur while the cursor is on the null row will always
write a NULL.

If cursor P1 is not previously opened, open it now to a special
pseudo-cursor that always returns NULL for every column.

Offset
Store in register r&#91;P3&#93; the byte offset into the database file that is the
start of the payload for the record at which that cursor P1 is currently
pointing.

P2 is the column number for the argument to the sqlite_offset() function.
This opcode does not use P2 itself, but the P2 value is used by the
code generator.  The P1, P2, and P3 operands to this opcode are the
same as for Column.

This opcode is only available if SQLite is compiled with the
-DSQLITE_ENABLE_OFFSET_SQL_FUNC option.

OffsetLimit
This opcode performs a commonly used computation associated with
LIMIT and OFFSET process.  r&#91;P1&#93; holds the limit counter.  r&#91;P3&#93;
holds the offset counter.  The opcode computes the combined value
of the LIMIT and OFFSET and stores that value in r&#91;P2&#93;.  The r&#91;P2&#93;
value computed is the total number of rows that will need to be
visited in order to complete the query.

If r&#91;P3&#93; is zero or negative, that means there is no OFFSET
and r&#91;P2&#93; is set to be the value of the LIMIT, r&#91;P1&#93;.

if r&#91;P1&#93; is zero or negative, that means there is no LIMIT
and r&#91;P2&#93; is set to -1.

Otherwise, r&#91;P2&#93; is set to the sum of r&#91;P1&#93; and r&#91;P3&#93;.

Once
Fall through to the next instruction the first time this opcode is
encountered on each invocation of the byte-code program.  Jump to P2
on the second and all subsequent encounters during the same invocation.

Top-level programs determine first invocation by comparing the P1
operand against the P1 operand on the Init opcode at the beginning
of the program.  If the P1 values differ, then fall through and make
the P1 of this opcode equal to the P1 of Init.  If P1 values are
the same then take the jump.

For subprograms, there is a bitmask in the VdbeFrame that determines
whether or not the jump should be taken.  The bitmask is necessary
because the self-altering code trick does not work for recursive
triggers.

OpenAutoindex
This opcode works the same as OpenEphemeral.  It has a
different name to distinguish its use.  Tables created using
by this opcode will be used for automatically created transient
indices in joins.

OpenDup
Open a new cursor P1 that points to the same ephemeral table as
cursor P2.  The P2 cursor must have been opened by a prior OpenEphemeral
opcode.  Only ephemeral cursors may be duplicated.

Duplicate ephemeral cursors are used for self-joins of materialized views.

OpenEphemeral
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 ephemeral
table is deleted automatically when the cursor is closed.

If the cursor P1 is already opened on an ephemeral table, the table
is cleared (all content is erased).

P2 is the number of columns in the ephemeral 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.

The P5 parameter can be a mask of the BTREE_* flags defined
in btree.h.  These flags control aspects of the operation of
the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
added automatically.

If P3 is positive, then reg&#91;P3&#93; is modified slightly so that it
can be used as zero-length data for Insert.  This is an optimization
that avoids an extra Blob opcode to initialize that register.

OpenPseudo
Open a new cursor that points to a fake table that contains a single
row of data.  The content of that one row is 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 a single
row output from the sorter so that the row can be decomposed into
individual columns using the Column opcode.  The 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.

OpenRead
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&gt;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.

Allowed P5 bits:

  0x02 OPFLAG_SEEKEQ: This cursor will only be used for
equality lookups (implemented as a pair of opcodes SeekGE/IdxGT
of SeekLE/IdxLT)


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
object, then table being opened must be an index b-tree where the
KeyInfo object defines the content and collating
sequence of that index b-tree. Otherwise, if P4 is an integer
value, then the table being opened must be a table b-tree with a
number of columns no less than the value of P4.

See also: OpenWrite, ReopenIdx

OpenWrite
Open a read/write cursor named P1 on the table or index whose root
page is P2 (or whose root page is held in register P2 if the
OPFLAG_P2ISREG bit is set in P5 - see below).

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
object, then table being opened must be an index b-tree where the
KeyInfo object defines the content and collating
sequence of that index b-tree. Otherwise, if P4 is an integer
value, then the table being opened must be a table b-tree with a
number of columns no less than the value of P4.

Allowed P5 bits:

  0x02 OPFLAG_SEEKEQ: This cursor will only be used for
equality lookups (implemented as a pair of opcodes SeekGE/IdxGT
of SeekLE/IdxLT)
  0x08 OPFLAG_FORDELETE: This cursor is used only to seek
and subsequently delete entries in an index btree.  This is a
hint to the storage engine that the storage engine is allowed to
ignore.  The hint is not used by the official SQLite b*tree storage
engine, but is used by COMDB2.
  0x10 OPFLAG_P2ISREG: Use the content of register P2
as the root page, not the value of P2 itself.


This instruction works like OpenRead except that it opens the cursor
in read/write mode.

See also: OpenRead, ReopenIdx

Or
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.

Pagecount
Write the current number of pages in database P1 to memory cell P2.

Param
This opcode is only ever present in sub-programs called via the
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 Program instruction.

ParseSchema
Read and parse all entries from the schema table of database P1
that match the WHERE clause P4.  If P4 is a NULL pointer, then the
entire schema for P1 is reparsed.

This opcode invokes the parser to create a new virtual machine,
then runs the new virtual machine.  It is thus a re-entrant opcode.

Permutation
Set the permutation used by the Compare operator in the next
instruction.  The permutation is stored in the P4 operand.

The permutation is only valid for the next opcode which must be
an Compare that has the OPFLAG_PERMUTE bit set in P5.

The first integer in the P4 integer array is the length of the array
and does not become part of the permutation.

Prev
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 Prev opcode is only valid following an SeekLT, SeekLE, or
Last opcode used to position the cursor.  Prev is not allowed
to follow SeekGT, SeekGE, or Rewind.

The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
not open then the behavior is undefined.

The P3 value is a hint to the btree implementation. If P3==1, that
means P1 is an SQL index and that this instruction could have been
omitted if that index had been unique.  P3 is usually 0.  P3 is
always either 0 or 1.

If P5 is positive and the jump is taken, then event counter
number P5-1 in the prepared statement is incremented.

Program
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.

If P5 is non-zero, then recursive program invocation is enabled.

PureFunc
Invoke a user function (P4 is a pointer to an sqlite3_context object that
contains a pointer to the function to be run) with arguments taken
from register P2 and successors.  The number of arguments is in
the sqlite3_context object that P4 points to.
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.

This opcode works exactly like Function.  The only difference is in
its name.  This opcode is used in places where the function must be
purely non-deterministic.  Some built-in date/time functions can be
either determinitic of non-deterministic, depending on their arguments.
When those function are used in a non-deterministic way, they will check
to see if they were called using PureFunc instead of Function, and
if they were, they throw an error.

See also: AggStep, AggFinal, Function

ReadCookie
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.

Real
P4 is a pointer to a 64-bit floating point value.
Write that value into register P2.

RealAffinity
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.

ReleaseReg
Release registers from service.  Any content that was in the
the registers is unreliable after this opcode completes.

The registers released will be the P2 registers starting at P1,
except if bit ii of P3 set, then do not release register P1+ii.
In other words, P3 is a mask of registers to preserve.

Releasing a register clears the Mem.pScopyFrom pointer.  That means
that if the content of the released register was set using SCopy,
a change to the value of the source register for the SCopy will no longer
generate an assertion fault in sqlite3VdbeMemAboutToChange().

If P5 is set, then all released registers have their type set
to MEM_Undefined so that any subsequent attempt to read the released
register (before it is reinitialized) will generate an assertion fault.

P5 ought to be set on every call to this opcode.
However, there are places in the code generator will release registers
before their are used, under the (valid) assumption that the registers
will not be reallocated for some other purpose before they are used and
hence are safe to release.

This opcode is only available in testing and debugging builds.  It is
not generated for release builds.  The purpose of this opcode is to help
validate the generated bytecode.  This opcode does not actually contribute
to computing an answer.

Remainder
Compute the remainder after integer register P2 is divided by
register P1 and store the result in register P3.
If the value in register P1 is zero the result is NULL.
If either operand is NULL, the result is NULL.

ReopenIdx
The ReopenIdx opcode works like OpenRead except that it first
checks to see if the cursor on P1 is already open on the same
b-tree and if it is this opcode becomes a no-op.  In other words,
if the cursor is already open, do not reopen it.

The ReopenIdx opcode may only be used with P5==0 or P5==OPFLAG_SEEKEQ
and with P4 being a P4_KEYINFO object.  Furthermore, the P3 value must
be the same as every other ReopenIdx or OpenRead for the same cursor
number.

Allowed P5 bits:

  0x02 OPFLAG_SEEKEQ: This cursor will only be used for
equality lookups (implemented as a pair of opcodes SeekGE/IdxGT
of SeekLE/IdxLT)


See also: OpenRead, OpenWrite

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.

ResetSorter
Delete all contents from the ephemeral table or sorter
that is open on cursor P1.

This opcode only works for cursors used for sorting and
opened with OpenEphemeral or SorterOpen.

ResultRow
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 r(P1)..r(P1+P2-1) values as
the result row.

Return
Jump to the address stored in register P1.  If P1 is a return address
register, then this accomplishes a return from a subroutine.

If P3 is 1, then the jump is only taken if register P1 holds an integer
values, otherwise execution falls through to the next opcode, and the
Return becomes a no-op. If P3 is 0, then register P1 must hold an
integer or else an assert() is raised.  P3 should be set to 1 when
this opcode is used in combination with BeginSubrtn, and set to 0
otherwise.

The value in register P1 is unchanged by this opcode.

P2 is not used by the byte-code engine.  However, if P2 is positive
and also less than the current address, then the "EXPLAIN" output
formatter in the CLI will indent all opcodes from the P2 opcode up
to be not including the current Return.   P2 should be the first opcode
in the subroutine from which this opcode is returning.  Thus the P2
value is a byte-code indentation hint.  See tag-20220407a in
wherecode.c and shell.c.

Rewind
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, jump immediately to P2.
If the table or index is not empty, fall through to the following
instruction.

This opcode leaves the cursor configured to move in forward order,
from the beginning toward the end.  In other words, the cursor is
configured to use Next, not Prev.

RowCell
P1 and P2 are both open cursors. Both must be opened on the same type
of table - intkey or index. This opcode is used as part of copying
the current row from P2 into P1. If the cursors are opened on intkey
tables, register P3 contains the rowid to use with the new record in
P1. If they are opened on index tables, P3 is not used.

This opcode must be followed by either an Insert or InsertIdx opcode
with the OPFLAG_PREFORMAT flag set to complete the insert operation.

RowData
Write into register P2 the complete row content for the row at
which cursor P1 is currently pointing.
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 cursor P1 is an index, then the content is the key of the row.
If cursor P2 is a table, then the content extracted is the data.

If the P1 cursor must be pointing to a valid row (not a NULL row)
of a real table, not a pseudo-table.

If P3!=0 then this opcode is allowed to make an ephemeral pointer
into the database page.  That means that the content of the output
register will be invalidated as soon as the cursor moves - including
moves caused by other cursors that "save" the current cursors
position in order that they can write to the same table.  If P3==0
then a copy of the data is made into memory.  P3!=0 is faster, but
P3==0 is safer.

If P3!=0 then the content of the P2 register is unsuitable for use
in OP_Result and any OP_Result will invalidate the P2 register content.
The P2 register content is invalidated by opcodes like Function or
by any use of another cursor pointing to the same table.

Rowid
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.

RowSetAdd
Insert the integer value held by register P2 into a RowSet object
held in register P1.

An assertion fails if P2 is not an integer.

RowSetRead
Extract the smallest value from the RowSet object in P1
and put that value into register P3.
Or, if RowSet object P1 is initially empty, leave P3
unchanged and jump to instruction P2.

RowSetTest
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 sets of integers
are inserted in distinct phases, which each set contains no duplicates.
Each set is identified by a unique P4 value. The first set
must have P4==0, the final set must have P4==-1, and for all other sets
must have P4&gt;0.

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).

Savepoint
Open, release or rollback the savepoint named by parameter P4, depending
on the value of P1. To open a new savepoint set P1==0 (SAVEPOINT_BEGIN).
To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).

SCopy
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 Copy to make a complete
copy.

SeekEnd
Position cursor P1 at the end of the btree for the purpose of
appending a new entry onto the btree.

It is assumed that the cursor is used only for appending and so
if the cursor is valid, then the cursor must already be pointing
at the end of the btree and so no changes are made to
the cursor.

SeekGE
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.

If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
opcode will either land on a record that exactly matches the key, or
else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
this opcode must be followed by an IdxLE opcode with the same arguments.
The IdxGT opcode will be skipped if this opcode succeeds, but the
IdxGT opcode will be used on subsequent loop iterations.  The
OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
is an equality search.

This opcode leaves the cursor configured to move in forward order,
from the beginning toward the end.  In other words, the cursor is
configured to use Next, not Prev.

See also: Found, NotFound, SeekLt, SeekGt, SeekLe

SeekGT
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.

This opcode leaves the cursor configured to move in forward order,
from the beginning toward the end.  In other words, the cursor is
configured to use Next, not Prev.

See also: Found, NotFound, SeekLt, SeekGe, SeekLe

SeekHit
Increase or decrease the seekHit value for cursor P1, if necessary,
so that it is no less than P2 and no greater than P3.

The seekHit integer represents the maximum of terms in an index for which
there is known to be at least one match.  If the seekHit value is smaller
than the total number of equality terms in an index lookup, then the
IfNoHope opcode might run to see if the IN loop can be abandoned
early, thus saving work.  This is part of the IN-early-out optimization.

P1 must be a valid b-tree cursor.

SeekLE
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.

This opcode leaves the cursor configured to move in reverse order,
from the end toward the beginning.  In other words, the cursor is
configured to use Prev, not Next.

If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
opcode will either land on a record that exactly matches the key, or
else it will cause a jump to P2.  When the cursor is OPFLAG_SEEKEQ,
this opcode must be followed by an IdxLE opcode with the same arguments.
The IdxGE opcode will be skipped if this opcode succeeds, but the
IdxGE opcode will be used on subsequent loop iterations.  The
OPFLAG_SEEKEQ flags is a hint to the btree layer to say that this
is an equality search.

See also: Found, NotFound, SeekGt, SeekGe, SeekLt

SeekLT
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.

This opcode leaves the cursor configured to move in reverse order,
from the end toward the beginning.  In other words, the cursor is
configured to use Prev, not Next.

See also: Found, NotFound, SeekGt, SeekGe, SeekLe

SeekRowid
P1 is the index of a cursor open on an SQL table btree (with integer
keys).  If register P3 does not contain an integer or if P1 does not
contain a record with rowid P3 then jump immediately to P2.
Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
a record with rowid P3 then
leave the cursor pointing at that record and fall through to the next
instruction.

The NotExists opcode performs the same operation, but with NotExists
the P3 register must be guaranteed to contain an integer value.  With this
opcode, register P3 might not contain an integer.

The NotFound opcode performs the same operation on index btrees
(with arbitrary multi-value keys).

This opcode leaves the cursor in a state where it cannot be advanced
in either direction.  In other words, the Next and Prev opcodes will
not work following this opcode.

See also: Found, NotFound, NoConflict, SeekRowid

SeekScan
This opcode is a prefix opcode to SeekGE.  In other words, this
opcode must be immediately followed by SeekGE. This constraint is
checked by assert() statements.

This opcode uses the P1 through P4 operands of the subsequent
SeekGE.  In the text that follows, the operands of the subsequent
SeekGE opcode are denoted as SeekOP.P1 through SeekOP.P4.   Only
the P1 and P2 operands of this opcode are also used, and  are called
This.P1 and This.P2.

This opcode helps to optimize IN operators on a multi-column index
where the IN operator is on the later terms of the index by avoiding
unnecessary seeks on the btree, substituting steps to the next row
of the b-tree instead.  A correct answer is obtained if this opcode
is omitted or is a no-op.

The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
is the desired entry that we want the cursor SeekGE.P1 to be pointing
to.  Call this SeekGE.P4/P5 row the "target".

If the SeekGE.P1 cursor is not currently pointing to a valid row,
then this opcode is a no-op and control passes through into the SeekGE.

If the SeekGE.P1 cursor is pointing to a valid row, then that row
might be the target row, or it might be near and slightly before the
target row.  This opcode attempts to position the cursor on the target
row by, perhaps by invoking sqlite3BtreeStep() on the cursor
between 0 and This.P1 times.

There are three possible outcomes from this opcode:

 If after This.P1 steps, the cursor is still pointing to a place that
is earlier in the btree than the target row, then fall through
into the subsquence SeekGE opcode.

 If the cursor is successfully moved to the target row by 0 or more
sqlite3BtreeNext() calls, then jump to This.P2, which will land just
past the IdxGT or IdxGE opcode that follows the SeekGE.

 If the cursor ends up past the target row (indicating the the target
row does not exist in the btree) then jump to SeekOP.P2.


Sequence
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.

SequenceTest
P1 is a sorter cursor. If the sequence counter is currently zero, jump
to P2. Regardless of whether or not the jump is taken, increment the
the sequence value.

SetCookie
Write the integer value P3 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.

If P2 is the SCHEMA_VERSION cookie (cookie number 1) then the internal
schema version is set to P3-P5.  The "PRAGMA schema_version=N" statement
has P5 set to 1, so that the internal schema version will be different
from the database schema version, resulting in a schema reset.

ShiftLeft
Shift the integer value in register P2 to the left 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.

ShiftRight
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.

SoftNull
Set register P1 to have the value NULL as seen by the MakeRecord
instruction, but do not free any string or blob memory associated with
the register, so that if the value was a string or blob that was
previously copied using SCopy, the copies will continue to be valid.

Sort
This opcode does exactly the same thing as 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 Sort opcode instead of 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.

SorterCompare
P1 is a sorter cursor. This instruction compares a prefix of the
record blob in register P3 against a prefix of the entry that
the sorter cursor currently points to.  Only the first P4 fields
of r&#91;P3&#93; and the sorter record are compared.

If either P3 or the sorter contains a NULL in one of their significant
fields (not counting the P4 fields at the end which are ignored) then
the comparison is assumed to be equal.

Fall through to next instruction if the two records compare equal to
each other.  Jump to P2 if they are different.

SorterData
Write into register P2 the current sorter data for sorter cursor P1.
Then clear the column header cache on cursor P3.

This opcode is normally use to move a record out of the sorter and into
a register that is the source for a pseudo-table cursor created using
OpenPseudo.  That pseudo-table cursor is the one that is identified by
parameter P3.  Clearing the P3 column cache as part of this opcode saves
us from having to issue a separate NullRow instruction to clear that cache.

SorterInsert
Register P2 holds an SQL index key made using the
MakeRecord instructions.  This opcode writes that key
into the sorter P1.  Data for the entry is nil.

SorterNext
This opcode works just like Next except that P1 must be a
sorter object for which the SorterSort opcode has been
invoked.  This opcode advances the cursor to the next sorted
record, or jumps to P2 if there are no more sorted records.

SorterOpen
This opcode works like OpenEphemeral except that it opens
a transient index that is specifically designed to sort large
tables using an external merge-sort algorithm.

If argument P3 is non-zero, then it indicates that the sorter may
assume that a stable sort considering the first P3 fields of each
key is sufficient to produce the required results.

SorterSort
After all records have been inserted into the Sorter object
identified by P1, invoke this opcode to actually do the sorting.
Jump to P2 if there are no records to be sorted.

This opcode is an alias for Sort and Rewind that is used
for Sorter objects.

SqlExec
Run the SQL statement or statements specified in the P4 string.

String
The string value P4 of length P1 (bytes) is stored in register P2.

If P3 is not zero and the content of register P3 is equal to P5, then
the datatype of the register P2 is converted to BLOB.  The content is
the same sequence of bytes, it is merely interpreted as a BLOB instead
of a string, as if it had been CAST.  In other words:

if( P3!=0 and reg&#91;P3&#93;==P5 ) reg&#91;P2&#93; := CAST(reg&#91;P2&#93; as BLOB)

String8
P4 points to a nul terminated UTF-8 string. This opcode is transformed
into a String opcode before it is executed for the first time.  During
this transformation, the length of string P4 is computed and stored
as the P1 parameter.

Subtract
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.

TableLock
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.

Trace
Write P4 on the statement trace output if statement tracing is
enabled.

Operand P1 must be 0x7fffffff and P2 must positive.

Transaction
Begin a transaction on database P1 if a transaction is not already
active.
If P2 is non-zero, then a write-transaction is started, or if a
read-transaction is already active, it is upgraded to a write-transaction.
If P2 is zero, then a read-transaction is started.  If P2 is 2 or more
then an exclusive transaction is started.

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 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 changes made by 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 P5!=0 then this opcode also checks the schema cookie against P3
and the schema generation counter against P4.
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.  If the schema
cookie in P3 differs from the schema cookie in the database header or
if the schema generation counter in P4 differs from the current
generation counter, then an SQLITE_SCHEMA error is raised and execution
halts.  The sqlite3_step() wrapper function might then reprepare the
statement and rerun it from the beginning.

TypeCheck
Apply affinities to the range of P2 registers beginning with P1.
Take the affinities from the Table object in P4.  If any value
cannot be coerced into the correct type, then raise an error.

This opcode is similar to Affinity except that this opcode
forces the register type to the Table column type.  This is used
to implement "strict affinity".

GENERATED ALWAYS AS ... STATIC columns are only checked if P3
is zero.  When P3 is non-zero, no type checking occurs for
static generated columns.  Virtual columns are computed at query time
and so they are never checked.

Preconditions:


 P2 should be the number of non-virtual columns in the
table of P4.
 Table P4 should be a STRICT table.


If any precondition is false, an assertion fault occurs.

Vacuum
Vacuum the entire database P1.  P1 is 0 for "main", and 2 or more
for an attached database.  The "temp" database may not be vacuumed.

If P2 is not zero, then it is a register holding a string which is
the file into which the result of vacuum should be written.  When
P2 is zero, the vacuum overwrites the original database.

Variable
Transfer the values of bound parameter P1 into register P2

If the parameter is named, then its name appears in P4.
The P4 value is used by sqlite3_bind_parameter_name().

VBegin
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.

VColumn
Store in register P3 the value of the P2-th column of
the current row of the virtual-table of cursor P1.

If the VColumn opcode is being used to fetch the value of
an unchanging column during an UPDATE operation, then the P5
value is OPFLAG_NOCHNG.  This will cause the sqlite3_vtab_nochange()
function to return true inside the xColumn method of the virtual
table implementation.  The P5 column might also contain other
bits (OPFLAG_LENGTHARG or OPFLAG_TYPEOFARG) but those bits are
unused by VColumn.

VCreate
P2 is a register that holds the name of a virtual table in database
P1. Call the xCreate method for that table.

VDestroy
P4 is the name of a virtual table in database P1.  Call the xDestroy method
of that table.

VFilter
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.

VInitIn
Set register P2 to be a pointer to a ValueList object for cursor P1
with cache register P3 and output register P3+1.  This ValueList object
can be used as the first argument to sqlite3_vtab_in_first() and
sqlite3_vtab_in_next() to extract all of the values stored in the P1
cursor.  Register P3 is used to hold the values returned by
sqlite3_vtab_in_first() and sqlite3_vtab_in_next().

VNext
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.

VOpen
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.

VRename
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.

VUpdate
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.

P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
apply in the case of a constraint failure on an insert or update.

Yield
Swap the program counter with the value in register P1.  This
has the effect of yielding to a coroutine.

If the coroutine that is launched by this instruction ends with
Yield or Return then continue to the next instruction.  But if
the coroutine launched by this instruction ends with
EndCoroutine, then jump to P2 rather than continuing with the
next instruction.

See also: InitCoroutine

ZeroOrNull
If all both registers P1 and P3 are NOT NULL, then store a zero in
register P2.  If either registers P1 or P3 are NULL then put
a NULL in register P2.


c2: Memory-Mapped I/O
c5: mmap.html
c4:
Memory-Mapped I/O

The default mechanism by which SQLite accesses and updates database disk
files is the xRead() and xWrite() methods of the
sqlite3_io_methods VFS object.  These methods are typically implemented as
"read()" and "write()" system calls which cause the operating system
to copy disk content between the kernel buffer cache and user space.

Beginning with version 3.7.17 (2013-05-20), SQLite has the option of 
accessing disk content directly using memory-mapped I/O and the new
xFetch() and xUnfetch() methods on sqlite3_io_methods.

There are advantages and disadvantages to using memory-mapped I/O.
Advantages include:


Many operations, especially I/O intensive operations, can be
    faster since content need not be copied between kernel space
    and user space.

The SQLite library may need less RAM since it shares pages with
    the operating-system page cache and does not always need its own copy of
    working pages.


But there are also disadvantages:


An I/O error on a memory-mapped file cannot be caught and dealt with by
    SQLite.  Instead, the I/O error causes a signal which, if not caught
    by the application, results in a program crash.

The operating system must have a unified buffer cache in order for
    the memory-mapped I/O extension to work correctly, especially in
    situations where two processes are accessing the same database
    file and one process is using memory-mapped I/O while the other
    is not.  Not all operating systems have a unified buffer cache.
    In some operating systems that claim to have a unified buffer cache,
    the implementation is buggy and can lead to corrupt databases.

Performance does not always increase with memory-mapped I/O.  In fact,
    it is possible to construct test cases where performance is reduced
    by the use of memory-mapped I/O.

Windows is unable to truncate a memory-mapped file.  Hence, on Windows,
    if an operation such as VACUUM or auto_vacuum tries to reduce the
    size of a memory-mapped database file, the size reduction attempt will
    silently fail, leaving unused space at the end of the database file.
    No data is lost due to this problem, and the unused space will be
    reused again the next time the database grows.  However if a version 
    of SQLite prior to 3.7.0 runs PRAGMA integrity_check on such a 
    database, it will (incorrectly) report database corruption due to 
    the unused space at the end.  Or if a version of SQLite prior to 3.7.0
    writes to the database while it still has unused space at the end, it
    may make that unused space inaccessible and unavailable for reuse until
    after the next VACUUM.


Because of the potential disadvantages, memory-mapped I/O is disabled
by default.  To activate memory-mapped I/O, use the mmap_size pragma
and set the mmap_size to some large number, usually 256MB or larger, depending
on how much address space your application can spare.  The rest is
automatic.  The PRAGMA mmap_size statement will be a silent no-op on
systems that do not support memory-mapped I/O.

How Memory-Mapped I/O Works

To read a page of database content using the legacy xRead() method,
SQLite first allocates a page-size chunk of heap memory then invokes
the xRead() method which causes the database page content to be copied
into the newly allocated heap memory.  This involves (at a minimum)
a copy of the entire page.

But if SQLite wants to access a page of the database file and
memory mapped I/O is enabled, it first calls the xFetch() method.
The xFetch() method asks the operating system to return a pointer to
the requested page, if possible.  If the requested page has been or
can be mapped into the application address space, then xFetch returns
a pointer to that page for SQLite to use without having to copy anything.
Skipping the copy step is what makes memory mapped I/O faster.

SQLite does not assume that the xFetch() method will work.  If
a call to xFetch() returns a NULL pointer (indicating that the requested
page is not currently mapped into the applications address space) then
SQLite silently falls back to using xRead().  An error is only reported
if xRead() also fails.

When updating the database file, SQLite always makes a copy of the
page content into heap memory before modifying the page.  This is necessary
for two reasons.  First, changes to the database
are not supposed to be visible to other processes until
after the transaction commits and so the changes must occur in private memory.
Second, SQLite uses a read-only memory map to prevent stray pointers in the 
application from overwriting and corrupting the database file.


After all needed changes are completed, xWrite() is used to move the content
back into the database file.
Hence the use of memory mapped I/O does not significantly change the
performance of database changes.
Memory mapped I/O is mostly a benefit for queries.

Configuring Memory-Mapped I/O

The "mmap_size" is the maximum number of bytes of the database file that
SQLite will try to map into the process address space at one time.  The
mmap_size applies separately to each database file, so the total amount
of process address space that could potentially be used is the mmap_size
times the number of open database files.

To activate memory-mapped I/O, an application can set the mmap_size to some
large value.  For example:


PRAGMA mmap_size=268435456;


To disable memory-mapped I/O, simply set the mmap_size to zero:


PRAGMA mmap_size=0;


If mmap_size is set to N then all current implementations map the first
N bytes of the database file and use legacy xRead() calls for any content
beyond N bytes.  If the database file is smaller than N bytes, then the entire
file is mapped.  In the future, new OS interfaces could, in theory, map
regions of the file other than the first N bytes, but no such 
implementation currently exists.

The mmap_size is set separately for each database file using the
"PRAGMA mmap_size" statement.  The usual default mmap_size is zero,
meaning that memory mapped I/O is disabled by default.  However, the
default mmap_size can be increased either at compile-time using
the SQLITE_DEFAULT_MMAP_SIZE macro or at start-time using the
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE,...) interface.

SQLite also maintains a hard upper bound on the mmap_size.  Attempts
to increase the mmap_size above this hard upper bound (using
PRAGMA mmap_size) will automatically cap the mmap_size at the hard
upper bound.  If the hard upper bound is zero, then memory mapped I/O
is impossible.  The hard upper bound can be set at compile-time using
the SQLITE_MAX_MMAP_SIZE macro.  If SQLITE_MAX_MMAP_SIZE is set to
zero, then the code used to implement memory mapped I/O is omitted from
the build.  The hard upper bound is automatically set to zero on certain
platforms (ex: OpenBSD) where memory mapped I/O does not work due to the
lack of a unified buffer cache.

If the hard upper bound on mmap_size is non-zero at compilation time,
it may still be reduced or zeroed at start-time using the
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE,X,Y) interface.  The X and
Y parameters must both be 64-bit signed integers. The X parameter
is the default mmap_size of the process and the Y is the new hard upper bound.
The hard upper bound cannot be increased above its compile-time setting
using SQLITE_CONFIG_MMAP_SIZE but it can be reduced or zeroed.


c2: Partial Indexes
c5: partialindex.html
c4:
1. Introduction


A partial index is an index over a subset of the rows of a table.



In ordinary indexes, there is exactly one entry in the index for every
row in the table.  In partial indexes, only some subset of the rows in the
table have corresponding index entries.  For example, a partial index might
omit entries for which the column being indexed is NULL.  When used 
judiciously, partial indexes can result in smaller database files and
improvements in both query and write performance.


2. Creating Partial Indexes


Create a partial index by adding a WHERE clause to the end of an 
ordinary CREATE INDEX statement.


create-index-stmt:
hide
 
 

expr:
show
 
 

filter-clause:
show
 
 


literal-value:
show
 
 


over-clause:
show
 
 

frame-spec:
show
 
 


ordering-term:
show
 
 



raise-function:
show
 
 


select-stmt:
show
 
 

common-table-expression:
show
 
 


compound-operator:
show
 
 


join-clause:
show
 
 

join-constraint:
show
 
 


join-operator:
show
 
 



ordering-term:
show
 
 


result-column:
show
 
 


table-or-subquery:
show
 
 


window-defn:
show
 
 

frame-spec:
show
 
 




type-name:
show
 
 

signed-number:
show
 
 




indexed-column:
show
 
 






Any index that includes the WHERE clause at the end is considered to be
a partial index.  Indexes that omit the WHERE clause (or indexes that
are created by UNIQUE or PRIMARY KEY constraints inside of CREATE TABLE
statements) are ordinary full indexes.



The expression following the WHERE clause may contain operators,
literal values, and names of columns in the table being indexed.
The WHERE clause may not contain subqueries, references to other
tables, non-deterministic functions, or bound parameters.


Only rows of the table for which the WHERE clause evaluates to true
are included in the index.  If the WHERE clause expression evaluates 
to NULL or to false for some rows of the table, then those rows are omitted 
from the index.



The columns referenced in the WHERE clause of a partial index can be
any of the columns in the table, not just columns that happen to be
indexed.  However, it is very common for the WHERE clause
expression of a partial index to be a simple expression on the column
being indexed.  The following is a typical example:

CREATE INDEX po_parent ON purchaseorder(parent_po) WHERE parent_po IS NOT NULL;


In the example above, if most purchase orders do not have a "parent"
purchase order, then most parent_po values will be NULL.  That means only
a small subset of the rows in the purchaseorder table will be indexed.
Hence the index will take up much less space.  And changes to the original
purchaseorder table will run faster since the po_parent index only needs
to be updated for those exceptional rows where parent_po is not NULL.
But the index is still useful for querying.  In particular, if one wants
to know all "children" of a particular purchase order "?1", the query
would be:

SELECT po_num FROM purchaseorder WHERE parent_po=?1;


The query above will use the po_parent index to help find the answer,
since the po_parent index contains entries for all rows of interest.
Note that since po_parent is smaller than a full index, the query will
likely run faster too.

2.1. Unique Partial Indexes

A partial index definition may include the UNIQUE keyword.  If it
does, then SQLite requires every entry in the index to be unique.
This provides a mechanism for enforcing uniqueness across some subset of
the rows in a table.

For example, suppose you have a database of the members of a large
organization where each person is assigned to a particular "team".  
Each team has a "leader" who is also a member of that team.  The
table might look something like this:

CREATE TABLE person(
  person_id       INTEGER PRIMARY KEY,
  team_id         INTEGER REFERENCES team,
  is_team_leader  BOOLEAN,
  -- other fields elided
);


The team_id field cannot be unique because there are usually multiple people
on the same team.  One cannot make the combination of team_id and is_team_leader
unique since there are usually multiple non-leaders on each team.  The
solution to enforcing one leader per team is to create a unique index
on team_id but restricted to those entries for which is_team_leader is
true:

CREATE UNIQUE INDEX team_leader ON person(team_id) WHERE is_team_leader;


Coincidentally, that same index is useful for locating the team leader
of a particular team:

SELECT person_id FROM person WHERE is_team_leader AND team_id=?1;


3. Queries Using Partial Indexes

Let X be the expression in the WHERE clause of a partial
index, and let W be the WHERE clause of a query that uses the
table that is indexed.  Then, the query is permitted to use 
the partial index if W&#x21d2;X, where the &#x21d2; operator
(usually pronounced "implies") is the logic operator 
equivalent to "X or not W".
Hence, determining whether or not a partial index
is usable in a particular query reduces to proving a theorem in
first-order logic.

SQLite does not have a sophisticated theorem
prover with which to determine W&#x21d2;X.  Instead, SQLite uses 
two simple rules to find the common cases where W&#x21d2;X is true, and
it assumes all the other cases are false.  The rules used by SQLite
are these:


If W is AND-connected terms and X is
OR-connected terms and if any term of W
appears as a term of X, then the partial index is usable.

For example, let the index be
CREATE INDEX ex1 ON tab1(a,b) WHERE a=5 OR b=6;

And let the query be:
SELECT * FROM tab1 WHERE b=6 AND a=7; -- uses partial index

Then the index is usable by the query because the "b=6" term appears
in both the index definition and in the query.  Remember: terms in the
index should be OR-connected and terms in the query should be AND-connected.

The terms in W and X must match exactly.  SQLite does not
do algebra to try to get them to look the same.
The term "b=6" does not match "b=3+3" or "b-6=0" or "b BETWEEN 6 AND 6".
"b=6" will match to "6=b" as long as "b=6" is on the index and "6=b" is
in the query.  If a term of the form "6=b" appears in the index, it will
never match anything.

If a term in X is of the form "z IS NOT NULL" and if a term in
       W is a comparison operator on "z" other than "IS", then those
       terms match.

Example:  Let the index be
CREATE INDEX ex2 ON tab2(b,c) WHERE c IS NOT NULL;

Then any query that uses operators =, &lt;, &gt;, &lt;=, &gt;=, &lt;&gt;,
IN, LIKE, or GLOB on column "c" 
would be usable with the partial index because those
comparison operators are only true if "c" is not NULL.  So the following
query could use the partial index:
SELECT * FROM tab2 WHERE b=456 AND c&lt;&gt;0;  -- uses partial index

But the next query can not use the partial index:
SELECT * FROM tab2 WHERE b=456;  -- cannot use partial index

The latter query can not use the partial index because there might be
rows in the table with b=456 and where c is NULL.  But those rows would
not be in the partial index.


These two rules describe how the query planner for SQLite works as of
this writing (2013-08-01).  And the rules above will always be honored.
However, future versions of SQLite might incorporate a better theorem prover
that can find other cases where W&#x21d2;X is true and thus may
find more instances where partial indexes are useful.

4. Supported Versions


Partial indexes have been supported in SQLite since version 3.8.0
(2013-08-26).


Database files that contain partial indices are not readable or writable
by versions of SQLite prior to 3.8.0.  However, a database file created
by SQLite 3.8.0 is still readable and writable by prior versions as long
as its schema contains no partial indexes.  A database that is unreadable
by legacy versions of SQLite can be made readable simply by running
DROP INDEX on the partial indexes.


c2: Run-Time Loadable Extensions
c5: loadext.html
c4:
1. Overview

SQLite has the ability to load extensions (including new
application-defined SQL functions,
collating sequences, virtual tables, and VFSes) at run-time.
This feature allows the code for extensions to be developed and
tested separately from the application and then loaded
on an as-needed basis.

Extensions can also be statically linked with the application.
The code template shown below will work just as well as a statically
linked extension as it does as a run-time loadable extension except that
you should give the entry point function ("sqlite3_extension_init")
a different name to avoid name collisions if your application contains
two or more extensions.

2. Loading An Extension

An SQLite extension is a shared library or DLL.  To load it, you
need to supply SQLite with the name of the file containing the
shared library or DLL and an entry point to initialize the extension.
In C code, this information is supplied using the
sqlite3_load_extension() API.  See the documentation on that
routine for additional information.

Note that different operating systems use different filename
suffixes for their shared libraries.  Windows uses ".dll", Mac uses
".dylib", and most unixes other than mac use ".so".  If you want to
make your code portable, you can omit the suffix from the shared
library filename and the appropriate suffix will be added automatically
by the sqlite3_load_extension() interface.

There is also an SQL function that can be used to load extensions:
load_extension(X,Y).  It works just like the sqlite3_load_extension()
C interface.

Both methods for loading an extension allow you to specify
the name of an entry point for the extension.  
You can leave this argument blank - passing in
a NULL pointer for the sqlite3_load_extension() C-language interface
or omitting the second argument for the load_extension() SQL interface -
and the extension loader logic will attempt to figure out the entry point
on its own.  It will first try the generic extension name
"sqlite3_extension_init".  If that does not work, it constructs a
entry point using the template "sqlite3_X_init" where the X is replaced
by the lowercase equivalent of every ASCII character in the filename
after the last "/" and before the first following "." omitting the
first three characters if they happen to be "lib".  So, for example,
if the filename is "/usr/lib/libmathfunc-4.8.so" the entry point name
would be "sqlite3_mathfunc_init".  Or if the filename is 
"./SpellFixExt.dll" then the entry point would be called
"sqlite3_spellfixext_init".

For security reasons, extension loading is turned off by default.
In order to use either the C-language or SQL extension loading functions,
one must first enable extension loading using the
sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,1,NULL)
C-language API in your application.

From the command-line shell, extensions can be loaded using the
".load" dot-command.  For example:


.load ./YourCode


Note that the command-line shell program has already enabled
extension loading for you (by calling the sqlite3_enable_load_extension()
interface as part of its setup) so the command above works without
any special switches, setup, or other complications.

The ".load" command with one argument invokes sqlite3_load_extension()
with the zProc parameter set to NULL, causing SQLite to first look for
an entry point named "sqlite3_extension_init" and then "sqlite3_X_init"
where "X" is derived from the filename.  If your extension has an entry
point with a different name, simply supply that name as the second
argument.  For example:


.load ./YourCode nonstandard_entry_point




3. Compiling A Loadable Extension

Loadable extensions are C-code.  To compile them on
most unix-like operating
systems, the usual command is something like this:


gcc -g -fPIC -shared YourCode.c -o YourCode.so


Macs are unix-like, but they do not follow the usual shared library
conventions.  To compile a shared library on a Mac, use a command like
this:


gcc -g -fPIC -dynamiclib YourCode.c -o YourCode.dylib


If when you try to load your library you get back an error message
that says "mach-o, but wrong architecture" then you might need to add
command-line options "-arch i386" or "arch x86_64" to gcc, depending
on how your application is built.

To compile on Windows using MSVC, a command similar to the following
will usually work:


cl YourCode.c -link -dll -out:YourCode.dll


To compile for Windows using MinGW, the command line is just like it
is for unix except that the output file suffix is changed to ".dll" and
the -fPIC argument is omitted:


gcc -g -shared YourCode.c -o YourCode.dll




4. Programming Loadable Extensions

A template loadable extension contains the following three elements:



Use "#include &lt;sqlite3ext.h&gt;" at the top of your source
code files instead of "#include &lt;sqlite3.h&gt;".



Put the macro "SQLITE_EXTENSION_INIT1" on a line by itself 
right after the "#include &lt;sqlite3ext.h&gt;" line.



Add an extension loading entry point routine that looks like 
something the following:

#ifdef _WIN32
__declspec(dllexport)
#endif
int sqlite3_extension_init( /* &lt;== Change this name, maybe */
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
  SQLITE_EXTENSION_INIT2(pApi);
  /* insert code to initialize your extension here */
  return rc;
}


You will do well to customize the name of your entry point to
correspond to the name of the shared library you will be generating,
rather than using the generic "sqlite3_extension_init" name.  Giving
your extension a custom entry point name will enable you to statically
link two or more extensions into the same program without a linker
conflict, if you later decide to use static linking rather than run-time
linking.
If your shared library ends up being named "YourCode.so" or
"YourCode.dll" or "YourCode.dylib" as shown in the compiler examples
above, then the correct entry point name would be
"sqlite3_yourcode_init".


Here is a complete template extension that you can copy/paste 
to get started:

/* Add your header comment here */
#include &lt;sqlite3ext.h&gt; /* Do not use &lt;sqlite3.h&gt;! */
SQLITE_EXTENSION_INIT1

/* Insert your extension code here */

#ifdef _WIN32
__declspec(dllexport)
#endif
/* TODO: Change the entry point name so that "extension" is replaced by
** text derived from the shared library filename as follows:  Copy every
** ASCII alphabetic character from the filename after the last "/" through
** the next following ".", converting each character to lowercase, and
** discarding the first three characters if they are "lib".
*/
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg, 
  const sqlite3_api_routines *pApi
){
  int rc = SQLITE_OK;
  SQLITE_EXTENSION_INIT2(pApi);
  /* Insert here calls to
  **     sqlite3_create_function_v2(),
  **     sqlite3_create_collation_v2(),
  **     sqlite3_create_module_v2(), and/or
  **     sqlite3_vfs_register()
  ** to register the new features that your extension adds.
  */
  return rc;
}


4.1. Example Extensions

Many examples of complete and working loadable extensions can be 
seen in the SQLite source tree in the
ext/misc subdirectory.
Each file in that directory is a separate extension.  Documentation
is provided by a header comment on the file.
Here are brief notes on a few of the extensions in 
the ext/misc subdirectory:



carray.c &mdash;
Implementation of the carray table-valued function.

compress.c &mdash;
Implementation of application-defined SQL functions compress() and
uncompress() that do zLib compression of text or blob content.

json1.c &mdash;
Implementation of JSON SQL functions and table-valued functions.
This is a larger and more complex extension.

memvfs.c &mdash;
Implementation of a new VFS that stores all content in-memory.

rot13.c &mdash;
Implementation of a rot13() 
SQL function.  This is a very simple example of an extension function
and is useful as a template for creating new extensions.

series.c &mdash;
Implementation of the generate_series virtual table and
table-valued function.  This is a relatively simple example of a
virtual table implementation which can serve as a template for writing
new virtual tables.


Other and more complex extensions can be found in subfolders
under ext/ other than ext/misc/.



5. Persistent Loadable Extensions

The default behavior for a loadable extension is that it is unloaded
from process memory when the database connection that originally invoked
sqlite3_load_extension() closes.  (In other words, the xDlClose method
of the sqlite3_vfs object is called for all extensions when a database
connection closes.)  However, if the initialization procedure returns
SQLITE_OK_LOAD_PERMANENTLY instead of SQLITE_OK, then the extension will
not be unloaded (xDlClose will not be invoked) and the extension will remain
in process memory indefinitely.  The SQLITE_OK_LOAD_PERMANENTLY return
value is useful for extensions that want to register new VFSes.

To clarify: an extension for which the initialization function returns
SQLITE_OK_LOAD_PERMANENTLY continues to exist in memory after the database
connection closes.  However, the extension is not automatically
registered with subsequent database connections.  This makes it possible
to load extensions that implement new VFSes.
To persistently load and register an extension that implements new SQL
functions, collating sequences, and/or virtual tables, such that those
added capabilities are available to all subsequent database connections,
then the initialization routine should also invoke sqlite3_auto_extension()
on a subfunction that will register those services.

The vfsstat.c extension
show an example of a loadable extension that persistently registers both
a new VFS and a new virtual table.  The
sqlite3_vfsstat_init()
initialization routine in that extension is called only once, when the
extension is first loaded.  It registers the new "vfslog" VFS just that
one time, and it returns SQLITE_OK_LOAD_PERMANENTLY so that the code used
to implement the "vfslog" VFS will remain in memory. The initialization routine
also invokes sqlite3_auto_extension() on a pointer to the "vstatRegister()"
function so that all subsequent database connections will invoke the
"vstatRegister()" function as they start up, and hence register the
"vfsstat" virtual table.  

6. Statically Linking A Run-Time Loadable Extension

The exact same source code can be used for both a run-time loadable
shared library or DLL and as a module that is statically linked with your
application.  This provides flexibility and allows you to reuse the same
code in different ways.

To statically link your extension, simply add the -DSQLITE_CORE
compile-time option.  The SQLITE_CORE macro causes the SQLITE_EXTENSION_INIT1
and SQLITE_EXTENSION_INIT2 macros to become no-ops.  Then modify your
application to invoke the entry point directly, passing in a NULL pointer
as the third "pApi" parameter.

It is particularly important to use an entry point name that is
based on the extension filename, rather than the generic
"sqlite3_extension_init" entry point name, if you will be statically
linking two or more extensions.  If you use the generic name, there
will be multiple definitions of the same symbol and the link will fail.

If you will be opening multiple database connections in your application,
rather than invoking the extension entry points for each database
connection separately, you might want to consider using the
sqlite3_auto_extension() interface to register your extensions and
to cause them to be automatically started as each database connection
is opened.  You only have to register each extension once, and you can
do so near the beginning of your main() routine.  Using the
sqlite3_auto_extension() interface to register your extensions makes
your extensions work as if they were built into the core SQLite - they
automatically exist whenever you open a new database connection
without needing to be initialized.  Just be sure to complete any
configuration you need to accomplish using sqlite3_config() before
registering your extensions, since the sqlite3_auto_extension()
interface implicitly calls sqlite3_initialize().

7. Implementation Details

SQLite implements run-time extension loading using the
xDlOpen(), xDlError(), xDlSym(), and xDlClose() methods of the
sqlite3_vfs object.  These methods are implemented using
the dlopen() library on unix (which explains why SQLite commonly
needs to be linked against the "-ldl" library on unix systems)
and using LoadLibrary() API on Windows.  In a custom VFS for
unusual systems, these methods can all be omitted, in which case
the run-time extension loading mechanism will not work (though
you will still be able to statically link the extension code, assuming
the entry pointers are uniquely named).
SQLite can be compiled with
SQLITE_OMIT_LOAD_EXTENSION to omit the extension loading code
from the build.


c2: The Session Extension
c3: 1. Introduction
c5: sessionintro.html#introduction
c4:
The session extension provide a mechanism for recording changes
to some or all of the rowid tables in an SQLite database, and packaging
those changes into a "changeset" or "patchset" file that can later
be used to apply the same set of changes to another database with
the same schema and compatible starting data.  A "changeset" may
also be inverted and used to "undo" a session.

This document is an introduction to the session extension.
The details of the interface are in the separate
Session Extension C-language Interface document.


c2: The Session Extension
c3: 1.1. Typical Use Case
c5: sessionintro.html#typical_use_case
c4:
Suppose SQLite is used as the application file format for a
particular design application.  Two users, Alice and Bob, each start
with a baseline design that is about a gigabyte in size.  They work
all day, in parallel, each making their own customizations and tweaks
to the design.  At the end of the day, they would like to merge their
changes together into a single unified design.

The session extension facilitates this by recording all changes to
both Alice's and Bob's databases and writing those changes into
changeset or patchset files.  At the end of the day, Alice can send her
changeset to Bob and Bob can "apply" it to his database.  The result (assuming
there are no conflicts) is that Bob's database then contains both his
changes and Alice's changes.  Likewise, Bob can send a changeset of
his work over to Alice and she can apply his changes to her database.

In other words, the session extension provides a facility for
SQLite database files that is similar to the unix
patch utility program,
or to the "merge" capabilities of version control systems such
as Fossil, Git, 
or Mercurial.


c2: The Session Extension
c3: 1.2. Obtaining the Session Extension
c5: sessionintro.html#obtaining_the_session_extension
c4:
Since version 3.13.0 (2016-05-18), 
the session extension has been included in the SQLite
amalgamation source distribution. By default, the session extension is 
disabled. To enable it, build with the following compiler switches:

-DSQLITE_ENABLE_SESSION -DSQLITE_ENABLE_PREUPDATE_HOOK


 Or, if using the autoconf build system, pass the --enable-session option to the configure script.


c2: The Session Extension
c3: 1.3. Limitations
c5: sessionintro.html#limitations
c4:
Prior to SQLite version 3.17.0, the session extension only worked with
        rowid tables, not WITHOUT ROWID tables. As of 3.17.0, both
        rowid and WITHOUT ROWID tables are supported.

 There is no support for virtual tables. Changes to virtual tables are
        not captured.

 The session extension only works with tables that have a declared
        PRIMARY KEY. The PRIMARY KEY of a table may be an INTEGER PRIMARY KEY
        (rowid alias) or an external PRIMARY KEY.

 SQLite allows NULL values to be stored in
        PRIMARY KEY columns. However, the session extension ignores all
        such rows. No changes affecting rows with one or more NULL values
        in PRIMARY KEY columns are recorded by the sessions module.


c2: The Session Extension
c3: 2.1. Changesets and Patchsets
c5: sessionintro.html#changesets_and_patchsets
c4:
The sessions module revolves around creating and manipulating 
changesets. A changeset is a blob of data that encodes a series of 
changes to a database. Each change in a changeset is one of the 
following:


   An INSERT. An INSERT change contains a single row to add to 
       a database table. The payload of the INSERT change consists of the
       values for each field of the new row.

   A DELETE. A DELETE change represents a row, identified by
       its primary key values, to remove from a database table. The payload
       of a DELETE change consists of the values for all fields of the 
       deleted row.

   An UPDATE. An UPDATE change represents the modification of
       one or more non-PRIMARY KEY fields of a single row within a database 
       table, identified by its PRIMARY KEY fields. The payload for an UPDATE
       change consists of:
   
      The PRIMARY KEY values identifying the modified row, 
      The new values for each modified field of the row, and
      The original values for each modified field of the row.
   
        An UPDATE change does not contain any information regarding
       non-PRIMARY KEY fields that are not modified by the change. It is not
       possible for an UPDATE change to specify modifications to PRIMARY 
       KEY fields. 


 A single changeset may contain changes that apply to more than one 
database table. For each table that the changeset includes at least one change
for, it also encodes the following data:


   The name of the database table, 
   The number of columns the table has, and
   Which of those columns are PRIMARY KEY columns.


 Changesets may only be applied to databases that contain tables 
matching the above three criteria as stored in the changeset.

 A patchset is similar to a changeset. It is slightly more compact than
a changeset, but provides more limited conflict detection and resolution
options (see the next section for details). The differences between a 
patchset and a changeset are that:


   For a DELETE change, the payload consists of the PRIMARY KEY 
          fields only. The original values of other fields are not stored as
          part of a patchset.

   For an UPDATE change, the payload consists of the PRIMARY KEY 
          fields and the new values of modified fields only. The original
          values of modified fields are not stored as part of a patchset.


c2: The Session Extension
c3: 2.2. Conflicts
c5: sessionintro.html#conflicts
c4:
When a changeset or patchset is applied to a database, an attempt is 
made to insert a new row for each INSERT change, remove a row for each
DELETE change and modify a row for each UPDATE change. If the target 
database is in the same state as the original database that the changeset
was recorded on, this is a simple matter. However, if the contents of the
target database is not in exactly this state, conflicts can occur when
applying the changeset or patchset.

When processing an INSERT change, the following conflicts can
occur:


   The target database may already contain a row with the same PRIMARY
       KEY values as specified by the INSERT change.

   Some other database constraint, for example a UNIQUE or CHECK 
       constraint, may be violated when the new row is inserted.


When processing a DELETE change, the following conflicts may be
detected:


   The target database may contain no row with the specified PRIMARY 
       KEY values to delete.

   The target database may contain a row with the specified PRIMARY
       KEY values, but the other fields may contain values that do not
       match those stored as part of the changeset. This type of conflict
       is not detected when using a patchset.


When processing an UPDATE change, the following conflicts may be
detected:


   The target database may contain no row with the specified PRIMARY 
       KEY values to modify.

   The target database may contain a row with the specified PRIMARY
       KEY values, but the current values of the fields that will be modified
       by the change may not match the original values stored within the
       changeset. This type of conflict is not detected when using a patchset.

   Some other database constraint, for example a UNIQUE or CHECK 
       constraint, may be violated when the row is updated.


 Depending on the type of conflict, a sessions application has a variety
of configurable options for dealing with conflicts, ranging from omitting the
conflicting change, aborting the entire changeset application or applying
the change despite the conflict. For details, refer to the documentation for
the sqlite3changeset_apply() API.


c2: The Session Extension
c3: 2.3. Changeset Construction
c5: sessionintro.html#changeset_construction
c4:
After a session object has been configured, it begins monitoring for 
changes to its configured tables. However, it does not record an entire
change each time a row within the database is modified. Instead, it records
just the PRIMARY KEY fields for each inserted row, and just the PRIMARY KEY 
and all original row values for any updated or deleted rows. If a row is 
modified more than once by a single session, no new information is recorded.

 The other information required to create a changeset or patchset is
read from the database file when sqlite3session_changeset() or
sqlite3session_patchset() is called. Specifically,


   For each primary key recorded as a result of an INSERT operation, 
       the sessions module checks if there is a row with a matching primary
       key still in the table. If so, an INSERT change is added to the 
       changeset.

   For each primary key recorded as a result of an UPDATE or DELETE
       operation, the sessions module also checks for a row with a matching
       primary key within the table. If one can be found, but one or more
       of the non-PRIMARY KEY fields does not match the original recorded
       value, an UPDATE is added to the changeset. Or, if there is no row
       at all with the specified primary key, a DELETE is added to the 
       changeset. If the row does exist but none of the non-PRIMARY KEY
       fields have been modified, no change is added to the changeset.


 One implication of the above is that if a change is made and then 
unmade within a single session (for example if a row is inserted and then
deleted again), the sessions module does not report any change at all. Or
if a row is updated multiple times within the same session, all updates
are coalesced into a single update within any changeset or patchset blob.


c2: The Session Extension
c3: 3.1. Capturing a Changeset
c5: sessionintro.html#capturing_a_changeset
c4:
The example code below demonstrates the steps involved in capturing a
changeset while executing SQL commands. In summary:


   A session object (type sqlite3_session*) is created by making a 
          call to the sqlite3session_create() API function.

       A single session object monitors changes made to a single database 
          (i.e. "main", "temp" or an attached database) via a single 
          sqlite3* database handle.

   The session object is configured with a set of tables to monitor
          changes on.

        By default a session object does not monitor changes on any 
           database table. Before it does so it must be configured. There 
           are three ways to configure the set of tables to monitor changes
           on:
       
          By explicitly specifying tables using one call to
              sqlite3session_attach() for each table, or

          By specifying that all tables in the database should be monitored
              for changes using a call to sqlite3session_attach() with a
              NULL argument, or

          By configuring a callback to be invoked the first time each table
              is written to that indicates to the session module whether or
              not changes on the table should be monitored.
       
         The example code below uses the second of the methods enumerated
            above - it monitors for changes on all database tables.

    Changes are made to the database by executing SQL statements. The
           session object records these changes.

    A changeset blob is extracted from the session object using a call
           to sqlite3session_changeset() (or, if using patchsets, a call to
           the sqlite3session_patchset() function).

    The session object is deleted using a call to the 
           sqlite3session_delete() API function.

        It is not necessary to delete a session object after extracting
           a changeset or patchset from it. It can be left attached to the
           database handle and will continue monitoring for changes on the
           configured tables as before. However, if 
           sqlite3session_changeset() or sqlite3session_patchset() is
           called a second time on a session object, the changeset or patchset
           will contain all changes that have taken place on the connection
           since the session was created. In other words,
           a session object is not reset or
           zeroed by a call to sqlite3session_changeset() or
           sqlite3session_patchset().


/*
** Argument zSql points to a buffer containing an SQL script to execute 
** against the database handle passed as the first argument. As well as
** executing the SQL script, this function collects a changeset recording
** all changes made to the "main" database file. Assuming no error occurs,
** output variables (*ppChangeset) and (*pnChangeset) are set to point
** to a buffer containing the changeset and the size of the changeset in
** bytes before returning SQLITE_OK. In this case it is the responsibility
** of the caller to eventually free the changeset blob by passing it to
** the sqlite3_free function.
**
** Or, if an error does occur, return an SQLite error code. The final
** value of (*pChangeset) and (*pnChangeset) are undefined in this case.
*/
int sql_exec_changeset(
  sqlite3 *db,                  /* Database handle */
  const char *zSql,             /* SQL script to execute */
  int *pnChangeset,             /* OUT: Size of changeset blob in bytes */
  void **ppChangeset            /* OUT: Pointer to changeset blob */
){
  sqlite3_session *pSession = 0;
  int rc;

  /* Create a new session object */
  rc = sqlite3session_create(db, "main", &pSession);

  /* Configure the session object to record changes to all tables */
  if( rc==SQLITE_OK ) rc = sqlite3session_attach(pSession, NULL);

  /* Execute the SQL script */
  if( rc==SQLITE_OK ) rc = sqlite3_exec(db, zSql, 0, 0, 0);

  /* Collect the changeset */
  if( rc==SQLITE_OK ){
    rc = sqlite3session_changeset(pSession, pnChangeset, ppChangeset);
  }

  /* Delete the session object */
  sqlite3session_delete(pSession);

  return rc;
}


c2: The Session Extension
c3: 3.2. Applying a Changeset to a Database
c5: sessionintro.html#applying_a_changeset_to_a_database
c4:
Applying a changeset to a database is simpler than capturing a changeset.
Usually, a single call to sqlite3changeset_apply(), as depicted in the
example code below, suffices.

 In cases where it is complicated, the complications in applying a 
changeset lie in conflict resolution. Refer to the API documentation linked
above for details.

  /*
** Conflict handler callback used by apply_changeset(). See below.
*/
static int xConflict(void *pCtx, int eConflict, sqlite3_changset_iter *pIter){
  int ret = (int)pCtx;
  return ret;
}

/*
** Apply the changeset contained in blob pChangeset, size nChangeset bytes,
** to the main database of the database handle passed as the first argument.
** Return SQLITE_OK if successful, or an SQLite error code if an error
** occurs.
**
** If parameter bIgnoreConflicts is true, then any conflicting changes 
** within the changeset are simply ignored. Or, if bIgnoreConflicts is
** false, then this call fails with an SQLTIE_ABORT error if a changeset
** conflict is encountered.
*/
int apply_changeset(
  sqlite3 *db,                  /* Database handle */
  int bIgnoreConflicts,         /* True to ignore conflicting changes */
  int nChangeset,               /* Size of changeset in bytes */
  void *pChangeset              /* Pointer to changeset blob */
){
  return sqlite3changeset_apply(
      db, 
      nChangeset, pChangeset, 
      0, xConflict, 
      (void*)bIgnoreConflicts
  );
}


c2: The Session Extension
c3: 3.3. Inspecting the Contents of a Changeset
c5: sessionintro.html#inspecting_the_contents_of_a_changeset
c4:
The example code below demonstrates the techniques used to iterate 
through and extract the data related to all changes in a changeset. To
summarize:


   The sqlite3changeset_start() API is called to create and
          initialize an iterator to iterate through the contents of a
          changeset. Initially, the iterator points to no element at all.

   The first call to sqlite3changeset_next() on the iterator moves
          it to point to the first change  in the changeset (or to EOF, if 
          the changeset is completely empty). sqlite3changeset_next() returns
          SQLITE_ROW if it moves the iterator to point to a valid entry,
          SQLITE_DONE if it moves the iterator to EOF, or an SQLite error
          code if an error occurs.

   If the iterator points to a valid entry, the sqlite3changeset_op()
          API may be used to determine the type of change (INSERT, UPDATE or
          DELETE) that the iterator points to. Additionally, the same API 
          can be used to obtain the name of the table the change applies to
          and its expected number of columns and primary key columns.

   If the iterator points to a valid INSERT or UPDATE entry, the
          sqlite3changeset_new() API may be used to obtain the new.* values
          within the change payload.

   If the iterator points to a valid DELETE or UPDATE entry, the
          sqlite3changeset_old() API may be used to obtain the old.* values
          within the change payload.

   An iterator is deleted using a call to the 
          sqlite3changeset_finalize() API. If an error occured while
          iterating, an SQLite error code is returned (even if the same error
          code has already been returned by sqlite3changeset_next()). Or,
          if no error has occurred, SQLITE_OK is returned.


  /*
** Print the contents of the changeset to stdout.
*/
static int print_changeset(void *pChangeset, int nChangeset){
  int rc;
  sqlite3_changeset_iter *pIter = 0;

  /* Create an iterator to iterate through the changeset */
  rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
  if( rc!=SQLITE_OK ) return rc;

  /* This loop runs once for each change in the changeset */
  while( SQLITE_ROW==sqlite3changeset_next(pIter) ){
    const char *zTab;           /* Table change applies to */
    int nCol;                   /* Number of columns in table zTab */
    int op;                     /* SQLITE_INSERT, UPDATE or DELETE */
    sqlite3_value *pVal;

    /* Print the type of operation and the table it is on */
    rc = sqlite3changeset_op(pIter, &zTab, &nCol, &op, 0);
    if( rc!=SQLITE_OK ) goto exit_print_changeset;
    printf("%s on table %s\n",
      op==SQLITE_INSERT?"INSERT" : op==SQLITE_UPDATE?"UPDATE" : "DELETE",
      zTab
    );

    /* If this is an UPDATE or DELETE, print the old.* values */
    if( op==SQLITE_UPDATE || op==SQLITE_DELETE ){
      printf("Old values:");
      for(i=0; i&lt;nCol; i++){
        rc = sqlite3changeset_old(pIter, i, &pVal);
        if( rc!=SQLITE_OK ) goto exit_print_changeset;
        printf(" %s", pVal ? sqlite3_value_text(pVal) : "-");
      }
      printf("\n");
    }

    /* If this is an UPDATE or INSERT, print the new.* values */
    if( op==SQLITE_UPDATE || op==SQLITE_INSERT ){
      printf("New values:");
      for(i=0; i&lt;nCol; i++){
        rc = sqlite3changeset_new(pIter, i, &pVal);
        if( rc!=SQLITE_OK ) goto exit_print_changeset;
        printf(" %s", pVal ? sqlite3_value_text(pVal) : "-");
      }
      printf("\n");
    }
  }

  /* Clean up the changeset and return an error code (or SQLITE_OK) */
 exit_print_changeset:
  rc2 = sqlite3changeset_finalize(pIter);
  if( rc==SQLITE_OK ) rc = rc2;
  return rc;
}


c2: The Session Extension
c3: 4. Extended Functionality
c5: sessionintro.html#extended_functionality
c4:
Most applications will only use the session module functionality described
in the previous section. However, the following additional functionality is
available for the use and manipulation of changeset and patchset blobs:


   Two or more changeset/patchsets may be combined using the 
       sqlite3changeset_concat() or sqlite3_changegroup interfaces.

   A changeset may be "inverted" using the sqlite3changeset_invert()
       API function. An inverted changeset undoes the changes made by the
       original. If changeset C+ is the inverse of changeset C, then
       applying C and then C+ to a database should leave
       the database unchanged.


c2: The SQLITE_STMT Virtual Table
c3: 1. Overview
c5: stmt.html#overview
c4:
The SQLITE_STMT extension implements an eponymous-only virtual table that
provides information about all prepared statements associated with
the database connection.



The SQLITE_STMT extension is included in the amalgamation though 
it is disabled
by default.  Use the SQLITE_ENABLE_STMTVTAB compile-time option to enable
the SQLITE_STMT extension.  The SQLITE_STMT extension can also be 
loaded at run-time
by compiling the extension into a shared library or DLL using the source
code at https://sqlite.org/src/file/ext/misc/stmt.c and following the
instructions for how to compile loadable extensions.



The SQLITE_STMT extension is enabled in default builds
of the command-line shell.


c2: The SQLITE_STMT Virtual Table
c3: 2. Usage
c5: stmt.html#usage
c4:
The SQLITE_STMT virtual table is a read-only table that can be directly
queried to access information about all prepared statements on the 
current database connection.  For example:

SELECT * FROM sqlite_stmt;



A statement such as the above can be run immediately prior to invoking
sqlite3_close() to confirm that all prepared statements have been 
finalized and to help identify and track down prepared
statements that have "leaked" and missed finalization.


The SQLITE_STMT virtual table can also be used to access performance
information about prepared statements, to aid in optimization an application.
For example,
to find out how much memory is being used by prepared statements that have
never been used, one could run:

SELECT sum(mem) FROM sqlite_stmt WHERE run=0;


c2: The SQLITE_STMT Virtual Table
c3: 2.1. Columns
c5: stmt.html#columns
c4:
The columns are provided by the SQLITE_STMT virtual table are summarized by
the hypothetical CREATE TABLE statement show here:

CREATE TABLE sqlite_stmt(
  sql    TEXT,    -- Original SQL text
  ncol   INT,     -- Number of output columns
  ro     BOOLEAN, -- True for "read only" statements
  busy   BOOLEAN, -- True if the statement is current running
  nscan  INT,     -- Number of full-scan steps
  nsort  INT,     -- Number of sort operations
  naidx  INT,     -- Number of automatic index inserts
  nstep  INT,     -- Number of byte-code engine steps
  reprep INT,     -- Number of reprepare operations
  run    INT,     -- Number of times this statement has been run
  mem    INT      -- Heap memory used by this statement
);


Future releases may add new output columns and may change the order
of legacy columns.
Further detail about the meaning of each column in the SQLITE_STMT virtual
table is provided below:


sql:
The original SQL text of the prepared statement.  If the prepared
statement is compiled using the sqlite3_prepare() interface, then
the SQL text might not have been saved, in which case this column
will be NULL.

ncol:
The number of columns in the result set of a query.
For DML statements, this column has a value of 0.

ro:
The "read only" column.  This column is true (non-zero) if the
SQL statement is a query and false (zero) if it is a DML statement.

busy:
This field is true if the prepared statement is currently running.
In other words, this field is true if sqlite3_step() has been called
on the prepared statement at least once but sqlite3_reset() has
not yet been called to reset it.

nscan:
This field is the number of times that the bytecode engine has stepped
through a table as part of a full-table scan.  A large number if this
field may indicate an opportunity to improve performance by adding an
index.  This field is equivalent to the SQLITE_STMTSTATUS_FULLSCAN_STEP
value.

nsort:
This field is the number of times that the bytecode engine had to sort.
A positive value in this field may indicate an opportunity to improve
performance by adding an index that will cause the query results to
appear naturally in the desired order.  
This field is equivalent to the SQLITE_STMTSTATUS_SORT value.

naidx:
This field is the number of rows that have been inserted into
automatic indexes.  A positive value in this field may indicate 
an opportunity to improve performance by adding a named index that
take the place of the automatic index.
This field is equivalent to the SQLITE_STMTSTATUS_AUTOINDEX value.

nstep:
This field is the number of bytecode engine operations that have
been performed for the prepared statement.  This field can be used
as a proxy for how much CPU time a statement has used.
This field is equivalent to the SQLITE_STMTSTATUS_VM_STEP value.

reprep:
This field is the number of times that the statement has had to be
reprepared due to schema changes or changes to parameter bindings.
This field is equivalent to the SQLITE_STMTSTATUS_REPREPARE value.

run:
This field is the number of times that the statement has been run.
This field is equivalent to the SQLITE_STMTSTATUS_RUN value.

mem:
This field is the number of bytes of heap storage used by the
prepared statement.
This field is equivalent to the SQLITE_STMTSTATUS_MEMUSED value.


c2: Pragma statements supported by SQLite
c5: pragma.html#
c4:
PRAGMA Statements



The PRAGMA statement is an SQL extension specific to SQLite and used to 
modify the operation of the SQLite library or to query the SQLite library for 
internal (non-table) data. The PRAGMA statement is issued using the same
interface as other SQLite commands (e.g. SELECT, INSERT) but is
different in the following important respects:


The pragma command is specific to SQLite and is
    not compatible with any other SQL database engine.
Specific pragma statements may be removed and others added in future
    releases of SQLite. There is no guarantee of backwards compatibility.
No error messages are generated if an unknown pragma is issued.
    Unknown pragmas are simply ignored. This means if there is a typo in 
    a pragma statement the library does not inform the user of the fact.
Some pragmas take effect during the SQL compilation stage, not the
    execution stage. This means if using the C-language sqlite3_prepare(), 
    sqlite3_step(), sqlite3_finalize() API (or similar in a wrapper 
    interface), the pragma may run during the sqlite3_prepare() call,
    not during the sqlite3_step() call as normal SQL statements do.
    Or the pragma might run during sqlite3_step() just like normal
    SQL statements.  Whether or not the pragma runs during sqlite3_prepare()
    or sqlite3_step() depends on the pragma and on the specific release
    of SQLite.
The EXPLAIN and EXPLAIN QUERY PLAN prefixes to SQL statements
    only affect the behavior of the statement during sqlite3_step().
    That means that PRAGMA statements that take effect during
    sqlite3_prepare() will behave the same way regardless of whether or
    not they are prefaced by "EXPLAIN".


The C-language API for SQLite provides the SQLITE_FCNTL_PRAGMA
file control which gives VFS implementations the
opportunity to add new PRAGMA statements or to override the meaning of
built-in PRAGMA statements.



PRAGMA command syntax
pragma-stmt:
hide
 
 

pragma-value:
hide
 
 

signed-number:
show
 
 







A pragma can take either zero or one argument.  The argument is may be either
in parentheses or it may be separated from the pragma name by an equal sign.
The two syntaxes yield identical results.
In many pragmas, the argument is a boolean.  The boolean can be one of:



1 yes true on0 no false off


Keyword arguments can optionally appear in quotes.  
(Example:  'yes' &#91;FALSE&#93;.) Some pragmas
takes a string literal as their argument.  When pragma takes a keyword
argument, it will usually also take a numeric equivalent as well.
For example, "0" and "no" mean the same thing, as does "1" and "yes".
When querying the value of a setting, many pragmas return the number
rather than the keyword.

A pragma may have an optional schema-name
before the pragma name.
The schema-name is the name of an ATTACH-ed database 
or "main" or "temp" for the main and the TEMP databases.  If the optional
schema name is omitted, "main" is assumed.  In some pragmas, the schema
name is meaningless and is simply ignored.  In the documentation below,
pragmas for which the schema name is meaningful are shown with a
"schema." prefix.



PRAGMA functions



PRAGMAs that return results and that have no side-effects can be 
accessed from ordinary SELECT statements as table-valued functions.
For each participating PRAGMA, the corresponding table-valued function
has the same name as the PRAGMA with a 7-character "pragma_" prefix.
The PRAGMA argument and schema, if any, are passed as arguments to the
table-valued function, with the schema as an optional, last argument.

For example, information about the columns in an index can be
read using the index_info pragma as follows:


PRAGMA index_info('idx52');


Or, the same content can be read using:


SELECT * FROM pragma_index_info('idx52');


The advantage of the table-valued function format is that the query
can return just a subset of the PRAGMA columns, can include a WHERE clause,
can use aggregate functions, and the table-valued function can be just
one of several data sources in a join.
For example, to get a list of all indexed columns in a schema, one
could query:


SELECT DISTINCT m.name || '.' || ii.name AS 'indexed-columns'
  FROM sqlite_schema AS m,
       pragma_index_list(m.name) AS il,
       pragma_index_info(il.name) AS ii
 WHERE m.type='table'
 ORDER BY 1;



Additional notes:


Table-valued functions exist only for built-in PRAGMAs, not for PRAGMAs
defined using the SQLITE_FCNTL_PRAGMA file control.

Table-valued functions exist only for PRAGMAs that return results and
that have no side-effects.

This feature could be used to implement
information schema
by first creating a separate schema using

ATTACH ':memory:' AS 'information_schema';

Then creating
VIEWs in that schema that implement the official information schema
tables using table-valued PRAGMA functions.

This feature is experimental and is subject to change.  Further documentation
will become available if and when the table-valued functions for PRAGMAs
feature becomes officially supported.

The table-valued functions for PRAGMA feature was added
in SQLite version 3.16.0 (2017-01-02).  Prior versions of SQLite
cannot use this feature.



List Of PRAGMAs


analysis_limit
application_id
auto_vacuum
automatic_index
busy_timeout
cache_size
cache_spill
case_sensitive_like
cell_size_check
checkpoint_fullfsync
collation_list
compile_options
count_changes&sup1;
data_store_directory&sup1;
data_version
database_list
default_cache_size&sup1;
defer_foreign_keys
empty_result_callbacks&sup1;
encoding
foreign_key_check
foreign_key_list
foreign_keys
freelist_count
full_column_names&sup1;
fullfsync
function_list
hard_heap_limit
ignore_check_constraints
incremental_vacuum
index_info
index_list
index_xinfo
integrity_check
journal_mode
journal_size_limit
legacy_alter_table
legacy_file_format
locking_mode
max_page_count
mmap_size
module_list
optimize
page_count
page_size
parser_trace&sup2;
pragma_list
query_only
quick_check
read_uncommitted
recursive_triggers
reverse_unordered_selects
schema_version&sup3;
secure_delete
short_column_names&sup1;
shrink_memory
soft_heap_limit
stats&sup3;
synchronous
table_info
table_list
table_xinfo
temp_store
temp_store_directory&sup1;
threads
trusted_schema
user_version
vdbe_addoptrace&sup2;
vdbe_debug&sup2;
vdbe_listing&sup2;
vdbe_trace&sup2;
wal_autocheckpoint
wal_checkpoint
writable_schema&sup3;



Notes:

Pragmas whose names are struck through
are deprecated. Do not use them. They exist
for historical compatibility.
These pragmas are only available in builds using non-standard
compile-time options.
These pragmas are used for testing SQLite and are not recommended
for use in application programs.


c2: Pragma statements supported by SQLite
c3: PRAGMA analysis_limit
c5: pragma.html#pragma_analysis_limit
c4:
PRAGMA analysis_limit;
        PRAGMA analysis_limit = N;
   Query or change a limit on the approximate ANALYZE setting.
      This is the approximate number of
      rows examined in each index by the ANALYZE command.
      If the argument N is omitted, then the analysis limit
      is unchanged.
      If the limit is zero, then the analysis limit is disabled and
      the ANALYZE command will examine all rows of each index.
      If N is greater than zero, then the analysis limit is set to N
      and subsequent ANALYZE commands will stop analyzing
      each index after it has examined approximately N rows.
      If N is a negative number or something other than an integer value,
      then the pragma behaves as if the N argument was omitted.
      In all cases, the value returned is the new analysis limit used
      for subsequent ANALYZE commands.
   This pragma can be used to help the ANALYZE command run faster
      on large databases.  The results of analysis are not as good
      when only part of each index is examined, but the results are
      usually good enough.  Setting N to 100 or 1000 allows the
      ANALYZE command to run very quickly, even on multi-gigabyte
      database files.  This pragma is particularly useful in combination
      with PRAGMA optimize.
   This pragma was added in SQLite version 3.32.0 (2020-05-22).
      The current implementation only uses the lower 31 bits of the
      N value - higher order bits are silently ignored.  Future versions
      of SQLite might begin using higher order bits.


c2: Pragma statements supported by SQLite
c3: PRAGMA application_id
c5: pragma.html#pragma_application_id
c4:
PRAGMA schema.application_id;
     PRAGMA schema.application_id = integer ;
  
    The application_id PRAGMA is used to query or set the 32-bit
       signed big-endian "Application ID" integer located at offset
       68 into the database header.  Applications that use SQLite as their
       application file-format should set the Application ID integer to
       a unique integer so that utilities such as 
       file(1) can determine the specific
       file type rather than just reporting "SQLite3 Database".  A list of
       assigned application IDs can be seen by consulting the
       magic.txt file in the SQLite source repository.

   See also the user_version pragma.


c2: Pragma statements supported by SQLite
c3: PRAGMA auto_vacuum
c5: pragma.html#pragma_auto_vacuum
c4:
PRAGMA schema.auto_vacuum;
          PRAGMA schema.auto_vacuum = 
           0 | NONE | 1 | FULL | 2 | INCREMENTAL;

    Query or set the auto-vacuum status in the database.

    The default setting for auto-vacuum is 0 or "none",
    unless the SQLITE_DEFAULT_AUTOVACUUM compile-time option is used.
    The "none" setting means that auto-vacuum is disabled.
    When auto-vacuum is disabled and data is deleted data from a database,
    the database file remains the same size.  Unused database file 
    pages are added to a "freelist" and reused for subsequent inserts.  So
    no database file space is lost.  However, the database file does not
    shrink.  In this mode the VACUUM
    command can be used to rebuild the entire database file and
    thus reclaim unused disk space.

    When the auto-vacuum mode is 1  or "full", the freelist pages are
    moved to the end of the database file and the database file is truncated
    to remove the freelist pages at every transaction commit.
    Note, however, that auto-vacuum only truncates the freelist pages
    from the file.  Auto-vacuum does not defragment the database nor
    repack individual database pages the way that the
    VACUUM command does.  In fact, because
    it moves pages around within the file, auto-vacuum can actually
    make fragmentation worse.

    Auto-vacuuming is only possible if the database stores some
    additional information that allows each database page to be
    traced backwards to its referrer.  Therefore, auto-vacuuming must
    be turned on before any tables are created.  It is not possible
    to enable or disable auto-vacuum after a table has been created.

    When the value of auto-vacuum is 2 or "incremental" then the additional
    information needed to do auto-vacuuming is stored in the database file
    but auto-vacuuming does not occur automatically at each commit as it
    does with auto_vacuum=full.  In incremental mode, the separate
    incremental_vacuum pragma must
    be invoked to cause the auto-vacuum to occur.

    The database connection can be changed between full and incremental
    autovacuum mode at any time.  However, changing from
    "none" to "full" or "incremental" can only occur when the database 
    is new (no tables
    have yet been created) or by running the VACUUM command.  To
    change auto-vacuum modes, first use the auto_vacuum pragma to set
    the new desired mode, then invoke the VACUUM command to 
    reorganize the entire database file.  To change from "full" or
    "incremental" back to "none" always requires running VACUUM even
    on an empty database.
    

    When the auto_vacuum pragma is invoked with no arguments, it
    returns the current auto_vacuum mode.


c2: Pragma statements supported by SQLite
c3: PRAGMA automatic_index
c5: pragma.html#pragma_automatic_index
c4:
PRAGMA automatic_index;
     PRAGMA automatic_index = boolean;

    Query, set, or clear the automatic indexing capability.
    Automatic indexing is enabled by default as of 
    version 3.7.17 (2013-05-20),
    but this might change in future releases of SQLite.


c2: Pragma statements supported by SQLite
c3: PRAGMA busy_timeout
c5: pragma.html#pragma_busy_timeout
c4:
PRAGMA busy_timeout;
         PRAGMA busy_timeout = milliseconds;
    Query or change the setting of the
    busy timeout.
    This pragma is an alternative to the sqlite3_busy_timeout() C-language
    interface which is made available as a pragma for use with language
    bindings that do not provide direct access to sqlite3_busy_timeout().

    Each database connection can only have a single
    busy handler.  This PRAGMA sets the busy handler
    for the process, possibly overwriting any previously set busy handler.


c2: Pragma statements supported by SQLite
c3: PRAGMA cache_size
c5: pragma.html#pragma_cache_size
c4:
PRAGMA schema.cache_size;
       PRAGMA schema.cache_size = pages;
       PRAGMA schema.cache_size = -kibibytes;
    Query or change the suggested maximum number of database disk pages
    that SQLite will hold in memory at once per open database file.  Whether
    or not this suggestion is honored is at the discretion of the
    Application Defined Page Cache.
    The default page cache that is built into SQLite honors the request,
    however alternative application-defined page cache implementations
    may choose to interpret the suggested cache size in different ways
    or to ignore it all together.
    The default suggested cache size is -2000, which means the cache size
    is limited to 2048000 bytes of memory.
    The default suggested cache size can be altered using the
    SQLITE_DEFAULT_CACHE_SIZE compile-time options.
    The TEMP database has a default suggested cache size of 0 pages.

    If the argument N is positive then the suggested cache size is set 
    to N. If the argument N is negative, then the
    number of cache pages is adjusted to be a number of pages that would
    use approximately abs(N*1024) bytes of memory based on the current
    page size.  SQLite remembers the number of pages in the page cache,
    not the amount of memory used.  So if you set the cache size using
    a negative number and subsequently change the page size (using the
    PRAGMA page_size command) then the maximum amount of cache
    memory will go up or down in proportion to the change in page size.

    Backwards compatibility note:
    The behavior of cache_size with a negative N
    was different prior to version 3.7.10 (2012-01-16).  In
    earlier versions, the number of pages in the cache was set
    to the absolute value of N.

    When you change the cache size using the cache_size pragma, the
    change only endures for the current session.  The cache size reverts
    to the default value when the database is closed and reopened.

    The default page cache implemention does not allocate
    the full amount of cache memory all at once.  Cache memory
    is allocated in smaller chunks on an as-needed basis.  The page_cache
    setting is a (suggested) upper bound on the amount of memory that the
    cache can use, not the amount of memory it will use all of the time.
    This is the behavior of the default page cache implementation, but an
    application defined page cache is free
    to behave differently if it wants.


c2: Pragma statements supported by SQLite
c3: PRAGMA cache_spill
c5: pragma.html#pragma_cache_spill
c4:
PRAGMA cache_spill;
         PRAGMA cache_spill=boolean;
         PRAGMA schema.cache_spill=N;

    The cache_spill pragma enables or disables the ability of the pager
    to spill dirty cache pages to the database file in the middle of a 
    transaction.  Cache_spill is enabled by default and most applications
    should leave it that way as cache spilling is usually advantageous.
    However, a cache spill has the side-effect of acquiring an
    EXCLUSIVE lock on the database file.  Hence, some applications that
    have large long-running transactions may want to disable cache spilling
    in order to prevent the application from acquiring an exclusive lock
    on the database until the moment that the transaction COMMITs.
    The "PRAGMA cache_spill=N" form of this pragma sets a minimum
    cache size threshold required for spilling to occur. The number of pages
    in cache must exceed both the cache_spill threshold and the maximum cache
    size set by the PRAGMA cache_size statement in order for spilling to
    occur.
    The "PRAGMA cache_spill=boolean" form of this pragma applies
    across all databases attached to the database connection.  But the
    "PRAGMA cache_spill=N" form of this statement only applies to
    the "main" schema or whatever other schema is specified as part of the
    statement.


c2: Pragma statements supported by SQLite
c3: PRAGMA case_sensitive_like
c5: pragma.html#pragma_case_sensitive_like
c4:
PRAGMA case_sensitive_like = boolean;
    The default behavior of the LIKE operator is to ignore case
    for ASCII characters. Hence, by default 'a' LIKE 'A' is
    true.  The case_sensitive_like pragma installs a new application-defined
    LIKE function that is either case sensitive or insensitive depending
    on the value of the case_sensitive_like pragma.
    When case_sensitive_like is disabled, the default LIKE behavior is
    expressed.  When case_sensitive_like is enabled, case becomes
    significant.  So, for example,
    'a' LIKE 'A' is false but 'a' LIKE 'a' is still true.

    This pragma uses sqlite3_create_function() to overload the
    LIKE and GLOB functions, which may override previous implementations
    of LIKE and GLOB registered by the application.  This pragma
    only changes the behavior of the SQL LIKE operator.  It does not
    change the behavior of the sqlite3_strlike() C-language interface,
    which is always case insensitive.


c2: Pragma statements supported by SQLite
c3: PRAGMA cell_size_check
c5: pragma.html#pragma_cell_size_check
c4:
PRAGMA cell_size_check
       PRAGMA cell_size_check = boolean;
    The cell_size_check pragma enables or disables additional sanity
    checking on database b-tree pages as they are initially read from disk.
    With cell size checking enabled, database corruption is detected earlier
    and is less likely to "spread".  However, there is a small performance
    hit for doing the extra checks and so cell size checking is turned off
    by default.


c2: Pragma statements supported by SQLite
c3: PRAGMA checkpoint_fullfsync
c5: pragma.html#pragma_checkpoint_fullfsync
c4:
PRAGMA checkpoint_fullfsync
       PRAGMA checkpoint_fullfsync = boolean;
    Query or change the fullfsync flag for checkpoint operations.
    If this flag is set, then the F_FULLFSYNC syncing method is used
    during checkpoint operations on systems that support F_FULLFSYNC. 
    The default value of the checkpoint_fullfsync flag
    is off.  Only Mac OS-X supports F_FULLFSYNC.

    If the fullfsync flag is set, then the F_FULLFSYNC syncing
    method is used for all sync operations and the checkpoint_fullfsync
    setting is irrelevant.


c2: Pragma statements supported by SQLite
c3: PRAGMA collation_list
c5: pragma.html#pragma_collation_list
c4:
PRAGMA collation_list;
    Return a list of the collating sequences defined for the current
    database connection.


c2: Pragma statements supported by SQLite
c3: PRAGMA compile_options
c5: pragma.html#pragma_compile_options
c4:
PRAGMA compile_options;
    This pragma returns the names of compile-time options used when
    building SQLite, one option per row.  The "SQLITE_" prefix is omitted
    from the returned option names.  See also the
    sqlite3_compileoption_get() C/C++ interface and the
    sqlite_compileoption_get() SQL functions.


c2: Pragma statements supported by SQLite
c3: PRAGMA count_changes
c5: pragma.html#pragma_count_changes
c4:
PRAGMA count_changes;
       PRAGMA count_changes = boolean;

    Query or change the count-changes flag. Normally, when the
    count-changes flag is not set, INSERT, UPDATE and DELETE statements
    return no data. When count-changes is set, each of these commands 
    returns a single row of data consisting of one integer value - the
    number of rows inserted, modified or deleted by the command. The 
    returned change count does not include any insertions, modifications
    or deletions performed by triggers, any changes made automatically
    by foreign key actions, or updates caused by an upsert.

    Another way to get the row change counts is to use the
    sqlite3_changes() or sqlite3_total_changes() interfaces.
    There is a subtle different, though.  When an INSERT, UPDATE, or
    DELETE is run against a view using an INSTEAD OF trigger,
    the count_changes pragma reports the number of rows in the view
    that fired the trigger, whereas sqlite3_changes() and
    sqlite3_total_changes() do not.

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA data_store_directory
c5: pragma.html#pragma_data_store_directory
c4:
PRAGMA data_store_directory;
      PRAGMA data_store_directory = 'directory-name';
    Query or change the value of the sqlite3_data_directory global
    variable, which windows operating-system interface backends use to
    determine where to store database files specified using a relative
    pathname.

    Changing the data_store_directory setting is not threadsafe.
    Never change the data_store_directory setting if another thread
    within the application is running any SQLite interface at the same time.
    Doing so results in undefined behavior.  Changing the data_store_directory
    setting writes to the sqlite3_data_directory global
    variable and that global variable is not protected by a mutex.

    This facility is provided for WinRT which does not have an OS
    mechanism for reading or changing the current working directory.
    The use of this pragma in any other context is discouraged and may
    be disallowed in future releases.

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA data_version
c5: pragma.html#pragma_data_version
c4:
PRAGMA schema.data_version;
    The "PRAGMA data_version" command provides an indication that the
    database file has been modified.
    Interactive programs that hold database content in memory or that
    display database content on-screen can use the PRAGMA data_version
    command to determine if they need to flush and reload their memory
    or update the screen display.

    The integer values returned by two
    invocations of "PRAGMA data_version" from the same connection
    will be different if changes were committed to the database 
    by any other connection in the interim.
    The "PRAGMA data_version" value is unchanged for commits made
    on the same database connection.
    The behavior of "PRAGMA data_version" is the same for all database
    connections, including database connections in separate processes
    and shared cache database connections.

    The "PRAGMA data_version" value is a local property of each
    database connection and so values returned by two concurrent invocations
    of "PRAGMA data_version" on separate database connections are 
    often different even though the underlying database is identical.
    It is only meaningful to compare the "PRAGMA data_version" values
    returned by the same database connection at two different points in
    time.


c2: Pragma statements supported by SQLite
c3: PRAGMA database_list
c5: pragma.html#pragma_database_list
c4:
PRAGMA database_list;
    This pragma works like a query to return one row for each database
    attached to the current database connection.
    The second column is "main" for the main database file, "temp"
    for the database file used to store TEMP objects, or the name of the
    ATTACHed database for other database files.
    The third column is the name of the database file itself, or an empty
    string if the database is not associated with a file.


c2: Pragma statements supported by SQLite
c3: PRAGMA default_cache_size
c5: pragma.html#pragma_default_cache_size
c4:
PRAGMA schema.default_cache_size;
       PRAGMA schema.default_cache_size
            = Number-of-pages;

    This pragma queries or sets the suggested maximum number of pages
    of disk cache that will be allocated per open database file.
    The difference between this pragma and cache_size is that the
    value set here persists across database connections.
    The value of the default cache size is stored in the 4-byte
    big-endian integer located at offset 48 in the header of the
    database file.
    

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA defer_foreign_keys
c5: pragma.html#pragma_defer_foreign_keys
c4:
PRAGMA defer_foreign_keys
       PRAGMA defer_foreign_keys = boolean;
    When the defer_foreign_keys PRAGMA is on,
    enforcement of all foreign key constraints is delayed until the
    outermost transaction is committed.  The defer_foreign_keys pragma
    defaults to OFF so that foreign key constraints are only deferred if
    they are created as "DEFERRABLE INITIALLY DEFERRED".  The 
    defer_foreign_keys pragma is automatically switched off at each
    COMMIT or ROLLBACK.  Hence, the defer_foreign_keys pragma must be
    separately enabled for each transaction.  This pragma is
    only meaningful if foreign key constraints are enabled, of course.

    The sqlite3_db_status(db,SQLITE_DBSTATUS_DEFERRED_FKS,...)
    C-language interface can be used during a transaction to determine 
    if there are deferred and unresolved foreign key constraints.


c2: Pragma statements supported by SQLite
c3: PRAGMA empty_result_callbacks
c5: pragma.html#pragma_empty_result_callbacks
c4:
PRAGMA empty_result_callbacks;
       PRAGMA empty_result_callbacks = boolean;

    Query or change the empty-result-callbacks flag.

    The empty-result-callbacks flag affects the sqlite3_exec() API only.
    Normally, when the empty-result-callbacks flag is cleared, the
    callback function supplied to the sqlite3_exec() is not invoked
    for commands that return zero rows of data.  When empty-result-callbacks
    is set in this situation, the callback function is invoked exactly once,
    with the third parameter set to 0 (NULL). This is to enable programs  
    that use the sqlite3_exec() API to retrieve column-names even when
    a query returns no data.

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA encoding
c5: pragma.html#pragma_encoding
c4:
PRAGMA encoding;
       PRAGMA encoding = 'UTF-8';
       PRAGMA encoding = 'UTF-16';
       PRAGMA encoding = 'UTF-16le';
       PRAGMA encoding = 'UTF-16be';
    In first form, if the main database has already been
    created, then this pragma returns the text encoding used by the
    main database, one of 'UTF-8', 'UTF-16le' (little-endian UTF-16
    encoding) or 'UTF-16be' (big-endian UTF-16 encoding).  If the main
    database has not already been created, then the value returned is the
    text encoding that will be used to create the main database, if 
    it is created by this session.

    The second through fifth forms of this pragma
    set the encoding that the main database will be created with if
    it is created by this session. The string 'UTF-16' is interpreted
    as "UTF-16 encoding using native machine byte-ordering".  It is not
    possible to change the text encoding of a database after it has been
    created and any attempt to do so will be silently ignored.

    If no encoding is first set with this pragma,
    then the encoding with which the main database will be created
    defaults to one determined by the
    API used to open the connection.

    Once an encoding has been set for a database, it cannot be changed.

    Databases created by the ATTACH command always use the same encoding
    as the main database.  An attempt to ATTACH a database with a different
    text encoding from the "main" database will fail.


c2: Pragma statements supported by SQLite
c3: PRAGMA foreign_key_check
c5: pragma.html#pragma_foreign_key_check
c4:
PRAGMA schema.foreign_key_check;
        PRAGMA schema.foreign_key_check(table-name);

    The foreign_key_check pragma checks the database, or the table
    called "table-name", for 
    foreign key constraints that are violated.  The foreign_key_check
    pragma returns one row output for each foreign key violation.
    There are four columns in each result row.
    The first column is the name of the table that contains the REFERENCES
    clause.  The second column is the rowid of the row that
    contains the invalid REFERENCES clause, or NULL if the child table is a
    WITHOUT ROWID table.  The third column is the name
    of the table that is referred to. The fourth column is the index of
    the specific foreign key constraint that failed.  The fourth column
    in the output of the foreign_key_check pragma is the same integer as
    the first column in the output of the foreign_key_list pragma.
    When a "table-name" is specified, the only foreign key constraints
    checked are those created by REFERENCES clauses in the
    CREATE TABLE statement for table-name.


c2: Pragma statements supported by SQLite
c3: PRAGMA foreign_key_list
c5: pragma.html#pragma_foreign_key_list
c4:
PRAGMA foreign_key_list(table-name);

    This pragma returns one row for each foreign key constraint
    created by a REFERENCES clause in the CREATE TABLE statement of
    table "table-name".


c2: Pragma statements supported by SQLite
c3: PRAGMA foreign_keys
c5: pragma.html#pragma_foreign_keys
c4:
PRAGMA foreign_keys;
       PRAGMA foreign_keys = boolean;
    Query, set, or clear the enforcement of foreign key constraints.

    This pragma is a no-op within a transaction; foreign key constraint
       enforcement may only be enabled or disabled when there is no pending
       BEGIN or SAVEPOINT.

    Changing the foreign_keys setting affects the execution of
       all statements prepared
       using the database connection, including those prepared before the
       setting was changed. Any existing statements prepared using the legacy 
       sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error
       after the foreign_keys setting is changed.

    As of SQLite version 3.6.19, the default setting for foreign
       key enforcement is OFF.  However, that might change in a future
       release of SQLite.  The default setting for foreign key enforcement
       can be specified at compile-time using the SQLITE_DEFAULT_FOREIGN_KEYS
       preprocessor macro.  To minimize future problems, applications should
       set the foreign key enforcement flag as required by the application
       and not depend on the default setting.


c2: Pragma statements supported by SQLite
c3: PRAGMA full_column_names
c5: pragma.html#pragma_full_column_names
c4:
PRAGMA full_column_names;
       PRAGMA full_column_names = boolean;

    Query or change the full_column_names flag. This flag together 
    with the short_column_names flag determine
    the way SQLite assigns names to result columns of SELECT statements.
    Result columns are named by applying the following rules in order:
    
    If there is an AS clause on the result, then the name of
        the column is the right-hand side of the AS clause.
    If the result is a general expression, not a just the name of
        a source table column,
        then the name of the result is a copy of the expression text.
    If the short_column_names pragma is ON, then the name of the
        result is the name of the source table column without the 
        source table name prefix:  COLUMN.
    If both pragmas short_column_names and full_column_names
        are OFF then case (2) applies.
        
    The name of the result column is a combination of the source table
        and source column name:  TABLE.COLUMN
    

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA fullfsync
c5: pragma.html#pragma_fullfsync
c4:
PRAGMA fullfsync
       PRAGMA fullfsync = boolean;
    Query or change the fullfsync flag. This flag
    determines whether or not the F_FULLFSYNC syncing method is used
    on systems that support it.  The default value of the fullfsync flag
    is off.  Only Mac OS X supports F_FULLFSYNC.

    See also checkpoint_fullfsync.


c2: Pragma statements supported by SQLite
c3: PRAGMA function_list
c5: pragma.html#pragma_function_list
c4:
PRAGMA function_list;
    This pragma returns a list of SQL functions
    known to the database connection.  Each row of the result
    describes a single calling signature for a single SQL function.
    Some SQL functions will have multiple rows in the result set
    if they can (for example) be invoked with a varying number of
    arguments or can accept text in various encodings.


c2: Pragma statements supported by SQLite
c3: PRAGMA hard_heap_limit
c5: pragma.html#pragma_hard_heap_limit
c4:
PRAGMA hard_heap_limit
          PRAGMA hard_heap_limit=N

    This pragma invokes the sqlite3_hard_heap_limit64() interface with
    the argument N, if N is specified and N is a positive integer that
    is less than the current hard heap limit.
    The hard_heap_limit pragma always returns the same integer
    that would be returned by the sqlite3_hard_heap_limit64(-1) C-language
    function.  That is to say, it always returns the value of the hard
    heap limit that is set after any changes imposed by this PRAGMA.
    

    This pragma can only lower the heap limit, never raise it.
    The C-language interface sqlite3_hard_heap_limit64() must be used
    to raise the heap limit.

    See also the soft_heap_limit pragma.


c2: Pragma statements supported by SQLite
c3: PRAGMA ignore_check_constraints
c5: pragma.html#pragma_ignore_check_constraints
c4:
PRAGMA ignore_check_constraints  = boolean;

    This pragma enables or disables the enforcement of CHECK constraints.
    The default setting is off, meaning that CHECK constraints are
    enforced by default.


c2: Pragma statements supported by SQLite
c3: PRAGMA incremental_vacuum
c5: pragma.html#pragma_incremental_vacuum
c4:
PRAGMA schema.incremental_vacuum(N);
      PRAGMA schema.incremental_vacuum;
    The incremental_vacuum pragma causes up to N pages to
    be removed from the freelist.  The database file is truncated by
    the same amount.  The incremental_vacuum pragma has no effect if
    the database is not in
    auto_vacuum=incremental mode
    or if there are no pages on the freelist.  If there are fewer than
    N pages on the freelist, or if N is less than 1, or
    if the "(N)" argument is omitted, then the entire
    freelist is cleared.


c2: Pragma statements supported by SQLite
c3: PRAGMA index_info
c5: pragma.html#pragma_index_info
c4:
PRAGMA schema.index_info(index-name);
    This pragma returns one row for each key column in the named index.
    A key column is a column that is actually named in the CREATE INDEX
    index statement or UNIQUE constraint or PRIMARY KEY constraint that
    created the index.  Index entries also usually contain auxiliary
    columns that point back to the table row being indexed.  The auxiliary
    index-columns are not shown by the index_info pragma, but they are
    listed by the index_xinfo pragma.

    Output columns from the index_info pragma are as follows:
    
    The rank of the column within the index.  (0 means left-most.)
    The rank of the column within the table being indexed.
        A value of -1 means rowid and a value of -2 means that an
        expression is being used.
    The name of the column being indexed.  This columns is NULL
        if the column is the rowid or an expression.
    

    If there is no index named index-name but there is a
    WITHOUT ROWID table with that name, then (as of
    SQLite version 3.30.0 on 2019-10-04) this pragma returns the
    PRIMARY KEY columns of the WITHOUT ROWID table as they are used
    in the records of the underlying b-tree, which is to say with
    duplicate columns removed.


c2: Pragma statements supported by SQLite
c3: PRAGMA index_list
c5: pragma.html#pragma_index_list
c4:
PRAGMA schema.index_list(table-name);
    This pragma returns one row for each index associated with the
    given table.
    Output columns from the index_list pragma are as follows:
    
    A sequence number assigned to each index for internal tracking
          purposes.
    The name of the index.
    "1" if the index is UNIQUE and "0" if not.
    "c" if the index was created by a CREATE INDEX statement,
          "u" if the index was created by a UNIQUE constraint, or
          "pk" if the index was created by a PRIMARY KEY constraint.
    "1" if the index is a partial index and "0" if not.


c2: Pragma statements supported by SQLite
c3: PRAGMA index_xinfo
c5: pragma.html#pragma_index_xinfo
c4:
PRAGMA schema.index_xinfo(index-name);
    This pragma returns information about every column in an index.
    Unlike this index_info pragma, this pragma returns information about
    every column in the index, not just the key columns.
    (A key column is a column that is actually named in the CREATE INDEX
    index statement or UNIQUE constraint or PRIMARY KEY constraint that
    created the index.  Auxiliary columns are additional columns needed to
    locate the table entry that corresponds to each index entry.)

    Output columns from the index_xinfo pragma are as follows:
    
    The rank of the column within the index. (0 means left-most.
         Key columns come before auxiliary columns.)
    The rank of the column within the table being indexed, or -1 if
         the index-column is the rowid of the table being indexed and -2
         if the index is on an expression.
    The name of the column being indexed, or NULL if the index-column
         is the rowid of the table being indexed or an
         expression.
    1 if the index-column is sorted in reverse (DESC) order by the
         index and 0 otherwise.
    The name for the collating sequence
         used to compare values in the index-column.
    1 if the index-column is a key column and 0 if the index-column
         is an auxiliary column.
    

    If there is no index named index-name but there is a
    WITHOUT ROWID table with that name, then (as of
    SQLite version 3.30.0 on 2019-10-04) this pragma returns the
    columns of the WITHOUT ROWID table as they are used
    in the records of the underlying b-tree, which is to say with
    de-duplicated PRIMARY KEY columns first followed by data columns.


c2: Pragma statements supported by SQLite
c3: PRAGMA integrity_check
c5: pragma.html#pragma_integrity_check
c4:
PRAGMA schema.integrity_check;
      PRAGMA schema.integrity_check(N)
      PRAGMA schema.integrity_check(TABLENAME)
    This pragma does a low-level formatting and consistency check
    of the database.  The integrity_check pragma look for:
    
     Table or index entries that are out of sequence
     Misformatted records
     Missing pages
     Missing or surplus index entries
     UNIQUE, CHECK, and NOT NULL constraint errors
     Integrity of the freelist
     Sections of the database that are used more than once, or not at all
    
    If the integrity_check pragma finds problems, strings are returned
    (as multiple rows with a single column per row) which describe
    the problems.  Pragma integrity_check will return at most N
    errors before the analysis quits, with N defaulting
    to 100.  If pragma integrity_check finds no errors, a
    single row with the value 'ok' is returned.

    The usual case is that the entire database file is checked.  However,
    if the argument is TABLENAME, then checking is only performed for the
    the table named and its associated indexes.
    This is called a "partial integrity check".  Because only a subset of the
    database is checked, errors such as unused sections of the file or duplication
    use of the same section of the file by two or more tables cannot be detected.
    The freelist is only verified on a
    partial integrity check if TABLENAME is sqlite_schema or one of its
    aliases.  Support for partial integrity checks was added with
    version 3.33.0 (2020-08-14).

    PRAGMA integrity_check does not find
    FOREIGN KEY errors.  
    Use the PRAGMA foreign_key_check command to find errors in
    FOREIGN KEY constraints.

    See also the PRAGMA quick_check command which does most of the
    checking of PRAGMA integrity_check but runs much faster.


c2: Pragma statements supported by SQLite
c3: PRAGMA journal_mode
c5: pragma.html#pragma_journal_mode
c4:
PRAGMA schema.journal_mode;
        PRAGMA schema.journal_mode
              = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF

    This pragma queries or sets the journal mode for databases
    associated with the current database connection.

    The first form of this pragma queries the current journaling
    mode for database.  When database is omitted, the
    "main" database is queried.

    The second form changes the journaling mode for "database"
    or for all attached databases if "database" is omitted.
    The new journal mode is returned.  If the journal mode
    could not be changed, the original journal mode is returned.

    The DELETE journaling mode is the normal behavior.  In the DELETE
    mode, the rollback journal is deleted at the conclusion of each
    transaction.  Indeed, the delete operation is the action that causes
    the transaction to commit.
    (See the document titled 
    Atomic Commit In SQLite for additional detail.)

    The TRUNCATE journaling mode commits transactions by truncating
    the rollback journal to zero-length instead of deleting it.  On many
    systems, truncating a file is much faster than deleting the file since
    the containing directory does not need to be changed.

    The PERSIST journaling mode prevents the rollback journal from
    being deleted at the end of each transaction.  Instead, the header
    of the journal is overwritten with zeros.  This will prevent other
    database connections from rolling the journal back.  The PERSIST
    journaling mode is useful as an optimization on platforms where
    deleting or truncating a file is much more expensive than overwriting
    the first block of a file with zeros.  See also:
    PRAGMA journal_size_limit and SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT.

    The MEMORY journaling mode stores the rollback journal in 
    volatile RAM.  This saves disk I/O but at the expense of database
    safety and integrity.  If the application using SQLite crashes in
    the middle of a transaction when the MEMORY journaling mode is set,
    then the database file will very likely 
    go corrupt.

    The WAL journaling mode uses a write-ahead log instead of a
    rollback journal to implement transactions.  The WAL journaling mode
    is persistent; after being set it stays in effect
    across multiple database connections and after closing and
    reopening the database.  A database in WAL journaling mode
    can only be accessed by SQLite version 3.7.0 (2010-07-21)
    or later.

    The OFF journaling mode disables the rollback journal completely.
    No rollback journal is ever created and hence there is never a rollback
    journal to delete.  The OFF journaling mode disables the atomic
    commit and rollback capabilities of SQLite. The ROLLBACK command
    no longer works; it behaves in an undefined way.  Applications must
    avoid using the ROLLBACK command when the journal mode is OFF.
    If the application crashes
    in the middle of a transaction when the OFF journaling mode is
    set, then the database file will very likely
    go corrupt. Without a journal, there is no way for
    a statement to unwind partially completed operations following
    a constraint error.  This might also leave the database in a corrupted
    state.  For example, if a duplicate entry causes a 
    CREATE UNIQUE INDEX statement to fail half-way through,
    it will leave behind a partially created, and hence corrupt, index.
    Because OFF journaling
    mode allows the database file to be corrupted using ordinary SQL,
    it is disabled when SQLITE_DBCONFIG_DEFENSIVE is enabled.

    Note that the journal_mode for an in-memory database
    is either MEMORY or OFF and can not be changed to a different value.
    An attempt to change the journal_mode of an in-memory database to
    any setting other than MEMORY or OFF is ignored.  Note also that
    the journal_mode cannot be changed while a transaction is active.


c2: Pragma statements supported by SQLite
c3: PRAGMA journal_size_limit
c5: pragma.html#pragma_journal_size_limit
c4:
PRAGMA schema.journal_size_limit
    PRAGMA schema.journal_size_limit = N ;

  If a database connection is operating in
  exclusive locking mode or in
  persistent journal mode 
  (PRAGMA journal_mode=persist) then
  after committing a transaction the rollback journal file may remain in
  the file-system. This increases performance for subsequent transactions
  since overwriting an existing file is faster than append to a file,
  but it also consumes
  file-system space. After a large transaction (e.g. a VACUUM),
  the rollback journal file may consume a very large amount of space.

  Similarly, in WAL mode, the write-ahead log file is not truncated
  following a checkpoint.  Instead, SQLite reuses the existing file
  for subsequent WAL entries since overwriting is faster than appending.

  The journal_size_limit pragma may be used to limit the size of 
  rollback-journal and WAL files left
  in the file-system after transactions or checkpoints.
  Each time a transaction is committed or a WAL file resets, SQLite 
  compares the size of the rollback journal file or WAL file left in 
  the file-system to the size limit
  set by this pragma and if the journal or WAL file is larger 
  it is truncated to the limit.

  The second form of the pragma listed above is used to set a new limit
  in bytes for the specified database.  A negative number implies no limit.
  To always truncate rollback journals and WAL files to their minimum size, 
  set the journal_size_limit to zero.
  Both the first and second forms of the pragma listed above return a single
  result row containing a single integer column - the value of the journal
  size limit in bytes. The default journal size limit is -1 (no limit).  The
  SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT preprocessor macro can be used to change
  the default journal size limit at compile-time.

  This pragma only operates on the single database specified prior
  to the pragma name (or on the "main" database if no database is specified.)
  There is no way to change the journal size limit on all attached databases
  using a single PRAGMA statement.  The size limit must be set separately for
  each attached database.


c2: Pragma statements supported by SQLite
c3: PRAGMA legacy_alter_table
c5: pragma.html#pragma_legacy_alter_table
c4:
PRAGMA legacy_alter_table;
       PRAGMA legacy_alter_table = boolean
    This pragma sets or queries the value of the legacy_alter_table
    flag.  When this flag is on, the ALTER TABLE RENAME
    command (for changing the name of a table) works as it did
    in SQLite 3.24.0 (2018-06-04) and earlier.  More specifically,
    when this flag is on
    the ALTER TABLE RENAME command only rewrites the initial occurrence
    of the table name in its CREATE TABLE statement and in any associated
    CREATE INDEX and CREATE TRIGGER statements.  Other references to the
    table are unmodified, including:
    
     References to the table within the bodies of triggers and views.
     References to the table within CHECK constraints in the original
         CREATE TABLE statement.
     References to the table within the WHERE clauses of partial indexes.
    
    The default setting for this pragma is OFF, which means that all
    references to the table anywhere in the schema are converted to the new name.
    This pragma is provided as a work-around for older programs that
    contain code that expect the incomplete behavior
    of ALTER TABLE RENAME found in older versions of SQLite.
    New applications should leave this flag turned off.
    For compatibility with older virtual table implementations,
    this flag is turned on temporarily while the sqlite3_module.xRename
    method is being run.  The value of this flag is restored after the 
    sqlite3_module.xRename method finishes.
    The legacy alter table behavior can also be toggled on and off
    using the SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option to the
    sqlite3_db_config() interface.
    The legacy alter table behavior is a per-connection setting.  Turning
    this features on or off affects all attached database files within the
    database connection.
    The setting does not persist.  Changing this setting in one connection
    does not affect any other connections.


c2: Pragma statements supported by SQLite
c3: PRAGMA legacy_file_format
c5: pragma.html#pragma_legacy_file_format
c4:
PRAGMA legacy_file_format;
    This pragma no longer functions.  It has become a no-op.
    The capabilities formerly provided by PRAGMA legacy_file_format
    are now available using the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
    option to the sqlite3_db_config() C-language interface.


c2: Pragma statements supported by SQLite
c3: PRAGMA locking_mode
c5: pragma.html#pragma_locking_mode
c4:
PRAGMA schema.locking_mode;
    PRAGMA schema.locking_mode
                = NORMAL | EXCLUSIVE
    This pragma sets or queries the database connection locking-mode. 
    The locking-mode is either NORMAL or EXCLUSIVE.

    In NORMAL locking-mode (the default unless overridden at compile-time
    using SQLITE_DEFAULT_LOCKING_MODE), a database connection
    unlocks the database file at the conclusion of each read or
    write transaction. When the locking-mode is set to EXCLUSIVE, the
    database connection never releases file-locks. The first time the
    database is read in EXCLUSIVE mode, a shared lock is obtained and 
    held. The first time the database is written, an exclusive lock is
    obtained and held.

    Database locks obtained by a connection in EXCLUSIVE mode may be
    released either by closing the database connection, or by setting the
    locking-mode back to NORMAL using this pragma and then accessing the
    database file (for read or write). Simply setting the locking-mode to
    NORMAL is not enough - locks are not released until the next time
    the database file is accessed.

    There are three reasons to set the locking-mode to EXCLUSIVE.
    
    The application wants to prevent other processes from
        accessing the database file.
    The number of system calls for filesystem operations is reduced,
        possibly resulting in a small performance increase.
    WAL databases can be accessed in EXCLUSIVE mode without the
        use of shared memory. 
        (Additional information)
    
    

    When the locking_mode pragma specifies a particular database,
    for example:

    
PRAGMA main.locking_mode=EXCLUSIVE;
    

    then the locking mode applies only to the named database.  If no
    database name qualifier precedes the "locking_mode" keyword then
    the locking mode is applied to all databases, including any new
    databases added by subsequent ATTACH commands.

   The "temp" database (in which TEMP tables and indices are stored)
   and in-memory databases
   always uses exclusive locking mode.  The locking mode of temp and
   in-memory databases cannot
   be changed.  All other databases use the normal locking mode by default
   and are affected by this pragma.

   If the locking mode is EXCLUSIVE when first entering
   WAL journal mode, then the locking mode cannot be changed to
   NORMAL until after exiting WAL journal mode. 
   If the locking mode is NORMAL when first entering WAL
   journal mode, then the locking mode can be changed between NORMAL and
   EXCLUSIVE and back again at any time and without needing to exit
   WAL journal mode.


c2: Pragma statements supported by SQLite
c3: PRAGMA max_page_count
c5: pragma.html#pragma_max_page_count
c4:
PRAGMA schema.max_page_count;
        PRAGMA schema.max_page_count = N;
    Query or set the maximum number of pages in the database file.
    Both forms of the pragma return the maximum page count.  The second
    form attempts to modify the maximum page count.  The maximum page
    count cannot be reduced below the current database size.


c2: Pragma statements supported by SQLite
c3: PRAGMA mmap_size
c5: pragma.html#pragma_mmap_size
c4:
PRAGMA schema.mmap_size;
         PRAGMA schema.mmap_size=N

    Query or change the maximum number of bytes that are set
       aside for memory-mapped I/O on a single database.  The first form
       (without an argument) queries the current limit.  The second
       form (with a numeric argument) sets the limit for the specified
       database, or for all databases if the optional database name is
       omitted.  In the second form, if the database name is omitted, the
       limit that is set becomes the default limit for all databases that
       are added to the database connection by subsequent ATTACH
       statements.

    The argument N is the maximum number of bytes of the database file
       that will be accessed using memory-mapped I/O.  If N is zero then
       memory mapped I/O is disabled.  If N is negative, then the limit
       reverts to the default value determined by the most recent
       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE), or to the compile
       time default determined by SQLITE_DEFAULT_MMAP_SIZE if not
       start-time limit has been set.

    The PRAGMA mmap_size statement will never increase the amount
       of address space used for memory-mapped I/O above the
       hard limit set by the SQLITE_MAX_MMAP_SIZE compile-time option,
       nor the hard limit set at startup-time by the second argument to
       sqlite3_config(SQLITE_CONFIG_MMAP_SIZE)

    The size of the memory-mapped I/O region cannot be changed while
       the memory-mapped I/O region is in active use, to avoid unmapping
       memory out from under running SQL statements.  For this reason,
       the mmap_size pragma may be a no-op if the prior mmap_size is non-zero
       and there are other SQL statements running concurrently on the same
       database connection.


c2: Pragma statements supported by SQLite
c3: PRAGMA module_list
c5: pragma.html#pragma_module_list
c4:
PRAGMA module_list;
    This pragma returns a list of 
    virtual table modules registered with the database connection.


c2: Pragma statements supported by SQLite
c3: PRAGMA optimize
c5: pragma.html#pragma_optimize
c4:
PRAGMA optimize;
       PRAGMA optimize(MASK);
       PRAGMA schema.optimize;
       PRAGMA schema.optimize(MASK);
  Attempt to optimize the database.  All schemas are optimized in the 
  first two forms, and only the specified schema is optimized in the latter
  two.
  To achieve the best long-term query performance without the need to
  do a detailed engineering analysis of the application schema and SQL,
  it is recommended that applications run "PRAGMA optimize" (with no arguments)
  just before closing each database connection.  Long-running applications
  might also benefit from setting a timer to run "PRAGMA optimize" every
  few hours.
  
  This pragma is usually a no-op or nearly so and is very fast.
  However if SQLite feels
  that performing database optimizations (such as running ANALYZE
  or creating new indexes) will improve the performance of future queries, then
  some database I/O may be done.  Applications that want to limit the amount
  of work performed can set a timer that will invoke
  sqlite3_interrupt() if the pragma goes on for too long.
  Or, since SQLite 3.32.0, the application can use 
  PRAGMA analysis_limit=N for some small
  value of N (a few hundred or a few thousand) to limit the depth
  of analyze.
  
  The details of optimizations performed by this pragma are expected
  to change and improve over time.  Applications should anticipate that
  this pragma will perform new optimizations in future releases.

  The optional MASK argument is a bitmask of optimizations to perform:
  
  
         Debugging mode.  Do not actually perform any optimizations
         but instead return one line of text for each optimization
         that would have been done.  Off by default.
  
         Run ANALYZE on tables that might benefit.  On by default.
         See below for additional information.
  
         (Not yet implemented)
         Record usage and performance 
         information from the current session in the
         database file so that it will be available to "optimize"
         pragmas run by future database connections.
  
         (Not yet implemented)
         Create indexes that might have been helpful to recent queries.
  
  The default MASK is and always shall be 0xfffe.  The 0xfffe mask means
  perform all of the optimizations listed above except Debug Mode.  If new
  optimizations are added in the future that should be off by default, those
  new optimizations will be given a mask of 0x10000 or larger.

  To see all optimizations that would have been done without actually
  doing them, run "PRAGMA optimize(-1)".  To use only the ANALYZE
  optimization, run "PRAGMA optimize(0x02)".
  
  Determination Of When To Run Analyze
   In the current implementation, a table is analyzed if and only if 
      all of the following are true:
  
  
    MASK bit 0x02 is set.
  
    The query planner used sqlite_stat1-style statistics for one or
    more indexes of the table at some point during the lifetime of
    the current connection.
  
    One or more indexes of the table are currently unanalyzed or
    the number of rows in the table has increased by 25 times or more
    since the last time ANALYZE was run.
  
   The rules for when tables are analyzed are likely to change in
      future releases.


c2: Pragma statements supported by SQLite
c3: PRAGMA page_size
c5: pragma.html#pragma_page_size
c4:
PRAGMA schema.page_size;
       PRAGMA schema.page_size = bytes;
    Query or set the page size of the database. The page
    size must be a power of two between 512 and 65536 inclusive.
    

    When a new database is created, SQLite assigns a page size to
    the database based on platform and filesystem.  For many years,
    the default page size was almost always 1024 bytes, but beginning
    with SQLite version 3.12.0 (2016-03-29), 
    the default page size increased to 4096.
    The default page size is recommended for most applications.

    Specifying a new page size does not change the page size
    immediately.  Instead, the new page size is remembered and is used
    to set the page size when the database is first created, if it does
    not already exist when the page_size pragma is issued, or at the
    next VACUUM command that is run on the same database connection
    while not in WAL mode.

    The SQLITE_DEFAULT_PAGE_SIZE compile-time option can be used
    to change the default page size assigned to new databases.


c2: Pragma statements supported by SQLite
c3: PRAGMA parser_trace
c5: pragma.html#pragma_parser_trace
c4:
PRAGMA parser_trace = boolean; 

    If SQLite has been compiled with the SQLITE_DEBUG compile-time
    option, then the parser_trace pragma can be used to turn on tracing
    for the SQL parser used internally by SQLite.
    This feature is used for debugging SQLite itself.

    
    
    This pragma is intended for use when debugging SQLite itself.  It
    is only available when the SQLITE_DEBUG compile-time option
    is used.


c2: Pragma statements supported by SQLite
c3: PRAGMA pragma_list
c5: pragma.html#pragma_pragma_list
c4:
PRAGMA pragma_list;
    This pragma returns a list of PRAGMA commands
    known to the database connection.


c2: Pragma statements supported by SQLite
c3: PRAGMA query_only
c5: pragma.html#pragma_query_only
c4:
PRAGMA query_only;
      PRAGMA query_only = boolean;

    The query_only pragma prevents data changes on database files when
    enabled.  When this pragma is enabled, any attempt to CREATE, DELETE,
    DROP, INSERT, or UPDATE will result in an SQLITE_READONLY error.
    However, the database is not truly read-only.  You can still run
    a checkpoint or a COMMIT and the return value of the
    sqlite3_db_readonly() routine is not affected.


c2: Pragma statements supported by SQLite
c3: PRAGMA quick_check
c5: pragma.html#pragma_quick_check
c4:
PRAGMA schema.quick_check;
      PRAGMA schema.quick_check(N)
      PRAGMA schema.quick_check(TABLENAME)
    The pragma is like integrity_check except that it does not verify
    UNIQUE constraints and does not verify
    that index content matches table content.  By skipping UNIQUE
    and index consistency checks, quick_check is able to run faster.
    PRAGMA quick_check runs in O(N) time whereas PRAGMA integrity_check
    requires O(NlogN) time where N is the total number of rows in the 
    database. Otherwise the two pragmas are the same.


c2: Pragma statements supported by SQLite
c3: PRAGMA read_uncommitted
c5: pragma.html#pragma_read_uncommitted
c4:
PRAGMA read_uncommitted;
       PRAGMA read_uncommitted = boolean;
    Query, set, or clear READ UNCOMMITTED isolation. The default isolation
    level for SQLite is SERIALIZABLE.  Any process or thread can select
    READ UNCOMMITTED isolation, but SERIALIZABLE will still be used except
    between connections that share a common page and schema cache.
    Cache sharing is enabled using the sqlite3_enable_shared_cache() API.
    Cache sharing is disabled by default.
    

    See SQLite Shared-Cache Mode for additional information.


c2: Pragma statements supported by SQLite
c3: PRAGMA recursive_triggers
c5: pragma.html#pragma_recursive_triggers
c4:
PRAGMA recursive_triggers;
       PRAGMA recursive_triggers = boolean;
    Query, set, or clear the recursive trigger capability.

    Changing the recursive_triggers setting affects the execution of
       all statements prepared
       using the database connection, including those prepared before the
       setting was changed. Any existing statements prepared using the legacy 
       sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error
       after the recursive_triggers setting is changed.

    Prior to SQLite version 3.6.18 (2009-09-11), 
    recursive triggers were not supported.
    The behavior of SQLite was always as if this pragma was
    set to OFF.  Support for recursive triggers was added in version 3.6.18
    but was initially turned OFF by default, for compatibility.  Recursive
    triggers may be turned on by default in future versions of SQLite.
    

    The depth of recursion for triggers has a hard upper limit set by
    the SQLITE_MAX_TRIGGER_DEPTH compile-time option and a run-time
    limit set by sqlite3_limit(db,SQLITE_LIMIT_TRIGGER_DEPTH,...).


c2: Pragma statements supported by SQLite
c3: PRAGMA reverse_unordered_selects
c5: pragma.html#pragma_reverse_unordered_selects
c4:
PRAGMA reverse_unordered_selects;
       PRAGMA reverse_unordered_selects = boolean;
    When enabled, this PRAGMA causes many SELECT statements without
    an ORDER BY clause to emit their results in the reverse order from what
    they normally would.  This can help debug applications that are
    making invalid assumptions about the result order.  
    The reverse_unordered_selects pragma works for most SELECT statements,
    however the query planner may sometimes choose an algorithm that is
    not easily reversed, in which case the output will appear in the same
    order regardless of the reverse_unordered_selects setting.
    SQLite makes no
    guarantees about the order of results if a SELECT omits the ORDER BY
    clause.  Even so, the order of results does not change from one
    run to the next, and so many applications mistakenly come to depend
    on the arbitrary output order whatever that order happens to be.  However, 
    sometimes new versions of SQLite will contain optimizer enhancements
    that will cause the output order of queries without ORDER BY clauses
    to shift.  When that happens, applications that depend on a certain
    output order might malfunction.  By running the application multiple
    times with this pragma both disabled and enabled, cases where the
    application makes faulty assumptions about output order can be
    identified and fixed early, reducing problems
    that might be caused by linking against a different version of SQLite.


c2: Pragma statements supported by SQLite
c3: PRAGMA schema_version
c5: pragma.html#pragma_schema_version
c4:
PRAGMA schema.schema_version; 
      PRAGMA schema.schema_version = integer ;

   The schema_version pragma will get or set
       the value of the schema-version integer at offset 40 in the
       database header. 

    SQLite automatically increments the schema-version whenever the
       schema changes. As each SQL statement runs, the schema version is
       checked to ensure that the schema has not changed since the SQL
       statement was prepared.
       Subverting this mechanism by using "PRAGMA schema_version"
       may cause SQL statement to run using an obsolete schema,
       which can lead to incorrect answers and/or
       database corruption.

       
    
    Warning:
    Misuse of this pragma can result in database corruption.
    
  

    For the purposes of this pragma, the VACUUM command is considered
       a schema change, since VACUUM will usually alter the "rootpage"
       values for entries in the sqlite_schema table.


    See also the application_id pragma and user_version pragma.


c2: Pragma statements supported by SQLite
c3: PRAGMA secure_delete
c5: pragma.html#pragma_secure_delete
c4:
PRAGMA schema.secure_delete;
     PRAGMA schema.secure_delete = boolean|FAST
    Query or change the secure-delete setting. When secure_delete is
    on, SQLite overwrites deleted content with zeros.  The default
    setting for secure_delete is determined by the SQLITE_SECURE_DELETE
    compile-time option and is normally off.  The off setting for
    secure_delete improves performance by reducing the number of CPU cycles
    and the amount of disk I/O.  Applications that wish to avoid leaving
    forensic traces after content is deleted or updated should enable the
    secure_delete pragma prior to performing the delete or update, or else
    run VACUUM after the delete or update.

    The "fast" setting for secure_delete (added circa 2017-08-01)
    is an intermediate setting in between "on" and "off".
    When secure_delete is set to "fast",
    SQLite will overwrite deleted content with zeros only if doing so
    does not increase the amount of I/O.  In other words, the "fast"
    setting uses more CPU cycles but does not use more I/O.
    This has the effect of purging all old content from b-tree pages,
    but leaving forensic traces on freelist pages.

    
    When there are attached databases and no database
    is specified in the pragma, all databases have their secure-delete
    setting altered.
    The secure-delete setting for newly attached databases is the setting
    of the main database at the time the ATTACH command is evaluated.

    
    When multiple database connections share the same cache, changing
    the secure-delete flag on one database connection changes it for them
    all.


c2: Pragma statements supported by SQLite
c3: PRAGMA short_column_names
c5: pragma.html#pragma_short_column_names
c4:
PRAGMA short_column_names;
       PRAGMA short_column_names = boolean;

    Query or change the short-column-names flag. This flag affects
    the way SQLite names columns of data returned by SELECT statements.
    See the full_column_names pragma for full details.
    

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA shrink_memory
c5: pragma.html#pragma_shrink_memory
c4:
PRAGMA shrink_memory

    This pragma causes the database connection on which it is invoked
    to free up as much memory as it can, by calling
    sqlite3_db_release_memory().


c2: Pragma statements supported by SQLite
c3: PRAGMA soft_heap_limit
c5: pragma.html#pragma_soft_heap_limit
c4:
PRAGMA soft_heap_limit
          PRAGMA soft_heap_limit=N

    This pragma invokes the sqlite3_soft_heap_limit64() interface with
    the argument N, if N is specified and is a non-negative integer.
    The soft_heap_limit pragma always returns the same integer
    that would be returned by the sqlite3_soft_heap_limit64(-1) C-language
    function.
    
    See also the hard_heap_limit pragma.


c2: Pragma statements supported by SQLite
c3: PRAGMA stats
c5: pragma.html#pragma_stats
c4:
PRAGMA stats; 
    This pragma returns auxiliary information about tables and
    indices.  The returned information is used during testing to help
    verify that the query planner is operating correctly.  The format
    and meaning of this pragma will likely change from one release
    to the next. Because of its volatility, the behavior and output
    format of this pragma are deliberately undocumented.

    
    
    The intended use of this pragma is only for testing and validation of
    SQLite.  This pragma is subject to change without notice and is not
    recommended for use by application programs.


c2: Pragma statements supported by SQLite
c3: PRAGMA synchronous
c5: pragma.html#pragma_synchronous
c4:
PRAGMA schema.synchronous;
        PRAGMA schema.synchronous = 
          0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA;

    Query or change the setting of the "synchronous" flag.
    The first (query) form will return the synchronous setting as an 
    integer.  The second form changes the synchronous setting.
    The meanings of the various synchronous settings are as follows:
    
    EXTRA (3)
    
    EXTRA synchronous is like FULL with the addition that the directory
    containing a rollback journal is synced after that journal is unlinked
    to commit a transaction in DELETE mode.  EXTRA provides additional
    durability if the commit is followed closely by a power loss.
    FULL (2)
    
    When synchronous is FULL (2), the SQLite database engine will
    use the xSync method of the VFS to ensure that all content is safely
    written to the disk surface prior to continuing.
    This ensures that an operating system crash or power failure will
    not corrupt the database.
    FULL synchronous is very safe, but it is also slower.  FULL is the
    most commonly used synchronous setting when not in WAL mode.
    NORMAL (1)
    
    When synchronous is NORMAL (1), the SQLite database
    engine will still sync at the most critical moments, but less often
    than in FULL mode.  There is a very small (though non-zero) chance that
    a power failure at just the wrong time could corrupt the database in
    journal_mode=DELETE on an older filesystem.
    WAL mode is safe from corruption with synchronous=NORMAL, and probably
    DELETE mode is safe too on modern filesystems.  WAL mode is always consistent
    with synchronous=NORMAL, but WAL mode does lose durability.  A transaction
    committed in WAL mode with synchronous=NORMAL might roll back following
    a power loss or system crash.  Transactions are durable across application
    crashes regardless of the synchronous setting or journal mode.
    The synchronous=NORMAL setting is a good choice for most applications
    running in WAL mode.
    OFF (0)
    
    With synchronous OFF (0), SQLite continues without syncing
    as soon as it has handed data off to the operating system.
    If the application running SQLite crashes, the data will be safe, but
    the database might become corrupted if the operating system
    crashes or the computer loses power before that data has been written
    to the disk surface.  On the other hand, commits can be orders of
    magnitude faster with synchronous OFF.
    
    
 
    In WAL mode when synchronous is NORMAL (1), the WAL file is
    synchronized before each checkpoint and the database file is
    synchronized after each completed checkpoint and the WAL file
    header is synchronized when a WAL file begins to be reused after
    a checkpoint, but no sync operations occur during most transactions.
    With synchronous=FULL in WAL mode, an additional
    sync operation of the WAL file happens after each transaction commit.
    The extra WAL sync following each transaction helps ensure that 
    transactions are durable across a power loss.  Transactions are
    consistent with or without the extra syncs provided by
    synchronous=FULL.
    If durability is not a concern, then synchronous=NORMAL is normally
    all one needs in WAL mode.

    The TEMP schema always has synchronous=OFF since the content of
    of TEMP is ephemeral and is not expected to survive a power outage.
    Attempts to change the synchronous setting for TEMP are
    silently ignored.

    See also the fullfsync and checkpoint_fullfsync pragmas.


c2: Pragma statements supported by SQLite
c3: PRAGMA table_info
c5: pragma.html#pragma_table_info
c4:
PRAGMA schema.table_info(table-name);
    This pragma returns one row for each column in the named table.
    Columns in the result set include the column name,
    data type, whether or not the column can be NULL, and the default
    value for the column.  The "pk" column in the result set is zero
    for columns that are not part of the primary key, and is the index of
    the column in the primary key for columns that are part of the primary
    key.
    The table named in the table_info pragma can also be a view.
    See also: PRAGMA table_xinfo


c2: Pragma statements supported by SQLite
c3: PRAGMA table_list
c5: pragma.html#pragma_table_list
c4:
PRAGMA table_list;
         PRAGMA schema.table_list;
         PRAGMA table_list(table-name);
    This pragma returns information about the tables and views in the schema,
    one table per row of output.  The table_list pragma first appeared
    in SQLite version 3.37.0 (2021-11-27).  As of its initial release
    the columns returned by the table_list pragma include those listed below.
    Future versions of SQLite will probably add additional columns of
    output.
    
    
     schema: the schema in which the table or view appears
    (for example "main" or "temp").
     name: the name of the table or view.
     type: the type of object - one of "table", "view",
           "shadow" (for shadow tables), or "virtual" for
           virtual tables.
     ncol: the number of columns in the table, including
         generated columns and hidden columns.
     wr: 1 if the table is a WITHOUT ROWID table or 0 if is not.
     strict: 1 if the table is a STRICT table or 0 if it is not.
     Additional columns will likely be added in future releases.
    
    
    The default behavior is to show all tables in all schemas.  If the
    schema. name appears before the pragma, then only tables in that
    one schema are shown.  If a table-name argument is supplied, then
    only information about that one table is returned.


c2: Pragma statements supported by SQLite
c3: PRAGMA table_xinfo
c5: pragma.html#pragma_table_xinfo
c4:
PRAGMA schema.table_xinfo(table-name);
    This pragma returns one row for each column in the named table,
    including hidden columns in virtual tables.
    The output is the same as for PRAGMA table_info except that
    hidden columns are shown rather than being omitted.


c2: Pragma statements supported by SQLite
c3: PRAGMA temp_store
c5: pragma.html#pragma_temp_store
c4:
PRAGMA temp_store;
        PRAGMA temp_store = 
            0 | DEFAULT | 1 | FILE | 2 | MEMORY;

    Query or change the setting of the "temp_store" parameter.
    When temp_store is DEFAULT (0), the compile-time C preprocessor macro
    SQLITE_TEMP_STORE is used to determine where temporary tables and indices
    are stored.  When
    temp_store is MEMORY (2) temporary tables and indices are kept
    as if they were in pure in-memory databases.
    When temp_store is FILE (1) temporary tables and indices are stored
    in a file.  The temp_store_directory pragma can be used to specify
    the directory containing temporary files when
    FILE is specified.  When the temp_store setting is changed,
    all existing temporary tables, indices, triggers, and views are
    immediately deleted.

    It is possible for the library compile-time C preprocessor symbol
    SQLITE_TEMP_STORE to override this pragma setting.
    The following table summarizes
    the interaction of the SQLITE_TEMP_STORE preprocessor macro and the
    temp_store pragma:

    
    
    SQLITE_TEMP_STORE
        PRAGMAtemp_store
        Storage used forTEMP tables and indices
    0
        any
        file
    1
        0
        file
    1
        1
        file
    1
        2
        memory
    2
        0
        memory
    2
        1
        file
    2
        2
        memory
    3
        any
        memory


c2: Pragma statements supported by SQLite
c3: PRAGMA temp_store_directory
c5: pragma.html#pragma_temp_store_directory
c4:
PRAGMA temp_store_directory;
      PRAGMA temp_store_directory = 'directory-name';
    Query or change the value of the sqlite3_temp_directory global
    variable, which many operating-system interface backends use to
    determine where to store temporary tables and indices.

    When the temp_store_directory setting is changed, all existing temporary
    tables, indices, triggers, and viewers in the database connection that
    issued the pragma are immediately deleted.  In
    practice, temp_store_directory should be set immediately after the first
    database connection for a process is opened.  If the temp_store_directory
    is changed for one database connection while other database connections
    are open in the same process, then the behavior is undefined and
    probably undesirable.

    Changing the temp_store_directory setting is not threadsafe.
    Never change the temp_store_directory setting if another thread
    within the application is running any SQLite interface at the same time.
    Doing so results in undefined behavior.  Changing the temp_store_directory
    setting writes to the sqlite3_temp_directory global
    variable and that global variable is not protected by a mutex.

    The value directory-name should be enclosed in single quotes.
    To revert the directory to the default, set the directory-name to
    an empty string, e.g., PRAGMA temp_store_directory = ''.  An
    error is raised if directory-name is not found or is not
    writable. 

    The default directory for temporary files depends on the OS.  Some
    OS interfaces may choose to ignore this variable and place temporary
    files in some other directory different from the directory specified
    here.  In that sense, this pragma is only advisory.

    
    
    This pragma is deprecated and exists
    for backwards compatibility only.  New applications
    should avoid using this pragma.  Older applications should discontinue
    use of this pragma at the earliest opportunity.  This pragma may be omitted
    from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


c2: Pragma statements supported by SQLite
c3: PRAGMA threads
c5: pragma.html#pragma_threads
c4:
PRAGMA threads;
      PRAGMA threads = N;
    Query or change the value of the 
    sqlite3_limit(db,SQLITE_LIMIT_WORKER_THREADS,...) limit for
    the current database connection.  This limit sets an upper bound
    on the number of auxiliary threads that a prepared statement is
    allowed to launch to assist with a query.  The default limit is 0
    unless it is changed using the SQLITE_DEFAULT_WORKER_THREADS
    compile-time option.  When the limit is zero, that means no
    auxiliary threads will be launched.

    This pragma is a thin wrapper around the
    sqlite3_limit(db,SQLITE_LIMIT_WORKER_THREADS,...) interface.


c2: Pragma statements supported by SQLite
c3: PRAGMA trusted_schema
c5: pragma.html#pragma_trusted_schema
c4:
PRAGMA trusted_schema;
      PRAGMA trusted_schema = boolean;
    The trusted_schema setting is a per-connection boolean that
    determines whether or not SQL functions and virtual tables that
    have not been security audited are allowed to be run by views,
    triggers, or in expressions of the schema such as CHECK constraints,
    DEFAULT clauses, generated columns, expression indexes, and/or
    partial indexes.  This setting can also be controlled using
    the sqlite3_db_config(db,SQLITE_DBCONFIG_TRUSTED_SCHEMA,...)
    C-language interface.
    In order to maintain backwards compatibility, this setting is
    ON by default.  There are advantages to turning it off, and most
    applications will be unaffected if it is turned off.  For that reason,
    all applications are encouraged to switch this setting off on every
    database connection as soon as that connection is opened.
    The -DSQLITE_TRUSTED_SCHEMA=0 compile-time option will cause
    this setting to default to OFF.


c2: Pragma statements supported by SQLite
c3: PRAGMA user_version
c5: pragma.html#pragma_user_version
c4:
PRAGMA schema.user_version;
      PRAGMA schema.user_version = integer ;

  
    The user_version pragma will get or set
       the value of the user-version integer at offset 60 in the
       database header.  The user-version is an integer that is
       available to applications to use however they want.  SQLite
       makes no use of the user-version itself.

    See also the application_id pragma and schema_version pragma.


c2: Pragma statements supported by SQLite
c3: PRAGMA vdbe_addoptrace
c5: pragma.html#pragma_vdbe_addoptrace
c4:
PRAGMA vdbe_addoptrace = boolean;

    If SQLite has been compiled with the SQLITE_DEBUG compile-time
    option, then the vdbe_addoptrace pragma can be used to cause a complete
    VDBE opcodes to be displayed as they are created during code generation.
    This feature is used for debugging SQLite itself.  See the 
    VDBE documentation for more 
    information.

    
    
    This pragma is intended for use when debugging SQLite itself.  It
    is only available when the SQLITE_DEBUG compile-time option
    is used.


c2: Pragma statements supported by SQLite
c3: PRAGMA vdbe_debug
c5: pragma.html#pragma_vdbe_debug
c4:
PRAGMA vdbe_debug = boolean;

    If SQLite has been compiled with the SQLITE_DEBUG compile-time
    option, then the vdbe_debug pragma is a shorthand for three other
    debug-only pragmas: vdbe_addoptrace, vdbe_listing, and vdbe_trace.
    This feature is used for debugging SQLite itself.  See the 
    VDBE documentation for more 
    information.

    
    
    This pragma is intended for use when debugging SQLite itself.  It
    is only available when the SQLITE_DEBUG compile-time option
    is used.


c2: Pragma statements supported by SQLite
c3: PRAGMA vdbe_listing
c5: pragma.html#pragma_vdbe_listing
c4:
PRAGMA vdbe_listing = boolean;

    If SQLite has been compiled with the SQLITE_DEBUG compile-time
    option, then the vdbe_listing pragma can be used to cause a complete
    listing of the virtual machine opcodes to appear on standard output
    as each statement is evaluated.
    With listing is on, the entire content of a program is printed
    just prior to beginning execution.  The statement
    executes normally after the listing is printed.
    This feature is used for debugging SQLite itself.  See the 
    VDBE documentation for more 
    information.

    
    
    This pragma is intended for use when debugging SQLite itself.  It
    is only available when the SQLITE_DEBUG compile-time option
    is used.


c2: Pragma statements supported by SQLite
c3: PRAGMA vdbe_trace
c5: pragma.html#pragma_vdbe_trace
c4:
PRAGMA vdbe_trace = boolean;

    If SQLite has been compiled with the SQLITE_DEBUG compile-time
    option, then the vdbe_trace pragma can be used to cause virtual machine
    opcodes to be printed on standard output as they are evaluated.
    This feature is used for debugging SQLite.  See the 
    VDBE documentation for more 
    information.

    
    
    This pragma is intended for use when debugging SQLite itself.  It
    is only available when the SQLITE_DEBUG compile-time option
    is used.


c2: Pragma statements supported by SQLite
c3: PRAGMA wal_autocheckpoint
c5: pragma.html#pragma_wal_autocheckpoint
c4:
PRAGMA wal_autocheckpoint;
          PRAGMA wal_autocheckpoint=N;

    This pragma queries or sets the write-ahead log 
    auto-checkpoint interval.
    When the write-ahead log is enabled (via the
    journal_mode pragma) a checkpoint will be run automatically whenever
    the write-ahead log equals or exceeds N pages in length.
    Setting the auto-checkpoint size to zero or a negative value
    turns auto-checkpointing off.
    
    This pragma is a wrapper around the
    sqlite3_wal_autocheckpoint() C interface.
    All automatic checkpoints are PASSIVE.

    Autocheckpointing is enabled by default with an interval
    of 1000 or SQLITE_DEFAULT_WAL_AUTOCHECKPOINT.


c2: Pragma statements supported by SQLite
c3: PRAGMA wal_checkpoint
c5: pragma.html#pragma_wal_checkpoint
c4:
PRAGMA schema.wal_checkpoint;
       PRAGMA schema.wal_checkpoint(PASSIVE);
       PRAGMA schema.wal_checkpoint(FULL);
       PRAGMA schema.wal_checkpoint(RESTART);
       PRAGMA schema.wal_checkpoint(TRUNCATE);
   

    If the write-ahead log is enabled (via the journal_mode pragma),
    this pragma causes a checkpoint operation to run on database
    database, or on all attached databases if database
    is omitted.  If write-ahead log mode is disabled, this pragma is a
    harmless no-op.

    Invoking this
    pragma without an argument is equivalent to calling the
    sqlite3_wal_checkpoint() C interface.
    Invoking this pragma with an argument is equivalent to calling the
    sqlite3_wal_checkpoint_v2() C interface with a 
    3rd parameter
    corresponding to the argument:

    
    PASSIVE
      Checkpoint as many frames as possible without waiting for any database 
      readers or writers to finish. Sync the db file if all frames in the log
      are checkpointed. This mode is the same as calling the
      sqlite3_wal_checkpoint() C interface. The
      busy-handler callback is never invoked in
      this mode.
   
    FULL
      This mode blocks 
      (invokes the busy-handler callback)
      until there is no
      database writer and all readers are reading from the most recent database
      snapshot. It then checkpoints all frames in the log file and syncs the
      database file. FULL blocks concurrent writers while it is
      running, but readers can proceed.
   
    RESTART
      This mode works the same way as FULL with the addition that after 
      checkpointing the log file it blocks (calls the 
      busy-handler callback)
      until all readers are finished with the log file. This ensures 
      that the next client to write to the database file restarts the log file 
      from the beginning. RESTART blocks concurrent writers while it is
      running, but allowed readers to proceed.
   
    TRUNCATE
      This mode works the same way as RESTART with the 
      addition that the WAL file is truncated to zero bytes upon successful
      completion.
    


    The wal_checkpoint pragma returns a single row with three
    integer columns.  The first column is usually 0 but will be
    1 if a RESTART or FULL or TRUNCATE checkpoint was blocked from completing,
    for example because another thread or process was actively
    using the database.  In other words, the first column is 0 if the
    equivalent call to sqlite3_wal_checkpoint_v2() would have returned
    SQLITE_OK or 1 if the equivalent call would have returned SQLITE_BUSY.
    The second column is the number of modified pages that have been
    written to the write-ahead log file.
    The third column is the number of pages in the write-ahead log file
    that have been successfully moved back into the database file at
    the conclusion of the checkpoint.
   The second and third column are -1 if there is no
    write-ahead log, for example if this pragma is invoked on a database
    connection that is not in WAL mode.


c2: Pragma statements supported by SQLite
c3: PRAGMA writable_schema
c5: pragma.html#pragma_writable_schema
c4:
PRAGMA writable_schema  = boolean;
         PRAGMA writable_schema = RESET

    When this pragma is on, and the SQLITE_DBCONFIG_DEFENSIVE flag
    is off, then the sqlite_schema table
    can be changed using ordinary UPDATE, INSERT, and DELETE
    statements.  If the argument is "RESET" then schema writing is
    disabled (as with "PRAGMA writable_schema=OFF") and, in addition, the
    schema is reloaded.  Warning:
    misuse of this pragma can easily result in
    a corrupt database file.


c2: The RBU Extension
c3: 1. The RBU Extension
c5: rbu.html#the_rbu_extension
c4:
The RBU extension is an add-on for SQLite designed for use with large 
SQLite database files on low-power devices at the edge of a network. RBU
may be used for two separate tasks:


   RBU Update operations. An RBU Update is a bulk update of a
          database file that may include many insert, update and delete
          operations on one or more tables.
   RBU Vacuum operations. An RBU Vacuum optimizes and rebuilds an
          entire database file, with results similar to SQLite's native VACUUM
          command.  


The acronym RBU stands for "Resumable Bulk Update".

Both of the RBU functions may be accomplished using SQLite's built-in 
SQL commands - RBU update via a series of INSERT, DELETE and 
UPDATE commands within a single transaction, and RBU vacuum by a single
VACUUM command.  The RBU module provides the following advantages over
these simpler approaches:



RBU may be more efficient

The most efficient way to apply changes to a B-Tree (the data structure
that SQLite uses to store each table and index on disk) is to make the
changes in key order. But if an SQL table has one or more indexes, the key
order for each index may be different from the main table and the other
auxiliary indexes. As a result, when executing a series of INSERT,
UPDATE and DELETE statements it is not generally possible to order the
operations so that all b-trees are updated in key order. The RBU update
process works around this by applying all changes to the main table in one 
pass, then applying changes to each index in separate passes, ensuring each
B-Tree is updated optimally. For a large database file (one that does not
fit in the OS disk cache) this procedure can result in two orders of
magnitude faster updates.

An RBU Vacuum operation requires less temporary disk space and writes
less data to disk than an SQLite VACUUM. An SQLite VACUUM requires roughly
twice the size of the final database file in temporary disk space to run.
The total amount of data written is around three times the size of the
final database file. By contrast, an RBU Vacuum requires roughly the size
of the final database file in temporary disk space and writes a total of
twice that to disk.

On the other hand, an RBU Vacuum uses more CPU than a regular SQLite
VACUUM - in one test as much as five times as much. For this reason, an RBU
Vacuum is often significantly slower than an SQLite VACUUM under the same
conditions.

RBU runs in the background

An ongoing RBU operation (either an update or a vacuum) does not
interfere with read access to the database file.

RBU runs incrementally

RBU operations may be suspended and then later resumed, perhaps with
intervening power outages and/or system resets. For an RBU update, the
original database content remains visible to all database readers until 
the entire update has been applied - even if the update is suspended and
then later resumed.



The RBU extension is not enabled by default. To enable it, compile the
amalgamation with the SQLITE_ENABLE_RBU compile-time option.


c2: The RBU Extension
c3: 2.1. RBU Update Limitations
c5: rbu.html#rbu_update_limitations
c4:
The following limitations apply to RBU updates:


The changes must consist of INSERT, UPDATE, and DELETE
    operations only.  CREATE and DROP operations are not
    supported.
INSERT statements may not use default values.
UPDATE and DELETE statements must identify the target rows
    by rowid or by non-NULL PRIMARY KEY values.
UPDATE statements may not modify PRIMARY KEY or rowid values.
    
RBU updates cannot be applied to any tables that contain a column
       named "rbu_control".
The RBU update will not fire any triggers.
The RBU update will not detect or prevent foreign key or
       CHECK constraint violations.
All RBU updates use the "OR ROLLBACK" constraint handling mechanism.
    
The target database may not be in WAL mode.
The target database may not contain indexes on expressions.
    Indexes on expressions are supported beginning with SQLite 3.30.0
    (2019-10-04).
No other writes may occur on the target database while the
       RBU update is being applied.  A read-lock is held on the target
       database to prevent this.


c2: The RBU Extension
c3: 2.2. Preparing an RBU Update File
c5: rbu.html#preparing_an_rbu_update_file
c4:
All changes to be applied by RBU are stored in a separate SQLite database
called the "RBU database".  The database that is to be modified is called
the "target database".

For each table in the target database that will be modified by the update,
a corresponding table is created within the RBU database. The RBU database
table schema is not the same as that of the target database, but is derived
from it as described below.

The RBU database table contains a single row for each target database 
row inserted, updated or deleted by the update. Populating the RBU database
tables is described in the following section.


c2: The RBU Extension
c3: 2.2.1. The RBU Database Schema
c5: rbu.html#the_rbu_database_schema
c4:
For each table in the target database, the RBU database should contain a table
named "data&lt;integer&gt;_&lt;target-table-name&gt;" where
&lt;target-table-name&gt; is the name of the table in the target
database and &lt;integer&gt; is any sequence of zero or more numeric
characters (0-9). Tables within the RBU database are processed in order by 
name (from smallest to largest according to the BINARY collation sequence),
so the order in which target tables are updated is influenced by the selection 
of the &lt;integer&gt; portion of the data_% table name. While this can
be useful when using RBU to update 
certain types of virtual tables, there is normally no
reason to use anything other than an empty string in place of
&lt;integer&gt;.

The data_% table must have all the same columns as the target table, plus
one additional column named "rbu_control". The data_% table should have no
PRIMARY KEY or UNIQUE constraints, but each column should have the same type as
the corresponding column in the target database. The rbu_control column should
have no type at all. For example, if the target database contains:

CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);


Then the RBU database should contain:

CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);


The order of the columns in the data_% table does not matter.

If the target database table is a virtual table or a table that has no
PRIMARY KEY declaration, the data_% table must also contain a column 
named "rbu_rowid". The rbu_rowid column is mapped to the tables ROWID.
For example, if the target database contains either of the following:

CREATE VIRTUAL TABLE x1 USING fts3(a, b);
CREATE TABLE x1(a, b);


then the RBU database should contain:

CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);


Virtual tables for which the "rowid" column does 
not function like a primary key value cannot be updated using RBU.


All non-hidden columns (i.e. all columns matched by "SELECT *") of the
target table must be present in the input table. For virtual tables,
hidden columns are optional - they are updated by RBU if present in
the input table, or not otherwise. For example, to write to an fts4
table with a hidden languageid column such as:

CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');


Either of the following input table schemas may be used:

CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);


c2: The RBU Extension
c3: 2.2.2. RBU Database Contents
c5: rbu.html#rbu_database_contents
c4:
For each row to INSERT into the target database as part of the RBU 
update, the corresponding data_% table should contain a single record
with the "rbu_control" column set to contain integer value 0. The
other columns should be set to the values that make up the new record 
to insert. 

The "rbu_control" column may also be set to integer value 2 for 
an INSERT. In this case, the new row silently replaces any existing row that
has the same primary key values. This is equivalent to a DELETE followed by an
INSERT with the same primary key values. It is not the same as an SQL REPLACE
command, as in that case the new row may replace any conflicting rows (i.e.
those that conflict due to UNIQUE constraints or indexes), not just those with
conflicting primary keys.

If the target database table has an INTEGER PRIMARY KEY, it is not 
possible to insert a NULL value into the IPK column. Attempting to 
do so results in an SQLITE_MISMATCH error.

For each row to DELETE from the target database as part of the RBU 
update, the corresponding data_% table should contain a single record
with the "rbu_control" column set to contain integer value 1. The
real primary key values of the row to delete should be stored in the
corresponding columns of the data_% table. The values stored in the
other columns are not used.

For each row to UPDATE from the target database as part of the RBU 
update, the corresponding data_% table should contain a single record
with the "rbu_control" column set to contain a value of type text.
The real primary key values identifying the row to update should be 
stored in the corresponding columns of the data_% table row, as should
the new values of all columns being update. The text value in the 
"rbu_control" column must contain the same number of characters as
there are columns in the target database table, and must consist entirely
of 'x' and '.' characters (or in some special cases 'd' - see below). For 
each column that is being updated, the corresponding character is set to
'x'. For those that remain as they are, the corresponding character of the
rbu_control value should be set to '.'. For example, given the tables 
above, the update statement:

UPDATE t1 SET c = 'usa' WHERE a = 4;


is represented by the data_t1 row created by:

INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');


If RBU is used to update a large BLOB value within a target database, it
may be more efficient to store a patch or delta that can be used to modify
the existing BLOB instead of an entirely new value within the RBU database. 
RBU allows deltas to be specified in two ways:


   In the "fossil delta" format - the format used for blob deltas by the 
  Fossil source-code management system, or

   In a custom format defined by the RBU application.


 The fossil delta format may only be used to update BLOB values. Instead
of storing the new BLOB within the data_% table, the fossil delta is stored
instead. And instead of specifying an 'x' as part of the rbu_control string
for the column to be updated, an 'f' character is stored. When processing
an 'f' update, RBU loads the original BLOB data from disk, applies the fossil
delta to it and stores the results back into the database file. The RBU
databases generated by sqldiff --rbu make use of fossil deltas wherever
doing so would save space in the RBU database.

 To use a custom delta format, the RBU application must register a
user-defined SQL function named "rbu_delta" before beginning to process the
update. rbu_delta() will be invoked with two arguments - the original value
stored in the target table column and the delta value provided as part of
the RBU update. It should return the result of applying the delta to the
original value. To use the custom delta function, the character of the
rbu_control value corresponding to the target column to update must be
set to 'd' instead of 'x'. Then, instead of updating the target table with the
value stored in the corresponding data_% column, RBU invokes the user-defined
SQL function "rbu_delta()" and the store in the target table column.

For example, this row:

INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');


causes RBU to update the target database table in a way similar to:

UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;


If the target database table is a virtual table or a table with no PRIMARY
KEY, the rbu_control value should not include a character corresponding 
to the rbu_rowid value. For example, this:

INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control) 
  VALUES(NULL, 'usa', 12, '.x');



causes a result similar to:

UPDATE ft1 SET b = 'usa' WHERE rowid = 12;


The data_% tables themselves should have no PRIMARY KEY declarations.
However, RBU is more efficient if reading the rows in from each data_%
table in "rowid" order is roughly the same as reading them sorted by
the PRIMARY KEY of the corresponding target database table. In other 
words, rows should be sorted using the destination table PRIMARY KEY 
fields before they are inserted into the data_% tables.


c2: The RBU Extension
c3: 2.2.3. Using RBU with FTS3/4 Tables
c5: rbu.html#using_rbu_with_fts3_4_tables
c4:
Usually, an FTS3 or FTS4 table is an example of a virtual table 
with a rowid that works like a PRIMARY KEY. So, for the following FTS4 tables:

CREATE VIRTUAL TABLE ft1 USING fts4(addr, text);
CREATE VIRTUAL TABLE ft2 USING fts4;             -- implicit "content" column


The data_% tables may be created as follows:

CREATE TABLE data_ft1 USING fts4(addr, text, rbu_rowid, rbu_control);
CREATE TABLE data_ft2 USING fts4(content, rbu_rowid, rbu_control);


And populated as if the target table were an ordinary SQLite table with no
explicit PRIMARY KEY columns.

Contentless FTS4 tables are handled similarly,
except that any attempt to update or delete rows will cause an error when
applying the update.

External content FTS4 tables may also be 
updated using RBU. In this case the user is required to configure the RBU
database so that the same set of UPDATE, DELETE and INSERT operations are
applied to the FTS4 index as to the underlying content table. As for all
updates of external content FTS4 tables, the user is also required to ensure
that any UPDATE or DELETE operations are applied to the FTS4 index before
they are applied to the underlying content table (refer to FTS4 documentation
for a detailed explanation). In RBU, this is done by ensuring that the name
of the data_% table used to write to the FTS4 table sorts before the name
of the data_% table used to update the underlying content table using the
BINARY collation sequence. In order to avoid duplicating data within the
RBU database, an SQL view may be used in place of one of the data_% tables.
For example, for the target database schema:

CREATE TABLE ccc(addr, text);
CREATE VIRTUAL TABLE ccc_fts USING fts4(addr, text, content=ccc);



  The following RBU database schema may be used: 

CREATE TABLE data_ccc(addr, text, rbu_rowid, rbu_control);
CREATE VIEW data0_ccc_fts AS SELECT * FROM data_ccc;

 

  The data_ccc table may then be populated as normal with the updates intended
  for target database table ccc. The same updates will be read by RBU from
  the data0_ccc_fts view and applied to FTS table ccc_fts. Because
  "data0_ccc_fts" is smaller than "data_ccc", the FTS table will be updated
  first, as required.


  Cases in which the underlying content table has an explicit INTEGER PRIMARY
  KEY column are slightly more difficult, as the text values stored in the
  rbu_control column are slightly different for the FTS index and its
  underlying content table. For the underlying content table, a character
  must be included in any rbu_control text values for the explicit IPK, but
  for the FTS table itself, which has an implicit rowid, it should not. This
  is inconvenient, but can be solved using a more complicated view, as follows:

-- Target database schema
CREATE TABLE ddd(i INTEGER PRIMARY KEY, k TEXT);
CREATE VIRTUAL TABLE ddd_fts USING fts4(k, content=ddd);

-- RBU database schema
CREATE TABLE data_ccc(i, k, rbu_control);
CREATE VIEW data0_ccc_fts AS SELECT i AS rbu_rowid, k, CASE 
  WHEN rbu_control IN (0,1) THEN rbu_control ELSE substr(rbu_control, 2) END
FROM data_ccc;



  The substr() function in the SQL view above returns the text of the
  rbu_control argument with the first character (the one corresponding to
  column "i", which is not required by the FTS table) removed.


c2: The RBU Extension
c3: 2.2.4. Automatically Generating RBU Updates with sqldiff
c5: rbu.html#automatically_generating_rbu_updates_with_sqldiff
c4:
As of SQLite version 3.9.0 (2015-10-14), 
  the sqldiff utility is able to generate
  RBU databases representing the difference between two databases with
  identical schemas. For example, the following command:

sqldiff --rbu t1.db t2.db



  Outputs an SQL script to create an RBU database which, if used to update
  database t1.db, patches it so that its contents are identical to that of
  database t2.db.


  By default, sqldiff attempts to process all non-virtual tables within
  the two databases provided to it. If any table appears in one database
  but not the other, or if any table has a slightly different schema in
  one database it is an error. The "--table" option may be useful if this
  causes a problem
  

  Virtual tables are ignored by default by sqldiff. However, it is possible 
  to explicitly create an RBU data_% table for a virtual table that features
  a rowid that functions like a primary key using a command such as:

sqldiff --rbu --table &lt;virtual-table-name&gt; t1.db t2.db



  Unfortunately, even though virtual tables are ignored by default, any
  underlying database tables that they create in order to
  store data within the database are not, and sqldiff will include add these
  to any RBU database. For this reason, users attempting to use sqldiff to
  create RBU updates to apply to target databases with one or more virtual
  tables will likely have to run sqldiff using the --table option separately
  for each table to update in the target database.


c2: The RBU Extension
c3: 2.3. RBU Update C/C++ Programming
c5: rbu.html#rbu_update_c_c_programming
c4:
The RBU extension interface allows an application to apply an RBU update 
stored in an RBU database to an existing target database.
The procedure is as follows:



Open an RBU handle using the sqlite3rbu_open(T,A,S) function.

The T argument is the name of the target database file.
The A argument is the name of the RBU database file.
The S argument is the name of a "state database" used to store
state information needed to resume the update after an interruption.
The S argument can be NULL in which case the state information
is stored in the RBU database in various tables whose names all
begin with "rbu_".

The sqlite3rbu_open(T,A,S) function returns a pointer to
an "sqlite3rbu" object, which is then passed into the subsequent
interfaces.



Register any required virtual table modules with the database
handle returned by sqlite3rbu_db(X) (where argument X is the sqlite3rbu
pointer returned from sqlite3rbu_open()).  Also, if required, register
the rbu_delta() SQL function using 
sqlite3_create_function_v2().


Invoke the sqlite3rbu_step(X) function one or more times on
the sqlite3rbu object pointer X. Each call to sqlite3rbu_step() 
performs a single b-tree operation, so thousands of calls may be 
required to apply a complete update.  The sqlite3rbu_step() 
interface will return SQLITE_DONE when the update has been
completely applied.


Call sqlite3rbu_close(X) to destroy the sqlite3rbu object pointer.
If sqlite3rbu_step(X) has been called enough times to completely
apply the update to the target database, then the RBU database
is marked as fully applied. Otherwise, the state of the RBU 
update application is saved in the state database (or in the RBU
database if the name of the state database file in sqlite3rbu_open()
is NULL) for later resumption of the update.


If an update is only partially applied to the target database by the
time sqlite3rbu_close() is called, state information is saved 
within the state database if it exists, or otherwise in the RBU database. 
This allows subsequent processes to automatically
resume the RBU update from where it left off.
If state information is stored in the RBU database, it can be removed
by dropping all tables whose names begin with "rbu_".

For more details, refer to the comments in 
header file
sqlite3rbu.h.


c2: The RBU Extension
c3: 3.1. RBU Vacuum Limitations
c5: rbu.html#rbu_vacuum_limitations
c4:
When compared with SQLite's built-in VACUUM command, RBU Vacuum has the
following limitations:


  It may not be used on a database that contains indexes on expressions.
  The database being vacuumed may not be in WAL mode.


c2: The RBU Extension
c3: 3.2. RBU Vacuum C/C++ Programming
c5: rbu.html#rbu_vacuum_c_c_programming
c4:
This section provides an overview of and example code demonstrating the
    integration of RBU Vacuum into an application program.  For full details,
    refer to the comments in 
    header file
    sqlite3rbu.h.

 RBU Vacuum applications all implement some variation of the following
procedure:


   An RBU handle is created by calling sqlite3rbu_vacuum(T, S).

       Argument T is the name of the database file to vacuum. Argument S is
      the name of a database in which the RBU module will save its state if the
      vacuum operation is suspended.

       If state database S does not exist when sqlite3rbu_vacuum() is
      invoked, it is automatically created and populated with the single table
      used to store the state of an RBU vacuum - "rbu_state". If an ongoing RBU
      vacuum is suspended, this table is populated with state data. The next
      time sqlite3rbu_vacuum() is called with the same S parameter, it detects
      this data and attempts to resume the suspended vacuum operation. When
      an RBU vacuum operation is completed or encounters an error, RBU 
      automatically deletes the contents of the rbu_state table. In this case,
      the next call to sqlite3rbu_vacuum() starts an entirely new vacuum
      operation from scratch.

       It is a good idea to establish a convention for determining the RBU
      vacuum state database name based on the target database name. The
      example code below uses "&lt;target&gt;-vacuum", where &lt;target&gt; is
      the name of the database being vacuumed.

   Any custom collation sequences used by indexes within the database
      being vacuumed are registered with both of the database handles returned
      by the sqlite3rbu_db() function.

   Function sqlite3rbu_step() is called on the RBU handle until either
      the RBU vacuum is finished, an error occurs or the application wishes to
      suspend the RBU vacuum.

       Each call to sqlite3rbu_step() does a small amount of work towards
      completing the vacuum operation. Depending on the size of the database, a
      single vacuum may require thousands of calls to sqlite3rbu_step().
      sqlite3rbu_step() returns SQLITE_DONE if the vacuum operation has
      finished, SQLITE_OK if the vacuum operation has not finished but no error
      has occurred, and an SQLite error code if an error is encountered. If
      an error does occur, all subsequent calls to sqlite3rbu_step() immediately
      return the same error code.

   Finally, sqlite3rbu_close() is called to close the RBU handle. If the
      application stopped calling sqlite3rbu_step() before either the vacuum
      finished or an error occurred, the state of the vacuum is saved in the
      state database so that it may be resumed later on.

       Like sqlite3rbu_step(), if the vacuum operation has finished,
      sqlite3rbu_close() returns SQLITE_DONE. If the vacuum has not finished
      but no error has occurred, SQLITE_OK is returned. Or, if an error has
      occurred, an SQLite error code is returned. If an error occurred as part
      of a prior call to sqlite3rbu_step(), sqlite3rbu_close() returns the
      same error code.


The following example code illustrates the techniques described above.  

/*
** Either start a new RBU vacuum or resume a suspended RBU vacuum on 
** database zTarget. Return when either an error occurs, the RBU 
** vacuum is finished or when the application signals an interrupt
** (code not shown).
**
** If the RBU vacuum is completed successfully, return SQLITE_DONE.
** If an error occurs, return SQLite error code. Or, if the application
** signals an interrupt, suspend the RBU vacuum operation so that it
** may be resumed by a subsequent call to this function and return
** SQLITE_OK.
**
** This function uses the database named "&lt;zTarget&gt;-vacuum" for
** the state database, where &lt;zTarget&gt; is the name of the database 
** being vacuumed.
*/
int do_rbu_vacuum(const char *zTarget){
  int rc;
  char *zState;                   /* Name of state database */
  sqlite3rbu *pRbu;               /* RBU vacuum handle */

  zState = sqlite3_mprintf("%s-vacuum", zTarget);
  if( zState==0 ) return SQLITE_NOMEM;
  pRbu = sqlite3rbu_vacuum(zTarget, zState);
  sqlite3_free(zState);

  if( pRbu ){
    sqlite3 *dbTarget = sqlite3rbu_db(pRbu, 0);
    sqlite3 *dbState = sqlite3rbu_db(pRbu, 1);

    /* Any custom collation sequences used by the target database must
    ** be registered with both database handles here.  */

    while( sqlite3rbu_step(pRbu)==SQLITE_OK ){
      if( &lt;application has signaled interrupt&gt; ) break;
    }
  }
  rc = sqlite3rbu_close(pRbu);
  return rc;
}


c2: The SQLite OS Interface or "VFS"
c3: 1. Introduction
c5: vfs.html#introduction
c4:
This article describes the SQLite OS portability layer or "VFS" - the
module at the bottom of the SQLite implementation stack
that provides portability across operating systems.


c2: The SQLite OS Interface or "VFS"
c3: 2. The VFS In Relation To The Rest Of SQLite
c5: vfs.html#the_vfs_in_relation_to_the_rest_of_sqlite
c4:
The internal organization of the SQLite library can be viewed as the
stack of modules shown to the right.
The Tokenizer, Parser, and Code Generator components are used to
process SQL statements and convert them into executable programs 
in a virtual machine language or byte code.
Roughly speaking, these top three layers implement
sqlite3_prepare_v2().  The byte code generated by the top three
layers is a prepared statement.
The Virtual Machine module is responsible for running the SQL statement 
byte code. The B-Tree module organizes a database file into multiple 
key/value stores with ordered keys and logarithmic performance. 
The Pager module is responsible for loading pages of the database
file into memory, for implementing and controlling transactions, and 
for creating and maintaining the journal files that prevent database 
corruption following a crash or power failure. 
The OS Interface is a thin abstraction that provides a common set of 
routines for adapting SQLite to run on different operating systems.
Roughly speaking, the bottom four layers implement
sqlite3_step().



This article is about the bottom layer.


The OS Interface - also called the "VFS" - is what makes SQLite 
portable across operating systems.  Whenever any of the other modules
in SQLite needs to communicate with the operating
system, they invoke methods in the VFS.  The VFS then invokes the
operating-specific code needed to satisfy the request.
Hence, porting SQLite to a new
operating system is simply a matter of writing a new OS interface layer
or "VFS".


c2: The SQLite OS Interface or "VFS"
c3: 3. Multiple VFSes
c5: vfs.html#multiple_vfses
c4:
The standard SQLite source tree contains built-in VFSes for unix
and windows.  Alternative VFSes can be
added at start-time or run-time using the
sqlite3_vfs_register() interface.



Multiple VFSes can be registered at the same time.
Each VFS has a unique names.
Separate database connections within the same process can be using
different VFSes at the same time.   For that matter, if a single
database connection has multiple database files open using
the ATTACH command, then each attached database might be using a
different VFS.


c2: The SQLite OS Interface or "VFS"
c3: 3.1. Standard Unix VFSes
c5: vfs.html#standard_unix_vfses
c4:
Unix builds come with multiple built-in VFSes.  The default VFS
for unix is called "unix" and is used in most applications.
Other VFSes that might be found in unix (depending on compile-time
options) include:



unix-dotfile - uses dot-file locking rather than
          POSIX advisory locks.
unix-excl - obtains and holds an exclusive lock on
          database files, preventing other processes from accessing the
          database.  Also keeps the wal-index in heap rather than in
          shared memory.
unix-none - all file locking operations are no-ops.
unix-namedsem - uses named semaphores for file locking.
       VXWorks only.



The various unix VFSes differ only in the way they handle file locking -
they share most of their implementation in common with one another and
are all located in the same SQLite source file:  
os_unix.c.
Note that except for "unix" and "unix-excl", the various unix VFSes all
use incompatible locking implementations.  If two processes are accessing
the same SQLite database using different unix VFSes, they may
not see each others locks and may end up interfering with one another,
resulting in database corruption.  The "unix-none" VFS in particular
does no locking at all and will easily result in database corruption if
used by two or more database connections at the same time.
Programmers are encouraged to use only "unix" or "unix-excl" unless
there is a compelling reason to do otherwise.


c2: The SQLite OS Interface or "VFS"
c3: 3.2. Standard Windows VFSes
c5: vfs.html#standard_windows_vfses
c4:
Windows builds also come with multiple built-in VFSes.  The default
Windows VFS is called "win32" and is used in most applications.
Other VFSes that might be found on windows builds include:



win32-longpath - like "win32" except that pathnames can
          be up to 65534 bytes in length, whereas pathnames max out at
          1040 bytes in "win32".
win32-none - all file locking operations are no-ops.
win32-longpath-none - combination of "win32-longpath"
          and "win32-none" - long pathnames are supported and all lock
          operations are no-ops.


As with unix, most of the code for the various Windows VFSes is shared.


c2: The SQLite OS Interface or "VFS"
c3: 3.3. Specifying Which VFS To Use
c5: vfs.html#specifying_which_vfs_to_use
c4:
There is always one VFS which is the default VFS.  On unix systems,
the "unix" VFS comes up as the default and on windows it is "win32".
If no other actions are taken, new database connections will make use
of the default VFS.



The default VFS can be changed by registering or re-registering the
VFS using the sqlite3_vfs_register() interface with a second parameter
of 1.  Hence, if a (unix) process wants to always use the "unix-nolock" VFS 
in place of "unix", the following code would work:



sqlite3_vfs_register(sqlite3_vfs_find("unix-nolock"), 1);



An alternate VFS can also be specified as the 4th parameter to the
sqlite3_open_v2() function.  For example:



int rc = sqlite3_open_v2("demo.db", &db, SQLITE_OPEN_READWRITE, "unix-nolock");



Finally, if URI filenames have been enabled, then the alternative
VFS can be specified using the "vfs=" parameter on the URI.  This technique
works with sqlite3_open(), sqlite3_open16(), sqlite3_open_v2(), and
when a new database is ATTACH-ed to an existing database connection.
For example:



ATTACH 'file:demo2.db?vfs=unix-none' AS demo2;



The VFS specified by a URI has the highest priority.  After that comes
a VFS specified as the fourth argument to sqlite3_open_v2().  The
default VFS is used if no VFS is specified otherwise.


c2: The SQLite OS Interface or "VFS"
c3: 3.4. VFS Shims
c5: vfs.html#vfs_shims
c4:
From the point of view of the uppers layers of the SQLite stack, each
open database file uses exactly one VFS.
But in practice, a particular VFS might
just be a thin wrapper around another VFS that does the real work.
We call a wrapper VFS a "shim".



A simple example of a shim is the "vfstrace" VFS.  This is a VFS
(implemented in the 
test_vfstrace.c
source file) that writes a message associated with each VFS method call
into a log file, then passes control off to another VFS to do the actual
work.


c2: The SQLite OS Interface or "VFS"
c3: 3.5. Other Example VFSes
c5: vfs.html#other_example_vfses
c4:
The following are other VFS implementations available in the public
SQLite source tree:




appendvfs.c -
This VFS allows an SQLite database to be appended to the end of some
other file.  This can be used, for example, to append an SQLite database
onto the end of an executable such that, when run, it can easily
locate the appended database. The command-line shell will use this
VFS if launched with the --append option, and its .archive command
will use it given the --append flag.


test_demovfs.c - 
This file implements a very simple VFS named "demo" that uses POSIX 
functions such as
open(), read(), write(), fsync(), close(), fsync(), sleep(), time(),
and so forth.  This VFS only works on unix systems.  But it is not
intended as a replacement for the standard "unix" VFS used by default
on unix platforms.  The "demo" VFS is deliberately kept very simple
so that it can be used as a learning aid or as template for building
other VFSes or for porting SQLite to new operating systems.


test_quota.c - 
This file implements a shim called "quota" that enforces cumulative
file size limits on a collection of database files.  An auxiliary
interface is used to define "quota groups".  A quota group is a
set of files (database files, journals, and temporary files) whose
names all match a GLOB pattern.  The sum of the sizes of all files
in each quota group is tracked, and if that sum exceeds a threshold
defined for the quota group, a callback function is invoked.  That
callback can either increase the threshold or cause the operation
that would have exceeded the quota to fail with an 
SQLITE_FULL error.  One of the uses of this shim is used to enforce 
resource limits on application databases in Firefox.


test_multiplex.c - 
This file implements a shim that allows database files to exceed the
maximum file size of the underlying filesystem.  This shim presents
an interface to the upper six layers of SQLite that makes it look like
very large files are being used, when in reality each such large file
is split up into many smaller files on the underlying system.
This shim has been used, for example, to allow databases to grow
larger than 2 gibibytes on FAT16 filesystems.


test_onefile.c - 
This file implements a demonstration VFS named "fs" that shows how SQLite 
can be used on an embedded device that lacks a filesystem.  Content is
written directly to the underlying media.  A VFS derived from this
demonstration code could be used by a gadget with a limited amount of
flash memory to make SQLite behave as the filesystem for the flash memory
on the device.


test_journal.c - 
This file implements a shim used during SQLite testing that verifies that
the database and rollback journal are written in the correct order and
are "synced" at appropriate times in order to guarantee that the database
can recover from a power lose are hard reset at any time.  The shim
checks several invariants on the operation of databases and rollback
journals and raises exceptions if any of those invariants are violated.
These invariants, in turn, assure that the database is always recoverable.
Running a large suite of test cases using this shim provides added
assurance that SQLite databases will not be damaged by unexpected
power failures or device resets.


test_vfs.c - 
This file implements a shim that can be used to simulate filesystem faults.
This shim is used during testing to verify that SQLite responses sanely
to hardware malfunctions or to other error conditions such as running out
of filesystem space that are difficult to test on a real system.



There are other VFS implementations both in the core SQLite source code
library and in available extensions.  The list above is not meant to be
exhaustive but merely representative of the kinds of features that can
be realized using the VFS interface.


c2: The SQLite OS Interface or "VFS"
c3: 4. VFS Implementations
c5: vfs.html#vfs_implementations
c4:
A new VFS is implemented by subclassing three objects:



sqlite3_vfs
sqlite3_io_methods
sqlite3_file



An sqlite3_vfs object defines the name of the VFS and the core
methods that implement the interface to the operating system, such
as checking for existence of files, deleting files, creating files
and opening and for reading and/or writing, converting filenames
into their canonical form.  The sqlite3_vfs object also contains
methods for obtaining randomness from the operating system, for
suspending a process (sleeping) and for finding the current date and
time.



The sqlite3_file object represents an open file.
The xOpen method of sqlite3_vfs constructs an sqlite3_file
object when the file is opened.  The sqlite3_file keeps track
of the state of the file while it is opened.



The sqlite3_io_methods object holds the methods used to interact
with an open file.  Each sqlite3_file contains a pointer to 
an sqlite3_io_methods object that is appropriate for the file it
represents.  The sqlite3_io_methods object contains methods to do
things such as read and write from the file, to truncate the file,
to flush any changes to persistent storage, to find the size of the
file, to lock and unlock the file, and to close file and destroy
the sqlite3_file object.



Writing the code for a new VFS involves constructing a subclass for
the sqlite3_vfs object and then registering that VFS object using
a call to sqlite3_vfs_register().  The VFS implementation also
provides subclasses for sqlite3_file and sqlite3_io_methods but
those objects are not registered directly with SQLite.  Instead, the
sqlite3_file object is returned from the xOpen method of
sqlite3_vfs and the sqlite3_file object points to an instance
of the sqlite3_io_methods object.


c2: An Introduction To The SQLite C/C++ Interface
c3: 1. Summary
c5: cintro.html#summary
c4:
The following two objects and eight methods comprise the essential
elements of the SQLite interface:


sqlite3 &rarr;
The database connection object.  Created by
sqlite3_open() and destroyed by sqlite3_close().

sqlite3_stmt &rarr;
The prepared statement object.  Created by
sqlite3_prepare() and destroyed by sqlite3_finalize().


sqlite3_open() &rarr;
Open a connection to a new or existing SQLite database.
The constructor for sqlite3.

sqlite3_prepare() &rarr;
Compile SQL text into
byte-code that will do the work of querying or updating the database. 
The constructor for sqlite3_stmt.

sqlite3_bind() &rarr;
Store application data into
parameters of the original SQL.


sqlite3_step() &rarr;
Advance an sqlite3_stmt to the next result row or to completion.

sqlite3_column() &rarr;
Column values in the current result row for an sqlite3_stmt.

sqlite3_finalize() &rarr;
Destructor for sqlite3_stmt.

sqlite3_close() &rarr;
Destructor for sqlite3.

sqlite3_exec() &rarr;
A wrapper function that does sqlite3_prepare(), sqlite3_step(),
sqlite3_column(), and sqlite3_finalize() for
a string of one or more SQL statements.


c2: An Introduction To The SQLite C/C++ Interface
c3: 2. Introduction
c5: cintro.html#introduction
c4:
SQLite has more than 225 APIs.
  However, most of the APIs are optional and very specialized
  and can be ignored by beginners.
  The core API is small, simple, and easy to learn.
  This article summarizes the core API.



  A separate document, The SQLite C/C++ Interface,
  provides detailed
  specifications for all C/C++ APIs for SQLite.  Once
  the reader
  understands the basic principles of operation for SQLite, 
  that document should be used as a reference
  guide.  This article is intended as introduction only and is neither a
  complete nor authoritative reference for the SQLite API.


c2: An Introduction To The SQLite C/C++ Interface
c3: 3. Core Objects And Interfaces
c5: cintro.html#core_objects_and_interfaces
c4:
The principal task of an SQL database engine is to evaluate SQL statements
  of SQL.  To accomplish this, the developer needs two objects:



   The database connection object: sqlite3 
   The prepared statement object: sqlite3_stmt 



  Strictly speaking, the prepared statement object is not required since
  the convenience wrapper interfaces, sqlite3_exec or
  sqlite3_get_table, can be used and these convenience wrappers
  encapsulate and hide the prepared statement object.
  Nevertheless, an understanding of
  prepared statements is needed to make full use of SQLite.



  The database connection and prepared statement objects are controlled
  by a small set of C/C++ interface routine listed below.



   sqlite3_open() 
   sqlite3_prepare() 
   sqlite3_step() 
   sqlite3_column() 
   sqlite3_finalize() 
   sqlite3_close() 



  Note that the list of routines above is conceptual rather than actual.
  Many of these routines come in multiple versions.
  For example, the list above shows a single routine
  named sqlite3_open() when in fact there are three separate routines
  that accomplish the same thing in slightly different ways:
  sqlite3_open(), sqlite3_open16() and sqlite3_open_v2().
  The list mentions sqlite3_column()
  when in fact no such routine exists.
  The "sqlite3_column()" shown in the list is a placeholder for
  an entire family of routines that extra column
  data in various datatypes.



  Here is a summary of what the core interfaces do:




sqlite3_open()

  This routine 
  opens a connection to an SQLite database file and returns a
  database connection object.  This is often the first SQLite API
  call that an application makes and is a prerequisite for most other
  SQLite APIs.  Many SQLite interfaces require a pointer to
  the database connection object as their first parameter and can
  be thought of as methods on the database connection object.
  This routine is the constructor for the database connection object.


sqlite3_prepare()

  This routine
  converts SQL text into a prepared statement object and returns a pointer
  to that object.  This interface requires a database connection pointer
  created by a prior call to sqlite3_open() and a text string containing
  the SQL statement to be prepared.  This API does not actually evaluate
  the SQL statement.  It merely prepares the SQL statement for evaluation.

  Think of each SQL statement as a small computer program.  The purpose
  of sqlite3_prepare() is to compile that program into object code.
  The prepared statement is the object code.  The sqlite3_step() interface
  then runs the object code to get a result.

  New applications should always invoke sqlite3_prepare_v2() instead
  of sqlite3_prepare().  The older sqlite3_prepare() is retained for
  backwards compatibility.  But sqlite3_prepare_v2() provides a much
  better interface.

sqlite3_step()

  This routine is used to evaluate a prepared statement that has been
  previously created by the sqlite3_prepare() interface.  The statement
  is evaluated up to the point where the first row of results are available.
  To advance to the second row of results, invoke sqlite3_step() again.
  Continue invoking sqlite3_step() until the statement is complete.
  Statements that do not return results (ex: INSERT, UPDATE, or DELETE
  statements) run to completion on a single call to sqlite3_step().

sqlite3_column()

  This routine returns a single column from the current row of a result
  set for a prepared statement that is being evaluated by sqlite3_step().
  Each time sqlite3_step() stops with a new result set row, this routine
  can be called multiple times to find the values of all columns in that row.
  
  As noted above, there really is no such thing as a "sqlite3_column()"
  function in the SQLite API.  Instead, what we here call "sqlite3_column()"
  is a place-holder for an entire family of functions that return
  a value from the result set in various data types.  There are also routines
  in this family that return the size of the result (if it is a string or
  BLOB) and the number of columns in the result set.  

  
     sqlite3_column_blob() 
     sqlite3_column_bytes() 
     sqlite3_column_bytes16() 
     sqlite3_column_count() 
     sqlite3_column_double() 
     sqlite3_column_int() 
     sqlite3_column_int64() 
     sqlite3_column_text() 
     sqlite3_column_text16() 
     sqlite3_column_type() 
     sqlite3_column_value() 
  


sqlite3_finalize()

  This routine destroys a prepared statement created by a prior call
  to sqlite3_prepare().  Every prepared statement must be destroyed using
  a call to this routine in order to avoid memory leaks.

sqlite3_close()

  This routine closes a database connection previously opened by a call
  to sqlite3_open().  All prepared statements associated with the
  connection should be finalized prior to closing the
  connection.


c2: An Introduction To The SQLite C/C++ Interface
c3: 4. Typical Usage Of Core Routines And Objects
c5: cintro.html#typical_usage_of_core_routines_and_objects
c4:
An application will typically use
  sqlite3_open() to create a single database connection
  during initialization.
  Note that sqlite3_open() can be used to either open existing database
  files or to create and open new database files.
  While many applications use only a single database connection, there is
  no reason why an application cannot call sqlite3_open() multiple times
  in order to open multiple database connections - either to the same
  database or to different databases.  Sometimes a multi-threaded application
  will create separate database connections for each thread.
  Note that a single database connection can access two or more
  databases using the ATTACH SQL command, so it is not necessary to
  have a separate database connection for each database file.



  Many applications destroy their database connections using calls to
  sqlite3_close() at shutdown.  Or, for example, an application that
  uses SQLite as its application file format might
  open database connections in response to a File/Open menu action
  and then destroy the corresponding database connection in response
  to the File/Close menu.



  To run an SQL statement, the application follows these steps:



   Create a prepared statement using sqlite3_prepare(). 
   Evaluate the prepared statement by calling sqlite3_step() one
       or more times. 
   For queries, extract results by calling 
       sqlite3_column() in between
       two calls to sqlite3_step(). 
   Destroy the prepared statement using sqlite3_finalize(). 



  The foregoing is all one really needs to know in order to use SQLite
  effectively.  All the rest is optimization and detail.


c2: An Introduction To The SQLite C/C++ Interface
c3: 5. Convenience Wrappers Around Core Routines
c5: cintro.html#convenience_wrappers_around_core_routines
c4:
The sqlite3_exec() interface is a convenience wrapper that carries out
  all four of the above steps with a single function call.  A callback
  function passed into sqlite3_exec() is used to process each row of
  the result set.  The sqlite3_get_table() is another convenience wrapper
  that does all four of the above steps.  The sqlite3_get_table() interface
  differs from sqlite3_exec() in that it stores the results of queries
  in heap memory rather than invoking a callback.



  It is important to realize that neither sqlite3_exec() nor
  sqlite3_get_table() do anything that cannot be accomplished using
  the core routines.  In fact, these wrappers are implemented purely in
  terms of the core routines.


c2: An Introduction To The SQLite C/C++ Interface
c3: 6. Binding Parameters and Reusing Prepared Statements
c5: cintro.html#binding_parameters_and_reusing_prepared_statements
c4:
In prior discussion, it was assumed that each SQL statement is prepared
  once, evaluated, then destroyed.  However, SQLite allows the same
  prepared statement to be evaluated multiple times.  This is accomplished
  using the following routines:



   sqlite3_reset() 
   sqlite3_bind() 



  After a prepared statement has been evaluated by one or more calls to
  sqlite3_step(), it can be reset in order to be evaluated again by a
  call to sqlite3_reset().
  Think of sqlite3_reset() as rewinding the prepared statement program
  back to the beginning.
  Using sqlite3_reset() on an existing prepared statement rather than
  creating a new prepared statement avoids unnecessary calls to
  sqlite3_prepare().
  For many SQL statements, the time needed
  to run sqlite3_prepare() equals or exceeds the time needed by
  sqlite3_step().  So avoiding calls to sqlite3_prepare() can give
  a significant performance improvement.



  It is not commonly useful to evaluate the exact same SQL
  statement more than once.  More often, one wants to evaluate similar
  statements.  For example, you might want to evaluate an INSERT statement
  multiple times with different values.  Or you might want to evaluate
  the same query multiple times using a different key in the WHERE clause.
  To accommodate
  this, SQLite allows SQL statements to contain parameters
  which are "bound" to values prior to being evaluated.  These values can
  later be changed and the same prepared statement can be evaluated
  a second time using the new values.



  SQLite allows a parameter wherever
  a string literal, numeric constant, or NULL is allowed.
  (Parameters may not be used for column or table names.)
  A parameter takes one of the following forms:



   ? 
   ?NNN 
   :AAA 
   $AAA 
   @AAA 



  In the examples above, NNN is an integer value and
  AAA is an identifier.
  A parameter initially has a value of NULL.
  Prior to calling sqlite3_step() for the first time or immediately
  after sqlite3_reset(), the application can invoke the
  sqlite3_bind() interfaces to attach values
  to the parameters.  Each call to sqlite3_bind()
  overrides prior bindings on the same parameter.



  An application is allowed to prepare multiple SQL statements in advance
  and evaluate them as needed.
  There is no arbitrary limit to the number of outstanding
  prepared statements.
  Some applications call sqlite3_prepare() multiple times at start-up to
  create all of the prepared statements they will ever need.  Other
  applications keep a cache of the most recently used prepared statements
  and then reuse prepared statements out of the cache when available.
  Another approach is to only reuse prepared statements when they are
  inside of a loop.


c2: An Introduction To The SQLite C/C++ Interface
c3: 7. Configuring SQLite
c5: cintro.html#configuring_sqlite
c4:
The default configuration for SQLite works great for most applications.
  But sometimes developers want to tweak the setup to try to squeeze out
  a little more performance, or take advantage of some obscure feature.

  The sqlite3_config() interface is used to make global, process-wide
  configuration changes for SQLite.  The sqlite3_config() interface must
  be called before any database connections are created.  The
  sqlite3_config() interface allows the programmer to do things like:

Adjust how SQLite does memory allocation, including setting up
    alternative memory allocators appropriate for safety-critical
    real-time embedded systems and application-defined memory allocators.
Set up a process-wide error log.
Specify an application-defined page cache.
Adjust the use of mutexes so that they are appropriate for various
    threading models, or substitute an 
    application-defined mutex system.
 

  After process-wide configuration is complete and database connections
  have been created, individual database connections can be configured using
  calls to sqlite3_limit() and sqlite3_db_config().


c2: An Introduction To The SQLite C/C++ Interface
c3: 8. Extending SQLite
c5: cintro.html#extending_sqlite
c4:
SQLite includes interfaces that can be used to extend its functionality.
  Such routines include:



   sqlite3_create_collation() 
   sqlite3_create_function() 
   sqlite3_create_module() 
   sqlite3_vfs_register() 



  The sqlite3_create_collation() interface is used to create new
  collating sequences for sorting text.
  The sqlite3_create_module() interface is used to register new
  virtual table implementations.
  The sqlite3_vfs_register() interface creates new VFSes.



  The sqlite3_create_function() interface creates new SQL functions - 
  either scalar or aggregate.  The new function implementation typically
  makes use of the following additional interfaces:



   sqlite3_aggregate_context() 
   sqlite3_result() 
   sqlite3_user_data() 
   sqlite3_value() 



  All of the built-in SQL functions of SQLite are created using exactly
  these same interfaces.  Refer to the SQLite source code, and in particular
  the 
  date.c and
  func.c source files
  for examples.



  Shared libraries or DLLs can be used as loadable extensions to SQLite.


c2: An Introduction To The SQLite C/C++ Interface
c3: 9. Other Interfaces
c5: cintro.html#other_interfaces
c4:
This article only mentions the most important and most commonly
  used SQLite interfaces.
  The SQLite library includes many other APIs implementing useful
  features that are not described here.  
  A complete list of functions that form the SQLite
  application programming interface is found at the
  C/C++ Interface Specification.
  Refer to that document for complete and authoritative information about
  all SQLite interfaces.


c2: Many Small Queries Are Efficient In SQLite
c3: 1. Executive Summary
c5: np1queryprob.html#executive_summary
c4:
200 SQL statements per webpage is excessive for client/server database
engines like MySQL, PostgreSQL, or SQL Server.


But with SQLite, 200 or more SQL statement per webpage is not a problem.


SQLite can also do large and complex queries efficiently, just like
client/server databases.  But SQLite can do many smaller queries
efficiently too.  Application developers can use whichever technique
works best for the task at hand.


c2: Many Small Queries Are Efficient In SQLite
c3: 2. The Perceived Problem
c5: np1queryprob.html#the_perceived_problem
c4:
The Appropriate Uses For SQLite page says that
dynamic pages on the SQLite website typically do about 200 SQL
statements each.
This has provoked criticism from readers.  Examples:



"200 SQL statements is a ridiculously high number for a single page"

"For most sites, 200 queries is way, way, way too much."

"&#91;This is&#93; bad design"



Such criticism would be well-founded for a traditional client/server
database engine, such as MySQL, PostgreSQL, or SQL Server.  In
a client/server database, each SQL statement requires a message
round-trip from the application to the database server and back to
the application.  Doing over 200 round-trip messages, sequentially,
can be a serious performance drag.  This is sometimes called the
"N+1 Query Problem" or the "N+1 Select Problem" and it is an anti-pattern.


c2: Many Small Queries Are Efficient In SQLite
c3: 3. N+1 Queries Are Not A Problem With SQLite
c5: np1queryprob.html#n_1_queries_are_not_a_problem_with_sqlite
c4:
SQLite is not client/server, however.  The SQLite database runs
in the same process address space as the application.  Queries do not
involve message round-trips, only a function call.  The latency
of a single SQL query is far less in SQLite.  Hence, using a large number
of queries with SQLite is not the problem.


c2: Many Small Queries Are Efficient In SQLite
c3: 4. The Need For Over 200 SQL Statements Per Webpage
c5: np1queryprob.html#the_need_for_over_200_sql_statements_per_webpage
c4:
The dynamic webpages on the SQLite website are mostly generated by
the Fossil version control system.
A typical dynamic
page would be a timeline such as https://www.sqlite.org/src/timeline.
A log of all SQL used by the timeline is shown below.


The first group of queries in the log are extracting display options
from the "config" and "global_config" tables of the Fossil database.
Then there is a single complex query that extracts a list of all elements
to be displayed on the timeline.
This "timeline" query demonstrates that SQLite can easily process complex
relational database queries involving multiple tables, subqueries, and
complex WHERE clause constraints, and it can make effective use of indexes
to solve the queries with minimal disk I/O.


Following the single big "timeline" query, 
there are additional queries for each timeline element.
Fossil is using the "N+1 Query" pattern rather than trying
to grab all the information in as few queries as possible.
But that is ok because there is no unnecessary IPC overhead.
At the bottom of
each timeline page, Fossil shows approximately how long it took to generate
the page.  For a 50-entry timeline, the latency is usually less than
25 milliseconds.  Profiling shows that few of those milliseconds
were spent inside the database engine.


Using the N+1 Query pattern in Fossil does not harm the application.  
But the N+1 Query pattern does have benefits.  For one, the
section of the code that creates the timeline query can be
completely separate from the section that prepares each timeline
entry for display.
This provides a separation of responsibility that helps keep the code
simple and easy to maintain.  Secondly, the information
needed for display, and the queries needed to extract that information,
vary according to what type of objects to be shown.  Check-ins need one
set of queries.  Tickets need another set of queries.  Wiki pages need a
different query.  And so forth.  By implementing these queries on-demand
and in the part of the code dealing with the various entities, there is
further separation of responsibility and simplification of the overall 
code base.


So, SQLite is able to do one or two large and complex queries, or it can
do many smaller and simpler queries.  Both are efficient.  An application
can use either or both techniques, depending on what works best for the
situation at hand.


The following is a log of all SQL used to generate one particular
timeline (captured on 2016-09-16):

-- sqlite3_open: /home/drh/sqlite/sqlite/.fslckout
PRAGMA foreign_keys=OFF;
SELECT sql FROM localdb.sqlite_schema WHERE name=='vfile';
-- sqlite3_open: /home/drh/.fossil
PRAGMA foreign_keys=OFF;
SELECT value FROM vvar WHERE name='repository';
ATTACH DATABASE '/home/drh/www/repos/sqlite.fossil' AS 'repository' KEY '';
SELECT value FROM config WHERE name='allow-symlinks';
SELECT value FROM global_config WHERE name='allow-symlinks';
SELECT value FROM config WHERE name='aux-schema';
SELECT 1 FROM config WHERE name='baseurl:http://';
SELECT value FROM config WHERE name='ip-prefix-terms';
SELECT value FROM global_config WHERE name='ip-prefix-terms';
SELECT value FROM config WHERE name='localauth';
SELECT value FROM vvar WHERE name='default-user';
SELECT uid FROM user WHERE cap LIKE '%s%';
SELECT login FROM user WHERE uid=1;
SELECT cap FROM user WHERE login = 'nobody';
SELECT cap FROM user WHERE login = 'anonymous';
SELECT value FROM config WHERE name='public-pages';
SELECT value FROM global_config WHERE name='public-pages';
SELECT value FROM config WHERE name='header';
SELECT value FROM config WHERE name='project-name';
SELECT value FROM config WHERE name='th1-setup';
SELECT value FROM global_config WHERE name='th1-setup';
SELECT value FROM config WHERE name='redirect-to-https';
SELECT value FROM global_config WHERE name='redirect-to-https';
SELECT value FROM config WHERE name='index-page';
SELECT mtime FROM config WHERE name='css';
SELECT mtime FROM config WHERE name='logo-image';
SELECT mtime FROM config WHERE name='background-image';
CREATE TEMP TABLE IF NOT EXISTS timeline(
  rid INTEGER PRIMARY KEY,
  uuid TEXT,
  timestamp TEXT,
  comment TEXT,
  user TEXT,
  isleaf BOOLEAN,
  bgcolor TEXT,
  etype TEXT,
  taglist TEXT,
  tagid INTEGER,
  short TEXT,
  sortby REAL
)
;
INSERT OR IGNORE INTO timeline SELECT
  blob.rid AS blobRid,
  uuid AS uuid,
  datetime(event.mtime,toLocal()) AS timestamp,
  coalesce(ecomment, comment) AS comment,
  coalesce(euser, user) AS user,
  blob.rid IN leaf AS leaf,
  bgcolor AS bgColor,
  event.type AS eventType,
  (SELECT group_concat(substr(tagname,5), ', ') FROM tag, tagxref
    WHERE tagname GLOB 'sym-*' AND tag.tagid=tagxref.tagid
      AND tagxref.rid=blob.rid AND tagxref.tagtype&gt;0) AS tags,
  tagid AS tagid,
  brief AS brief,
  event.mtime AS mtime
 FROM event CROSS JOIN blob
WHERE blob.rid=event.objid
 AND NOT EXISTS(SELECT 1 FROM tagxref WHERE tagid=5 AND tagtype&gt;0 AND rid=blob.rid)
 ORDER BY event.mtime DESC LIMIT 50;
-- SELECT value FROM config WHERE name='timeline-utc';
SELECT count(*) FROM timeline WHERE etype!='div';
SELECT min(timestamp) FROM timeline;
SELECT julianday('2016-09-15 14:54:51',fromLocal());
SELECT EXISTS (SELECT 1 FROM event CROSS JOIN blob WHERE blob.rid=event.objid AND mtime&lt;=2457647.121412037);
SELECT max(timestamp) FROM timeline;
SELECT julianday('2016-09-24 17:42:43',fromLocal());
SELECT EXISTS (SELECT 1 FROM event CROSS JOIN blob WHERE blob.rid=event.objid AND mtime&gt;=2457656.238009259);
SELECT value FROM config WHERE name='search-ci';
SELECT value FROM vvar WHERE name='checkout';
SELECT value FROM config WHERE name='timeline-max-comment';
SELECT value FROM global_config WHERE name='timeline-max-comment';
SELECT value FROM config WHERE name='timeline-date-format';
SELECT value FROM config WHERE name='timeline-truncate-at-blank';
SELECT value FROM global_config WHERE name='timeline-truncate-at-blank';
SELECT * FROM timeline ORDER BY sortby DESC;
SELECT value FROM config WHERE name='hash-digits';
SELECT value FROM global_config WHERE name='hash-digits';
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68028;
SELECT pid FROM plink WHERE cid=68028 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM tagxref WHERE rid=68028 AND tagid=9 AND tagtype&gt;0;
SELECT value FROM config WHERE name='timeline-block-markup';
SELECT value FROM config WHERE name='timeline-plaintext';
SELECT value FROM config WHERE name='wiki-use-html';
SELECT value FROM global_config WHERE name='wiki-use-html';
SELECT 1 FROM private WHERE rid=68028;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68026;
SELECT pid FROM plink WHERE cid=68026 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68026;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68024;
SELECT pid FROM plink WHERE cid=68024 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68024;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68018;
SELECT pid FROM plink WHERE cid=68018 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68018;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68012;
SELECT pid FROM plink WHERE cid=68012 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68012;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68011;
SELECT value FROM config WHERE name='details';
SELECT pid FROM plink WHERE cid=68011 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM tagxref WHERE rid=68011 AND tagid=9 AND tagtype&gt;0;
SELECT 1 FROM private WHERE rid=68011;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68008;
SELECT pid FROM plink WHERE cid=68008 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68008;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68006;
SELECT pid FROM plink WHERE cid=68006 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68006;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=68000;
SELECT pid FROM plink WHERE cid=68000 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=68000;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67997;
SELECT pid FROM plink WHERE cid=67997 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67997;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67992;
SELECT pid FROM plink WHERE cid=67992 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67992;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67990;
SELECT pid FROM plink WHERE cid=67990 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67990;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67989;
SELECT pid FROM plink WHERE cid=67989 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67989;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67984;
SELECT pid FROM plink WHERE cid=67984 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67984;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67983;
SELECT pid FROM plink WHERE cid=67983 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67983;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67979;
SELECT pid FROM plink WHERE cid=67979 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67979;
SELECT value FROM config WHERE name='ticket-closed-expr';
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='1ec41379c9c1e400' AND tkt_uuid&lt;'1ec41379c9c1e401';
SELECT 1 FROM private WHERE rid=67980;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67977;
SELECT pid FROM plink WHERE cid=67977 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='1ec41379c9c1e400' AND tkt_uuid&lt;'1ec41379c9c1e401';
SELECT 1 FROM private WHERE rid=67977;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='1ec41379c9c1e400' AND tkt_uuid&lt;'1ec41379c9c1e401';
SELECT 1 FROM private WHERE rid=67974;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67971;
SELECT pid FROM plink WHERE cid=67971 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67971;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67972;
SELECT pid FROM plink WHERE cid=67972 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67972;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67969;
SELECT pid FROM plink WHERE cid=67969 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67969;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67966;
SELECT pid FROM plink WHERE cid=67966 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67966;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67962;
SELECT pid FROM plink WHERE cid=67962 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67962;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67960;
SELECT pid FROM plink WHERE cid=67960 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67960;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67957;
SELECT pid FROM plink WHERE cid=67957 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67957;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67955;
SELECT pid FROM plink WHERE cid=67955 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67955;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67953;
SELECT pid FROM plink WHERE cid=67953 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='5990a1bdb4a073' AND tkt_uuid&lt;'5990a1bdb4a074';
SELECT 1 FROM blob WHERE uuid&gt;='5990a1bdb4a073' AND uuid&lt;'5990a1bdb4a074';
SELECT 1 FROM private WHERE rid=67953;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67941;
SELECT pid FROM plink WHERE cid=67941 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67941;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67940;
SELECT pid FROM plink WHERE cid=67940 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67940;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67938;
SELECT pid FROM plink WHERE cid=67938 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67938;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67935;
SELECT pid FROM plink WHERE cid=67935 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67935;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67934;
SELECT pid FROM plink WHERE cid=67934 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67934;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67932;
SELECT pid FROM plink WHERE cid=67932 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67932;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67930;
SELECT pid FROM plink WHERE cid=67930 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67930;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67928;
SELECT pid FROM plink WHERE cid=67928 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM tagxref WHERE rid=67928 AND tagid=9 AND tagtype&gt;0;
SELECT 1 FROM private WHERE rid=67928;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='0eab1ac7591f511d' AND tkt_uuid&lt;'0eab1ac7591f511e';
SELECT 1 FROM private WHERE rid=67919;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='01874d252ac44861' AND tkt_uuid&lt;'01874d252ac44862';
SELECT 1 FROM blob WHERE uuid&gt;='01874d252ac44861' AND uuid&lt;'01874d252ac44862';
SELECT 1 FROM private WHERE rid=67918;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67916;
SELECT pid FROM plink WHERE cid=67916 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='0eab1ac759' AND tkt_uuid&lt;'0eab1ac75:';
SELECT 1 FROM private WHERE rid=67916;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='a49bc0a8244feb08' AND tkt_uuid&lt;'a49bc0a8244feb09';
SELECT 1 FROM blob WHERE uuid&gt;='a49bc0a8244feb08' AND uuid&lt;'a49bc0a8244feb09';
SELECT 1 FROM private WHERE rid=67914;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67913;
SELECT pid FROM plink WHERE cid=67913 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='0eab1ac7591f' AND tkt_uuid&lt;'0eab1ac7591g';
SELECT 1 FROM private WHERE rid=67913;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67911;
SELECT pid FROM plink WHERE cid=67911 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67911;
SELECT status='Closed' OR status='Fixed' FROM ticket  WHERE tkt_uuid&gt;='0eab1ac7591f511d' AND tkt_uuid&lt;'0eab1ac7591f511e';
SELECT 1 FROM private WHERE rid=67909;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67907;
SELECT pid FROM plink WHERE cid=67907 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67907;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67899;
SELECT pid FROM plink WHERE cid=67899 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67899;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67897;
SELECT pid FROM plink WHERE cid=67897 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67897;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67895;
SELECT pid FROM plink WHERE cid=67895 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67895;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67893;
SELECT pid FROM plink WHERE cid=67893 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67893;
SELECT value FROM tagxref WHERE tagid=8 AND tagtype&gt;0 AND rid=67891;
SELECT pid FROM plink WHERE cid=67891 AND pid NOT IN phantom ORDER BY isprim DESC;
SELECT 1 FROM private WHERE rid=67891;
SELECT count(*) FROM plink
 WHERE pid=67928 AND isprim
   AND coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.pid), 'trunk')
      =coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.cid), 'trunk')
;
SELECT count(*) FROM plink
 WHERE pid=68011 AND isprim
   AND coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.pid), 'trunk')
      =coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.cid), 'trunk')
;
SELECT count(*) FROM plink
 WHERE pid=68028 AND isprim
   AND coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.pid), 'trunk')
      =coalesce((SELECT value FROM tagxref
                  WHERE tagid=8 AND rid=plink.cid), 'trunk')
;
SELECT value FROM config WHERE name='show-version-diffs';
SELECT value FROM config WHERE name='adunit-omit-if-admin';
SELECT value FROM global_config WHERE name='adunit-omit-if-admin';
SELECT value FROM config WHERE name='adunit-omit-if-user';
SELECT value FROM global_config WHERE name='adunit-omit-if-user';
SELECT value FROM config WHERE name='adunit';
SELECT value FROM global_config WHERE name='adunit';
SELECT value FROM config WHERE name='auto-hyperlink-delay';
SELECT value FROM global_config WHERE name='auto-hyperlink-delay';
SELECT value FROM config WHERE name='footer';
PRAGMA database_list;
PRAGMA database_list;
PRAGMA localdb.freelist_count;
PRAGMA localdb.page_count;


c2: Uniform Resource Identifiers
c3: 1. URI Filenames In SQLite
c5: uri.html#uri_filenames_in_sqlite
c4:
Beginning with version 3.7.7 (2011-06-23),
the SQLite database file argument to the
sqlite3_open(), sqlite3_open16(), and sqlite3_open_v2() interfaces
and to the ATTACH command can be specified
either as an ordinary filename or as a Uniform Resource Identifier or URI.
The advantage of using a URI filename is that query parameters on the URI can
be used to control details of the newly created database connection.
For example, an alternative VFS can be specified using a 
"vfs=" query parameter.
Or the database can be opened read-only by using "mode=ro" as a query
parameter.


c2: Uniform Resource Identifiers
c3: 2. Backwards Compatibility
c5: uri.html#backwards_compatibility
c4:
In order to maintain full backwards compatibility for legacy applications,
the URI filename capability is disabled by default.
URI filenames can be enabled or disabled using the SQLITE_USE_URI=1
or SQLITE_USE_URI=0 compile-time options.
The compile-time setting for URI filenames can be changed
at start-time using the sqlite3_config(SQLITE_CONFIG_URI,1)
or sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
Regardless of the compile-time or start-time settings, URI filenames
can be enabled for individual database connections by including the
SQLITE_OPEN_URI bit in the set of bits passed as the F parameter
to sqlite3_open_v2(N,P,F,V).



If URI filenames are recognized when the database connection is originally
opened, then URI filenames will also be recognized on ATTACH statements.
Similarly, if URI filenames are not recognized when the database connection
is first opened, they will not be recognized by ATTACH.



Since SQLite always interprets any filename that does not begin
with "file:"
as an ordinary filename regardless of the URI setting, and because it is
very unusual to have an actual file begin with "file:", 
it is safe for most applications to enable URI processing even if URI 
filenames are not currently being used.


c2: Uniform Resource Identifiers
c3: 3. URI Format
c5: uri.html#uri_format
c4:
According to RFC 3986, a URI consists
of a scheme, an authority, a path, a query string, and a fragment.  The
scheme is always required.  One of either the authority or the path is also
always required.  The query string and fragment are optional.



SQLite uses the "file:" URI syntax to identify database files.
SQLite strives to interpret file: URIs in exactly the same way as
popular web-browsers such as 
Firefox, 
Chrome, 
Safari, 
Internet Explorer, and
Opera,
and command-line programs such as 
Windows "start" and the Mac OS-X
"open" command.
A succinct summary of the URI parsing rules follows:



 The scheme of the URI must be "file:".  Any other scheme
     results in the input being treated as an ordinary filename.
 The authority may be omitted, may be blank, or may be
      "localhost".  Any other authority results in an error.
      Exception: If SQLite is compiled with SQLITE_ALLOW_URI_AUTHORITY
      then any authority value other than "localhost" is passed through to the 
      underlying operating system as a UNC filename.
 The path is optional if the authority is present.  If the authority
     is omitted then the path is required. 
 The query string is optional.  If the query string is present, then
      all query parameters are passed through into the xOpen method of
      the underlying VFS.  
 The fragment is optional.  If present, it is ignored.


Zero or more escape sequences of the form  "%HH" 
(where H represents any hexadecimal digit) can occur 
in the path, query string, or fragment.

A filename that is not a well-formed URI is interpreted as an
ordinary filename.

URIs are processed as UTF8 text.
The filename argument sqlite3_open16() is converted from UTF16 
native byte order into UTF8 prior to processing.


c2: Uniform Resource Identifiers
c3: 3.1. The URI Path
c5: uri.html#the_uri_path
c4:
The path component of the URI specifies the disk file that is the
SQLite database to be opened.  If the path component is omitted, then
the database is stored in a temporary file that will be automatically
deleted when the database connection closes.  If the authority section
is present, then the path is always an absolute pathname.  If the 
authority section is omitted, then the path is an absolute pathname if it
begins with the "/" character (ASCII code 0x2f) and is a relative
pathname otherwise.  On windows, if the absolute path begins with
"/X:/" where X is any single ASCII alphabetic
character ("a" through "z" or "A" through "Z") then the "X:"
is understood to be the drive letter of the volume containing the file,
not the toplevel directory.

An ordinary filename can usually be converted into an equivalent URI 
by the steps shown below.  The one exception is that a relative windows
pathname with a drive letter cannot be converted directly into a URI; it must
be changed into an absolute pathname first.


Convert all "?" characters into "%3f".
Convert all "#" characters into "%23".
On windows only, convert all "\" characters into "/".
Convert all sequences of two or more "/" characters into a
    single "/" character.
On windows only, if the filename begins with a drive letter, prepend
    a single "/" character.
Prepend the "file:" scheme.


c2: Uniform Resource Identifiers
c3: 3.2. Query String
c5: uri.html#query_string
c4:
A URI filename can optionally be followed by a query string.
The query string consists of text following the first "?"
character but excluding the optional fragment that begins with
"#".  The query string is divided into key/value pairs.
We usually refer to these key/value pairs as "query parameters".
Key/value pairs are separated by a single "&amp;" character.
The key comes first and is separated from the value by a single
"=" character.
Both key and value may contain %HH escape sequences.


The text of query parameters is appended to the filename argument of
the xOpen method of the VFS.
Any %HH escape sequences in the query parameters are resolved prior to
being appended to the xOpen filename.
A single zero-byte separates the xOpen filename argument from the key of
the first query parameters, each key and value, and each subsequent key
from the prior value.
The list of query parameters appended to the xOpen filename
is terminated by a single zero-length key.
Note that the value of a query parameter can be an empty string.


c2: Uniform Resource Identifiers
c3: 3.3. Recognized Query Parameters
c5: uri.html#recognized_query_parameters
c4:
Some query parameters are interpreted by the SQLite core and used to 
modify the characteristics of the new connection.  All query parameters
are always passed through into the xOpen method of the VFS even if
they are previously read and interpreted by the SQLite core.



The following query parameters are recognized by SQLite as of 
version 3.15.0 (2016-10-14).
New query parameters might be added in the future.





cache=sharedcache=private
The cache query parameter determines if the new database is opened
using shared cache mode or with a private cache.




immutable=1
The immutable query parameter is a boolean that signals to
SQLite that the underlying database file is held on read-only media
and cannot be modified, even by another process with elevated 
privileges.  SQLite always opens immutable database files
read-only and it skips all file locking and change detection
on immutable database files.  If this query parameter (or
the SQLITE_IOCAP_IMMUTABLE bit in xDeviceCharacteristics)
asserts that a database file is immutable and that file 
changes anyhow, then SQLite might return incorrect query 
results and/or SQLITE_CORRUPT errors.




mode=romode=rwmode=rwcmode=memory
The mode query parameter determines if the new database is opened
read-only, read-write, read-write and created if it does not exist, or
that the database is a pure in-memory database that never interacts with
disk, respectively.




modeof=filename
When creating a new database file during sqlite3_open_v2()
on unix systems, SQLite will try to set the permissions of the new
database file to match the existing file "filename".




nolock=1
The nolock query parameter is a boolean that disables all calls
to the xLock, xUnlock, and xCheckReservedLock methods of the VFS when true.
The nolock query parameter might be used, for example, when trying to
access a file on a filesystem that does not support file locking.
Caution:  If two or more database connections try to interact with 
the same SQLite database and one or more of those connections has
enabled "nolock", then database corruption can result.  The "nolock"
query parameter should only be used if the application can guarantee
that writes to the database are serialized.



psow=0psow=1
The psow query parameter overrides the powersafe overwrite
property of the database file being opened.  The psow query parameter
works with the default windows and unix VFSes but might be a no-op for
other proprietary or non-standard VFSes.




vfs=NAME
The vfs query parameter causes the database connection to be opened
using the VFS called NAME.
The open attempt fails if NAME is not the name of a VFS that
is built into SQLite or that has been previously registered using
sqlite3_vfs_register().


c2: Datatypes In SQLite
c3: 1. Datatypes In SQLite
c5: datatype3.html#datatypes_in_sqlite
c4:
Most SQL database engines (every SQL database engine other than SQLite,
as far as we know) uses static, rigid typing.  With static typing, the datatype
of a value is determined by its container - the particular column in
which the value is stored.

SQLite uses a more general dynamic type system.  In SQLite, the datatype
of a value is associated with the value itself, not with its container.
The dynamic type system of SQLite is backwards
compatible with the more common static type systems of other database engines
in the sense that SQL statements that work on statically typed databases
work the same way in SQLite.  However, the dynamic typing in SQLite allows
it to do things which are not possible in traditional rigidly typed
databases.  Flexible typing is a feature of SQLite, not a bug.

Update:
As of version 3.37.0 (2021-11-27), SQLite provides STRICT tables
that do rigid type enforcement, for developers who prefer that kind of thing.


c2: Datatypes In SQLite
c3: 2. Storage Classes and Datatypes
c5: datatype3.html#storage_classes_and_datatypes
c4:
Each value stored in an SQLite database (or manipulated by the
database engine) has one of the following storage classes:

  NULL.
  The value is a NULL value.

  INTEGER. The value is a signed integer, stored in 0, 1,
  2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.

  REAL. The value is a floating point value, stored as
  an 8-byte IEEE floating point number.

  TEXT. The value is a text string, stored using the
  database encoding (UTF-8, UTF-16BE or UTF-16LE).

  BLOB. The value is a blob of data, stored exactly as
  it was input.


A storage class is more general than a datatype.
The INTEGER storage class, for example, includes 7 different integer
datatypes of different lengths.
This makes a difference on disk. 
But as soon as INTEGER values are read off of disk and into memory for
processing, they are converted to the most general datatype
(8-byte signed integer).
And so for the most part, "storage class" is indistinguishable from 
"datatype" and the two terms can be used interchangeably.

Any column in an SQLite version 3 database,
except an INTEGER PRIMARY KEY column, may be used to store a value 
of any storage class.

All values in SQL statements, whether they are literals embedded in SQL
statement text or parameters bound to 
precompiled SQL statements
have an implicit storage class.
Under circumstances described below, the
database engine may convert values between numeric storage classes
(INTEGER and REAL) and TEXT during query execution.


c2: Datatypes In SQLite
c3: 2.1. Boolean Datatype
c5: datatype3.html#boolean_datatype
c4:
SQLite does not have a separate Boolean storage class.
Instead, Boolean values are stored as integers 0 (false) and 1 (true).

SQLite recognizes the keywords "TRUE" and "FALSE",
as of version 3.23.0 (2018-04-02) but those keywords are
really just alternative spellings for the integer literals 1 and 0
respectively.


c2: Datatypes In SQLite
c3: 2.2. Date and Time Datatype
c5: datatype3.html#date_and_time_datatype
c4:
SQLite does not have a storage class set aside for storing
dates and/or times.
Instead, the built-in Date And Time Functions of SQLite are capable of 
storing dates and times as TEXT, REAL, or INTEGER values:


TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
REAL as Julian day numbers, the number of days since
noon in Greenwich on November 24, 4714 B.C. according to the
proleptic Gregorian calendar.
INTEGER as Unix Time, the number of seconds since
1970-01-01 00:00:00 UTC.


Applications can choose to store dates and times in any of these
formats and freely convert between formats using the built-in
date and time functions.


c2: Datatypes In SQLite
c3: 3. Type Affinity
c5: datatype3.html#type_affinity
c4:
SQL database engines that use rigid typing will usually try to
automatically convert values to the appropriate datatype.  Consider this:


CREATE TABLE t1(a INT, b VARCHAR(10));
INSERT INTO t1(a,b) VALUES('123',456);



Rigidly-typed database will convert the string '123' into an
integer 123 and the integer 456 into a string '456' prior to
doing the insert.


In order to maximize compatibility between SQLite and other database
engines, and so that the example above will work on SQLite as it does
on other SQL database engines,
SQLite supports the concept of "type affinity" on columns.
The type affinity of a column is the recommended type for data stored
in that column.  The important idea here is that the type is recommended, not
required.  Any column can still store any type of data.
It is just that some columns, given the choice, will prefer to use
one storage class over another.  The preferred storage class for
a column is called its "affinity".


Each column in an SQLite 3 database is assigned one of the
following type affinities:

	TEXT
	NUMERIC
	INTEGER
        REAL
	BLOB


(Historical note:  The "BLOB" type affinity used to be called "NONE".
But that term was easy to confuse with "no affinity" and so it was
renamed.)

A column with TEXT affinity stores all data using storage classes
NULL, TEXT or BLOB. If numerical data is inserted into a column with
TEXT affinity it is converted into text form before being stored.

A column with NUMERIC affinity may contain values using all five
storage classes.  When text data is inserted into a NUMERIC column, the
storage class of the text is converted to INTEGER or REAL (in order of
preference) if the text is a well-formed integer or real literal, respectively.
If the TEXT value is a well-formed integer literal that is too large
to fit in a 64-bit signed integer, it is converted to REAL.
For conversions between TEXT and REAL storage classes, only the first
15 significant decimal digits of the number are preserved.
If the TEXT value is not a well-formed integer or real literal,
then the value is stored as TEXT.
For the purposes of this paragraph, hexadecimal integer
literals are not considered well-formed and are stored as TEXT.
(This is done for historical compatibility with versions of SQLite
prior to version 3.8.6 2014-08-15 where hexadecimal integer
literals were first introduced into SQLite.)
If a floating point value that can be represented exactly as an integer
is inserted into a column with NUMERIC affinity, the value is
converted into an integer.
No attempt is made to convert NULL or BLOB values.

A string might look like a floating-point literal with
a decimal point and/or exponent notation but as long as
the value can be expressed as an integer, the NUMERIC affinity will convert
it into an integer. Hence, the string '3.0e+5' is stored in a
column with NUMERIC affinity as the integer 300000, not as the floating
point value 300000.0.

A column that uses INTEGER affinity behaves the same as a column
with NUMERIC affinity.  The difference between INTEGER and NUMERIC affinity
is only evident in a CAST expression:  The expression
"CAST(4.0 AS INT)" returns an integer 4, whereas
"CAST(4.0 AS NUMERIC)" leaves the value as a floating-point 4.0.

A column with REAL affinity behaves like a column with NUMERIC
affinity except that it forces integer values into floating point
representation.  (As an internal optimization, small floating point
values with no fractional component and stored in columns with REAL
affinity are written to disk as integers in order to take up less 
space and are automatically converted back into floating point as
the value is read out.
This optimization is completely invisible at the SQL level and can only
be detected by examining the raw bits of the database file.)

A column with affinity BLOB does not prefer one storage class over
another and no attempt is made to coerce data from one storage class into
another.


c2: Datatypes In SQLite
c3: 3.1. Determination Of Column Affinity
c5: datatype3.html#determination_of_column_affinity
c4:
For tables not declared as STRICT,
the affinity of a column is determined by the declared type
of the column, according to the following rules in the order shown:


  If the declared type contains the string "INT" then it
  is assigned INTEGER affinity.

  If the declared type of the column contains any of the strings
  "CHAR", "CLOB", or "TEXT" then that
  column has TEXT affinity.  Notice that the type VARCHAR contains the
  string "CHAR" and is thus assigned TEXT affinity.

  If the declared type for a column
  contains the string "BLOB" or if
  no type is specified then the column has affinity BLOB.

  If the declared type for a column
  contains any of the strings "REAL", "FLOA",
  or "DOUB" then the column has REAL affinity.

  Otherwise, the affinity is NUMERIC.


Note that the order of the rules for determining column affinity
is important.  A column whose declared type is "CHARINT" will match
both rules 1 and 2 but the first rule takes precedence and so the 
column affinity will be INTEGER.


c2: Datatypes In SQLite
c3: 3.1.1. Affinity Name Examples
c5: datatype3.html#affinity_name_examples
c4:
The following table shows how many common datatype names from
more traditional SQL implementations are converted into affinities by the five rules of the
previous section.  This table shows only a small subset of the
datatype names that SQLite will accept.  Note that numeric arguments
in parentheses that following the type name (ex: "VARCHAR(255)") are
ignored by SQLite - SQLite does not impose any length restrictions
(other than the large global SQLITE_MAX_LENGTH limit) on the length of
strings, BLOBs or numeric values.

 

Example Typenames From TheCREATE TABLE Statement
        or CAST Expression
    Resulting Affinity
    Rule Used To Determine Affinity


  INT
  INTEGER
  TINYINT
  SMALLINT
  MEDIUMINT
  BIGINT
  UNSIGNED BIG INT
  INT2
  INT8
INTEGER
1


  CHARACTER(20)
  VARCHAR(255)
  VARYING CHARACTER(255)
  NCHAR(55)
  NATIVE CHARACTER(70)
  NVARCHAR(100)
  TEXT
  CLOB
TEXT
2


  BLOB
  no datatype specified
BLOB
3


  REAL
  DOUBLE
  DOUBLE PRECISION
  FLOAT
REAL
4


  NUMERIC
  DECIMAL(10,5)
  BOOLEAN
  DATE
  DATETIME
NUMERIC
5



Note that a declared type of "FLOATING POINT" would give INTEGER
affinity, not REAL affinity, due to the "INT" at the end of "POINT".
And the declared type of "STRING" has an affinity of NUMERIC, not TEXT.


c2: Datatypes In SQLite
c3: 3.2. Affinity Of Expressions
c5: datatype3.html#affinity_of_expressions
c4:
Every table column has a type affinity (one of BLOB, TEXT, INTEGER,
REAL, or NUMERIC) but expressions do not necessarily have an affinity.

Expression affinity is determined by the following rules:


  The right-hand operand of an IN or NOT IN
  operator has no affinity if the operand is a list, or has the same
  affinity as the affinity of the result set expression if the operand
  is a SELECT.

  When an expression is a simple reference to a column of a
  real table (not a VIEW or subquery) then the expression
  has the same affinity as the table column.
  
  Parentheses around the column name are ignored.  Hence if
  X and Y.Z are column names, then (X) and (Y.Z) are also considered
  column names and have the affinity of the corresponding columns.
  
  Any operators applied to column names, including the no-op 
   unary "+" operator, convert the column name into an expression which
   always has no affinity.  Hence even if X and Y.Z are column names, the
   expressions +X and +Y.Z are not column names and have no affinity.
  

  An expression of the form "CAST(expr AS type)"
  has an affinity that is the same as a column with a declared
  type of "type".

  A COLLATE operator has the same affinity as its left-hand side operand.

  Otherwise, an expression has no affinity.


c2: Datatypes In SQLite
c3: 3.3. Column Affinity For Views And Subqueries
c5: datatype3.html#column_affinity_for_views_and_subqueries
c4:
The "columns" of a VIEW or FROM-clause subquery are really
the expressions
in the result set of the SELECT statement that implements the VIEW
or subquery.  Thus, the affinity for columns of a VIEW or subquery
are determined by the expression affinity rules above.
Consider an example:


CREATE TABLE t1(a INT, b TEXT, c REAL);
CREATE VIEW v1(x,y,z) AS SELECT b, a+c, 42 FROM t1 WHERE b!=11;


The affinity of the v1.x column will be the same as the affinity
of t1.b (TEXT), since v1.x maps directly into t1.b.  But
columns v1.y and v1.z both have no affinity, since those columns
map into expression a+c and 42, and expressions always have no
affinity.


c2: Datatypes In SQLite
c3: 3.3.1. Column Affinity For Compound Views
c5: datatype3.html#column_affinity_for_compound_views
c4:
When the SELECT statement that implements a VIEW or 
FROM-clause subquery is a compound SELECT then the affinity of 
each column of the VIEW or subquery will
be the affinity of the corresponding result column for
one of the individual SELECT statements that make up 
the compound.  
However, it is indeterminate which of the SELECT statements will 
be used to determine affinity.
Different constituent SELECT statements might be used to determine 
affinity at different times during query evaluation.  The choice
might vary across different versions of SQLite.  The choice might
change between one query and the next in the same version of SQLite.
The choice might be different at different times within the same
query.  Hence, you can never be sure what affinity will be used
for columns of a compound SELECT that have different affinities in
the constituent subqueries.

Best practice is to avoid mixing affinities in a compound SELECT
if you care about the datatype of the result.  Mixing affinities in
a compound SELECT can lead to surprising and unintuitive results.
See, for example, forum post 02d7be94d7.


c2: Datatypes In SQLite
c3: 3.4. Column Affinity Behavior Example
c5: datatype3.html#column_affinity_behavior_example
c4:
The following SQL demonstrates how SQLite uses column affinity
to do type conversions when values are inserted into a table.



CREATE TABLE t1(
    t  TEXT,     -- text affinity by rule 2
    nu NUMERIC,  -- numeric affinity by rule 5
    i  INTEGER,  -- integer affinity by rule 1
    r  REAL,     -- real affinity by rule 4
    no BLOB      -- no affinity by rule 3
);

-- Values stored as TEXT, INTEGER, INTEGER, REAL, TEXT.
INSERT INTO t1 VALUES('500.0', '500.0', '500.0', '500.0', '500.0');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|text

-- Values stored as TEXT, INTEGER, INTEGER, REAL, REAL.
DELETE FROM t1;
INSERT INTO t1 VALUES(500.0, 500.0, 500.0, 500.0, 500.0);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|real

-- Values stored as TEXT, INTEGER, INTEGER, REAL, INTEGER.
DELETE FROM t1;
INSERT INTO t1 VALUES(500, 500, 500, 500, 500);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
text|integer|integer|real|integer

-- BLOBs are always stored as BLOBs regardless of column affinity.
DELETE FROM t1;
INSERT INTO t1 VALUES(x'0500', x'0500', x'0500', x'0500', x'0500');
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
blob|blob|blob|blob|blob

-- NULLs are also unaffected by affinity
DELETE FROM t1;
INSERT INTO t1 VALUES(NULL,NULL,NULL,NULL,NULL);
SELECT typeof(t), typeof(nu), typeof(i), typeof(r), typeof(no) FROM t1;
null|null|null|null|null


c2: Datatypes In SQLite
c3: 4. Comparison Expressions
c5: datatype3.html#comparison_expressions
c4:
SQLite version 3 has the usual set of SQL comparison operators
including "=", "==", "&lt;", "&lt;=", "&gt;", "&gt;=", "!=", "",
"IN", "NOT IN", "BETWEEN", "IS", and "IS NOT", .


c2: Datatypes In SQLite
c3: 4.1. Sort Order
c5: datatype3.html#sort_order
c4:
The results of a comparison depend on the storage classes of the
operands, according to the following rules:

  A value with storage class NULL is considered less than any
  other value (including another value with storage class NULL).

  An INTEGER or REAL value is less than any TEXT or BLOB value.
  When an INTEGER or REAL is compared to another INTEGER or REAL, a
  numerical comparison is performed.

  A TEXT value is less than a BLOB value.  When two TEXT values
  are compared an appropriate collating sequence is used to determine 
  the result.  

  When two BLOB values are compared, the result is
  determined using memcmp().


c2: Datatypes In SQLite
c3: 4.2. Type Conversions Prior To Comparison
c5: datatype3.html#type_conversions_prior_to_comparison
c4:
SQLite may attempt to convert values between the storage classes
INTEGER, REAL, and/or TEXT before performing a comparison.
Whether or not any conversions are attempted before the comparison takes
place depends on the type affinity of the operands.

To "apply affinity" means to convert an operand to a particular storage
class if and only if the conversion does not lose essential information.
Numeric values can always be converted into TEXT.  TEXT values 
can be converted into numeric values if the text content is a well-formed 
integer or real literal, but not a hexadecimal integer literal.
BLOB values are converted into TEXT values by simply interpreting
the binary BLOB content as a text string in the current database
encoding.

Affinity is applied to operands of a comparison operator prior to
the comparison according to the following rules in the order shown:


If one operand has INTEGER, REAL or NUMERIC affinity
and the other operand has TEXT or BLOB or no affinity
then NUMERIC affinity is applied to other operand.

If one operand has TEXT affinity and the other has no affinity,
then TEXT affinity is applied to the other operand.

Otherwise, no affinity is applied and both operands are compared
as is.


The expression "a BETWEEN b AND c" is treated as two separate
binary comparisons "a &gt;= b AND a &lt;= c", even if that means
different affinities are applied to 'a' in each of the comparisons.
Datatype conversions in comparisons of the
form "x IN (SELECT y ...)" are handled as if
the comparison were really "x=y".
The expression "a IN (x, y, z, ...)" is equivalent to "a = +x OR
a = +y OR a = +z OR ...".  
In other words, the values to the right of the IN operator (the "x", "y",
and "z" values in this example) are considered to have no affinity, 
even if they happen to be column values or CAST expressions.


c2: Datatypes In SQLite
c3: 4.3. Comparison Example
c5: datatype3.html#comparison_example
c4:
CREATE TABLE t1(
    a TEXT,      -- text affinity
    b NUMERIC,   -- numeric affinity
    c BLOB,      -- no affinity
    d            -- no affinity
);

-- Values will be stored as TEXT, INTEGER, TEXT, and INTEGER respectively
INSERT INTO t1 VALUES('500', '500', '500', 500);
SELECT typeof(a), typeof(b), typeof(c), typeof(d) FROM t1;
text|integer|text|integer

-- Because column "a" has text affinity, numeric values on the
-- right-hand side of the comparisons are converted to text before
-- the comparison occurs.
SELECT a &lt; 40,   a &lt; 60,   a &lt; 600 FROM t1;
0|1|1

-- Text affinity is applied to the right-hand operands but since
-- they are already TEXT this is a no-op; no conversions occur.
SELECT a &lt; '40', a &lt; '60', a &lt; '600' FROM t1;
0|1|1

-- Column "b" has numeric affinity and so numeric affinity is applied
-- to the operands on the right.  Since the operands are already numeric,
-- the application of affinity is a no-op; no conversions occur.  All
-- values are compared numerically.
SELECT b &lt; 40,   b &lt; 60,   b &lt; 600 FROM t1;
0|0|1

-- Numeric affinity is applied to operands on the right, converting them
-- from text to integers.  Then a numeric comparison occurs.
SELECT b &lt; '40', b &lt; '60', b &lt; '600' FROM t1;
0|0|1

-- No affinity conversions occur.  Right-hand side values all have
-- storage class INTEGER which are always less than the TEXT values
-- on the left.
SELECT c &lt; 40,   c &lt; 60,   c &lt; 600 FROM t1;
0|0|0

-- No affinity conversions occur.  Values are compared as TEXT.
SELECT c &lt; '40', c &lt; '60', c &lt; '600' FROM t1;
0|1|1

-- No affinity conversions occur.  Right-hand side values all have
-- storage class INTEGER which compare numerically with the INTEGER
-- values on the left.
SELECT d &lt; 40,   d &lt; 60,   d &lt; 600 FROM t1;
0|0|1

-- No affinity conversions occur.  INTEGER values on the left are
-- always less than TEXT values on the right.
SELECT d &lt; '40', d &lt; '60', d &lt; '600' FROM t1;
1|1|1



All of the results in the example are the same if the comparisons are
commuted - if expressions of the form "a&lt;40" are rewritten
as "40&gt;a".


c2: Datatypes In SQLite
c3: 5. Operators
c5: datatype3.html#operators
c4:
Mathematical operators (+, -, *, /, %, &lt;&lt;, &gt;&gt;,
&amp;, and |) interpret both operands as if they were numbers.
STRING or BLOB operands automatically convert into REAL or INTEGER values.
If the STRING or BLOB looks like a real number (if it has a decimal point
or an exponent) or if the value is outside the range that can be represented
as a 64-bit signed integer, then it converts to REAL.  Otherwise the operand
converts to INTEGER.
The implied type conversion of mathematical operands is slightly different
from CAST to NUMERIC in that string and BLOB values that
look like real numbers but have no fractional part are kept as REAL
instead of being converted into INTEGER as they would be for CAST to NUMERIC.
The conversion from STRING or BLOB into REAL or INTEGER is performed
even if it is lossy and irreversible.
Some mathematical operators (%, &lt;&lt;, &gt;&gt;, &amp;, and |) expect
INTEGER operands.  For those operators, REAL operands are converted into INTEGER
in the same way as a CAST to INTEGER.
The &lt;&lt;, &gt;&gt;, &amp;, and | operators always return an INTEGER (or NULL)
result, but the % operator returns either INTEGER or REAL (or NULL)
depending on the type of its operands.
A NULL operand on a mathematical operator yields a NULL result.
An operand on a mathematical operator that does not look in any way
numeric and is not NULL is converted to 0 or 0.0.
Division by zero gives a result of NULL.


c2: Datatypes In SQLite
c3: 6. Sorting, Grouping and Compound SELECTs
c5: datatype3.html#sorting_grouping_and_compound_selects
c4:
When query results are sorted by an ORDER BY clause, values with storage
class NULL come first, followed by INTEGER and REAL values
interspersed in numeric order, followed by TEXT values in collating
sequence order, and finally BLOB values in memcmp() order.  No storage
class conversions occur before the sort.

When grouping values with the GROUP BY clause values with
different storage classes are considered distinct, except for INTEGER
and REAL values which are considered equal if they are numerically
equal. No affinities are applied to any values as the result of a
GROUP by clause.

The compound SELECT operators UNION,
INTERSECT and EXCEPT perform implicit comparisons between values.
No affinity is applied to comparison operands for the implicit
comparisons associated with UNION, INTERSECT, or EXCEPT - the values
are compared as is.


c2: Datatypes In SQLite
c3: 7. Collating Sequences
c5: datatype3.html#collating_sequences
c4:
When SQLite compares two strings, it uses a collating sequence or
collating function (two terms for the same thing) to determine which
string is greater or if the two strings are equal.
SQLite has three built-in collating functions:  BINARY, NOCASE, and 
RTRIM.


BINARY - Compares string data using memcmp(), regardless
                   of text encoding.
NOCASE - Similar to binary, except that it uses
     sqlite3_strnicmp() for the comparison.  Hence the 26 upper case
     characters of ASCII are folded to their lower case equivalents before
     the comparison is performed.  Note that only ASCII characters
     are case folded.  SQLite does not attempt to do full
     UTF case folding due to the size of the tables required.
     Also note that any U+0000 characters in the string are considered
     string terminators for comparison purposes.

RTRIM - The same as binary, except that trailing space
     characters are ignored.


An application can register additional collating functions using
the sqlite3_create_collation() interface.

Collating functions only matter when comparing string values.
Numeric values are always compared numerically, and BLOBs are always
compared byte-by-byte using memcmp().


c2: Datatypes In SQLite
c3: 7.1. Assigning Collating Sequences from SQL
c5: datatype3.html#assigning_collating_sequences_from_sql
c4:
Every column of every
table has an associated collating function.  If no collating function
is explicitly defined, then the collating function defaults to BINARY.
The COLLATE clause of the column definition is used
to define alternative collating functions for a column.






The rules for determining which collating function to use for a
binary comparison operator (=, &lt;, &gt;, &lt;=, &gt;=, !=, IS, and
IS NOT) are as follows:


If either operand has an explicit collating function assignment
using the postfix COLLATE operator, then the explicit collating function
is used for comparison, with precedence to the collating function of the
left operand.

If either operand is a column, then the collating function of
that column is used with precedence to the left operand.
For the purposes of the previous sentence, a column name
preceded by one or more unary "+" operators and/or CAST operators
is still considered a column name.


Otherwise, the BINARY collating function is used for comparison.




An operand of a comparison is considered to have an explicit
collating function assignment (rule 1 above) 
if any subexpression of the operand uses
the postfix COLLATE operator.  Thus, if a COLLATE operator is used
anywhere in a comparison expression, the collating function defined
by that operator is used for string comparison regardless of what 
table columns might be a part of that expression.  If two or more
COLLATE operator subexpressions appear anywhere in a comparison, the 
left most explicit collating function is used regardless of how deeply the
COLLATE operators are nested in the expression and regardless of
how the expression is parenthesized.



The expression "x BETWEEN y and z" is logically
equivalent to two comparisons "x &gt;= y AND x &lt;= z" and works with
respect to collating functions as if it were two separate comparisons.
The expression "x IN (SELECT y ...)" is handled in the same way as the
expression "x = y" for the purposes of determining the collating sequence.
The collating sequence used for expressions of the form 
"x IN (y, z, ...)" is the collating sequence of x.
If an explicit collating sequence is required on an IN operator
it should be applied to the left operand, like this: 
"x COLLATE nocase IN (y,z, ...)".
  


Terms of the ORDER BY clause that is part of a SELECT
statement may be assigned a collating sequence using the 
COLLATE operator, in which case the specified collating function is
used for sorting.
Otherwise, if the expression sorted by an ORDER BY clause is
a column, then the collating sequence of the column is used to
determine sort order. If the expression is not a column and has no
COLLATE clause, then the BINARY collating sequence is used.


c2: Datatypes In SQLite
c3: 7.2. Collation Sequence Examples
c5: datatype3.html#collation_sequence_examples
c4:
The examples below identify the collating sequences that would be used to
determine the results of text comparisons that may be performed by various
SQL statements. Note that a text comparison may not be required, and no
collating sequence used, in the case of numeric, blob or NULL values.



CREATE TABLE t1(
    x INTEGER PRIMARY KEY,
    a,                 /* collating sequence BINARY */
    b COLLATE BINARY,  /* collating sequence BINARY */
    c COLLATE RTRIM,   /* collating sequence RTRIM  */
    d COLLATE NOCASE   /* collating sequence NOCASE */
);
                   /* x   a     b     c       d */
INSERT INTO t1 VALUES(1,'abc','abc', 'abc  ','abc');
INSERT INTO t1 VALUES(2,'abc','abc', 'abc',  'ABC');
INSERT INTO t1 VALUES(3,'abc','abc', 'abc ', 'Abc');
INSERT INTO t1 VALUES(4,'abc','abc ','ABC',  'abc');
 
/* Text comparison a=b is performed using the BINARY collating sequence. */
SELECT x FROM t1 WHERE a = b ORDER BY x;
--result 1 2 3

/* Text comparison a=b is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE a = b COLLATE RTRIM ORDER BY x;
--result 1 2 3 4

/* Text comparison d=a is performed using the NOCASE collating sequence. */
SELECT x FROM t1 WHERE d = a ORDER BY x;
--result 1 2 3 4

/* Text comparison a=d is performed using the BINARY collating sequence. */
SELECT x FROM t1 WHERE a = d ORDER BY x;
--result 1 4

/* Text comparison 'abc'=c is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE 'abc' = c ORDER BY x;
--result 1 2 3

/* Text comparison c='abc' is performed using the RTRIM collating sequence. */
SELECT x FROM t1 WHERE c = 'abc' ORDER BY x;
--result 1 2 3

/* Grouping is performed using the NOCASE collating sequence (Values
** 'abc', 'ABC', and 'Abc' are placed in the same group). */
SELECT count(*) FROM t1 GROUP BY d ORDER BY 1;
--result 4

/* Grouping is performed using the BINARY collating sequence.  'abc' and
** 'ABC' and 'Abc' form different groups */
SELECT count(*) FROM t1 GROUP BY (d || '') ORDER BY 1;
--result 1 1 2

/* Sorting or column c is performed using the RTRIM collating sequence. */
SELECT x FROM t1 ORDER BY c, x;
--result 4 1 2 3

/* Sorting of (c||'') is performed using the BINARY collating sequence. */
SELECT x FROM t1 ORDER BY (c||''), x;
--result 4 2 3 1

/* Sorting of column c is performed using the NOCASE collating sequence. */
SELECT x FROM t1 ORDER BY c COLLATE NOCASE, x;
--result 2 4 3 1


c2: The Next-Generation Query Planner
c3: 1. Introduction
c5: queryplanner-ng.html#_introduction
c4:
The task of the "query planner" is to figure
out the best algorithm or "query plan" to accomplish an SQL statement.
Beginning with SQLite version 3.8.0 (2013-08-26),
the query planner component has been
rewritten so that it runs faster and generates better plans.  The
rewrite is called the "next generation query planner" or "NGQP".


This article overviews the importance of query planning, describes some
of the problems inherent to query planning, and outlines how the NGQP
solves those problems.

The NGQP is almost always better than the legacy query planner.
However, there may exist legacy applications that unknowingly depend on 
undefined and/or suboptimal behavior in the legacy query planner, and
upgrading to the NGQP on those legacy applications could cause performance
regressions.  This risk is considered and a checklist is provided
for reducing the risk and for fixing any issues that do arise.

This document focuses on the NGQP.  For a more general overview of the
SQLite query planner that encompasses the entire history of SQLite, see the
"The SQLite Query Optimizer Overview" and
"How Indexes Work" documents.


c2: The Next-Generation Query Planner
c3: 2. Background
c5: queryplanner-ng.html#_background
c4:
For simple queries against a single table with few indexes, there is usually
an obvious choice for the best algorithm.
But for larger and more complex queries, such as
multi-way joins with many indexes
and subqueries, there can be hundreds, thousands, or millions
of reasonable algorithms for computing the result.
The job of the query planner is to choose the single "best" query plan from
this multitude of possibilities.

Query planners are what make SQL database engines so amazingly useful and powerful.
(This is true of all SQL database engines, not just SQLite.)
The query planner frees the programmer from the chore of selecting
a particular query plan, and thereby allows the programmer to
focus more mental energy on higher-level application issues and on 
providing more value to the end user.  For simple queries where the choice
of query plan is obvious, this is convenient but not hugely important.
But as applications and schemas and queries grow more complex, a
clever query planner can greatly speed and simplify the work of application
development. 
There is amazing power in being about to tell
the database engine what content is desired, and then let the database
engine figure out the best way to retrieve that content.

Writing a good query planner is more art than science.
The query planner must work with incomplete information.
It cannot determine how long any particular plan will take
without actually running that plan.  So when comparing two
or more plans to figure out which is "best", the query planner has to make
some guesses and assumptions and those guesses and assumptions will 
sometimes be wrong. A good query planner is one that will
find the correct solution often enough that application
programmers rarely need to get involved.


c2: The Next-Generation Query Planner
c3: 2.1. Query Planning In SQLite
c5: queryplanner-ng.html#_query_planning_in_sqlite
c4:
SQLite computes joins using nested loops, 
one loop for each table
in the join.  (Additional loops might be inserted for IN
and OR operators in the WHERE clause.  SQLite considers those too,
but for simplicity we will ignore them in this essay.)
One or more indexes might be used on each loop to speed the search,
or a loop might be a "full table scan" that reads every row in the
table.  Thus query planning decomposes into two subtasks:

 Picking the nested order of the various loops
 Choosing good indexes for each loop

Picking the nesting order is generally the more challenging problem.
Once the nesting order of the join is established, the choice of indexes
for each loop is normally obvious.


c2: The Next-Generation Query Planner
c3: 2.2. The SQLite Query Planner Stability Guarantee
c5: queryplanner-ng.html#_the_sqlite_query_planner_stability_guarantee
c4:
When the Query Planner Stability Guarantee (QPSG) is enabled
SQLite will always pick the same query plan for any
given SQL statement as long as:


the database schema does not change in significant ways such as 
    adding or dropping indexes,
the ANALYZE command is not rerun, 
the same version of SQLite is used.


The QPSG is disabled by default.  It can be enabled at compile-time
using the SQLITE_ENABLE_QPSG compile-time option, or at run-time by
invoking sqlite3_db_config(db,SQLITE_DBCONFIG_ENABLE_QPSG,1,0).

The QPSG means that if all of your queries run efficiently
during testing, and if your application does not change the schema,
then SQLite will not suddenly decide to start using a different
query plan, possibly causing a performance problem, after your application 
is released to users.  If your application works in the lab, it
will continue working the same way after deployment.

Enterprise-class client/server SQL database engines do not normally 
make this guarantee.
In client/server SQL database engines, the server keeps track of
statistics on the sizes of tables and on the quality of indexes 
and the query planner uses those statistics to help select the best plans.
As content is added, deleted, or changed in the database, the statistics 
will evolve and may cause the query planner to begin using a different 
query plan for some particular query.  Usually the new plan will be better 
for the evolving structure of the data.  But sometimes the new query plan will
cause a performance reduction.  With a client/server database engine, there
is typically a Database Administrator (DBA) on hand to deal with these 
rare problems as they come up.  But DBAs are not available to fix problems 
in an embedded database like SQLite, and hence SQLite is careful to
ensure that plans do not change unexpectedly after deployment.

It is important to note that changing versions of SQLite might cause
changes in query plans.
The same version of SQLite will
always pick the same query plan, but if you relink your application to use
a different version of SQLite, then query plans might change.  In rare
cases, an SQLite version change might lead to a performance regression.  
This is one reason
you should consider statically linking your applications against SQLite 
rather than use a system-wide SQLite shared library which might 
change without your knowledge or control.


