System.Data.SQLite

Check-in [7b0eeb3816]
Login

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

Overview
Comment:1.0.44.0
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | sourceforge
Files: files | file ages | folders
SHA1: 7b0eeb381651a99fc30c20d5fcf4009fbb9cbfc8
User & Date: rmsimpson 2007-07-21 08:46:09.000
Context
2007-07-21
08:46
1.0.44.0 check-in: d189b55f98 user: rmsimpson tags: sourceforge
08:46
1.0.44.0 check-in: 7b0eeb3816 user: rmsimpson tags: sourceforge
2007-06-19
22:42
Code merge with SQLite 3.4.0 check-in: d9903df39e user: rmsimpson tags: sourceforge
Changes
Side-by-Side Diff Show Whitespace Changes Patch
Changes to Doc/Extra/dbfactorysupport.html.
93
94
95
96
97
98
99
100

101
102
103
104
105
106
107
93
94
95
96
97
98
99

100
101
102
103
104
105
106
107







-
+







<configuration>
  <system.data>
    <DbProviderFactories>
      <remove invariant="System.Data.SQLite"/>
      <add name="SQLite Data Provider" invariant="System.Data.SQLite" 
           description=".Net Framework Data Provider for SQLite"
           type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite,
                 Version=1.0.42.0, Culture=neutral,
                 Version=1.0.44.0, Culture=neutral,
                 PublicKeyToken=db937bc2d44ff139"/>
    </DbProviderFactories>
  </system.data>
</configuration>
</pre>
      </div>
      <p>
Changes to Doc/Extra/lang_analyze.html.
96
97
98
99
100
101
102
103
104

105
106
107
108
109
110
111
96
97
98
99
100
101
102

103
104
105
106
107
108
109
110
111







-

+







        with that one table are analyzed.</p>
      <p>
        The initial implementation stores all statistics in a single table named <b>sqlite_stat1</b>.
        Future enhancements may create additional tables with the same name pattern except
        with the "1" changed to a different digit. The <b>sqlite_stat1</b> table cannot be <a href="lang_droptable.html">DROP</a>ped, but all the content can be <a href="lang_delete.html">
          DELETE</a>d which has the same effect.</p>
      <p>
      <hr>
        &nbsp;</p>
      <hr>
      <div id="footer">
        <p>
          &nbsp;</p>
        <p>
        </p>
      </div>
    </div>
Changes to Doc/Extra/lang_explain.html.
76
77
78
79
80
81
82
83
84

85
86
87
88
89
90
91
76
77
78
79
80
81
82

83
84
85
86
87
88
89
90
91







-

+







        of actually executing the command, the SQLite library will report back the sequence
        of virtual machine instructions it would have used to execute the command had the
        EXPLAIN keyword not been present. For additional information about virtual machine
        instructions see the <a href="http://www.sqlite.org/arch.html">architecture description</a>
        or the documentation on <a href="http://www.sqlite.org/opcode.html">available opcodes</a>
        for the virtual machine.</p>
      <p>
      <hr>
        &nbsp;</p>
      <hr>
      <div id="footer">
        <p>
          &nbsp;</p>
        <p>
        </p>
      </div>
    </div>
Changes to Doc/Extra/lang_select.html.
238
239
240
241
242
243
244
245
246

247
248
249
250
251
252
253
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252
253







-

+







        UNION ALL operators combine the results of the SELECTs to the right and left into
        a single big table. The difference is that in UNION all result rows are distinct
        where in UNION ALL there may be duplicates. The INTERSECT operator takes the intersection
        of the results of the left and right SELECTs. EXCEPT takes the result of left SELECT
        after removing the results of the right SELECT. When three or more SELECTs are connected
        into a compound, they group from left to right.</p>
      <p>
      <hr>
        &nbsp;</p>
      <hr>
      <div id="footer">
        <p>
          &nbsp;</p>
        <p>
        </p>
      </div>
    </div>
Added Doc/Extra/lang_types.html.



















































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
<html dir="LTR" xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:tool="http://www.microsoft.com/tooltip" xmlns:ndoc="urn:ndoc-preprocess">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <title>TYPES</title>
    <link rel="stylesheet" type="text/css" href="ndoc.css"> </link>
    <link rel="stylesheet" type="text/css" href="user.css"> </link>
    <script type="text/javascript" src="ndoc.js"> </script>
  </head>
  <body style="display: none;">
    <input type="hidden" id="userDataCache" class="userDataStyle" />
    <input type="hidden" id="hiddenScrollOffset" />
    <img id="dropDownImage" style="display:none; height:0; width:0;" src="drpdown.gif" />
    <img id="dropDownHoverImage" style="display:none; height:0; width:0;" src="drpdown_orange.gif" />
    <img id="collapseImage" style="display:none; height:0; width:0;" src="collapse.gif" />
    <img id="expandImage" style="display:none; height:0; width:0;" src="exp.gif" />
    <img id="collapseAllImage" style="display:none; height:0; width:0;" src="collall.gif" />
    <img id="expandAllImage" style="display:none; height:0; width:0;" src="expall.gif" />
    <img id="copyImage" style="display:none; height:0; width:0;" src="copycode.gif" />
    <img id="copyHoverImage" style="display:none; height:0; width:0;" src="copycodeHighlight.gif" />
    <div id="header">
      <table width="100%" id="topTable">
        <tr id="headerTableRow1">
          <td align="left">
            TYPES&nbsp;</td>
        </tr>
        <tr id="headerTableRow2">
          <td align="left">
            <span id="nsrTitle">SQLite Language Reference Documentation</span>
          </td>
        </tr>
        <tr id="headerTableRow3" style="display:none">
          <td>
            <a id="seeAlsoSectionLink" href="#seeAlsoToggle" onclick="OpenSection(seeAlsoToggle)">See Also</a>
            <a id="exampleSectionLink" href="#codeExampleToggle" onclick="OpenSection(codeExampleToggle)">Example</a>
          </td>
        </tr>
     </table>
      <table width="100%" id="bottomTable" cellspacing="0" cellpadding="0" style="display:none">
        <tr>
          <td>
            <span onclick="ExpandCollapseAll(toggleAllImage)" style="cursor:default;" onkeypress="ExpandCollapseAll_CheckKey(toggleAllImage)" tabindex="0">
              <img ID="toggleAllImage" class="toggleAll" src="collall.gif" />
              <label id="collapseAllLabel" for="toggleAllImage" style="display: none;">
							Collapse All
						</label>
              <label id="expandAllLabel" for="toggleAllImage" style="display: none;">
							Expand All
						</label>
            </span>
          </td>
        </tr>
      </table>
    </div>
    <div id="mainSection">
    <div id="mainBody">
      <h1 class="heading">
        SQL As Understood By SQLite (sortof)</h1>
      <h4>
        TYPES</h4>
      <p>
        <table cellpadding="10">
          <tr>
            <td align="right" width="1%" nowrap>
              <i><font color="#ff3434">sql-statement</font></i> ::=</td>
            <td>
              <b><font color="#2c2cf0">TYPES </font></b>[<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype
                      name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">...</font></i>] ; <em><span style="color: #ff3434">select-stmt</span></em></td>            
          </tr>
          <tr>
          <td align="right" width="1%" nowrap>
          <i><font color="#ff3434">select-stmt</font></i> ::=</td>
          <td>
            see <a href="lang_select.html">SELECT</a></td>
          </tr>
        </table>
      </p>
      <p>
        Use the TYPES keyword before a SELECT statement to provide the SQLite ADO.NET provider
        a list of return datatypes to expect from the subsequent SELECT statement.&nbsp;
      </p>
      <p>
        This is a language extension (aka <strong>hack</strong>) to SQLite specifically for the ADO.NET data
        provider.&nbsp; It is a pseudo-statement, meaning only the ADO.NET provider understands
        it.</p>
      <h3>
        Background</h3>
      <p>
        Due to SQLite's typeless nature, there are certain kinds of queries for which the
        ADO.NET provider cannot determine the proper return data type.&nbsp; Scalar and
        aggregate functions pose a particular problem because
        there is no requirement for a given scalar or aggregate function to return any particular
        datatype.&nbsp; As a matter of fact, scalar functions could theoretically return
        a different datatype for every row or column in a query and this is perfectly legal
        from SQLite's point of view.</p>
      <p>
        Since ADO.NET is designed around a typed system and we're shoe-horning SQLite into
        it, this keyword helps the provider out in cases where the return type cannot be easily determined.</p>
      <p>
        This command must be used in conjunction with a SELECT statement.&nbsp; It only
        works when both the TYPES keyword and its value(s) are passed along with a SELECT
        statement as a single semi-colon separated unit.</p>
      <h3>
        Examples</h3>
      <p>
        <strong><span style="color: #2c2cf0">TYPES</span> [bigint], [int], [smallint], [tinyint];<br />
          <span style="color: #2c2cf0">SELECT</span> 1, 2, 3, 4;</strong></p>
      <p>
        The above query would return the columns as types System.Int64, System.Int32, System.Int16
        and System.Byte respectively.</p>
      <p>
        <strong><span style="color: #2c2cf0">TYPES</span> [bigint], [int], , [tinyint];<br />
          <span style="color: #2c2cf0">SELECT</span> 1, 2, 3, 4;</strong></p>
      <p>
        In this sample, only columns 1, 2 and 4 would have explicit typing.&nbsp; Column
        3's datatype would pass though the system and be discovered normally.</p>
      <p>
        <strong><span style="color: #2c2cf0">TYPES</span> real;<br />
          <span style="color: #2c2cf0">SELECT</span> SUM(Cost) FROM [Products];</strong></p>
      <p>
        The above query explicitly tells the provider that the SUM aggregate function returns
        a System.Double.</p>
      <h3>
        Usage Notes</h3>
      <ul>
        <li>You cannot use parameters in the TYPES statement.</li>
        <li>The TYPES statement must be immediately followed by a SELECT statement.</li>
        <li>It is legal to pass multiple TYPES and SELECT statements in a multi-statement
          command.</li>
        <li>You may enclose datatypes in quotes <strong>""</strong> or brackets <strong>[]</strong>
          or those <strong>``</strong> thingies if you want.<br />
        </li>
      </ul>
      <hr>
      <div id="footer">
        <p>
          &nbsp;</p>
        <p>
        </p>
      </div>
    </div>
    </div>
  </body>
</html>
Changes to Doc/Extra/lang_vacuum.html.
1
2
3
4

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

25
26
27
28
29
30
31
1
2
3

4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

24
25
26
27
28
29
30
31



-
+



















-
+







<html dir="LTR" xmlns="http://www.w3.org/1999/xhtml" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:MSHelp="http://msdn.microsoft.com/mshelp" xmlns:tool="http://www.microsoft.com/tooltip" xmlns:ndoc="urn:ndoc-preprocess">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <title>VACUUM</title>
    <title>TYPES</title>
    <link rel="stylesheet" type="text/css" href="ndoc.css"> </link>
    <link rel="stylesheet" type="text/css" href="user.css"> </link>
    <script type="text/javascript" src="ndoc.js"> </script>
  </head>
  <body style="display: none;">
    <input type="hidden" id="userDataCache" class="userDataStyle" />
    <input type="hidden" id="hiddenScrollOffset" />
    <img id="dropDownImage" style="display:none; height:0; width:0;" src="drpdown.gif" />
    <img id="dropDownHoverImage" style="display:none; height:0; width:0;" src="drpdown_orange.gif" />
    <img id="collapseImage" style="display:none; height:0; width:0;" src="collapse.gif" />
    <img id="expandImage" style="display:none; height:0; width:0;" src="exp.gif" />
    <img id="collapseAllImage" style="display:none; height:0; width:0;" src="collall.gif" />
    <img id="expandAllImage" style="display:none; height:0; width:0;" src="expall.gif" />
    <img id="copyImage" style="display:none; height:0; width:0;" src="copycode.gif" />
    <img id="copyHoverImage" style="display:none; height:0; width:0;" src="copycodeHighlight.gif" />
    <div id="header">
      <table width="100%" id="topTable">
        <tr id="headerTableRow1">
          <td align="left">
            VACUUM&nbsp;</td>
            TYPES&nbsp;</td>
        </tr>
        <tr id="headerTableRow2">
          <td align="left">
            <span id="nsrTitle">SQLite Language Reference Documentation</span>
          </td>
        </tr>
        <tr id="headerTableRow3" style="display:none">
52
53
54
55
56
57
58
59

60
61
62
63
64
65
66
67
68






69
70
71
72
73
74
75
52
53
54
55
56
57
58

59
60
61
62
63
64
65



66
67
68
69
70
71
72
73
74
75
76
77
78







-
+






-
-
-
+
+
+
+
+
+







      </table>
    </div>
    <div id="mainSection">
    <div id="mainBody">
      <h1 class="heading">
        SQL As Understood By SQLite</h1>
      <h4>
        VACUUM</h4>
        TYPES</h4>
      <p>
        <table cellpadding="10">
          <tr>
            <td align="right" width="1%" nowrap>
              <i><font color="#ff3434">sql-statement</font></i> ::=</td>
            <td>
              <b><font color="#2c2cf0">VACUUM </font></b>[<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">index-or-table-name</font></i><b><font color="#2c2cf0"></font></b>]<b><font
                  color="#2c2cf0"></font></b></td>
              <b><font color="#2c2cf0">TYPES </font></b>[<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">datatype
                      name</font></i><b><font color="#2c2cf0"></font></b>][,<b><font color="#2c2cf0"></font></b><i><font
                color="#ff3434">...</font></i>] ; <em><span style="color: #ff3434">select stmt</span></em></td>
          </tr>
        </table>
      </p>
      <p>
        The VACUUM command is an SQLite extension modeled after a similar command found
        in PostgreSQL. If VACUUM is invoked with the name of a table or index then it is
        suppose to clean up the named table or index. In version 1.0 of SQLite, the VACUUM
91
92
93
94
95
96
97
98
99

100
101
102
103
104
105
106
107
108
109
94
95
96
97
98
99
100

101
102
103
104
105
106
107
108
109
110
111
112







-

+










      <p>
        This command will fail if there is an active transaction. This command has no effect
        on an in-memory database.</p>
      <p>
        As of SQLite version 3.1, an alternative to using the VACUUM command is auto-vacuum
        mode, enabled using the <a href="pragma.html#pragma_auto_vacuum">auto_vacuum pragma</a>.</p>
      <p>
      <hr>
        &nbsp;</p>
      <hr>
      <div id="footer">
        <p>
          &nbsp;</p>
        <p>
        </p>
      </div>
    </div>
    </div>
  </body>
</html>
Changes to Doc/Extra/version.html.
52
53
54
55
56
57
58





















59
60
61
62
63
64
65
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







        </tr>
      </table>
    </div>
    <div id="mainSection">
    <div id="mainBody">

      <h1 class="heading">Version History</h1>
    <p><b>1.0.44.0 - July 22, 2007</b></p>
    <ul>
    <li>Code merge with SQLite 3.4.1</li>
      <li>Fixed a bug in SQLiteConnection.Open() which threw the wrong kind of error in
        the wrong kind of way when a database file could not be opened or created.&nbsp;</li>
      <li>Small enhancements to the TYPES keyword, and added documentation for it in the
        help file.</li>
      <li>Hopefully fixed the occasional SQLITE_BUSY errors that cropped up when starting
        a transaction.&nbsp; Usually occurred in high-contention scenarios, and the underlying
        SQLite engine bypasses the busy handler in this scenario to return immediately.</li>
    </ul>
    <p><b>1.0.43.0 - June 21, 2007</b></p>
    <ul>
    <li>Code merge with SQLite 3.4.0</li>
      <li>Fixed a reuse bug in the SQLiteDataAdapter in conjunction with the SQLiteCommandBuilder.&nbsp;
      It's been there unnoticed for more than a year, so it looks like most folks never
      encountered it. </li>
      <li>Fixed an event handler bug in SQLiteCommandBuilder in which it could fail to unlatch
        from the DataAdapter when reused.&nbsp; Relates to the previous bugfix.</li>
      <li>Fixed a double-dispose bug in SQLiteStatement that triggered a SQLiteException.&nbsp;</li>
    </ul>
    <p><b>1.0.42.0 - June 1, 2007</b></p>
    <ul>
    <li>Code merge with SQLite 3.3.17</li>
      <li>Changed the SQLiteFunction static constructor so it only enumerates loaded modules
        that have referenced the SQLite assembly, which hopefully should cut down dramatically
        the time it takes for that function to execute.&nbsp;</li>
      <li>Added the FTS2 full-text search extension to the project.&nbsp; Look for FTS1
Changes to Doc/SQLite.NET.chm.

cannot compute difference between binary files

Changes to SQLite.Designer/AssemblyInfo.cs.
28
29
30
31
32
33
34
35
36


37
38
39
28
29
30
31
32
33
34


35
36
37
38
39







-
-
+
+



//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.31.0")]
[assembly: AssemblyFileVersion("1.0.31.0")]
[assembly: AssemblyVersion("1.0.32.0")]
[assembly: AssemblyFileVersion("1.0.32.0")]
[assembly: AssemblyDelaySignAttribute(false)]
[assembly: AssemblyKeyFileAttribute("..\\System.Data.SQLite\\System.Data.SQLite.snk")]
[assembly: AssemblyKeyNameAttribute("")]
Changes to SQLite.Designer/SQLite.Designer.csproj.
148
149
150
151
152
153
154
155

156
157
158
159
160
148
149
150
151
152
153
154

155
156
157
158
159
160







-
+





    <None Include="CtcComponents\PkgCmdID.h" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Properties\" />
    <Folder Include="Resources\" />
  </ItemGroup>
  <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
  <Import Project="C:\Program Files (x86)\Visual Studio 2005 SDK\2006.09\VisualStudioIntegration\Tools\Build\Microsoft.VsSDK.targets" />
  <Import Project="C:\Program Files (x86)\Visual Studio 2005 SDK\2007.02\VisualStudioIntegration\Tools\Build\Microsoft.VsSDK.targets" />
  <PropertyGroup>
    <PostBuildEvent>
    </PostBuildEvent>
  </PropertyGroup>
</Project>
Changes to SQLite.Interop/FTS1/FTS1.vcproj.
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60
46
47
48
49
50
51
52

53
54
55
56
57
58
59
60







-
+







			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
109
110
111
112
113
114
115
116

117
118
119
120
121
122
123
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123







-
+







			/>
			<Tool
				Name="VCCLCompilerTool"
				ExecutionBucket="7"
				AdditionalOptions="/GS-"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
177
178
179
180
181
182
183
184

185
186
187
188
189
190
191
177
178
179
180
181
182
183

184
185
186
187
188
189
190
191







-
+







				Name="VCMIDLTool"
				TargetEnvironment="2"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN64;_DEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
238
239
240
241
242
243
244
245

246
247
248
249
250
251
252
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252







-
+







				Name="VCMIDLTool"
				TargetEnvironment="3"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN64;_DEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
299
300
301
302
303
304
305
306

307
308
309
310
311
312
313
299
300
301
302
303
304
305

306
307
308
309
310
311
312
313







-
+







			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
364
365
366
367
368
369
370
371

372
373
374
375
376
377
378
364
365
366
367
368
369
370

371
372
373
374
375
376
377
378







-
+







				TargetEnvironment="1"
			/>
			<Tool
				Name="VCCLCompilerTool"
				ExecutionBucket="7"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
436
437
438
439
440
441
442
443

444
445
446
447
448
449
450
436
437
438
439
440
441
442

443
444
445
446
447
448
449
450







-
+







				Name="VCMIDLTool"
				TargetEnvironment="2"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN64;NDEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
500
501
502
503
504
505
506
507

508
509
510
511
512
513
514
500
501
502
503
504
505
506

507
508
509
510
511
512
513
514







-
+







				Name="VCMIDLTool"
				TargetEnvironment="3"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS1"
				PreprocessorDefinitions="WIN64;NDEBUG;_LIB;SQLITE_ENABLE_FTS1;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
Changes to SQLite.Interop/FTS1/fts1.c.
1560
1561
1562
1563
1564
1565
1566

1567
1568
1569
1570
1571
1572
1573
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574







+







      return 0;
    }
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; safe_isspace(z[i]); i++){}
      *tokenType = TOKEN_SPACE;
      return i;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
Changes to SQLite.Interop/FTS2/FTS2.vcproj.
46
47
48
49
50
51
52
53

54
55
56
57
58
59
60
46
47
48
49
50
51
52

53
54
55
56
57
58
59
60







-
+







			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
109
110
111
112
113
114
115
116

117
118
119
120
121
122
123
109
110
111
112
113
114
115

116
117
118
119
120
121
122
123







-
+







			/>
			<Tool
				Name="VCCLCompilerTool"
				ExecutionBucket="7"
				AdditionalOptions="/GS-"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
177
178
179
180
181
182
183
184

185
186
187
188
189
190
191
177
178
179
180
181
182
183

184
185
186
187
188
189
190
191







-
+







				Name="VCMIDLTool"
				TargetEnvironment="2"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN64;_DEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
238
239
240
241
242
243
244
245

246
247
248
249
250
251
252
238
239
240
241
242
243
244

245
246
247
248
249
250
251
252







-
+







				Name="VCMIDLTool"
				TargetEnvironment="3"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;_DEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN64;_DEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
299
300
301
302
303
304
305
306

307
308
309
310
311
312
313
299
300
301
302
303
304
305

306
307
308
309
310
311
312
313







-
+







			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
362
363
364
365
366
367
368
369

370
371

372
373
374
375
376
377
378
362
363
364
365
366
367
368

369
370

371
372
373
374
375
376
377
378







-
+

-
+







			<Tool
				Name="VCMIDLTool"
				TargetEnvironment="1"
			/>
			<Tool
				Name="VCCLCompilerTool"
				ExecutionBucket="7"
				FavorSizeOrSpeed="1"
				Optimization="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
436
437
438
439
440
441
442
443

444
445
446
447
448
449
450
436
437
438
439
440
441
442

443
444
445
446
447
448
449
450







-
+







				Name="VCMIDLTool"
				TargetEnvironment="2"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN64;NDEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
500
501
502
503
504
505
506
507

508
509
510
511
512
513
514
500
501
502
503
504
505
506

507
508
509
510
511
512
513
514







-
+







				Name="VCMIDLTool"
				TargetEnvironment="3"
			/>
			<Tool
				Name="VCCLCompilerTool"
				FavorSizeOrSpeed="1"
				AdditionalIncludeDirectories="..\src"
				PreprocessorDefinitions="WIN32;NDEBUG;_LIB;SQLITE_ENABLE_FTS2"
				PreprocessorDefinitions="WIN64;NDEBUG;_LIB;SQLITE_ENABLE_FTS2;SQLITE_CORE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
				RuntimeTypeInfo="false"
				UsePrecompiledHeader="0"
			/>
556
557
558
559
560
561
562




563
564
565
566
567
568
569
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573







+
+
+
+







			<File
				RelativePath=".\fts2_hash.c"
				>
			</File>
			<File
				RelativePath=".\fts2_porter.c"
				>
			</File>
			<File
				RelativePath=".\fts2_tokenizer.c"
				>
			</File>
			<File
				RelativePath=".\fts2_tokenizer1.c"
				>
			</File>
		</Filter>
		<Filter
Changes to SQLite.Interop/FTS2/fts2.c.



1
2
3










4
5
6
7
8
9
10
1
2
3



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
+
+
+
-
-
-
+
+
+
+
+
+
+
+
+
+







/*
** 2006 Oct 10
**
/* The author disclaims copyright to this source code.
 *
 * This is an SQLite module implementing full-text search.
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is an SQLite module implementing full-text search.
 */

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
1843
1844
1845
1846
1847
1848
1849
1850

1851
1852
1853
1854
1855
1856
1857
1853
1854
1855
1856
1857
1858
1859

1860
1861
1862
1863
1864
1865
1866
1867







-
+







  DLReader reader;                 /* Result reader if result not empty */
} fulltext_cursor;

static struct fulltext_vtab *cursor_vtab(fulltext_cursor *c){
  return (fulltext_vtab *) c->base.pVtab;
}

static const sqlite3_module fulltextModule;   /* forward declaration */
static const sqlite3_module fts2Module;   /* forward declaration */

/* Return a dynamically generated statement of the form
 *   insert into %_content (rowid, ...) values (?, ...)
 */
static const char *contentInsertStatement(fulltext_vtab *v){
  StringBuffer sb;
  int i;
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943



1944
1945
1946
1947
1948


1949
1950


1951
1952

1953
1954
1955
1956
1957
1958
1959
1960
1943
1944
1945
1946
1947
1948
1949




1950
1951
1952





1953
1954


1955
1956
1957

1958

1959
1960
1961
1962
1963
1964
1965







-
-
-
-
+
+
+
-
-
-
-
-
+
+
-
-
+
+

-
+
-








  while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){
    sqlite3_stmt *pNewStmt;

    if( rc==SQLITE_BUSY ) continue;
    if( rc!=SQLITE_ERROR ) return rc;

    rc = sqlite3_reset(s);
    if( rc!=SQLITE_SCHEMA ) return SQLITE_ERROR;

    v->pFulltextStatements[iStmt] = NULL;   /* Still in s */
    /* If an SQLITE_SCHEMA error has occured, then finalizing this
     * statement is going to delete the fulltext_vtab structure. If
     * the statement just executed is in the pFulltextStatements[]
    rc = sql_get_statement(v, iStmt, &pNewStmt);
    if( rc!=SQLITE_OK ) goto err;
    *ppStmt = pNewStmt;

    rc = sqlite3_transfer_bindings(s, pNewStmt);
     * array, it will be finalized twice. So remove it before
     * calling sqlite3_finalize().
    if( rc!=SQLITE_OK ) goto err;

     */
    v->pFulltextStatements[iStmt] = NULL;
    rc = sqlite3_finalize(s);
    if( rc!=SQLITE_OK ) return rc;
    break;
    s = pNewStmt;
  }
  return rc;

 err:
  sqlite3_finalize(s);
  return rc;
}
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014



2015
2016
2017
2018
2019


2020
2021


2022
2023

2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2009
2010
2011
2012
2013
2014
2015




2016
2017
2018





2019
2020


2021
2022
2023

2024

2025

2026


2027
2028
2029
2030
2031
2032
2033







-
-
-
-
+
+
+
-
-
-
-
-
+
+
-
-
+
+

-
+
-

-

-
-








  while( (rc=sqlite3_step(s))!=SQLITE_DONE && rc!=SQLITE_ROW ){
    sqlite3_stmt *pNewStmt;

    if( rc==SQLITE_BUSY ) continue;
    if( rc!=SQLITE_ERROR ) return rc;

    rc = sqlite3_reset(s);
    if( rc!=SQLITE_SCHEMA ) return SQLITE_ERROR;

    v->pLeafSelectStmts[idx] = NULL;   /* Still in s */
    /* If an SQLITE_SCHEMA error has occured, then finalizing this
     * statement is going to delete the fulltext_vtab structure. If
     * the statement just executed is in the pLeafSelectStmts[]
    rc = sql_get_leaf_statement(v, idx, &pNewStmt);
    if( rc!=SQLITE_OK ) goto err;
    *ppStmt = pNewStmt;

    rc = sqlite3_transfer_bindings(s, pNewStmt);
     * array, it will be finalized twice. So remove it before
     * calling sqlite3_finalize().
    if( rc!=SQLITE_OK ) goto err;

     */
    v->pLeafSelectStmts[idx] = NULL;
    rc = sqlite3_finalize(s);
    if( rc!=SQLITE_OK ) return rc;
    break;
    s = pNewStmt;
  }
  return rc;

 err:
  sqlite3_finalize(s);
  return rc;
}

/* insert into %_content (rowid, ...) values ([rowid], [pValues]) */
static int content_insert(fulltext_vtab *v, sqlite3_value *rowid,
                          sqlite3_value **pValues){
  sqlite3_stmt *s;
2398
2399
2400
2401
2402
2403
2404

2405
2406
2407
2408
2409
2410
2411
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409







+







      return 0;
    }
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; safe_isspace(z[i]); i++){}
      *tokenType = TOKEN_SPACE;
      return i;
    }
    case '`':
    case '\'':
    case '"': {
      int delim = z[0];
      for(i=1; (c=z[i])!=0; i++){
        if( c==delim ){
          if( z[i+1]==delim ){
            i++;
2757
2758
2759
2760
2761
2762
2763

2764
2765
2766
2767
2768
2769
2770
2771
2772



2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794








2795

2796
2797
2798
2799

2800
2801
2802
2803
2804
2805
2806
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791





2792
2793
2794
2795
2796
2797
2798
2799

2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812







+









+
+
+

















-
-
-
-
-
+
+
+
+
+
+
+
+
-
+




+








/*
** Build a new sqlite3_vtab structure that will describe the
** fulltext index defined by spec.
*/
static int constructVtab(
  sqlite3 *db,              /* The SQLite database connection */
  fts2Hash *pHash,          /* Hash table containing tokenizers */
  TableSpec *spec,          /* Parsed spec information from parseSpec() */
  sqlite3_vtab **ppVTab,    /* Write the resulting vtab structure here */
  char **pzErr              /* Write any error message here */
){
  int rc;
  int n;
  fulltext_vtab *v = 0;
  const sqlite3_tokenizer_module *m = NULL;
  char *schema;

  char const *zTok;         /* Name of tokenizer to use for this fts table */
  int nTok;                 /* Length of zTok, including nul terminator */

  v = (fulltext_vtab *) malloc(sizeof(fulltext_vtab));
  if( v==0 ) return SQLITE_NOMEM;
  CLEAR(v);
  /* sqlite will initialize v->base */
  v->db = db;
  v->zDb = spec->zDb;       /* Freed when azColumn is freed */
  v->zName = spec->zName;   /* Freed when azColumn is freed */
  v->nColumn = spec->nColumn;
  v->azContentColumn = spec->azContentColumn;
  spec->azContentColumn = 0;
  v->azColumn = spec->azColumn;
  spec->azColumn = 0;

  if( spec->azTokenizer==0 ){
    return SQLITE_NOMEM;
  }
  /* TODO(shess) For now, add new tokenizers as else if clauses. */
  if( spec->azTokenizer[0]==0 || startsWith(spec->azTokenizer[0], "simple") ){
    sqlite3Fts2SimpleTokenizerModule(&m);
  }else if( startsWith(spec->azTokenizer[0], "porter") ){
    sqlite3Fts2PorterTokenizerModule(&m);

  zTok = spec->azTokenizer[0]; 
  if( !zTok ){
    zTok = "simple";
  }
  nTok = strlen(zTok)+1;

  m = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zTok, nTok);
  }else{
  if( !m ){
    *pzErr = sqlite3_mprintf("unknown tokenizer: %s", spec->azTokenizer[0]);
    rc = SQLITE_ERROR;
    goto err;
  }

  for(n=0; spec->azTokenizer[n]; n++){}
  if( n ){
    rc = m->xCreate(n-1, (const char*const*)&spec->azTokenizer[1],
                    &v->pTokenizer);
  }else{
    rc = m->xCreate(0, 0, &v->pTokenizer);
  }
2837
2838
2839
2840
2841
2842
2843
2844

2845
2846
2847
2848
2849
2850
2851
2843
2844
2845
2846
2847
2848
2849

2850
2851
2852
2853
2854
2855
2856
2857







-
+







  sqlite3_vtab **ppVTab,
  char **pzErr
){
  TableSpec spec;
  int rc = parseSpec(&spec, argc, argv, pzErr);
  if( rc!=SQLITE_OK ) return rc;

  rc = constructVtab(db, &spec, ppVTab, pzErr);
  rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);
  clearTableSpec(&spec);
  return rc;
}

/* The %_content table holds the text of each document, with
** the rowid used as the docid.
*/
2883
2884
2885
2886
2887
2888
2889
2890

2891
2892
2893
2894
2895
2896
2897
2889
2890
2891
2892
2893
2894
2895

2896
2897
2898
2899
2900
2901
2902
2903







-
+







                "  leaves_end_block integer,"
                "  end_block integer,"
                "  root blob,"
                "  primary key(level, idx)"
                ");");
  if( rc!=SQLITE_OK ) goto out;

  rc = constructVtab(db, &spec, ppVTab, pzErr);
  rc = constructVtab(db, (fts2Hash *)pAux, &spec, ppVTab, pzErr);

out:
  clearTableSpec(&spec);
  return rc;
}

/* Decide how to handle an SQL query. */
3101
3102
3103
3104
3105
3106
3107
3108

3109
3110
3111
3112
3113
3114
3115
3107
3108
3109
3110
3111
3112
3113

3114
3115
3116
3117
3118
3119
3120
3121







-
+







  int iFirst, iLast;
  fulltext_vtab *pFts;

  if( p->snippet.nMatch ) return;
  if( p->q.nTerms==0 ) return;
  pFts = p->q.pFts;
  nColumn = pFts->nColumn;
  iColumn = p->iCursorType;
  iColumn = (p->iCursorType - QUERY_FULLTEXT);
  if( iColumn<0 || iColumn>=nColumn ){
    iFirst = 0;
    iLast = nColumn-1;
  }else{
    iFirst = iColumn;
    iLast = iColumn;
  }
5829
5830
5831
5832
5833
5834
5835
























5836

5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855

5856
5857





























5858




































5859
5860
5861






5862
5863









5864
5865
5866





5867
5868
5869
5870
5871
5872
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865

5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954



5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972


5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
+



















+


+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+


+
+
+
+
+
+
+
+
+

-
-
+
+
+
+
+






  }else if( strcmp(zName,"offsets")==0 ){
    *pxFunc = snippetOffsetsFunc;
    return 1;
  }
  return 0;
}

/*
** Rename an fts2 table.
*/
static int fulltextRename(
  sqlite3_vtab *pVtab,
  const char *zName
){
  fulltext_vtab *p = (fulltext_vtab *)pVtab;
  int rc = SQLITE_NOMEM;
  char *zSql = sqlite3_mprintf(
    "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';"
    "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';"
    "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';"
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName 
    , p->zDb, p->zName, zName
  );
  if( zSql ){
    rc = sqlite3_exec(p->db, zSql, 0, 0, 0);
    sqlite3_free(zSql);
  }
  return rc;
}

static const sqlite3_module fulltextModule = {
static const sqlite3_module fts2Module = {
  /* iVersion      */ 0,
  /* xCreate       */ fulltextCreate,
  /* xConnect      */ fulltextConnect,
  /* xBestIndex    */ fulltextBestIndex,
  /* xDisconnect   */ fulltextDisconnect,
  /* xDestroy      */ fulltextDestroy,
  /* xOpen         */ fulltextOpen,
  /* xClose        */ fulltextClose,
  /* xFilter       */ fulltextFilter,
  /* xNext         */ fulltextNext,
  /* xEof          */ fulltextEof,
  /* xColumn       */ fulltextColumn,
  /* xRowid        */ fulltextRowid,
  /* xUpdate       */ fulltextUpdate,
  /* xBegin        */ fulltextBegin,
  /* xSync         */ fulltextSync,
  /* xCommit       */ fulltextCommit,
  /* xRollback     */ fulltextRollback,
  /* xFindFunction */ fulltextFindFunction,
  /* xRename */       fulltextRename,
};

static void hashDestroy(void *p){
  fts2Hash *pHash = (fts2Hash *)p;
  sqlite3Fts2HashClear(pHash);
  sqlite3_free(pHash);
}

/*
** The fts2 built-in tokenizers - "simple" and "porter" - are implemented
** in files fts2_tokenizer1.c and fts2_porter.c respectively. The following
** two forward declarations are for functions declared in these files
** used to retrieve the respective implementations.
**
** Calling sqlite3Fts2SimpleTokenizerModule() sets the value pointed
** to by the argument to point a the "simple" tokenizer implementation.
** Function ...PorterTokenizerModule() sets *pModule to point to the
** porter tokenizer/stemmer implementation.
*/
void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);

int sqlite3Fts2InitHashTable(sqlite3 *, fts2Hash *, const char *);

/*
** Initialise the fts2 extension. If this extension is built as part
** of the sqlite library, then this function is called directly by
** SQLite. If fts2 is built as a dynamically loadable extension, this
** function is called by the sqlite3_extension_init() entry point.
*/
int sqlite3Fts2Init(sqlite3 *db){
  int rc = SQLITE_OK;
  fts2Hash *pHash = 0;
  const sqlite3_tokenizer_module *pSimple = 0;
  const sqlite3_tokenizer_module *pPorter = 0;
  const sqlite3_tokenizer_module *pIcu = 0;

  sqlite3Fts2SimpleTokenizerModule(&pSimple);
  sqlite3Fts2PorterTokenizerModule(&pPorter);
#ifdef SQLITE_ENABLE_ICU
  sqlite3Fts2IcuTokenizerModule(&pIcu);
#endif

  /* Allocate and initialise the hash-table used to store tokenizers. */
  pHash = sqlite3_malloc(sizeof(fts2Hash));
  if( !pHash ){
    rc = SQLITE_NOMEM;
  }else{
    sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
  }

  /* Load the built-in tokenizers into the hash table */
  if( rc==SQLITE_OK ){
    if( sqlite3Fts2HashInsert(pHash, "simple", 7, (void *)pSimple)
     || sqlite3Fts2HashInsert(pHash, "porter", 7, (void *)pPorter) 
     || (pIcu && sqlite3Fts2HashInsert(pHash, "icu", 4, (void *)pIcu))
    ){
      rc = SQLITE_NOMEM;
    }
  }

  /* Create the virtual table wrapper around the hash-table and overload 
  ** the two scalar functions. If this is successful, register the
  ** module with sqlite.
  */
  if( SQLITE_OK==rc 
   && SQLITE_OK==(rc = sqlite3Fts2InitHashTable(db, pHash, "fts2_tokenizer"))
  sqlite3_overload_function(db, "snippet", -1);
  sqlite3_overload_function(db, "offsets", -1);
  return sqlite3_create_module(db, "fts2", &fulltextModule, 0);
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
   && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", -1))
  ){
    return sqlite3_create_module_v2(
        db, "fts2", &fts2Module, (void *)pHash, hashDestroy
    );
}

  /* An error has occured. Delete the hash table and return the error code. */
  assert( rc!=SQLITE_OK );
  if( pHash ){
    sqlite3Fts2HashClear(pHash);
    sqlite3_free(pHash);
  }
  return rc;
}

#if !SQLITE_CORE
int sqlite3_extension_init(sqlite3 *db, char **pzErrMsg,
                           const sqlite3_api_routines *pApi){
int sqlite3_extension_init(
  sqlite3 *db, 
  char **pzErrMsg,
  const sqlite3_api_routines *pApi
){
  SQLITE_EXTENSION_INIT2(pApi)
  return sqlite3Fts2Init(db);
}
#endif

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */
Changes to SQLite.Interop/FTS2/fts2.h.
1











2
3
4
5
6
7
8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

+
+
+
+
+
+
+
+
+
+
+







/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This header file is used by programs that want to link against the
** FTS2 library.  All it does is declare the sqlite3Fts2Init() interface.
*/
#include "sqlite3.h"

#ifdef __cplusplus
extern "C" {
Changes to SQLite.Interop/FTS2/fts2_hash.c.
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30



31
32
33
34
35
36
37
9
10
11
12
13
14
15



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37







-
-
-












+
+
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables used in SQLite.
** We've modified it slightly to serve as a standalone hash table
** implementation for the full-text indexing module.
*/
#include <assert.h>
#include <stdlib.h>
#include <string.h>

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)

#include <assert.h>
#include <stdlib.h>
#include <string.h>

#include "fts2_hash.h"

static void *malloc_and_zero(int n){
  void *p = malloc(n);
  if( p ){
    memset(p, 0, n);
Added SQLite.Interop/FTS2/fts2_tokenizer.c.



















































































































































































































































































































































































1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
/*
** 2007 June 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This is part of an SQLite module implementing full-text search.
** This particular file implements the generic tokenizer interface.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
**       (in which case SQLITE_CORE is not defined), or
**
**     * The FTS2 module is being built into the core of
**       SQLite (in which case SQLITE_ENABLE_FTS2 is defined).
*/
#if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2)


#include "sqlite3.h"
#include "sqlite3ext.h"
SQLITE_EXTENSION_INIT1

#include "fts2_hash.h"
#include "fts2_tokenizer.h"
#include <assert.h>

/*
** Implementation of the SQL scalar function for accessing the underlying 
** hash table. This function may be called as follows:
**
**   SELECT <function-name>(<key-name>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer').
**
** If the <pointer> argument is specified, it must be a blob value
** containing a pointer to be stored as the hash data corresponding
** to the string <key-name>. If <pointer> is not specified, then
** the string <key-name> must already exist in the has table. Otherwise,
** an error is returned.
**
** Whether or not the <pointer> argument is specified, the value returned
** is a blob containing the pointer stored as the hash data corresponding
** to string <key-name> (after the hash-table is updated, if applicable).
*/
static void scalarFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts2Hash *pHash;
  void *pPtr = 0;
  const unsigned char *zName;
  int nName;

  assert( argc==1 || argc==2 );

  pHash = (fts2Hash *)sqlite3_user_data(context);

  zName = sqlite3_value_text(argv[0]);
  nName = sqlite3_value_bytes(argv[0])+1;

  if( argc==2 ){
    void *pOld;
    int n = sqlite3_value_bytes(argv[1]);
    if( n!=sizeof(pPtr) ){
      sqlite3_result_error(context, "argument type mismatch", -1);
      return;
    }
    pPtr = *(void **)sqlite3_value_blob(argv[1]);
    pOld = sqlite3Fts2HashInsert(pHash, (void *)zName, nName, pPtr);
    if( pOld==pPtr ){
      sqlite3_result_error(context, "out of memory", -1);
      return;
    }
  }else{
    pPtr = sqlite3Fts2HashFind(pHash, zName, nName);
    if( !pPtr ){
      char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
      sqlite3_result_error(context, zErr, -1);
      sqlite3_free(zErr);
      return;
    }
  }

  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
}

#ifdef SQLITE_TEST

#include <tcl.h>
#include <string.h>

/*
** Implementation of a special SQL scalar function for testing tokenizers 
** designed to be used in concert with the Tcl testing framework. This
** function must be called with two arguments:
**
**   SELECT <function-name>(<key-name>, <input-string>);
**   SELECT <function-name>(<key-name>, <pointer>);
**
** where <function-name> is the name passed as the second argument
** to the sqlite3Fts2InitHashTable() function (e.g. 'fts2_tokenizer')
** concatenated with the string '_test' (e.g. 'fts2_tokenizer_test').
**
** The return value is a string that may be interpreted as a Tcl
** list. For each token in the <input-string>, three elements are
** added to the returned list. The first is the token position, the 
** second is the token text (folded, stemmed, etc.) and the third is the
** substring of <input-string> associated with the token. For example, 
** using the built-in "simple" tokenizer:
**
**   SELECT fts_tokenizer_test('simple', 'I don't see how');
**
** will return the string:
**
**   "{0 i I 1 dont don't 2 see see 3 how how}"
**   
*/
static void testFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  fts2Hash *pHash;
  sqlite3_tokenizer_module *p;
  sqlite3_tokenizer *pTokenizer = 0;
  sqlite3_tokenizer_cursor *pCsr = 0;

  const char *zErr = 0;

  const char *zName;
  int nName;
  const char *zInput;
  int nInput;

  const char *zArg = 0;

  const char *zToken;
  int nToken;
  int iStart;
  int iEnd;
  int iPos;

  Tcl_Obj *pRet;

  assert( argc==2 || argc==3 );

  nName = sqlite3_value_bytes(argv[0]);
  zName = (const char *)sqlite3_value_text(argv[0]);
  nInput = sqlite3_value_bytes(argv[argc-1]);
  zInput = (const char *)sqlite3_value_text(argv[argc-1]);

  if( argc==3 ){
    zArg = (const char *)sqlite3_value_text(argv[1]);
  }

  pHash = (fts2Hash *)sqlite3_user_data(context);
  p = (sqlite3_tokenizer_module *)sqlite3Fts2HashFind(pHash, zName, nName+1);

  if( !p ){
    char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
    sqlite3_result_error(context, zErr, -1);
    sqlite3_free(zErr);
    return;
  }

  pRet = Tcl_NewObj();
  Tcl_IncrRefCount(pRet);

  if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
    zErr = "error in xCreate()";
    goto finish;
  }
  pTokenizer->pModule = p;
  if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
    zErr = "error in xOpen()";
    goto finish;
  }
  pCsr->pTokenizer = pTokenizer;

  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
    zToken = &zInput[iStart];
    nToken = iEnd-iStart;
    Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  }

  if( SQLITE_OK!=p->xClose(pCsr) ){
    zErr = "error in xClose()";
    goto finish;
  }
  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
    zErr = "error in xDestroy()";
    goto finish;
  }

finish:
  if( zErr ){
    sqlite3_result_error(context, zErr, -1);
  }else{
    sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  }
  Tcl_DecrRefCount(pRet);
}

static
int registerTokenizer(
  sqlite3 *db, 
  char *zName, 
  const sqlite3_tokenizer_module *p
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts2_tokenizer(?, ?)";

  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  sqlite3_step(pStmt);

  return sqlite3_finalize(pStmt);
}

static
int queryTokenizer(
  sqlite3 *db, 
  char *zName,  
  const sqlite3_tokenizer_module **pp
){
  int rc;
  sqlite3_stmt *pStmt;
  const char zSql[] = "SELECT fts2_tokenizer(?)";

  *pp = 0;
  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  if( rc!=SQLITE_OK ){
    return rc;
  }

  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  if( SQLITE_ROW==sqlite3_step(pStmt) ){
    if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
      memcpy(pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
    }
  }

  return sqlite3_finalize(pStmt);
}

void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);

/*
** Implementation of the scalar function fts2_tokenizer_internal_test().
** This function is used for testing only, it is not included in the
** build unless SQLITE_TEST is defined.
**
** The purpose of this is to test that the fts2_tokenizer() function
** can be used as designed by the C-code in the queryTokenizer and
** registerTokenizer() functions above. These two functions are repeated
** in the README.tokenizer file as an example, so it is important to
** test them.
**
** To run the tests, evaluate the fts2_tokenizer_internal_test() scalar
** function with no arguments. An assert() will fail if a problem is
** detected. i.e.:
**
**     SELECT fts2_tokenizer_internal_test();
**
*/
static void intTestFunc(
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  int rc;
  const sqlite3_tokenizer_module *p1;
  const sqlite3_tokenizer_module *p2;
  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);

  /* Test the query function */
  sqlite3Fts2SimpleTokenizerModule(&p1);
  rc = queryTokenizer(db, "simple", &p2);
  assert( rc==SQLITE_OK );
  assert( p1==p2 );
  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_ERROR );
  assert( p2==0 );
  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );

  /* Test the storage function */
  rc = registerTokenizer(db, "nosuchtokenizer", p1);
  assert( rc==SQLITE_OK );
  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  assert( rc==SQLITE_OK );
  assert( p2==p1 );

  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
}

#endif

/*
** Set up SQL objects in database db used to access the contents of
** the hash table pointed to by argument pHash. The hash table must
** been initialised to use string keys, and to take a private copy 
** of the key when a value is inserted. i.e. by a call similar to:
**
**    sqlite3Fts2HashInit(pHash, FTS2_HASH_STRING, 1);
**
** This function adds a scalar function (see header comment above
** scalarFunc() in this file for details) and, if ENABLE_TABLE is
** defined at compilation time, a temporary virtual table (see header 
** comment above struct HashTableVtab) to the database schema. Both 
** provide read/write access to the contents of *pHash.
**
** The third argument to this function, zName, is used as the name
** of both the scalar and, if created, the virtual table.
*/
int sqlite3Fts2InitHashTable(
  sqlite3 *db, 
  fts2Hash *pHash, 
  const char *zName
){
  int rc = SQLITE_OK;
  void *p = (void *)pHash;
  const int any = SQLITE_ANY;
  char *zTest = 0;
  char *zTest2 = 0;

#ifdef SQLITE_TEST
  void *pdb = (void *)db;
  zTest = sqlite3_mprintf("%s_test", zName);
  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  if( !zTest || !zTest2 ){
    rc = SQLITE_NOMEM;
  }
#endif

  if( rc!=SQLITE_OK
   || (rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
#ifdef SQLITE_TEST
   || (rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
   || (rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
#endif
  );

  sqlite3_free(zTest);
  sqlite3_free(zTest2);
  return rc;
}

#endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS2) */
Changes to SQLite.Interop/FTS2/fts2_tokenizer.h.
23
24
25
26
27
28
29
30

















31
32
33
34



35
36




37

38
39
40
41















42
43
44










45
46
47





48
49
50
51
52
53



























54
55
56
57
58
59

60
61

62
63
64
65





66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
23
24
25
26
27
28
29

30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47



48
49
50
51
52
53
54
55
56

57
58
59


60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75


76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93






94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125

126


127




128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144












145







-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
+
+
+


+
+
+
+
-
+


-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+
+
+
+
+
+
+
+
+



+
+
+
+
+
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+





-
+
-
-
+
-
-
-
-
+
+
+
+
+












-
-
-
-
-
-
-
-
-
-
-
-

/* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
** If tokenizers are to be allowed to call sqlite3_*() functions, then
** we will need a way to register the API consistently.
*/
#include "sqlite3.h"

/*
** Structures used by the tokenizer interface.
** Structures used by the tokenizer interface. When a new tokenizer
** implementation is registered, the caller provides a pointer to
** an sqlite3_tokenizer_module containing pointers to the callback
** functions that make up an implementation.
**
** When an fts2 table is created, it passes any arguments passed to
** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
** implementation. The xCreate() function in turn returns an 
** sqlite3_tokenizer structure representing the specific tokenizer to
** be used for the fts2 table (customized by the tokenizer clause arguments).
**
** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
** method is called. It returns an sqlite3_tokenizer_cursor object
** that may be used to tokenize a specific input buffer based on
** the tokenization rules supplied by a specific sqlite3_tokenizer
** object.
*/
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
typedef struct sqlite3_tokenizer sqlite3_tokenizer;
typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;

struct sqlite3_tokenizer_module {

  /*
  ** Structure version. Should always be set to 0.
  */
  int iVersion;                  /* currently 0 */
  int iVersion;

  /*
  ** Create and destroy a tokenizer.  argc/argv are passed down from
  ** the fulltext virtual table creation to allow customization.
  ** Create a new tokenizer. The values in the argv[] array are the
  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  ** TABLE statement that created the fts2 table. For example, if
  ** the following SQL is executed:
  **
  **   CREATE .. USING fts2( ... , tokenizer <tokenizer-name> arg1 arg2)
  **
  ** then argc is set to 2, and the argv[] array contains pointers
  ** to the strings "arg1" and "arg2".
  **
  ** This method should return either SQLITE_OK (0), or an SQLite error 
  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  ** to point at the newly created tokenizer structure. The generic
  ** sqlite3_tokenizer.pModule variable should not be initialised by
  ** this callback. The caller will do so.
  */
  int (*xCreate)(int argc, const char *const*argv,
                 sqlite3_tokenizer **ppTokenizer);
  int (*xCreate)(
    int argc,                           /* Size of argv array */
    const char *const*argv,             /* Tokenizer argument strings */
    sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
  );

  /*
  ** Destroy an existing tokenizer. The fts2 module calls this method
  ** exactly once for each successful call to xCreate().
  */
  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);

  /*
  ** Create a tokenizer cursor to tokenize an input buffer. The caller
  ** is responsible for ensuring that the input buffer remains valid
  ** until the cursor is closed (using the xClose() method). 
  */
  int (*xOpen)(
  ** Tokenize a particular input.  Call xOpen() to prepare to
  ** tokenize, xNext() repeatedly until it returns SQLITE_DONE, then
  ** xClose() to free any internal state.  The pInput passed to
  ** xOpen() must exist until the cursor is closed.  The ppToken
  ** result from xNext() is only valid until the next call to xNext()
  ** or until xClose() is called.
    sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
    const char *pInput, int nBytes,      /* Input buffer */
    sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
  );

  /*
  ** Destroy an existing tokenizer cursor. The fts2 module calls this 
  ** method exactly once for each successful call to xOpen().
  */
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);

  /*
  ** Retrieve the next token from the tokenizer cursor pCursor. This
  ** method should either return SQLITE_OK and set the values of the
  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  ** the end of the buffer has been reached, or an SQLite error code.
  **
  ** *ppToken should be set to point at a buffer containing the 
  ** normalized version of the token (i.e. after any case-folding and/or
  ** stemming has been performed). *pnBytes should be set to the length
  ** of this buffer in bytes. The input text that generated the token is
  ** identified by the byte offsets returned in *piStartOffset and
  ** *piEndOffset.
  **
  ** The buffer *ppToken is set to point at is managed by the tokenizer
  ** implementation. It is only required to be valid until the next call
  ** to xNext() or xClose(). 
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
  ** should be converted to zInput.
  */
  int (*xOpen)(sqlite3_tokenizer *pTokenizer,
  int (*xNext)(
               const char *pInput, int nBytes,
               sqlite3_tokenizer_cursor **ppCursor);
    sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
               const char **ppToken, int *pnBytes,
               int *piStartOffset, int *piEndOffset, int *piPosition);
    const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
    int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
    int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
    int *piPosition      /* OUT: Number of tokens returned before this one */
  );
};

struct sqlite3_tokenizer {
  const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
  /* Tokenizer implementations will typically add additional fields */
};

struct sqlite3_tokenizer_cursor {
  sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
  /* Tokenizer implementations will typically add additional fields */
};

/*
** Get the module for a tokenizer which generates tokens based on a
** set of non-token characters.  The default is to break tokens at any
** non-alnum character, though the set of delimiters can also be
** specified by the first argv argument to xCreate().
*/
/* TODO(shess) This doesn't belong here.  Need some sort of
** registration process.
*/
void sqlite3Fts2SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
void sqlite3Fts2PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);

#endif /* _FTS2_TOKENIZER_H_ */
Changes to SQLite.Interop/FTS2/fts2_tokenizer1.c.
1


2


3




4


5
6
7
8
9
10
11
1
2
3

4
5
6
7
8
9
10

11
12
13
14
15
16
17
18
19

+
+
-
+
+

+
+
+
+
-
+
+







/*
** 2006 Oct 10
**
** The author disclaims copyright to this source code.
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
******************************************************************************
**
** Implementation of the "simple" full-text-search tokenizer.
*/

/*
** The code in this file is only compiled if:
**
**     * The FTS2 module is being built as an extension
Changes to SQLite.Interop/SQLite.Interop.rc.
49
50
51
52
53
54
55
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74

75
76
77

78
79
80
81
82
83
84
49
50
51
52
53
54
55

56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73

74
75
76

77
78
79
80
81
82
83
84







-
+

















-
+


-
+








/////////////////////////////////////////////////////////////////////////////
//
// Version
//

VS_VERSION_INFO VERSIONINFO
 FILEVERSION 1,0,42,0
 FILEVERSION 1,0,44,0
 PRODUCTVERSION 1,0,0,0
 FILEFLAGSMASK 0x17L
#ifdef _DEBUG
 FILEFLAGS 0x1L
#else
 FILEFLAGS 0x0L
#endif
 FILEOS 0x4L
 FILETYPE 0x2L
 FILESUBTYPE 0x0L
BEGIN
    BLOCK "StringFileInfo"
    BEGIN
        BLOCK "040904b0"
        BEGIN
            VALUE "Comments", "http://sqlite.phxsoftware.com"
            VALUE "FileDescription", "System.Data.SQLite Interop Library"
            VALUE "FileVersion", "1.0.42.0"
            VALUE "FileVersion", "1.0.44.0"
            VALUE "InternalName", "SQLite.Interop.DLL"
            VALUE "LegalCopyright", "Released to the public domain"
            VALUE "OriginalFilename", "SQLite3.DLL 3.3.17"
            VALUE "OriginalFilename", "SQLite3.DLL 3.4.1"
            VALUE "ProductName", "System.Data.SQLite"
            VALUE "ProductVersion", "1.0"
        END
    END
    BLOCK "VarFileInfo"
    BEGIN
        VALUE "Translation", 0x409, 1200
Changes to SQLite.Interop/SQLite.Interop.vcproj.
68
69
70
71
72
73
74
75

76
77
78
79
80
81
82
68
69
70
71
72
73
74

75
76
77
78
79
80
81
82







-
+







				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/System.Data.SQLite.DLL"
				GenerateManifest="false"
				IgnoreDefaultLibraryNames=""
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				OptimizeForWindows98="1"
135
136
137
138
139
140
141
142
143


144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164

165
166
167
168
169
170
171
135
136
137
138
139
140
141


142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163

164
165
166
167
168
169
170
171







-
-
+
+




















-
+







			/>
			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				ExecutionBucket="7"
				InlineFunctionExpansion="1"
				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_WINDOWS;_USRDLL;CPPSMART_EXPORTS;$(ARCHFAM);$(_ARCHFAM_);UNICODE;_UNICODE;SQLITE_HAS_CODEC;SQLITE_ENABLE_COLUMN_METADATA;SQLITE_ENABLE_FTS1;SQLITE_ENABLE_FTS2;SQLITE_OMIT_TRACE"
				Optimization="1"
				PreprocessorDefinitions="_WIN32_WCE=$(CEVER);UNDER_CE=$(CEVER);WINCE;$(PLATFORMDEFINES);NDEBUG;_WINDOWS;_USRDLL;CPPSMART_EXPORTS;$(ARCHFAM);$(_ARCHFAM_);UNICODE;_UNICODE;SQLITE_HAS_CODEC;SQLITE_ENABLE_COLUMN_METADATA;SQLITE_ENABLE_FTS2;SQLITE_OMIT_TRACE"
				StringPooling="true"
				ExceptionHandling="0"
				BufferSecurityCheck="false"
				EnableFunctionLevelLinking="true"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
				PreprocessorDefinitions="NDEBUG;_UNICODE;UNICODE;_WIN32_WCE;UNDER_CE"
				Culture="1033"
				AdditionalIncludeDirectories="$(IntDir)"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				IgnoreImportLibrary="true"
				AdditionalDependencies="fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib"
				AdditionalDependencies="&quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot;"
				OutputFile="../bin/CompactFramework/System.Data.SQLite.DLL"
				AdditionalLibraryDirectories=""
				IgnoreDefaultLibraryNames=""
				ModuleDefinitionFile="src\sqlite3.def"
				AddModuleNamesToAssembly=""
				EmbedManagedResourceFile=""
				SubSystem="9"
243
244
245
246
247
248
249
250

251
252
253
254
255
256
257
243
244
245
246
247
248
249

250
251
252
253
254
255
256
257







-
+







				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/Itanium/System.Data.SQLite.DLL"
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				OptimizeForWindows98="1"
				ImportLibrary=""
				TargetMachine="5"
330
331
332
333
334
335
336
337

338
339
340
341
342
343
344
330
331
332
333
334
335
336

337
338
339
340
341
342
343
344







-
+







				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/x64/System.Data.SQLite.DLL"
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				OptimizeForWindows98="1"
				ImportLibrary=""
				TargetMachine="17"
397
398
399
400
401
402
403
404

405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420

421

422
423
424
425
426
427
428
397
398
399
400
401
402
403

404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419

420
421
422
423
424
425
426
427
428
429







-
+















-
+

+







			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				AdditionalOptions="/GS-"
				Optimization="0"
				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE=1;SQLITE_HAS_CODEC;SQLITE_ENABLE_COLUMN_METADATA;SQLITE_ENABLE_FTS1;SQLITE_ENABLE_FTS2;SQLITE_OMIT_TRACE"
				PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS;_USRDLL;_CRT_SECURE_NO_DEPRECATE;NO_TCL;THREADSAFE=1;SQLITE_HAS_CODEC;SQLITE_ENABLE_COLUMN_METADATA;SQLITE_ENABLE_FTS2;SQLITE_OMIT_TRACE"
				RuntimeLibrary="3"
				RuntimeTypeInfo="false"
				DebugInformationFormat="3"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/$(InputName).DLL"
				LinkIncremental="1"
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				GenerateDebugInformation="true"
				ImportLibrary=""
				TargetMachine="1"
				KeyFile="..\System.Data.SQLite\System.Data.SQLite.snk"
499
500
501
502
503
504
505
506

507
508
509
510
511
512
513
500
501
502
503
504
505
506

507
508
509
510
511
512
513
514







-
+







			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				IgnoreImportLibrary="true"
				AdditionalOptions=" /subsystem:windowsce,4.20 /machine:ARM /ARMPADCODE"
				AdditionalDependencies="fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib"
				AdditionalDependencies="&quot;fts1/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot;"
				OutputFile="../bin/CompactFramework/$(InputName).DLL"
				AdditionalLibraryDirectories=""
				IgnoreDefaultLibraryNames=""
				ModuleDefinitionFile="src\sqlite3.def"
				AddModuleNamesToAssembly=""
				EmbedManagedResourceFile=""
				GenerateDebugInformation="true"
580
581
582
583
584
585
586
587

588
589
590
591
592
593
594
581
582
583
584
585
586
587

588
589
590
591
592
593
594
595







-
+







				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/Itanium/$(InputName).DLL"
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				GenerateDebugInformation="true"
				ImportLibrary=""
				TargetMachine="5"
662
663
664
665
666
667
668
669

670
671
672
673
674
675
676
663
664
665
666
667
668
669

670
671
672
673
674
675
676
677







-
+







				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies="advapi32.lib fts1/$(ConfigurationName)/SQLite.Interop.FTS1.lib fts2/$(ConfigurationName)/SQLite.Interop.FTS2.lib $(NOINHERIT)"
				AdditionalDependencies="advapi32.lib &quot;fts1/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS1.lib&quot; &quot;fts2/$(PlatformName)/$(ConfigurationName)/SQLite.Interop.FTS2.lib&quot; $(NOINHERIT)"
				OutputFile="../bin/x64/$(InputName).DLL"
				ModuleDefinitionFile="src\sqlite3.def"
				EmbedManagedResourceFile=""
				DelayLoadDLLs="advapi32.dll"
				GenerateDebugInformation="true"
				ImportLibrary=""
				TargetMachine="17"
Changes to SQLite.Interop/merge.h.
1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
1
2
3
4
5
6
7

8
9
10
11
12
13
14
15







-
+







// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\CompactFramework\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[130956] = {0}; // The number of bytes to reserve
  char __ph[130872] = {0}; // The number of bytes to reserve
#pragma data_seg()

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;
Changes to SQLite.Interop/merge_full.h.
1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
1
2
3
4
5
6
7

8
9
10
11
12
13
14
15







-
+







// This code was automatically generated from assembly
// C:\Src\SQLite.NET\System.Data.SQLite\bin\System.Data.SQLite.dll

#include <windef.h>

#pragma data_seg(".clr")
#pragma comment(linker, "/SECTION:.clr,ER")
  char __ph[140144] = {0}; // The number of bytes to reserve
  char __ph[140088] = {0}; // The number of bytes to reserve
#pragma data_seg()

typedef BOOL (WINAPI *DLLMAIN)(HANDLE, DWORD, LPVOID);
typedef struct EXTRA_STUFF
{
  DWORD dwNativeEntryPoint;
} EXTRA_STUFF, *LPEXTRA_STUFF;
Changes to SQLite.Interop/src/sqlite3.c.
1
2
3

4
5
6
7
8
9
10
11
12
13
14

15
16
17
18
19
20

21
22






23
24
25
26
27
28
29
1
2

3
4
5
6
7
8
9
10
11
12
13

14
15
16
17
18
19

20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35


-
+










-
+





-
+


+
+
+
+
+
+







/******************************************************************************
** This file is an amalgamation of many separate C source files from SQLite
** version 3.4.0.  By combining all the individual C code files into this 
** version 3.4.1.  By combining all the individual C code files into this 
** single large file, the entire code can be compiled as a one translation
** unit.  This allows many compilers to do optimizations that would not be
** possible if the files were compiled separately.  Performance improvements
** of 5% are more are commonly seen when SQLite is compiled as a single
** translation unit.
**
** This file is all you need to compile SQLite.  To use SQLite in other
** programs, you need this file and the "sqlite3.h" header file that defines
** the programming interface to the SQLite library.  (If you do not have 
** the "sqlite3.h" header file at hand, you will find a copy in the first
** 2679 lines past this header comment.)  Additional code files may be
** 2702 lines past this header comment.)  Additional code files may be
** needed if you want a wrapper to interface SQLite with your choice of
** programming language.  The code for the "sqlite3" command-line shell
** is also in a separate file.  This file contains only code for the core
** SQLite library.
**
** This amalgamation was generated on 2007-06-18 17:44:42 UTC.
** This amalgamation was generated on 2007-07-20 11:05:39 UTC.
*/
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
#ifndef SQLITE_API
# define SQLITE_API
#endif
/************** Begin file sqlite3.h *****************************************/
/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
49
50
51
52
53
54
55
56

57
58
59
60
61
62
63
55
56
57
58
59
60
61

62
63
64
65
66
67
68
69







-
+







** on how SQLite interfaces are suppose to operate.
**
** The name of this file under configuration management is "sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "sqlite3.h" as
** part of the build process.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITE3_H_
#define _SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
100
101
102
103
104
105
106
107
108


109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127

128
129
130
131
132
133
134
106
107
108
109
110
111
112


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132

133
134
135
136
137
138
139
140







-
-
+
+


















-
+







** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta", 
** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
** version 3.1.1 or greater at compile time, programs may use the test 
** (SQLITE_VERSION_NUMBER>=3001001).
**
** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
*/
#define SQLITE_VERSION         "3.4.0"
#define SQLITE_VERSION_NUMBER 3004000
#define SQLITE_VERSION         "3.4.1"
#define SQLITE_VERSION_NUMBER 3004001

/*
** CAPI3REF: Run-Time Library Version Numbers
**
** These routines return values equivalent to the header constants
** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER].  The values returned
** by this routines should only be different from the header values
** if you compile your program using an sqlite3.h header from a
** different version of SQLite that the version of the library you
** link against.
**
** The sqlite3_version[] string constant contains the text of the
** [SQLITE_VERSION] string.  The sqlite3_libversion() function returns
** a poiner to the sqlite3_version[] string constant.  The function
** is provided for DLL users who can only access functions and not
** constants within the DLL.
*/
extern const char sqlite3_version[];
const char *sqlite3_libversion(void);
SQLITE_API const char *sqlite3_libversion(void);
int sqlite3_libversion_number(void);

/*
** CAPI3REF: Database Connection Handle
**
** Each open SQLite database is represented by pointer to an instance of the
** opaque structure named "sqlite3".  It is useful to think of an sqlite3
177
178
179
180
181
182
183
184

185
186
187
188
189
190
191
183
184
185
186
187
188
189

190
191
192
193
194
195
196
197







-
+







** closed.
**
** All SQL statements prepared using [sqlite3_prepare_v2()] or
** [sqlite3_prepare16_v2()] must be destroyed using [sqlite3_finalize()]
** before this routine is called. Otherwise, SQLITE_BUSY is returned and the
** database connection remains open.
*/
int sqlite3_close(sqlite3 *);
SQLITE_API int sqlite3_close(sqlite3 *);

/*
** The type for a callback function.
** This is legacy and deprecated.  It is included for historical
** compatibility and is not documented.
*/
typedef int (*sqlite3_callback)(void*,int,char**, char**);
230
231
232
233
234
235
236
237

238
239
240
241
242
243
244
236
237
238
239
240
241
242

243
244
245
246
247
248
249
250







-
+







** then no error message is ever written.
**
** The return value is is SQLITE_OK if there are no errors and
** some other [SQLITE_OK | return code] if there is an error.  
** The particular return value depends on the type of error. 
**
*/
int sqlite3_exec(
SQLITE_API int sqlite3_exec(
  sqlite3*,                                  /* An open database */
  const char *sql,                           /* SQL to be evaluted */
  int (*callback)(void*,int,char**,char**),  /* Callback function */
  void *,                                    /* 1st argument to callback */
  char **errmsg                              /* Error msg written here */
);

388
389
390
391
392
393
394
395

396
397
398
399
400
401

402
403
404
405
406
407
408
394
395
396
397
398
399
400

401
402
403
404
405
406

407
408
409
410
411
412
413
414







-
+





-
+







**
** If a callback invokes [sqlite3_exec()] or [sqlite3_step()] recursively,
** then the changes in the inner, recursive call are counted together
** with the changes in the outer call.
**
** SQLite implements the command "DELETE FROM table" without a WHERE clause
** by dropping and recreating the table.  (This is much faster than going
** through and deleting individual elements form the table.)  Because of
** through and deleting individual elements from the table.)  Because of
** this optimization, the change count for "DELETE FROM table" will be
** zero regardless of the number of elements that were originally in the
** table. To get an accurate count of the number of rows deleted, use
** "DELETE FROM table WHERE 1" instead.
*/
int sqlite3_changes(sqlite3*);
SQLITE_API int sqlite3_changes(sqlite3*);

/*
** CAPI3REF: Total Number Of Rows Modified
***
** This function returns the number of database rows that have been
** modified by INSERT, UPDATE or DELETE statements since the database handle
** was opened. This includes UPDATE, INSERT and DELETE statements executed
435
436
437
438
439
440
441
442

443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463


464
465
466
467
468
469
470
441
442
443
444
445
446
447

448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467


468
469
470
471
472
473
474
475
476







-
+



















-
-
+
+







** thread that is currently running the database operation.
**
** The SQL operation that is interrupted will return [SQLITE_INTERRUPT].
** If an interrupted operation was an update that is inside an
** explicit transaction, then the entire transaction will be rolled
** back automatically.
*/
void sqlite3_interrupt(sqlite3*);
SQLITE_API void sqlite3_interrupt(sqlite3*);

/*
** CAPI3REF: Determine If An SQL Statement Is Complete
**
** These functions return true if the given input string comprises
** one or more complete SQL statements. For the sqlite3_complete() call,
** the parameter must be a nul-terminated UTF-8 string. For
** sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string
** is required.
**
** These routines are useful for command-line input to determine if the
** currently entered text forms one or more complete SQL statements or
** if additional input is needed before sending the statements into
** SQLite for parsing. The algorithm is simple.  If the 
** last token other than spaces and comments is a semicolon, then return 
** true.  Actually, the algorithm is a little more complicated than that
** in order to deal with triggers, but the basic idea is the same:  the
** statement is not complete unless it ends in a semicolon.
*/
int sqlite3_complete(const char *sql);
int sqlite3_complete16(const void *sql);
SQLITE_API int sqlite3_complete(const char *sql);
SQLITE_API int sqlite3_complete16(const void *sql);

/*
** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
**
** This routine identifies a callback function that might be invoked
** whenever an attempt is made to open a database table 
** that another thread or process has locked.
689
690
691
692
693
694
695
696
697
698



699
700
701
702
703
704
705
706
707
708
709
710
711



712
713
714
715
716
717
718
695
696
697
698
699
700
701



702
703
704
705
706
707
708
709
710
711
712
713
714



715
716
717
718
719
720
721
722
723
724







-
-
-
+
+
+










-
-
-
+
+
+







**  sqlite3_exec(db, zSQL, 0, 0, 0);
**  sqlite3_free(zSQL);
** </pre></blockquote>
**
** The code above will render a correct SQL statement in the zSQL
** variable even if the zText variable is a NULL pointer.
*/
char *sqlite3_mprintf(const char*,...);
char *sqlite3_vmprintf(const char*, va_list);
char *sqlite3_snprintf(int,char*,const char*, ...);
SQLITE_API char *sqlite3_mprintf(const char*,...);
SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);

/*
** CAPI3REF: Memory Allocation Functions
**
** SQLite uses its own memory allocator.  On some installations, this
** memory allocator is identical to the standard malloc()/realloc()/free()
** and can be used interchangable.  On others, the implementations are
** different.  For maximum portability, it is best not to mix calls
** to the standard malloc/realloc/free with the sqlite versions.
*/
void *sqlite3_malloc(int);
void *sqlite3_realloc(void*, int);
void sqlite3_free(void*);
SQLITE_API void *sqlite3_malloc(int);
SQLITE_API void *sqlite3_realloc(void*, int);
SQLITE_API void sqlite3_free(void*);

/*
** CAPI3REF: Compile-Time Authorization Callbacks
***
** This routine registers a authorizer callback with the SQLite library.  
** The authorizer callback is invoked as SQL statements are being compiled
** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
844
845
846
847
848
849
850
851
852


853
854
855
856
857
858
859
850
851
852
853
854
855
856


857
858
859
860
861
862
863
864
865







-
-
+
+







** The callback function registered by sqlite3_profile() is invoked
** as each SQL statement finishes and includes
** information on how long that statement ran.
**
** The sqlite3_profile() API is currently considered experimental and
** is subject to change.
*/
void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
void *sqlite3_profile(sqlite3*,
SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
SQLITE_API void *sqlite3_profile(sqlite3*,
   void(*xProfile)(void*,const char*,sqlite_uint64), void*);

/*
** CAPI3REF: Query Progress Callbacks
**
** This routine configures a callback function - the progress callback - that
** is invoked periodically during long running calls to [sqlite3_exec()],
905
906
907
908
909
910
911
912

913
914
915
916

917
918
919
920
921
922
923
911
912
913
914
915
916
917

918
919
920
921

922
923
924
925
926
927
928
929







-
+



-
+







** sqlite3_close() when it is no longer required.
**
** Note to windows users:  The encoding used for the filename argument
** of sqlite3_open() must be UTF-8, not whatever codepage is currently
** defined.  Filenames containing international characters must be converted
** to UTF-8 prior to passing them into sqlite3_open().
*/
int sqlite3_open(
SQLITE_API int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);
int sqlite3_open16(
SQLITE_API int sqlite3_open16(
  const void *filename,   /* Database filename (UTF-16) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

/*
** CAPI3REF: Error Codes And Messages
**
942
943
944
945
946
947
948
949
950
951



952
953
954
955
956
957
958
948
949
950
951
952
953
954



955
956
957
958
959
960
961
962
963
964







-
-
-
+
+
+







** an error code (examples: [sqlite3_data_count()] or [sqlite3_mprintf()]) do
** not change the error code returned by this routine.
**
** Assuming no other intervening sqlite3_* API calls are made, the error
** code returned by this function is associated with the same error as
** the strings returned by [sqlite3_errmsg()] and [sqlite3_errmsg16()].
*/
int sqlite3_errcode(sqlite3 *db);
const char *sqlite3_errmsg(sqlite3*);
const void *sqlite3_errmsg16(sqlite3*);
SQLITE_API int sqlite3_errcode(sqlite3 *db);
SQLITE_API const char *sqlite3_errmsg(sqlite3*);
SQLITE_API const void *sqlite3_errmsg16(sqlite3*);

/*
** CAPI3REF: SQL Statement Object
**
** Instance of this object represent single SQL statements.  This
** is variously known as a "prepared statement" or a 
** "compiled SQL statement" or simply as a "statement".
982
983
984
985
986
987
988
989



990
991
992




993
994
995
996
997
998
999
988
989
990
991
992
993
994

995
996
997
998


999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009







-
+
+
+

-
-
+
+
+
+







** program using one of these routines. 
**
** The first argument "db" is an [sqlite3 | SQLite database handle] 
** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()].
** The second argument "zSql" is the statement to be compiled, encoded
** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
** use UTF-16. If the next argument, "nBytes", is less
** use UTF-16.
**
** If the nByte argument is less
** than zero, then zSql is read up to the first zero terminator.  If
** "nBytes" is not less than zero, then it is the length of the string zSql
** in bytes (not characters).
** nByte is non-negative, then it is the maximum number of 
** bytes read from zSql.  When nByte is non-negative, the
** zSql string ends at either the first '\000' character or 
** until the nByte-th byte, whichever comes first.
**
** *pzTail is made to point to the first byte past the end of the first
** SQL statement in zSql.  This routine only compiles the first statement
** in zSql, so *pzTail is left pointing to what remains uncompiled.
**
** *ppStmt is left pointing to a compiled 
** [sqlite3_stmt | SQL statement structure] that can be
1035
1036
1037
1038
1039
1040
1041
1042

1043
1044
1045

1046
1047
1048
1049
1050
1051
1052

1053
1054
1055
1056

1057
1058
1059

1060
1061
1062
1063
1064
1065
1066

1067
1068
1069
1070
1071
1072
1073
1045
1046
1047
1048
1049
1050
1051

1052
1053
1054

1055
1056
1057
1058
1059
1060
1061

1062
1063
1064
1065

1066
1067
1068

1069
1070
1071
1072
1073
1074
1075

1076
1077
1078
1079
1080
1081
1082
1083







-
+


-
+






-
+



-
+


-
+






-
+







** [SQLITE_ERROR] result code and you would have to make a second call to
** [sqlite3_reset()] in order to find the underlying cause of the problem.
** With the "v2" prepare interfaces, the underlying reason for the error is
** returned immediately.
** </li>
** </ol>
*/
int sqlite3_prepare(
SQLITE_API int sqlite3_prepare(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare_v2(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16(
SQLITE_API int sqlite3_prepare16(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16_v2(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);

/*
** CAPI3REF:  Dynamically Typed Value Object
**
1256
1257
1258
1259
1260
1261
1262
1263




1264
1265
1266




1267
1268
1269
1270
1271
1272
1273
1266
1267
1268
1269
1270
1271
1272

1273
1274
1275
1276
1277
1278

1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289







-
+
+
+
+


-
+
+
+
+








/*
** CAPI3REF: Source Of Data In A Query Result
**
** These routines provide a means to determine what column of what
** table in which database a result of a SELECT statement comes from.
** The name of the database or table or column can be returned as
** either a UTF8 or UTF16 string.  The returned string is valid until
** either a UTF8 or UTF16 string.  The _database_ routines return
** the database name, the _table_ routines return the table name, and
** the origin_ routines return the column name.
** The returned string is valid until
** the [sqlite3_stmt | prepared statement] is destroyed using
** [sqlite3_finalize()] or until the same information is requested
** again about the same column.
** again in a different encoding.
**
** The names returned are the original un-aliased names of the
** database, table, and column.
**
** The first argument to the following calls is a 
** [sqlite3_stmt | compiled SQL statement].
** These functions return information about the Nth column returned by 
** the statement, where N is the second function argument.
**
** If the Nth column returned by the statement is an expression
1387
1388
1389
1390
1391
1392
1393
1394

1395
1396
1397
1398
1399
1400
1401
1403
1404
1405
1406
1407
1408
1409

1410
1411
1412
1413
1414
1415
1416
1417







-
+







** We admit that this is a goofy design.  The problem has been fixed
** with the "v2" interface.  If you prepare all of your SQL statements
** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()], then the 
** more specific [SQLITE_ERROR | result codes] are returned directly
** by sqlite3_step().  The use of the "v2" interface is recommended.
*/
int sqlite3_step(sqlite3_stmt*);
SQLITE_API int sqlite3_step(sqlite3_stmt*);

/*
** CAPI3REF:
**
** Return the number of values in the current row of the result set.
**
** After a call to [sqlite3_step()] that returns [SQLITE_ROW], this routine
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481


1482
1483
1484
1485
1486
1487
1488







-
-







** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
** returned by sqlite3_column_type() is only meaningful if no type
** conversions have occurred as described below.  After a type conversion,
** the value returned by sqlite3_column_type() is undefined.  Future
** versions of SQLite may change the behavior of sqlite3_column_type()
** following a type conversion.
**
*** The sqlite3_column_nm
**
** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
** routine returns the number of bytes in that BLOB or string.
** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
** the string to UTF-8 and then returns the number of bytes.
** If the result is a numeric value then sqlite3_column_bytes() uses
** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
** the number of bytes in that string.
1583
1584
1585
1586
1587
1588
1589
1590

1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602

1603
1604
1605
1606
1607
1608
1609
1597
1598
1599
1600
1601
1602
1603

1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615

1616
1617
1618
1619
1620
1621
1622
1623







-
+











-
+







** [sqlite3_stmt | virtual machine].  If the virtual machine has not 
** completed execution when this routine is called, that is like
** encountering an error or an interrupt.  (See [sqlite3_interrupt()].) 
** Incomplete updates may be rolled back and transactions cancelled,  
** depending on the circumstances, and the 
** [SQLITE_ERROR | result code] returned will be [SQLITE_ABORT].
*/
int sqlite3_finalize(sqlite3_stmt *pStmt);
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Reset A Prepared Statement Object
**
** The sqlite3_reset() function is called to reset a 
** [sqlite_stmt | compiled SQL statement] object.
** back to it's initial state, ready to be re-executed.
** Any SQL statement variables that had values bound to them using
** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
** Use [sqlite3_clear_bindings()] to reset the bindings.
*/
int sqlite3_reset(sqlite3_stmt *pStmt);
SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);

/*
** CAPI3REF: Create Or Redefine SQL Functions
**
** The following two functions are used to add SQL functions or aggregates
** or to redefine the behavior of existing SQL functions or aggregates.  The
** difference only between the two is that the second parameter, the
1699
1700
1701
1702
1703
1704
1705
1706

1707
1708
1709
1710
1711
1712
1713
1713
1714
1715
1716
1717
1718
1719

1720
1721
1722
1723
1724
1725
1726
1727







-
+







** These functions are all now obsolete.  In order to maintain
** backwards compatibility with older code, we continue to support
** these functions.  However, new development projects should avoid
** the use of these functions.  To help encourage people to avoid
** using these functions, we are not going to tell you want they do.
*/
int sqlite3_aggregate_count(sqlite3_context*);
int sqlite3_expired(sqlite3_stmt*);
SQLITE_API int sqlite3_expired(sqlite3_stmt*);
int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
int sqlite3_global_recover(void);


/*
** CAPI3REF: Obtaining SQL Function Parameter Values
**
1986
1987
1988
1989
1990
1991
1992
1993

1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006

2007
2008
2009
2010
2011
2012
2013
2014

2015
2016
2017
2018
2019
2020
2021
2022

2023
2024
2025
2026
2027
2028
2029
2000
2001
2002
2003
2004
2005
2006

2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019

2020
2021
2022
2023
2024
2025
2026
2027

2028
2029
2030
2031
2032
2033
2034
2035

2036
2037
2038
2039
2040
2041
2042
2043







-
+












-
+







-
+







-
+







/*
** Specify the key for an encrypted database.  This routine should be
** called right after sqlite3_open().
**
** The code to implement this API is not available in the public release
** of SQLite.
*/
int sqlite3_key(
SQLITE_API int sqlite3_key(
  sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The key */
);

/*
** Change the key on an open database.  If the current database is not
** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
** database is decrypted.
**
** The code to implement this API is not available in the public release
** of SQLite.
*/
int sqlite3_rekey(
SQLITE_API int sqlite3_rekey(
  sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);

/*
** CAPI3REF:  Suspend Execution For A Short Time
**
** This function causes the current thread to suspect execution
** This function causes the current thread to suspend execution
** a number of milliseconds specified in its parameter.
**
** If the operating system does not support sleep requests with 
** millisecond time resolution, then the time will be rounded up to 
** the nearest second. The number of milliseconds of sleep actually 
** requested from the operating system is returned.
*/
int sqlite3_sleep(int);
SQLITE_API int sqlite3_sleep(int);

/*
** CAPI3REF:  Name Of The Folder Holding Temporary Files
**
** If this global variable is made to point to a string which is
** the name of a folder (a.ka. directory), then all temporary files
** created by SQLite will be placed in that directory.  If this variable
2418
2419
2420
2421
2422
2423
2424


2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447







+
+







  int (*xBegin)(sqlite3_vtab *pVTab);
  int (*xSync)(sqlite3_vtab *pVTab);
  int (*xCommit)(sqlite3_vtab *pVTab);
  int (*xRollback)(sqlite3_vtab *pVTab);
  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
                       void **ppArg);

  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
};

/*
** The sqlite3_index_info structure and its substructures is used to
** pass information into and receive the reply from the xBestIndex
** method of an sqlite3_module.  The fields under **Inputs** are the
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
2511
2512
2513
2514
2515
2516
2517













2518
2519
2520
2521
2522
2523
2524
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553







+
+
+
+
+
+
+
+
+
+
+
+
+







*/
int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *,    /* Methods for the module */
  void *                     /* Client data for xCreate/xConnect */
);

/*
** This routine is identical to the sqlite3_create_module() method above,
** except that it allows a destructor function to be specified. It is
** even more experimental than the rest of the virtual tables API.
*/
int sqlite3_create_module_v2(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *,    /* Methods for the module */
  void *,                    /* Client data for xCreate/xConnect */
  void(*xDestroy)(void*)     /* Module destructor function */
);

/*
** Every module implementation uses a subclass of the following structure
** to describe a particular instance of the module.  Each subclass will
** be taylored to the specific needs of the module implementation.   The
** purpose of this superclass is to define certain fields that are common
** to all module implementations.
2717
2718
2719
2720
2721
2722
2723
2724

2725
2726
2727
2728
2729
2730
2731
2746
2747
2748
2749
2750
2751
2752

2753
2754
2755
2756
2757
2758
2759
2760







-
+







** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system. 
**
** 1970-01-01 00:00:00 is JD 2440587.5
2761
2762
2763
2764
2765
2766
2767
2768

2769
2770
2771
2772
2773


2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788

2789
2790
2791
2792
2793
2794
2795
2790
2791
2792
2793
2794
2795
2796

2797
2798
2799
2800


2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816

2817
2818
2819
2820
2821
2822
2823
2824







-
+



-
-
+
+














-
+







**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Internal interface definitions for SQLite.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_
/************** Include limits.h in the middle of sqliteInt.h ****************/
/************** Begin file limits.h ******************************************/
/************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
/************** Begin file sqliteLimit.h *************************************/
/*
** 2007 May 7
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** 
** This file defines various limits of what SQLite can process.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The maximum length of a TEXT or BLOB in bytes.   This also
** limits the size of a row in a table or index.
**
** The hard limit is the ability of a 32-bit signed integer
2926
2927
2928
2929
2930
2931
2932
2933

2934
2935
2936
2937
2938
2939
2940
2955
2956
2957
2958
2959
2960
2961

2962
2963
2964
2965
2966
2967
2968
2969







-
+







** Maximum length (in bytes) of the pattern in a LIKE or GLOB
** operator.
*/
#ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
# define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
#endif

/************** End of limits.h **********************************************/
/************** End of sqliteLimit.h *****************************************/
/************** Continuing where we left off in sqliteInt.h ******************/


#if defined(SQLITE_TCL) || defined(TCLSH)
# include <tcl.h>
#endif

2984
2985
2986
2987
2988
2989
2990
2991

2992
2993
2994
2995
2996
2997
2998
3013
3014
3015
3016
3017
3018
3019

3020
3021
3022
3023
3024
3025
3026
3027







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the header file for the generic hash-table implemenation
** used in SQLite.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITE_HASH_H_
#define _SQLITE_HASH_H_

/* Forward declarations of structures. */
typedef struct Hash Hash;
typedef struct HashElem HashElem;
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062




3063
3064
3065
3066
3067
3068
3069
3081
3082
3083
3084
3085
3086
3087




3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098







-
-
-
-
+
+
+
+







/* #define SQLITE_HASH_POINTER   2 // NOT USED */
#define SQLITE_HASH_STRING    3
#define SQLITE_HASH_BINARY    4

/*
** Access routines.  To delete, insert a NULL pointer.
*/
static void sqlite3HashInit(Hash*, int keytype, int copyKey);
static void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
static void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
static void sqlite3HashClear(Hash*);
SQLITE_PRIVATE void sqlite3HashInit(Hash*, int keytype, int copyKey);
SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const void *pKey, int nKey, void *pData);
SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const void *pKey, int nKey);
SQLITE_PRIVATE void sqlite3HashClear(Hash*);

/*
** Macros for looping over all elements of a hash table.  The idiom is
** like this:
**
**   Hash h;
**   HashElem *p;
3247
3248
3249
3250
3251
3252
3253
3254
3255

3256
3257
3258
3259
3260
3261
3262
3263
3276
3277
3278
3279
3280
3281
3282


3283

3284
3285
3286
3287
3288
3289
3290







-
-
+
-







/************** Continuing where we left off in sqliteInt.h ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stddef.h>

#if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
# define isnan(X)  ((X)!=(X))
#define sqlite3_isnan(X)  ((X)!=(X))
#endif

/*
** If compiling for a processor that lacks floating point support,
** substitute integer for floating-point
*/
#ifdef SQLITE_OMIT_FLOATING_POINT
# define double sqlite_int64
3418
3419
3420
3421
3422
3423
3424
3425

3426
3427
3428
3429
3430
3431
3432
3445
3446
3447
3448
3449
3450
3451

3452
3453
3454
3455
3456
3457
3458
3459







-
+







*************************************************************************
** Header file for the Virtual DataBase Engine (VDBE)
**
** This header defines the interface to the virtual database engine
** or VDBE.  The VDBE implements an abstract machine that runs a
** simple program to access and modify the underlying database.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITE_VDBE_H_
#define _SQLITE_VDBE_H_

/*
** A single VDBE is an opaque structure named "Vdbe".  Only routines
** in the source file sqliteVdbe.c are allowed to see the insides
3549
3550
3551
3552
3553
3554
3555

3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
















3572
3573
3574
3575



3576
3577

3578
3579
3580


3581
3582
3583
3584
3585



3586
3587
3588
3589



3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603













3604
3605
3606


3607
3608
3609
3610
3611
3612
3613
3614







3615
3616
3617
3618



3619
3620
3621
3622
3623
3624
3625




3626
3627
3628
3629


3630
3631
3632
3633



3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645











3646
3647
3648
3649
3650
3651





3652
3653
3654
3655
3656
3657





3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669



3670
3671
3672
3673
3674




3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
















3700
3701

3702
3703
3704
3705
3706
3707
3708
3709
3710
3711









3712
3713
3714

3715
3716
3717
3718
3719
3720
3721
3576
3577
3578
3579
3580
3581
3582
3583
















3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600



3601
3602
3603
3604

3605
3606


3607
3608
3609
3610



3611
3612
3613
3614



3615
3616
3617
3618













3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632


3633
3634
3635







3636
3637
3638
3639
3640
3641
3642
3643



3644
3645
3646
3647
3648
3649




3650
3651
3652
3653
3654
3655


3656
3657
3658



3659
3660
3661
3662











3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674





3675
3676
3677
3678
3679
3680





3681
3682
3683
3684
3685
3686
3687

3688
3689
3690
3691
3692
3693



3694
3695
3696
3697




3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
















3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727

3728
3729









3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740

3741
3742
3743
3744
3745
3746
3747
3748







+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
+
+
+

-
+

-
-
+
+


-
-
-
+
+
+

-
-
-
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+

-
-
-
-
-
-
-
+
+
+
+
+
+
+

-
-
-
+
+
+



-
-
-
-
+
+
+
+


-
-
+
+

-
-
-
+
+
+

-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+


-






-
-
-
+
+
+

-
-
-
-
+
+
+
+









-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
+

-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+


-
+







#define OP_Remainder                           82   /* same as TK_REM      */
#define OP_NewRowid                            23
#define OP_Multiply                            80   /* same as TK_STAR     */
#define OP_IfMemNeg                            24
#define OP_Variable                            25
#define OP_String                              26
#define OP_RealAffinity                        27
#define OP_VRename                             28
#define OP_ParseSchema                         28
#define OP_VOpen                               29
#define OP_Close                               30
#define OP_CreateIndex                         31
#define OP_IsUnique                            32
#define OP_NotFound                            33
#define OP_Int64                               34
#define OP_MustBeInt                           35
#define OP_Halt                                36
#define OP_Rowid                               37
#define OP_IdxLT                               38
#define OP_AddImm                              39
#define OP_Statement                           40
#define OP_RowData                             41
#define OP_MemMax                              42
#define OP_Push                                43
#define OP_ParseSchema                         29
#define OP_VOpen                               30
#define OP_Close                               31
#define OP_CreateIndex                         32
#define OP_IsUnique                            33
#define OP_NotFound                            34
#define OP_Int64                               35
#define OP_MustBeInt                           36
#define OP_Halt                                37
#define OP_Rowid                               38
#define OP_IdxLT                               39
#define OP_AddImm                              40
#define OP_Statement                           41
#define OP_RowData                             42
#define OP_MemMax                              43
#define OP_Push                                44
#define OP_Or                                  60   /* same as TK_OR       */
#define OP_NotExists                           44
#define OP_MemIncr                             45
#define OP_Gosub                               46
#define OP_NotExists                           45
#define OP_MemIncr                             46
#define OP_Gosub                               47
#define OP_Divide                              81   /* same as TK_SLASH    */
#define OP_Integer                             47
#define OP_Integer                             48
#define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
#define OP_MemInt                              48
#define OP_Prev                                49
#define OP_MemInt                              49
#define OP_Prev                                50
#define OP_Concat                              83   /* same as TK_CONCAT   */
#define OP_BitAnd                              74   /* same as TK_BITAND   */
#define OP_VColumn                             50
#define OP_CreateTable                         51
#define OP_Last                                52
#define OP_VColumn                             51
#define OP_CreateTable                         52
#define OP_Last                                53
#define OP_IsNull                              65   /* same as TK_ISNULL   */
#define OP_IncrVacuum                          53
#define OP_IdxRowid                            54
#define OP_MakeIdxRec                          55
#define OP_IncrVacuum                          54
#define OP_IdxRowid                            55
#define OP_MakeIdxRec                          56
#define OP_ShiftRight                          77   /* same as TK_RSHIFT   */
#define OP_ResetCount                          56
#define OP_FifoWrite                           57
#define OP_Callback                            58
#define OP_ContextPush                         59
#define OP_DropTrigger                         62
#define OP_DropIndex                           63
#define OP_IdxGE                               64
#define OP_IdxDelete                           73
#define OP_Vacuum                              84
#define OP_MoveLe                              86
#define OP_IfNot                               89
#define OP_DropTable                           90
#define OP_MakeRecord                          91
#define OP_ResetCount                          57
#define OP_FifoWrite                           58
#define OP_Callback                            59
#define OP_ContextPush                         62
#define OP_DropTrigger                         63
#define OP_DropIndex                           64
#define OP_IdxGE                               73
#define OP_IdxDelete                           84
#define OP_Vacuum                              86
#define OP_MoveLe                              89
#define OP_IfNot                               90
#define OP_DropTable                           91
#define OP_MakeRecord                          92
#define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
#define OP_Delete                              92
#define OP_AggFinal                            93
#define OP_Delete                              93
#define OP_AggFinal                            94
#define OP_ShiftLeft                           76   /* same as TK_LSHIFT   */
#define OP_Dup                                 94
#define OP_Goto                                95
#define OP_TableLock                           96
#define OP_FifoRead                            97
#define OP_Clear                               98
#define OP_IdxGT                               99
#define OP_MoveLt                             100
#define OP_Dup                                 95
#define OP_Goto                                96
#define OP_TableLock                           97
#define OP_FifoRead                            98
#define OP_Clear                               99
#define OP_IdxGT                              100
#define OP_MoveLt                             101
#define OP_Le                                  70   /* same as TK_LE       */
#define OP_VerifyCookie                       101
#define OP_AggStep                            102
#define OP_Pull                               103
#define OP_VerifyCookie                       102
#define OP_AggStep                            103
#define OP_Pull                               104
#define OP_ToText                             138   /* same as TK_TO_TEXT  */
#define OP_Not                                 16   /* same as TK_NOT      */
#define OP_ToReal                             142   /* same as TK_TO_REAL  */
#define OP_SetNumColumns                      104
#define OP_AbsValue                           105
#define OP_Transaction                        106
#define OP_VFilter                            107
#define OP_SetNumColumns                      105
#define OP_AbsValue                           106
#define OP_Transaction                        107
#define OP_VFilter                            108
#define OP_Negative                            85   /* same as TK_UMINUS   */
#define OP_Ne                                  67   /* same as TK_NE       */
#define OP_VDestroy                           108
#define OP_ContextPop                         109
#define OP_VDestroy                           109
#define OP_ContextPop                         110
#define OP_BitOr                               75   /* same as TK_BITOR    */
#define OP_Next                               110
#define OP_IdxInsert                          111
#define OP_Distinct                           112
#define OP_Next                               111
#define OP_IdxInsert                          112
#define OP_Distinct                           113
#define OP_Lt                                  71   /* same as TK_LT       */
#define OP_Insert                             113
#define OP_Destroy                            114
#define OP_ReadCookie                         115
#define OP_ForceInt                           116
#define OP_LoadAnalysis                       117
#define OP_Explain                            118
#define OP_IfMemZero                          119
#define OP_OpenPseudo                         120
#define OP_OpenEphemeral                      121
#define OP_Null                               122
#define OP_Blob                               123
#define OP_Insert                             114
#define OP_Destroy                            115
#define OP_ReadCookie                         116
#define OP_ForceInt                           117
#define OP_LoadAnalysis                       118
#define OP_Explain                            119
#define OP_IfMemZero                          120
#define OP_OpenPseudo                         121
#define OP_OpenEphemeral                      122
#define OP_Null                               123
#define OP_Blob                               124
#define OP_Add                                 78   /* same as TK_PLUS     */
#define OP_MemStore                           124
#define OP_Rewind                             127
#define OP_MoveGe                             128
#define OP_VBegin                             129
#define OP_VUpdate                            130
#define OP_MemStore                           127
#define OP_Rewind                             128
#define OP_MoveGe                             129
#define OP_VBegin                             130
#define OP_VUpdate                            131
#define OP_BitNot                              87   /* same as TK_BITNOT   */
#define OP_VCreate                            131
#define OP_MemMove                            132
#define OP_MemNull                            133
#define OP_Found                              134
#define OP_NullRow                            135
#define OP_VCreate                            132
#define OP_MemMove                            133
#define OP_MemNull                            134
#define OP_Found                              135
#define OP_NullRow                            136

/* The following opcode values are never used */
#define OP_NotUsed_136                        136
#define OP_NotUsed_137                        137

/* Opcodes that are guaranteed to never push a value onto the stack
** contain a 1 their corresponding position of the following mask
** set.  See the opcodeNoPush() function in vdbeaux.c  */
#define NOPUSH_MASK_0 0xeeb4
#define NOPUSH_MASK_1 0x796b
#define NOPUSH_MASK_2 0x7ddb
#define NOPUSH_MASK_3 0xff32
#define NOPUSH_MASK_1 0xf96b
#define NOPUSH_MASK_2 0xfbb6
#define NOPUSH_MASK_3 0xfe64
#define NOPUSH_MASK_4 0xffff
#define NOPUSH_MASK_5 0xb6f7
#define NOPUSH_MASK_6 0xfdfd
#define NOPUSH_MASK_7 0x93b3
#define NOPUSH_MASK_8 0x7ccf
#define NOPUSH_MASK_5 0x6ef7
#define NOPUSH_MASK_6 0xfbfb
#define NOPUSH_MASK_7 0x8767
#define NOPUSH_MASK_8 0x7d9f
#define NOPUSH_MASK_9 0x0000

/************** End of opcodes.h *********************************************/
/************** Continuing where we left off in vdbe.h ***********************/

/*
** Prototypes for the VDBE interface.  See comments on the implementation
** for a description of what each of these routines does.
*/
static Vdbe *sqlite3VdbeCreate(sqlite3*);
static int sqlite3VdbeAddOp(Vdbe*,int,int,int);
static int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
static int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
static void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
static void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
static void sqlite3VdbeJumpHere(Vdbe*, int addr);
static void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
static void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
static VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
static int sqlite3VdbeMakeLabel(Vdbe*);
static void sqlite3VdbeDelete(Vdbe*);
static void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
static int sqlite3VdbeFinalize(Vdbe*);
static void sqlite3VdbeResolveLabel(Vdbe*, int);
static int sqlite3VdbeCurrentAddr(Vdbe*);
SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe*,int,int,int);
SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int);
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
#ifdef SQLITE_DEBUG
static   void sqlite3VdbeTrace(Vdbe*,FILE*);
SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
#endif
static void sqlite3VdbeResetStepResult(Vdbe*);
static int sqlite3VdbeReset(Vdbe*);
static void sqlite3VdbeSetNumCols(Vdbe*,int);
static int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
static void sqlite3VdbeCountChanges(Vdbe*);
static sqlite3 *sqlite3VdbeDb(Vdbe*);
static void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
static const char *sqlite3VdbeGetSql(Vdbe*);
static void sqlite3VdbeSwap(Vdbe*,Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, int);
SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n);
SQLITE_PRIVATE const char *sqlite3VdbeGetSql(Vdbe*);
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);

#ifndef NDEBUG
static   void sqlite3VdbeComment(Vdbe*, const char*, ...);
SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
# define VdbeComment(X)  sqlite3VdbeComment X
#else
# define VdbeComment(X)
#endif

#endif

3734
3735
3736
3737
3738
3739
3740
3741

3742
3743
3744
3745
3746
3747
3748
3761
3762
3763
3764
3765
3766
3767

3768
3769
3770
3771
3772
3773
3774
3775







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite B-Tree file
** subsystem.  See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_

/* TODO: This definition is just included so other modules compile. It
** needs to be revisited.
*/
3764
3765
3766
3767
3768
3769
3770
3771

3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813


























3814
3815
3816
3817
3818




3819
3820

3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832




3833
3834

3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846




3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860












3861
3862
3863


3864
3865
3866


3867
3868
3869
3870
3871



3872
3873
3874
3875
3876
3877
3878
3791
3792
3793
3794
3795
3796
3797

3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814


























3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841




3842
3843
3844
3845
3846

3847
3848
3849
3850
3851
3852
3853
3854
3855




3856
3857
3858
3859
3860

3861
3862
3863
3864
3865
3866
3867
3868
3869




3870
3871
3872
3873
3874
3875












3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888


3889
3890
3891


3892
3893
3894
3895



3896
3897
3898
3899
3900
3901
3902
3903
3904
3905







-
+
















-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
+
+
+
+

-
+








-
-
-
-
+
+
+
+

-
+








-
-
-
-
+
+
+
+


-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+

-
-
+
+


-
-
-
+
+
+







** Forward declarations of structure
*/
typedef struct Btree Btree;
typedef struct BtCursor BtCursor;
typedef struct BtShared BtShared;


static int sqlite3BtreeOpen(
SQLITE_PRIVATE int sqlite3BtreeOpen(
  const char *zFilename,   /* Name of database file to open */
  sqlite3 *db,             /* Associated database connection */
  Btree **,                /* Return open Btree* here */
  int flags                /* Flags */
);

/* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
** following values.
**
** NOTE:  These values must match the corresponding PAGER_ values in
** pager.h.
*/
#define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
#define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
#define BTREE_MEMORY        4  /* In-memory DB.  No argument */

static int sqlite3BtreeClose(Btree*);
static int sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*);
static int sqlite3BtreeSetCacheSize(Btree*,int);
static int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
static int sqlite3BtreeSyncDisabled(Btree*);
static int sqlite3BtreeSetPageSize(Btree*,int,int);
static int sqlite3BtreeGetPageSize(Btree*);
static int sqlite3BtreeMaxPageCount(Btree*,int);
static int sqlite3BtreeGetReserve(Btree*);
static int sqlite3BtreeSetAutoVacuum(Btree *, int);
static int sqlite3BtreeGetAutoVacuum(Btree *);
static int sqlite3BtreeBeginTrans(Btree*,int);
static int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
static int sqlite3BtreeCommitPhaseTwo(Btree*);
static int sqlite3BtreeCommit(Btree*);
static int sqlite3BtreeRollback(Btree*);
static int sqlite3BtreeBeginStmt(Btree*);
static int sqlite3BtreeCommitStmt(Btree*);
static int sqlite3BtreeRollbackStmt(Btree*);
static int sqlite3BtreeCreateTable(Btree*, int*, int flags);
static int sqlite3BtreeIsInTrans(Btree*);
static int sqlite3BtreeIsInStmt(Btree*);
static int sqlite3BtreeIsInReadTrans(Btree*);
static void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
static int sqlite3BtreeSchemaLocked(Btree *);
static int sqlite3BtreeLockTable(Btree *, int, u8);
SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
SQLITE_PRIVATE int sqlite3BtreeSetBusyHandler(Btree*,BusyHandler*);
SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree*,int,int);
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*);
SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree*);
SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree*);
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree*);
SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *);
SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *, int, u8);

static const char *sqlite3BtreeGetFilename(Btree *);
static const char *sqlite3BtreeGetDirname(Btree *);
static const char *sqlite3BtreeGetJournalname(Btree *);
static int sqlite3BtreeCopyFile(Btree *, Btree *);
SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *);
SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);

static int sqlite3BtreeIncrVacuum(Btree *);
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);

/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
** of the following flags:
*/
#define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
#define BTREE_ZERODATA   2    /* Table has keys only - no data */
#define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */

static int sqlite3BtreeDropTable(Btree*, int, int*);
static int sqlite3BtreeClearTable(Btree*, int);
static int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
static int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int);
SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree*, int idx, u32 *pValue);
SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);

static int sqlite3BtreeCursor(
SQLITE_PRIVATE int sqlite3BtreeCursor(
  Btree*,                              /* BTree containing table to open */
  int iTable,                          /* Index of root page */
  int wrFlag,                          /* 1 for writing.  0 for read-only */
  int(*)(void*,int,const void*,int,const void*),  /* Key comparison function */
  void*,                               /* First argument to compare function */
  BtCursor **ppCursor                  /* Returned cursor */
);

static int sqlite3BtreeCloseCursor(BtCursor*);
static int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
static int sqlite3BtreeDelete(BtCursor*);
static int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
SQLITE_PRIVATE int sqlite3BtreeMoveto(BtCursor*,const void *pKey,i64 nKey,int bias,int *pRes);
SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
                                  const void *pData, int nData,
                                  int nZero, int bias);
static int sqlite3BtreeFirst(BtCursor*, int *pRes);
static int sqlite3BtreeLast(BtCursor*, int *pRes);
static int sqlite3BtreeNext(BtCursor*, int *pRes);
static int sqlite3BtreeEof(BtCursor*);
static int sqlite3BtreeFlags(BtCursor*);
static int sqlite3BtreePrevious(BtCursor*, int *pRes);
static int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
static int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
static const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
static const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
static int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
static int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor*);
SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);

static char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
static struct Pager *sqlite3BtreePager(Btree*);
SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);

static int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
static void sqlite3BtreeCacheOverflow(BtCursor *);
SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);

#ifdef SQLITE_TEST
static int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
static void sqlite3BtreeCursorList(Btree*);
static int sqlite3BtreePageDump(Btree*, int, int recursive);
SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
SQLITE_PRIVATE int sqlite3BtreePageDump(Btree*, int, int recursive);
#endif

#endif /* _BTREE_H_ */

/************** End of btree.h ***********************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
/************** Include pager.h in the middle of sqliteInt.h *****************/
3888
3889
3890
3891
3892
3893
3894
3895

3896
3897
3898
3899
3900
3901
3902
3915
3916
3917
3918
3919
3920
3921

3922
3923
3924
3925
3926
3927
3928
3929







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem.  The page cache subsystem reads and writes a file a page
** at a time and provides a journal for rollback.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

#ifndef _PAGER_H_
#define _PAGER_H_

/*
** The type used to represent a page number.  The first page in a file
3929
3930
3931
3932
3933
3934
3935
3936

3937
3938
3939
3940
3941
3942
3943
3944
3945
3946









3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974



























3975
3976
3977

3978
3979
3980
3981

3982
3983
3984
3985
3986


3987
3988
3989
3990

3991
3992
3993
3994
3995


3996
3997
3998
3999
4000
4001
4002
3956
3957
3958
3959
3960
3961
3962

3963
3964









3965
3966
3967
3968
3969
3970
3971
3972
3973
3974



























3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003

4004
4005
4006
4007

4008
4009
4010
4011


4012
4013
4014
4015
4016

4017
4018
4019
4020


4021
4022
4023
4024
4025
4026
4027
4028
4029







-
+

-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+



-
+



-
-
+
+



-
+



-
-
+
+







#define PAGER_LOCKINGMODE_NORMAL      0
#define PAGER_LOCKINGMODE_EXCLUSIVE   1

/*
** See source code comments for a detailed description of the following
** routines:
*/
static int sqlite3PagerOpen(Pager **ppPager, const char *zFilename,
SQLITE_PRIVATE int sqlite3PagerOpen(Pager **ppPager, const char *zFilename,
                     int nExtra, int flags);
static void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
static void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
static void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
static int sqlite3PagerSetPagesize(Pager*, int);
static int sqlite3PagerMaxPageCount(Pager*, int);
static int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
static void sqlite3PagerSetCachesize(Pager*, int);
static int sqlite3PagerClose(Pager *pPager);
static int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, BusyHandler *pBusyHandler);
SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager*, void(*)(DbPage*,int));
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*,int));
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, int);
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
static DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
static int sqlite3PagerRef(DbPage*);
static int sqlite3PagerUnref(DbPage*);
static int sqlite3PagerWrite(DbPage*);
static int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
static int sqlite3PagerPagecount(Pager*);
static int sqlite3PagerTruncate(Pager*,Pgno);
static int sqlite3PagerBegin(DbPage*, int exFlag);
static int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
static int sqlite3PagerCommitPhaseTwo(Pager*);
static int sqlite3PagerRollback(Pager*);
static int sqlite3PagerIsreadonly(Pager*);
static int sqlite3PagerStmtBegin(Pager*);
static int sqlite3PagerStmtCommit(Pager*);
static int sqlite3PagerStmtRollback(Pager*);
static void sqlite3PagerDontRollback(DbPage*);
static void sqlite3PagerDontWrite(DbPage*);
static int sqlite3PagerRefcount(Pager*);
static void sqlite3PagerSetSafetyLevel(Pager*,int,int);
static const char *sqlite3PagerFilename(Pager*);
static const char *sqlite3PagerDirname(Pager*);
static const char *sqlite3PagerJournalname(Pager*);
static int sqlite3PagerNosync(Pager*);
static int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
static void *sqlite3PagerGetData(DbPage *); 
static void *sqlite3PagerGetExtra(DbPage *); 
static int sqlite3PagerLockingMode(Pager *, int);
SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);
SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void*);
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*);
SQLITE_PRIVATE int sqlite3PagerTruncate(Pager*,Pgno);
SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, Pgno);
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager*);
SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager*);
SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager*);
SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager*);
SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager*);
SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno);
SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);

#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
static   int sqlite3PagerReleaseMemory(int);
SQLITE_PRIVATE   int sqlite3PagerReleaseMemory(int);
#endif

#ifdef SQLITE_HAS_CODEC
static   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
#endif

#if !defined(NDEBUG) || defined(SQLITE_TEST)
static   Pgno sqlite3PagerPagenumber(DbPage*);
static   int sqlite3PagerIswriteable(DbPage*);
SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
#endif

#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
static   int sqlite3PagerLockstate(Pager*);
SQLITE_PRIVATE   int sqlite3PagerLockstate(Pager*);
#endif

#ifdef SQLITE_TEST
static   int *sqlite3PagerStats(Pager*);
static   void sqlite3PagerRefdump(Pager*);
SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
  int pager3_refinfo_enable;
#endif

#ifdef SQLITE_TEST
void disable_simulated_io_errors(void);
void enable_simulated_io_errors(void);
#else
4174
4175
4176
4177
4178
4179
4180
4181

4182
4183
4184
4185
4186
4187
4188
4201
4202
4203
4204
4205
4206
4207

4208
4209
4210
4211
4212
4213
4214
4215







-
+







#if !defined(OS_UNIX) && !defined(OS_OTHER)
# define OS_OTHER 0
# ifndef OS_WIN
#   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
#     define OS_WIN 1
#     define OS_UNIX 0
#     define OS_OS2 0
#   elif defined(_EMX_) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
#   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
#     define OS_WIN 0
#     define OS_UNIX 0
#     define OS_OS2 1
#   else
#     define OS_WIN 0
#     define OS_UNIX 1
#     define OS_OS2 0
4201
4202
4203
4204
4205
4206
4207



4208
4209
4210
4211
4212

4213
4214
4215
4216
4217
4218
4219
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250







+
+
+





+







/*
** Define the maximum size of a temporary filename
*/
#if OS_WIN
# include <windows.h>
# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
#elif OS_OS2
# if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
#  include <os2safe.h> /* has to be included before os2.h for linking to work */
# endif
# define INCL_DOSDATETIME
# define INCL_DOSFILEMGR
# define INCL_DOSERRORS
# define INCL_DOSMISC
# define INCL_DOSPROCESS
# define INCL_DOSMODULEMGR
# include <os2.h>
# define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
#else
# define SQLITE_TEMPNAME_SIZE 200
#endif

/* If the SET_FULLSYNC macro is not defined above, then make it
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520




































4521
4522
4523
4524


4525
4526
4527
4528
4529
4530
4531
4509
4510
4511
4512
4513
4514
4515




































4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553


4554
4555
4556
4557
4558
4559
4560
4561
4562







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
+
+







#define RESERVED_BYTE     (PENDING_BYTE+1)
#define SHARED_FIRST      (PENDING_BYTE+2)
#define SHARED_SIZE       510

/*
** Prototypes for operating system interface routines.
*/
static int sqlite3OsClose(OsFile**);
static int sqlite3OsOpenDirectory(OsFile*, const char*);
static int sqlite3OsRead(OsFile*, void*, int amt);
static int sqlite3OsWrite(OsFile*, const void*, int amt);
static int sqlite3OsSeek(OsFile*, i64 offset);
static int sqlite3OsTruncate(OsFile*, i64 size);
static int sqlite3OsSync(OsFile*, int);
static void sqlite3OsSetFullSync(OsFile *id, int setting);
static int sqlite3OsFileSize(OsFile*, i64 *pSize);
static int sqlite3OsLock(OsFile*, int);
static int sqlite3OsUnlock(OsFile*, int);
static int sqlite3OsCheckReservedLock(OsFile *id);
static int sqlite3OsOpenReadWrite(const char*, OsFile**, int*);
static int sqlite3OsOpenExclusive(const char*, OsFile**, int);
static int sqlite3OsOpenReadOnly(const char*, OsFile**);
static int sqlite3OsDelete(const char*);
static int sqlite3OsFileExists(const char*);
static char *sqlite3OsFullPathname(const char*);
static int sqlite3OsIsDirWritable(char*);
static int sqlite3OsSyncDirectory(const char*);
static int sqlite3OsSectorSize(OsFile *id);
static int sqlite3OsTempFileName(char*);
static int sqlite3OsRandomSeed(char*);
static int sqlite3OsSleep(int ms);
static int sqlite3OsCurrentTime(double*);
static void sqlite3OsEnterMutex(void);
static void sqlite3OsLeaveMutex(void);
static int sqlite3OsInMutex(int);
static ThreadData *sqlite3OsThreadSpecificData(int);
static void *sqlite3OsMalloc(int);
static void *sqlite3OsRealloc(void *, int);
static void sqlite3OsFree(void *);
static int sqlite3OsAllocationSize(void *);
static void *sqlite3OsDlopen(const char*);
static void *sqlite3OsDlsym(void*, const char*);
static int sqlite3OsDlclose(void*);
SQLITE_PRIVATE int sqlite3OsClose(OsFile**);
SQLITE_PRIVATE int sqlite3OsOpenDirectory(OsFile*, const char*);
SQLITE_PRIVATE int sqlite3OsRead(OsFile*, void*, int amt);
SQLITE_PRIVATE int sqlite3OsWrite(OsFile*, const void*, int amt);
SQLITE_PRIVATE int sqlite3OsSeek(OsFile*, i64 offset);
SQLITE_PRIVATE int sqlite3OsTruncate(OsFile*, i64 size);
SQLITE_PRIVATE int sqlite3OsSync(OsFile*, int);
SQLITE_PRIVATE void sqlite3OsSetFullSync(OsFile *id, int setting);
SQLITE_PRIVATE int sqlite3OsFileSize(OsFile*, i64 *pSize);
SQLITE_PRIVATE int sqlite3OsLock(OsFile*, int);
SQLITE_PRIVATE int sqlite3OsUnlock(OsFile*, int);
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(OsFile *id);
SQLITE_PRIVATE int sqlite3OsOpenReadWrite(const char*, OsFile**, int*);
SQLITE_PRIVATE int sqlite3OsOpenExclusive(const char*, OsFile**, int);
SQLITE_PRIVATE int sqlite3OsOpenReadOnly(const char*, OsFile**);
SQLITE_PRIVATE int sqlite3OsDelete(const char*);
SQLITE_PRIVATE int sqlite3OsFileExists(const char*);
SQLITE_PRIVATE char *sqlite3OsFullPathname(const char*);
SQLITE_PRIVATE int sqlite3OsIsDirWritable(char*);
SQLITE_PRIVATE int sqlite3OsSyncDirectory(const char*);
SQLITE_PRIVATE int sqlite3OsSectorSize(OsFile *id);
SQLITE_PRIVATE int sqlite3OsTempFileName(char*);
SQLITE_PRIVATE int sqlite3OsRandomSeed(char*);
SQLITE_PRIVATE int sqlite3OsSleep(int ms);
SQLITE_PRIVATE int sqlite3OsCurrentTime(double*);
SQLITE_PRIVATE void sqlite3OsEnterMutex(void);
SQLITE_PRIVATE void sqlite3OsLeaveMutex(void);
SQLITE_PRIVATE int sqlite3OsInMutex(int);
SQLITE_PRIVATE ThreadData *sqlite3OsThreadSpecificData(int);
SQLITE_PRIVATE void *sqlite3OsMalloc(int);
SQLITE_PRIVATE void *sqlite3OsRealloc(void *, int);
SQLITE_PRIVATE void sqlite3OsFree(void *);
SQLITE_PRIVATE int sqlite3OsAllocationSize(void *);
SQLITE_PRIVATE void *sqlite3OsDlopen(const char*);
SQLITE_PRIVATE void *sqlite3OsDlsym(void*, const char*);
SQLITE_PRIVATE int sqlite3OsDlclose(void*);

#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
static   int sqlite3OsFileHandle(OsFile *id);
static   int sqlite3OsLockState(OsFile *id);
SQLITE_PRIVATE   int sqlite3OsFileHandle(OsFile *id);
SQLITE_PRIVATE   int sqlite3OsLockState(OsFile *id);
#endif

/*
** If the SQLITE_ENABLE_REDEF_IO macro is defined, then the OS-layer
** interface routines are not called directly but are invoked using
** pointers to functions.  This allows the implementation of various
** OS-layer interface routines to be modified at run-time.  There are
4918
4919
4920
4921
4922
4923
4924

4925
4926
4927
4928
4929
4930
4931
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963







+







** instance of the following structure, stored in the sqlite3.aModule
** hash table.
*/
struct Module {
  const sqlite3_module *pModule;       /* Callback pointers */
  const char *zName;                   /* Name passed to create_module() */
  void *pAux;                          /* pAux passed to create_module() */
  void (*xDestroy)(void *);            /* Module destructor function */
};

/*
** Possible values for FuncDef.flags
*/
#define SQLITE_FUNC_LIKE   0x01  /* Candidate for the LIKE optimization */
#define SQLITE_FUNC_CASE   0x02  /* Case-sensitive LIKE-type function */
4939
4940
4941
4942
4943
4944
4945



4946
4947
4948
4949
4950
4951
4952
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987







+
+
+







  char *zName;     /* Name of this column */
  Expr *pDflt;     /* Default value of this column */
  char *zType;     /* Data type for this column */
  char *zColl;     /* Collating sequence.  If NULL, use the default */
  u8 notNull;      /* True if there is a NOT NULL constraint */
  u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
  char affinity;   /* One of the SQLITE_AFF_... values */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  u8 isHidden;     /* True if this column is 'hidden' */
#endif
};

/*
** A "Collating Sequence" is defined by an instance of the following
** structure. Conceptually, a collating sequence consists of a name and
** a comparison routine that defines the order of that sequence.
**
5078
5079
5080
5081
5082
5083
5084

5085
5086

5087
5088
5089
5090
5091
5092
5093
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130







+


+







/*
** Test to see whether or not a table is a virtual table.  This is
** done as a macro so that it will be optimized out when virtual
** table support is omitted from the build.
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE
#  define IsVirtual(X) ((X)->isVirtual)
#  define IsHiddenColumn(X) ((X)->isHidden)
#else
#  define IsVirtual(X) 0
#  define IsHiddenColumn(X) 0
#endif

/*
** Each foreign key constraint is an instance of the following structure.
**
** A foreign key is associated with two tables.  The "from" table is
** the table that contains the REFERENCES clause that creates the foreign
5947
5948
5949
5950
5951
5952
5953
5954

5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965



5966
5967
5968
5969
5970
5971





5972
5973
5974
5975



5976
5977

5978
5979
5980
5981


5982
5983
5984


5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020



































6021
6022

6023
6024
6025

6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037








6038
6039
6040
6041
6042
6043





6044
6045
6046
6047



6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071























6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108




































6109
6110
6111

6112
6113
6114
6115
6116
6117





6118
6119
6120
6121
6122
6123
6124
6125
6126







6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137



6138
6139
6140
6141
6142




6143
6144
6145
6146
6147
6148
6149
6150
6151



6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188




































6189
6190
6191
6192
6193
6194
6195
6196
6197








6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229































6230
6231
6232
6233
6234
6235




6236
6237
6238
6239


6240
6241
6242
6243
6244
6245
6246

6247
6248
6249
6250
6251
6252

6253
6254
6255
6256
6257
6258



6259
6260
6261
6262
6263
6264
6265
6266
6267


6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282




6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297














6298
6299
6300
6301
6302


6303
6304
6305
6306
6307
6308
6309
6310




6311
6312
6313
6314
6315
6316
6317

6318
6319
6320
6321
6322
6323
6324
6325
6326
6327

6328
6329
6330
6331
6332
6333
6334
5984
5985
5986
5987
5988
5989
5990

5991
5992
5993
5994
5995
5996
5997
5998
5999



6000
6001
6002
6003





6004
6005
6006
6007
6008
6009



6010
6011
6012
6013

6014
6015
6016


6017
6018
6019


6020
6021
6022



































6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058

6059
6060
6061

6062
6063
6064
6065
6066








6067
6068
6069
6070
6071
6072
6073
6074
6075





6076
6077
6078
6079
6080
6081



6082
6083
6084
6085























6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109




































6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147

6148
6149





6150
6151
6152
6153
6154
6155
6156







6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171



6172
6173
6174
6175




6176
6177
6178
6179
6180
6181
6182
6183
6184
6185



6186
6187
6188
6189




































6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226








6227
6228
6229
6230
6231
6232
6233
6234
6235































6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268




6269
6270
6271
6272
6273
6274


6275
6276
6277
6278
6279
6280
6281
6282

6283
6284
6285
6286
6287
6288

6289
6290
6291
6292



6293
6294
6295
6296
6297
6298
6299
6300
6301
6302


6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315




6316
6317
6318
6319
6320














6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337


6338
6339
6340
6341
6342
6343




6344
6345
6346
6347
6348
6349
6350
6351
6352
6353

6354
6355
6356
6357
6358
6359
6360
6361
6362
6363

6364
6365
6366
6367
6368
6369
6370
6371







-
+








-
-
-
+
+
+

-
-
-
-
-
+
+
+
+
+

-
-
-
+
+
+

-
+


-
-
+
+

-
-
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
+


-
+




-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+

-
-
-
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+

-
-
-
-
-
+
+
+
+
+


-
-
-
-
-
-
-
+
+
+
+
+
+
+








-
-
-
+
+
+

-
-
-
-
+
+
+
+






-
-
-
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
-
+
+
+
+


-
-
+
+






-
+





-
+



-
-
-
+
+
+







-
-
+
+











-
-
-
-
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+



-
-
+
+




-
-
-
-
+
+
+
+






-
+









-
+







/*
** The SQLITE_CORRUPT_BKPT macro can be either a constant (for production
** builds) or a function call (for debugging).  If it is a function call,
** it allows the operator to set a breakpoint at the spot where database
** corruption is first detected.
*/
#ifdef SQLITE_DEBUG
static   int sqlite3Corrupt(void);
SQLITE_PRIVATE   int sqlite3Corrupt(void);
# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
#else
# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
#endif

/*
** Internal function prototypes
*/
static int sqlite3StrICmp(const char *, const char *);
static int sqlite3StrNICmp(const char *, const char *, int);
static int sqlite3IsNumber(const char*, int*, u8);
SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
SQLITE_PRIVATE int sqlite3StrNICmp(const char *, const char *, int);
SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);

static void *sqlite3Malloc(int,int);
static void *sqlite3MallocRaw(int,int);
static void *sqlite3Realloc(void*,int);
static char *sqlite3StrDup(const char*);
static char *sqlite3StrNDup(const char*, int);
SQLITE_PRIVATE void *sqlite3Malloc(int,int);
SQLITE_PRIVATE void *sqlite3MallocRaw(int,int);
SQLITE_PRIVATE void *sqlite3Realloc(void*,int);
SQLITE_PRIVATE char *sqlite3StrDup(const char*);
SQLITE_PRIVATE char *sqlite3StrNDup(const char*, int);
# define sqlite3CheckMemory(a,b)
static void *sqlite3ReallocOrFree(void*,int);
static void sqlite3FreeX(void*);
static void *sqlite3MallocX(int);
SQLITE_PRIVATE void *sqlite3ReallocOrFree(void*,int);
SQLITE_PRIVATE void sqlite3FreeX(void*);
SQLITE_PRIVATE void *sqlite3MallocX(int);
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
static   int sqlite3AllocSize(void *);
SQLITE_PRIVATE   int sqlite3AllocSize(void *);
#endif

static char *sqlite3MPrintf(const char*, ...);
static char *sqlite3VMPrintf(const char*, va_list);
SQLITE_PRIVATE char *sqlite3MPrintf(const char*, ...);
SQLITE_PRIVATE char *sqlite3VMPrintf(const char*, va_list);
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
static   void sqlite3DebugPrintf(const char*, ...);
static   void *sqlite3TextToPtr(const char*);
SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
SQLITE_PRIVATE   void *sqlite3TextToPtr(const char*);
#endif
static void sqlite3SetString(char **, ...);
static void sqlite3ErrorMsg(Parse*, const char*, ...);
static void sqlite3ErrorClear(Parse*);
static void sqlite3Dequote(char*);
static void sqlite3DequoteExpr(Expr*);
static int sqlite3KeywordCode(const unsigned char*, int);
static int sqlite3RunParser(Parse*, const char*, char **);
static void sqlite3FinishCoding(Parse*);
static Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
static Expr *sqlite3ExprOrFree(int, Expr*, Expr*, const Token*);
static Expr *sqlite3RegisterExpr(Parse*,Token*);
static Expr *sqlite3ExprAnd(Expr*, Expr*);
static void sqlite3ExprSpan(Expr*,Token*,Token*);
static Expr *sqlite3ExprFunction(ExprList*, Token*);
static void sqlite3ExprAssignVarNumber(Parse*, Expr*);
static void sqlite3ExprDelete(Expr*);
static ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
static void sqlite3ExprListDelete(ExprList*);
static int sqlite3Init(sqlite3*, char**);
static int sqlite3InitCallback(void*, int, char**, char**);
static void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
static void sqlite3ResetInternalSchema(sqlite3*, int);
static void sqlite3BeginParse(Parse*,int);
static void sqlite3CommitInternalChanges(sqlite3*);
static Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
static void sqlite3OpenMasterTable(Parse *, int);
static void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
static void sqlite3AddColumn(Parse*,Token*);
static void sqlite3AddNotNull(Parse*, int);
static void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
static void sqlite3AddCheckConstraint(Parse*, Expr*);
static void sqlite3AddColumnType(Parse*,Token*);
static void sqlite3AddDefaultValue(Parse*,Expr*);
static void sqlite3AddCollateType(Parse*, const char*, int);
static void sqlite3EndTable(Parse*,Token*,Token*,Select*);
SQLITE_PRIVATE void sqlite3SetString(char **, ...);
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
SQLITE_PRIVATE void sqlite3ErrorClear(Parse*);
SQLITE_PRIVATE void sqlite3Dequote(char*);
SQLITE_PRIVATE void sqlite3DequoteExpr(Expr*);
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
SQLITE_PRIVATE Expr *sqlite3Expr(int, Expr*, Expr*, const Token*);
SQLITE_PRIVATE Expr *sqlite3ExprOrFree(int, Expr*, Expr*, const Token*);
SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse*,Token*);
SQLITE_PRIVATE Expr *sqlite3ExprAnd(Expr*, Expr*);
SQLITE_PRIVATE void sqlite3ExprSpan(Expr*,Token*,Token*);
SQLITE_PRIVATE Expr *sqlite3ExprFunction(ExprList*, Token*);
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
SQLITE_PRIVATE void sqlite3ExprDelete(Expr*);
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(ExprList*,Expr*,Token*);
SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList*);
SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,char*,Select*);
SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,Expr*);
SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, const char*, int);
SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);

static void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);

#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
static   int sqlite3ViewGetColumnNames(Parse*,Table*);
SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
#else
# define sqlite3ViewGetColumnNames(A,B) 0
#endif

static void sqlite3DropTable(Parse*, SrcList*, int, int);
static void sqlite3DeleteTable(Table*);
static void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
static void *sqlite3ArrayAllocate(void*,int,int,int*,int*,int*);
static IdList *sqlite3IdListAppend(IdList*, Token*);
static int sqlite3IdListIndex(IdList*,const char*);
static SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
static SrcList *sqlite3SrcListAppendFromTerm(SrcList*, Token*, Token*, Token*,
SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
SQLITE_PRIVATE void *sqlite3ArrayAllocate(void*,int,int,int*,int*,int*);
SQLITE_PRIVATE IdList *sqlite3IdListAppend(IdList*, Token*);
SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(SrcList*, Token*, Token*);
SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(SrcList*, Token*, Token*, Token*,
                                      Select*, Expr*, IdList*);
static void sqlite3SrcListShiftJoinType(SrcList*);
static void sqlite3SrcListAssignCursors(Parse*, SrcList*);
static void sqlite3IdListDelete(IdList*);
static void sqlite3SrcListDelete(SrcList*);
static void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
SQLITE_PRIVATE void sqlite3IdListDelete(IdList*);
SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList*);
SQLITE_PRIVATE void sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
                        Token*, int, int);
static void sqlite3DropIndex(Parse*, SrcList*, int);
static int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
static Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, int, int, Select*, int, int*, char *aff);
SQLITE_PRIVATE Select *sqlite3SelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
                        int,Expr*,Expr*);
static void sqlite3SelectDelete(Select*);
static Table *sqlite3SrcListLookup(Parse*, SrcList*);
static int sqlite3IsReadOnly(Parse*, Table*, int);
static void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
static void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
static void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
static WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
static void sqlite3WhereEnd(WhereInfo*);
static void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
static void sqlite3ExprCode(Parse*, Expr*);
static void sqlite3ExprCodeAndCache(Parse*, Expr*);
static int sqlite3ExprCodeExprList(Parse*, ExprList*);
static void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
static void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
static Table *sqlite3FindTable(sqlite3*,const char*, const char*);
static Table *sqlite3LocateTable(Parse*,const char*, const char*);
static Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
static void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
static void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
static void sqlite3Vacuum(Parse*);
static int sqlite3RunVacuum(char**, sqlite3*);
static char *sqlite3NameFromToken(Token*);
static int sqlite3ExprCompare(Expr*, Expr*);
SQLITE_PRIVATE void sqlite3SelectDelete(Select*);
SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**);
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe*, Table*, int, int);
SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*);
SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*);
SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*);
SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,const char*, const char*);
SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
SQLITE_PRIVATE char *sqlite3NameFromToken(Token*);
SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
int sqliteFuncId(Token*);
static int sqlite3ExprResolveNames(NameContext *, Expr *);
static int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
static int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
static Vdbe *sqlite3GetVdbe(Parse*);
static Expr *sqlite3CreateIdExpr(const char*);
static void sqlite3Randomness(int, void*);
static void sqlite3RollbackAll(sqlite3*);
static void sqlite3CodeVerifySchema(Parse*, int);
static void sqlite3BeginTransaction(Parse*, int);
static void sqlite3CommitTransaction(Parse*);
static void sqlite3RollbackTransaction(Parse*);
static int sqlite3ExprIsConstant(Expr*);
static int sqlite3ExprIsConstantNotJoin(Expr*);
static int sqlite3ExprIsConstantOrFunction(Expr*);
static int sqlite3ExprIsInteger(Expr*, int*);
static int sqlite3IsRowid(const char*);
static void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
static void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
static void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
static void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
static void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
static void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
static void sqlite3BeginWriteOperation(Parse*, int, int);
static Expr *sqlite3ExprDup(Expr*);
static void sqlite3TokenCopy(Token*, Token*);
static ExprList *sqlite3ExprListDup(ExprList*);
static SrcList *sqlite3SrcListDup(SrcList*);
static IdList *sqlite3IdListDup(IdList*);
static Select *sqlite3SelectDup(Select*);
static FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
static void sqlite3RegisterBuiltinFunctions(sqlite3*);
static void sqlite3RegisterDateTimeFunctions(sqlite3*);
static int sqlite3SafetyOn(sqlite3*);
static int sqlite3SafetyOff(sqlite3*);
static int sqlite3SafetyCheck(sqlite3*);
static void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);
SQLITE_PRIVATE int sqlite3ExprResolveNames(NameContext *, Expr *);
SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(const char*);
SQLITE_PRIVATE void sqlite3Randomness(int, void*);
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
SQLITE_PRIVATE int sqlite3IsRowid(const char*);
SQLITE_PRIVATE void sqlite3GenerateRowDelete(sqlite3*, Vdbe*, Table*, int, int);
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Vdbe*, Table*, int, char*);
SQLITE_PRIVATE void sqlite3GenerateIndexKey(Vdbe*, Index*, int);
SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, char*, int, int, int, int);
SQLITE_PRIVATE void sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
SQLITE_PRIVATE Expr *sqlite3ExprDup(Expr*);
SQLITE_PRIVATE void sqlite3TokenCopy(Token*, Token*);
SQLITE_PRIVATE ExprList *sqlite3ExprListDup(ExprList*);
SQLITE_PRIVATE SrcList *sqlite3SrcListDup(SrcList*);
SQLITE_PRIVATE IdList *sqlite3IdListDup(IdList*);
SQLITE_PRIVATE Select *sqlite3SelectDup(Select*);
SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3*);
SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3*);
SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3*);
SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3*);
SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3*, Vdbe*, int);

#ifndef SQLITE_OMIT_TRIGGER
static   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
                           Expr*,int, int);
static   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
static   void sqlite3DropTrigger(Parse*, SrcList*, int);
static   void sqlite3DropTriggerPtr(Parse*, Trigger*);
static   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
static   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
SQLITE_PRIVATE   int sqlite3TriggersExist(Parse*, Table*, int, ExprList*);
SQLITE_PRIVATE   int sqlite3CodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int, 
                           int, int);
  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
static   void sqlite3DeleteTriggerStep(TriggerStep*);
static   TriggerStep *sqlite3TriggerSelectStep(Select*);
static   TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
static   TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
static   TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
static   void sqlite3DeleteTrigger(Trigger*);
static   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(TriggerStep*);
SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(Select*);
SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(Token*, IdList*, ExprList*,Select*,int);
SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(Token*, ExprList*, Expr*, int);
SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(Token*, Expr*);
SQLITE_PRIVATE   void sqlite3DeleteTrigger(Trigger*);
SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
#else
# define sqlite3TriggersExist(A,B,C,D,E,F) 0
# define sqlite3DeleteTrigger(A)
# define sqlite3DropTriggerPtr(A,B)
# define sqlite3UnlinkAndDeleteTrigger(A,B,C)
# define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I) 0
#endif

static int sqlite3JoinType(Parse*, Token*, Token*, Token*);
static void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
static void sqlite3DeferForeignKey(Parse*, int);
SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
#ifndef SQLITE_OMIT_AUTHORIZATION
static   void sqlite3AuthRead(Parse*,Expr*,SrcList*);
static   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
static   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
static   void sqlite3AuthContextPop(AuthContext*);
SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,SrcList*);
SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
#else
# define sqlite3AuthRead(a,b,c)
# define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
# define sqlite3AuthContextPush(a,b,c)
# define sqlite3AuthContextPop(a)  ((void)(a))
#endif
static void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
static void sqlite3Detach(Parse*, Expr*);
static int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
SQLITE_PRIVATE int sqlite3BtreeFactory(const sqlite3 *db, const char *zFilename,
                       int omitJournal, int nCache, Btree **ppBtree);
static int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
static int sqlite3FixSrcList(DbFixer*, SrcList*);
static int sqlite3FixSelect(DbFixer*, Select*);
static int sqlite3FixExpr(DbFixer*, Expr*);
static int sqlite3FixExprList(DbFixer*, ExprList*);
static int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
static int sqlite3AtoF(const char *z, double*);
char *sqlite3_snprintf(int,char*,const char*,...);
static int sqlite3GetInt32(const char *, int*);
static int sqlite3FitsIn64Bits(const char *);
static int sqlite3Utf16ByteLen(const void *pData, int nChar);
static int sqlite3Utf8CharLen(const char *pData, int nByte);
static u32 sqlite3ReadUtf8(const unsigned char *);
static int sqlite3PutVarint(unsigned char *, u64);
static int sqlite3GetVarint(const unsigned char *, u64 *);
static int sqlite3GetVarint32(const unsigned char *, u32 *);
static int sqlite3VarintLen(u64 v);
static void sqlite3IndexAffinityStr(Vdbe *, Index *);
static void sqlite3TableAffinityStr(Vdbe *, Table *);
static char sqlite3CompareAffinity(Expr *pExpr, char aff2);
static int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
static char sqlite3ExprAffinity(Expr *pExpr);
static int sqlite3Atoi64(const char*, i64*);
static void sqlite3Error(sqlite3*, int, const char*,...);
static void *sqlite3HexToBlob(const char *z);
static int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
static const char *sqlite3ErrStr(int);
static int sqlite3ReadSchema(Parse *pParse);
static CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
static CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
static CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
static Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
static int sqlite3CheckCollSeq(Parse *, CollSeq *);
static int sqlite3CheckObjectName(Parse *, const char *);
static void sqlite3VdbeSetChanges(sqlite3 *, int);
static void sqlite3Utf16Substr(sqlite3_context *,int,sqlite3_value **);
SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
SQLITE_API char *sqlite3_snprintf(int,char*,const char*,...);
SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *);
SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
SQLITE_PRIVATE u32 sqlite3ReadUtf8(const unsigned char *);
SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *, u64);
SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *, u64 *);
SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *, u32 *);
SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *, Index *);
SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
SQLITE_PRIVATE void *sqlite3HexToBlob(const char *z);
SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
SQLITE_PRIVATE const char *sqlite3ErrStr(int);
SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char *,int,int);
SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName);
SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
SQLITE_PRIVATE void sqlite3Utf16Substr(sqlite3_context *,int,sqlite3_value **);

static const void *sqlite3ValueText(sqlite3_value*, u8);
static int sqlite3ValueBytes(sqlite3_value*, u8);
static void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
static void sqlite3ValueFree(sqlite3_value*);
static sqlite3_value *sqlite3ValueNew(void);
static char *sqlite3Utf16to8(const void*, int);
static int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
static void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, void(*)(void*));
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(void);
SQLITE_PRIVATE char *sqlite3Utf16to8(const void*, int);
SQLITE_PRIVATE int sqlite3ValueFromExpr(Expr *, u8, u8, sqlite3_value **);
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
extern const unsigned char sqlite3UpperToLower[];
static void sqlite3RootPageMoved(Db*, int, int);
static void sqlite3Reindex(Parse*, Token*, Token*);
static void sqlite3AlterFunctions(sqlite3*);
static void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
static int sqlite3GetToken(const unsigned char *, int *);
static void sqlite3NestedParse(Parse*, const char*, ...);
static void sqlite3ExpirePreparedStatements(sqlite3*);
static void sqlite3CodeSubselect(Parse *, Expr *);
static int sqlite3SelectResolve(Parse *, Select *, NameContext *);
static void sqlite3ColumnDefault(Vdbe *, Table *, int);
static void sqlite3AlterFinishAddColumn(Parse *, Token *);
static void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
static CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
static char sqlite3AffinityType(const Token*);
static void sqlite3Analyze(Parse*, Token*, Token*);
static int sqlite3InvokeBusyHandler(BusyHandler*);
static int sqlite3FindDb(sqlite3*, Token*);
static int sqlite3AnalysisLoad(sqlite3*,int iDB);
static void sqlite3DefaultRowEst(Index*);
static void sqlite3RegisterLikeFunctions(sqlite3*, int);
static int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
static ThreadData *sqlite3ThreadData(void);
static const ThreadData *sqlite3ThreadDataReadOnly(void);
static void sqlite3ReleaseThreadData(void);
static void sqlite3AttachFunctions(sqlite3 *);
static void sqlite3MinimumFileFormat(Parse*, int, int);
static void sqlite3SchemaFree(void *);
static Schema *sqlite3SchemaGet(Btree *);
static int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
static KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
static int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *, Expr *);
SQLITE_PRIVATE int sqlite3SelectResolve(Parse *, Select *, NameContext *);
SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int);
SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, CollSeq *, const char *, int);
SQLITE_PRIVATE char sqlite3AffinityType(const Token*);
SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
SQLITE_PRIVATE ThreadData *sqlite3ThreadData(void);
SQLITE_PRIVATE const ThreadData *sqlite3ThreadDataReadOnly(void);
SQLITE_PRIVATE void sqlite3ReleaseThreadData(void);
SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *);
SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
SQLITE_PRIVATE void sqlite3SchemaFree(void *);
SQLITE_PRIVATE Schema *sqlite3SchemaGet(Btree *);
SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
  void (*)(sqlite3_context*,int,sqlite3_value **),
  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
static int sqlite3ApiExit(sqlite3 *db, int);
static void sqlite3FailedMalloc(void);
static void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
static int sqlite3OpenTempDatabase(Parse *);
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
SQLITE_PRIVATE void sqlite3FailedMalloc(void);
SQLITE_PRIVATE void sqlite3AbortOtherActiveVdbes(sqlite3 *, Vdbe *);
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);

#ifndef SQLITE_OMIT_LOAD_EXTENSION
static   void sqlite3CloseExtensions(sqlite3*);
static   int sqlite3AutoLoadExtensions(sqlite3*);
SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
SQLITE_PRIVATE   int sqlite3AutoLoadExtensions(sqlite3*);
#else
# define sqlite3CloseExtensions(X)
# define sqlite3AutoLoadExtensions(X)  SQLITE_OK
#endif

#ifndef SQLITE_OMIT_SHARED_CACHE
static   void sqlite3TableLock(Parse *, int, int, u8, const char *);
SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
#else
  #define sqlite3TableLock(v,w,x,y,z)
#endif

#ifdef SQLITE_TEST
static   int sqlite3Utf8To8(unsigned char*);
SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
#endif

#ifdef SQLITE_MEMDEBUG
static   void sqlite3MallocDisallow(void);
static   void sqlite3MallocAllow(void);
static   int sqlite3TestMallocFail(void);
SQLITE_PRIVATE   void sqlite3MallocDisallow(void);
SQLITE_PRIVATE   void sqlite3MallocAllow(void);
SQLITE_PRIVATE   int sqlite3TestMallocFail(void);
#else
  #define sqlite3TestMallocFail() 0
  #define sqlite3MallocDisallow()
  #define sqlite3MallocAllow()
#endif

#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
static   void *sqlite3ThreadSafeMalloc(int);
static   void sqlite3ThreadSafeFree(void *);
SQLITE_PRIVATE   void *sqlite3ThreadSafeMalloc(int);
SQLITE_PRIVATE   void sqlite3ThreadSafeFree(void *);
#else
  #define sqlite3ThreadSafeMalloc sqlite3MallocX
  #define sqlite3ThreadSafeFree sqlite3FreeX
#endif

#ifdef SQLITE_OMIT_VIRTUALTABLE
#  define sqlite3VtabClear(X)
#  define sqlite3VtabSync(X,Y) (Y)
#  define sqlite3VtabRollback(X)
#  define sqlite3VtabCommit(X)
#else
static    void sqlite3VtabClear(Table*);
static    int sqlite3VtabSync(sqlite3 *db, int rc);
static    int sqlite3VtabRollback(sqlite3 *db);
static    int sqlite3VtabCommit(sqlite3 *db);
SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, int rc);
SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
#endif
static void sqlite3VtabLock(sqlite3_vtab*);
static void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
static void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
static void sqlite3VtabFinishParse(Parse*, Token*);
static void sqlite3VtabArgInit(Parse*);
static void sqlite3VtabArgExtend(Parse*, Token*);
static int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
static int sqlite3VtabCallConnect(Parse*, Table*);
static int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
static int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
static FuncDef *sqlite3VtabOverloadFunction(FuncDef*, int nArg, Expr*);
static void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
static int sqlite3Reprepare(Vdbe*);
static void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab*);
SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3*, sqlite3_vtab*);
SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, sqlite3_vtab *);
SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(FuncDef*, int nArg, Expr*);
SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, int, const char*);
CollSeq* sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);

#if SQLITE_MAX_EXPR_DEPTH>0
static   void sqlite3ExprSetHeight(Expr *);
static   int sqlite3SelectExprHeight(Select *);
SQLITE_PRIVATE   void sqlite3ExprSetHeight(Expr *);
SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
#else
  #define sqlite3ExprSetHeight(x)
#endif

static u32 sqlite3Get2byte(const u8*);
static u32 sqlite3Get4byte(const u8*);
static void sqlite3Put2byte(u8*, u32);
static void sqlite3Put4byte(u8*, u32);
SQLITE_PRIVATE u32 sqlite3Get2byte(const u8*);
SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
SQLITE_PRIVATE void sqlite3Put2byte(u8*, u32);
SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);

#ifdef SQLITE_SSE
#include "sseInt.h"
#endif

#ifdef SQLITE_DEBUG
static   void sqlite3ParserTrace(FILE*, char *);
SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
#endif

/*
** If the SQLITE_ENABLE IOTRACE exists then the global variable
** sqlite3_io_trace is a pointer to a printf-like routine used to
** print I/O tracing messages. 
*/
#ifdef SQLITE_ENABLE_IOTRACE
# define IOTRACE(A)  if( sqlite3_io_trace ){ sqlite3_io_trace A; }
static   void sqlite3VdbeIOTraceSql(Vdbe*);
SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
#else
# define IOTRACE(A)
# define sqlite3VdbeIOTraceSql(X)
#endif
extern void (*sqlite3_io_trace)(const char*,...);

#endif
7277
7278
7279
7280
7281
7282
7283
7284

7285
7286
7287
7288
7289
7290
7291
7314
7315
7316
7317
7318
7319
7320

7321
7322
7323
7324
7325
7326
7327
7328







-
+







#endif

/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
static void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(sqlite3 *db){
#ifndef SQLITE_OMIT_DATETIME_FUNCS
  static const struct {
     char *zName;
     int nArg;
     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  } aFuncs[] = {
    { "julianday", -1, juliandayFunc   },
7343
7344
7345
7346
7347
7348
7349
7350

7351
7352
7353
7354
7355
7356
7357
7358

7359
7360
7361

7362
7363
7364

7365
7366
7367

7368
7369
7370

7371
7372
7373

7374
7375
7376

7377
7378
7379

7380
7381
7382

7383
7384
7385

7386
7387
7388

7389
7390
7391

7392
7393
7394
7395
7396
7397
7398
7380
7381
7382
7383
7384
7385
7386

7387
7388
7389
7390
7391
7392
7393
7394

7395
7396
7397

7398
7399
7400

7401
7402
7403

7404
7405
7406

7407
7408
7409

7410
7411
7412

7413
7414
7415

7416
7417
7418

7419
7420
7421

7422
7423
7424

7425
7426
7427

7428
7429
7430
7431
7432
7433
7434
7435







-
+







-
+


-
+


-
+


-
+


-
+


-
+


-
+


-
+


-
+


-
+


-
+


-
+








/*
** The following routines are convenience wrappers around methods
** of the OsFile object.  This is mostly just syntactic sugar.  All
** of this would be completely automatic if SQLite were coded using
** C++ instead of plain old C.
*/
static int sqlite3OsClose(OsFile **pId){
SQLITE_PRIVATE int sqlite3OsClose(OsFile **pId){
  OsFile *id;
  if( pId!=0 && (id = *pId)!=0 ){
    return id->pMethod->xClose(pId);
  }else{
    return SQLITE_OK;
  }
}
static int sqlite3OsOpenDirectory(OsFile *id, const char *zName){
SQLITE_PRIVATE int sqlite3OsOpenDirectory(OsFile *id, const char *zName){
  return id->pMethod->xOpenDirectory(id, zName);
}
static int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
SQLITE_PRIVATE int sqlite3OsRead(OsFile *id, void *pBuf, int amt){
  return id->pMethod->xRead(id, pBuf, amt);
}
static int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
SQLITE_PRIVATE int sqlite3OsWrite(OsFile *id, const void *pBuf, int amt){
  return id->pMethod->xWrite(id, pBuf, amt);
}
static int sqlite3OsSeek(OsFile *id, i64 offset){
SQLITE_PRIVATE int sqlite3OsSeek(OsFile *id, i64 offset){
  return id->pMethod->xSeek(id, offset);
}
static int sqlite3OsTruncate(OsFile *id, i64 size){
SQLITE_PRIVATE int sqlite3OsTruncate(OsFile *id, i64 size){
  return id->pMethod->xTruncate(id, size);
}
static int sqlite3OsSync(OsFile *id, int fullsync){
SQLITE_PRIVATE int sqlite3OsSync(OsFile *id, int fullsync){
  return id->pMethod->xSync(id, fullsync);
}
static void sqlite3OsSetFullSync(OsFile *id, int value){
SQLITE_PRIVATE void sqlite3OsSetFullSync(OsFile *id, int value){
  id->pMethod->xSetFullSync(id, value);
}
static int sqlite3OsFileSize(OsFile *id, i64 *pSize){
SQLITE_PRIVATE int sqlite3OsFileSize(OsFile *id, i64 *pSize){
  return id->pMethod->xFileSize(id, pSize);
}
static int sqlite3OsLock(OsFile *id, int lockType){
SQLITE_PRIVATE int sqlite3OsLock(OsFile *id, int lockType){
  return id->pMethod->xLock(id, lockType);
}
static int sqlite3OsUnlock(OsFile *id, int lockType){
SQLITE_PRIVATE int sqlite3OsUnlock(OsFile *id, int lockType){
  return id->pMethod->xUnlock(id, lockType);
}
static int sqlite3OsCheckReservedLock(OsFile *id){
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(OsFile *id){
  return id->pMethod->xCheckReservedLock(id);
}
static int sqlite3OsSectorSize(OsFile *id){
SQLITE_PRIVATE int sqlite3OsSectorSize(OsFile *id){
  int (*xSectorSize)(OsFile*) = id->pMethod->xSectorSize;
  return xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE;
}

#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  /* These methods are currently only used for testing and debugging. */
  int sqlite3OsFileHandle(OsFile *id){
7430
7431
7432
7433
7434
7435
7436
7437

7438
7439
7440
7441
7442
7443
7444
7467
7468
7469
7470
7471
7472
7473

7474
7475
7476
7477
7478
7479
7480
7481







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** Memory allocation functions used throughout sqlite.
**
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** MALLOC WRAPPER ARCHITECTURE
**
** The sqlite code accesses dynamic memory allocation/deallocation by invoking
** the following six APIs (which may be implemented as macros).
7623
7624
7625
7626
7627
7628
7629
7630

7631
7632
7633
7634
7635
7636
7637
7660
7661
7662
7663
7664
7665
7666

7667
7668
7669
7670
7671
7672
7673
7674







-
+







int sqlite3_iLine = 0;            /* Line number for debug info */
int sqlite3_mallocfail_trace = 0; /* Print a msg on malloc fail if true */

/*
** Check for a simulated memory allocation failure.  Return true if
** the failure should be simulated.  Return false to proceed as normal.
*/
static int sqlite3TestMallocFail(){
SQLITE_PRIVATE int sqlite3TestMallocFail(){
  if( sqlite3_isFail ){
    return 1;
  }
  if( sqlite3_iMallocFail>=0 ){
    sqlite3_iMallocFail--;
    if( sqlite3_iMallocFail==0 ){
      sqlite3_iMallocFail = sqlite3_iMallocReset;
7809
7810
7811
7812
7813
7814
7815
7816

7817
7818
7819
7820
7821
7822
7823
7846
7847
7848
7849
7850
7851
7852

7853
7854
7855
7856
7857
7858
7859
7860







-
+







**     * The value of the sqlite3_malloc_id variable ...
**     * The output of backtrace() (if available) ...
**
** Todo: We could have a version of this function that outputs to stdout, 
** to debug memory leaks when Tcl is not available.
*/
#if defined(TCLSH) && defined(SQLITE_DEBUG) && SQLITE_MEMDEBUG>1
static int sqlite3OutstandingMallocs(Tcl_Interp *interp){
SQLITE_PRIVATE int sqlite3OutstandingMallocs(Tcl_Interp *interp){
  void *p;
  Tcl_Obj *pRes = Tcl_NewObj();
  Tcl_IncrRefCount(pRes);


  for(p=sqlite3_pFirst; p; p=((void **)p)[1]){
    Tcl_Obj *pEntry = Tcl_NewObj();
7999
8000
8001
8002
8003
8004
8005
8006

8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025

8026
8027
8028
8029
8030
8031
8032
8036
8037
8038
8039
8040
8041
8042

8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061

8062
8063
8064
8065
8066
8067
8068
8069







-
+


















-
+







#endif

/*
** Allocate and return N bytes of uninitialised memory by calling
** sqlite3OsMalloc(). If the Malloc() call fails, attempt to free memory 
** by calling sqlite3_release_memory().
*/
static void *sqlite3MallocRaw(int n, int doMemManage){
SQLITE_PRIVATE void *sqlite3MallocRaw(int n, int doMemManage){
  void *p = 0;
  if( n>0 && !sqlite3MallocFailed() && (!doMemManage || enforceSoftLimit(n)) ){
    while( (p = OSMALLOC(n))==0 && sqlite3_release_memory(n) ){}
    if( !p ){
      sqlite3FailedMalloc();
      OSMALLOC_FAILED();
    }else if( doMemManage ){
      updateMemoryUsedCount(OSSIZEOF(p));
    }
  }
  return p;
}

/*
** Resize the allocation at p to n bytes by calling sqlite3OsRealloc(). The
** pointer to the new allocation is returned.  If the Realloc() call fails,
** attempt to free memory by calling sqlite3_release_memory().
*/
static void *sqlite3Realloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3Realloc(void *p, int n){
  if( sqlite3MallocFailed() ){
    return 0;
  }

  if( !p ){
    return sqlite3Malloc(n, 1);
  }else{
8047
8048
8049
8050
8051
8052
8053
8054

8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065

8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076

8077
8078
8079
8080
8081
8082
8083

8084
8085
8086
8087
8088
8089
8090
8084
8085
8086
8087
8088
8089
8090

8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101

8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112

8113
8114
8115
8116
8117
8118
8119

8120
8121
8122
8123
8124
8125
8126
8127







-
+










-
+










-
+






-
+







  }
}

/*
** Free the memory pointed to by p. p must be either a NULL pointer or a 
** value returned by a previous call to sqlite3Malloc() or sqlite3Realloc().
*/
static void sqlite3FreeX(void *p){
SQLITE_PRIVATE void sqlite3FreeX(void *p){
  if( p ){
    updateMemoryUsedCount(0 - OSSIZEOF(p));
    OSFREE(p);
  }
}

/*
** A version of sqliteMalloc() that is always a function, not a macro.
** Currently, this is used only to alloc to allocate the parser engine.
*/
static void *sqlite3MallocX(int n){
SQLITE_PRIVATE void *sqlite3MallocX(int n){
  return sqliteMalloc(n);
}

/*
** sqlite3Malloc
** sqlite3ReallocOrFree
**
** These two are implemented as wrappers around sqlite3MallocRaw(), 
** sqlite3Realloc() and sqlite3Free().
*/ 
static void *sqlite3Malloc(int n, int doMemManage){
SQLITE_PRIVATE void *sqlite3Malloc(int n, int doMemManage){
  void *p = sqlite3MallocRaw(n, doMemManage);
  if( p ){
    memset(p, 0, n);
  }
  return p;
}
static void *sqlite3ReallocOrFree(void *p, int n){
SQLITE_PRIVATE void *sqlite3ReallocOrFree(void *p, int n){
  void *pNew;
  pNew = sqlite3Realloc(p, n);
  if( !pNew ){
    sqlite3FreeX(p);
  }
  return pNew;
}
8099
8100
8101
8102
8103
8104
8105
8106

8107
8108
8109
8110

8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130

8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142

8143
8144
8145
8146
8147
8148
8149
8150
8151

8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169

8170
8171
8172
8173
8174
8175
8176
8136
8137
8138
8139
8140
8141
8142

8143
8144
8145
8146

8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166

8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178

8179
8180
8181
8182
8183
8184
8185
8186
8187

8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205

8206
8207
8208
8209
8210
8211
8212
8213







-
+



-
+



















-
+











-
+








-
+

















-
+







**     respect to the soft-heap-limit, and
**
**   * sqlite3ThreadSafeMalloc() must be matched with ThreadSafeFree(),
**     not sqlite3Free(). Calling sqlite3Free() on memory obtained from
**     ThreadSafeMalloc() will cause an error somewhere down the line.
*/
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
static void *sqlite3ThreadSafeMalloc(int n){
SQLITE_PRIVATE void *sqlite3ThreadSafeMalloc(int n){
  (void)ENTER_MALLOC;
  return sqlite3Malloc(n, 0);
}
static void sqlite3ThreadSafeFree(void *p){
SQLITE_PRIVATE void sqlite3ThreadSafeFree(void *p){
  (void)ENTER_MALLOC;
  if( p ){
    OSFREE(p);
  }
}
#endif


/*
** Return the number of bytes allocated at location p. p must be either 
** a NULL pointer (in which case 0 is returned) or a pointer returned by 
** sqlite3Malloc(), sqlite3Realloc() or sqlite3ReallocOrFree().
**
** The number of bytes allocated does not include any overhead inserted by 
** any malloc() wrapper functions that may be called. So the value returned
** is the number of bytes that were available to SQLite using pointer p, 
** regardless of how much memory was actually allocated.
*/
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
static int sqlite3AllocSize(void *p){
SQLITE_PRIVATE int sqlite3AllocSize(void *p){
  return OSSIZEOF(p);
}
#endif

/*
** Make a copy of a string in memory obtained from sqliteMalloc(). These 
** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
** is because when memory debugging is turned on, these two functions are 
** called via macros that record the current file and line number in the
** ThreadData structure.
*/
static char *sqlite3StrDup(const char *z){
SQLITE_PRIVATE char *sqlite3StrDup(const char *z){
  char *zNew;
  int n;
  if( z==0 ) return 0;
  n = strlen(z)+1;
  zNew = sqlite3MallocRaw(n, 1);
  if( zNew ) memcpy(zNew, z, n);
  return zNew;
}
static char *sqlite3StrNDup(const char *z, int n){
SQLITE_PRIVATE char *sqlite3StrNDup(const char *z, int n){
  char *zNew;
  if( z==0 ) return 0;
  zNew = sqlite3MallocRaw(n+1, 1);
  if( zNew ){
    memcpy(zNew, z, n);
    zNew[n] = 0;
  }
  return zNew;
}

/*
** Create a string from the 2nd and subsequent arguments (up to the
** first NULL argument), store the string in memory obtained from
** sqliteMalloc() and make the pointer indicated by the 1st argument
** point to that string.  The 1st argument must either be NULL or 
** point to memory obtained from sqliteMalloc().
*/
static void sqlite3SetString(char **pz, ...){
SQLITE_PRIVATE void sqlite3SetString(char **pz, ...){
  va_list ap;
  int nByte;
  const char *z;
  char *zResult;

  assert( pz!=0 );
  nByte = 1;
8206
8207
8208
8209
8210
8211
8212
8213

8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226

8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239

8240
8241
8242
8243
8244
8245
8246
8247
8248

8249
8250
8251
8252
8253
8254
8255
8243
8244
8245
8246
8247
8248
8249

8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262

8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275

8276
8277
8278
8279
8280
8281
8282
8283
8284

8285
8286
8287
8288
8289
8290
8291
8292







-
+












-
+












-
+








-
+







** invocation SQLITE_NOMEM is returned instead. 
**
** If the first argument, db, is not NULL and a malloc() error has occured,
** then the connection error-code (the value returned by sqlite3_errcode())
** is set to SQLITE_NOMEM.
*/
int sqlite3_mallocHasFailed = 0;
static int sqlite3ApiExit(sqlite3* db, int rc){
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  if( sqlite3MallocFailed() ){
    sqlite3_mallocHasFailed = 0;
    sqlite3OsLeaveMutex();
    sqlite3Error(db, SQLITE_NOMEM, 0);
    rc = SQLITE_NOMEM;
  }
  return rc & (db ? db->errMask : 0xff);
}

/* 
** Set the "malloc has failed" condition to true for this thread.
*/
static void sqlite3FailedMalloc(){
SQLITE_PRIVATE void sqlite3FailedMalloc(){
  if( !sqlite3MallocFailed() ){
    sqlite3OsEnterMutex();
    assert( sqlite3_mallocHasFailed==0 );
    sqlite3_mallocHasFailed = 1;
  }
}

#ifdef SQLITE_MEMDEBUG
/*
** This function sets a flag in the thread-specific-data structure that will
** cause an assert to fail if sqliteMalloc() or sqliteRealloc() is called.
*/
static void sqlite3MallocDisallow(){
SQLITE_PRIVATE void sqlite3MallocDisallow(){
  assert( sqlite3_mallocDisallowed>=0 );
  sqlite3_mallocDisallowed++;
}

/*
** This function clears the flag set in the thread-specific-data structure set
** by sqlite3MallocDisallow().
*/
static void sqlite3MallocAllow(){
SQLITE_PRIVATE void sqlite3MallocAllow(){
  assert( sqlite3_mallocDisallowed>0 );
  sqlite3_mallocDisallowed--;
}
#endif

/************** End of malloc.c **********************************************/
/************** Begin file printf.c ******************************************/
8324
8325
8326
8327
8328
8329
8330

8331
8332
8333
8334
8335
8336
8337
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375







+







#define etCHARLIT    10 /* Literal characters.  %' */
#define etSQLESCAPE  11 /* Strings with '\'' doubled.  %q */
#define etSQLESCAPE2 12 /* Strings with '\'' doubled and enclosed in '',
                          NULL pointers replaced by SQL NULL.  %Q */
#define etTOKEN      13 /* a pointer to a Token structure */
#define etSRCLIST    14 /* a pointer to a SrcList */
#define etPOINTER    15 /* The %p conversion */
#define etSQLESCAPE3 16 /* %w -> Strings with '\"' doubled */


/*
** An "etByte" is an 8-bit unsigned value.
*/
typedef unsigned char etByte;

8365
8366
8367
8368
8369
8370
8371

8372
8373
8374
8375
8376
8377
8378
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417







+







static const et_info fmtinfo[] = {
  {  'd', 10, 1, etRADIX,      0,  0 },
  {  's',  0, 4, etSTRING,     0,  0 },
  {  'g',  0, 1, etGENERIC,    30, 0 },
  {  'z',  0, 6, etDYNSTRING,  0,  0 },
  {  'q',  0, 4, etSQLESCAPE,  0,  0 },
  {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
  {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
  {  'c',  0, 0, etCHARX,      0,  0 },
  {  'o',  8, 0, etRADIX,      0,  2 },
  {  'u', 10, 0, etRADIX,      0,  0 },
  {  'x', 16, 0, etRADIX,      16, 1 },
  {  'X', 16, 0, etRADIX,      0,  4 },
#ifndef SQLITE_OMIT_FLOATING_POINT
  {  'f',  0, 1, etFLOAT,      0,  0 },
8704
8705
8706
8707
8708
8709
8710
8711

8712
8713
8714
8715
8716
8717
8718
8743
8744
8745
8746
8747
8748
8749

8750
8751
8752
8753
8754
8755
8756
8757







-
+







#else
        /* It makes more sense to use 0.5 */
        for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
#endif
        if( xtype==etFLOAT ) realvalue += rounder;
        /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
        exp = 0;
        if( isnan(realvalue) ){
        if( sqlite3_isnan(realvalue) ){
          bufpt = "NaN";
          length = 3;
          break;
        }
        if( realvalue>0.0 ){
          while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
          while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
8861
8862
8863
8864
8865
8866
8867

8868

8869
8870

8871
8872
8873
8874
8875

8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886

8887
8888
8889

8890
8891

8892
8893
8894
8895
8896
8897
8898
8900
8901
8902
8903
8904
8905
8906
8907

8908
8909
8910
8911
8912
8913
8914
8915

8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926

8927
8928
8929

8930
8931

8932
8933
8934
8935
8936
8937
8938
8939







+
-
+


+




-
+










-
+


-
+

-
+







        }else if( xtype==etDYNSTRING ){
          zExtra = bufpt;
        }
        length = strlen(bufpt);
        if( precision>=0 && precision<length ) length = precision;
        break;
      case etSQLESCAPE:
      case etSQLESCAPE2:
      case etSQLESCAPE2: {
      case etSQLESCAPE3: {
        int i, j, n, ch, isnull;
        int needQuote;
        char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
        char *escarg = va_arg(ap,char*);
        isnull = escarg==0;
        if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
        for(i=n=0; (ch=escarg[i])!=0; i++){
          if( ch=='\'' )  n++;
          if( ch==q )  n++;
        }
        needQuote = !isnull && xtype==etSQLESCAPE2;
        n += i + 1 + needQuote*2;
        if( n>etBUFSIZE ){
          bufpt = zExtra = sqliteMalloc( n );
          if( bufpt==0 ) return -1;
        }else{
          bufpt = buf;
        }
        j = 0;
        if( needQuote ) bufpt[j++] = '\'';
        if( needQuote ) bufpt[j++] = q;
        for(i=0; (ch=escarg[i])!=0; i++){
          bufpt[j++] = ch;
          if( ch=='\'' ) bufpt[j++] = ch;
          if( ch==q ) bufpt[j++] = ch;
        }
        if( needQuote ) bufpt[j++] = '\'';
        if( needQuote ) bufpt[j++] = q;
        bufpt[j] = 0;
        length = j;
        /* The precision is ignored on %q and %Q */
        /* if( precision>=0 && precision<length ) length = precision; */
        break;
      }
      case etTOKEN: {
9051
9052
9053
9054
9055
9056
9057
9058

9059
9060
9061
9062
9063
9064
9065
9066
9067

9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081

9082
9083
9084
9085
9086
9087
9088
9089
9090

9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105

9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125

9126
9127
9128
9129
9130
9131
9132
9092
9093
9094
9095
9096
9097
9098

9099
9100
9101
9102
9103
9104
9105
9106
9107

9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121

9122
9123
9124
9125
9126
9127
9128
9129
9130

9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145

9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165

9166
9167
9168
9169
9170
9171
9172
9173







-
+








-
+













-
+








-
+














-
+



















-
+







  return sqliteRealloc(old,size);
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
static char *sqlite3VMPrintf(const char *zFormat, va_list ap){
SQLITE_PRIVATE char *sqlite3VMPrintf(const char *zFormat, va_list ap){
  char zBase[SQLITE_PRINT_BUF_SIZE];
  return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
}

/*
** Print into memory obtained from sqliteMalloc().  Use the internal
** %-conversion extensions.
*/
static char *sqlite3MPrintf(const char *zFormat, ...){
SQLITE_PRIVATE char *sqlite3MPrintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  char zBase[SQLITE_PRINT_BUF_SIZE];
  va_start(ap, zFormat);
  z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
  va_end(ap);
  return z;
}

/*
** Print into memory obtained from sqlite3_malloc().  Omit the internal
** %-conversion extensions.
*/
char *sqlite3_vmprintf(const char *zFormat, va_list ap){
SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  char zBase[SQLITE_PRINT_BUF_SIZE];
  return base_vprintf(sqlite3_realloc, 0, zBase, sizeof(zBase), zFormat, ap);
}

/*
** Print into memory obtained from sqlite3_malloc()().  Omit the internal
** %-conversion extensions.
*/
char *sqlite3_mprintf(const char *zFormat, ...){
SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  va_list ap;
  char *z;
  va_start(ap, zFormat);
  z = sqlite3_vmprintf(zFormat, ap);
  va_end(ap);
  return z;
}

/*
** sqlite3_snprintf() works like snprintf() except that it ignores the
** current locale settings.  This is important for SQLite because we
** are not able to use a "," as the decimal point in place of "." as
** specified by some locales.
*/
char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  char *z;
  va_list ap;

  if( n<=0 ){
    return zBuf;
  }
  zBuf[0] = 0;
  va_start(ap,zFormat);
  z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
  va_end(ap);
  return z;
}

#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG) || defined(SQLITE_MEMDEBUG)
/*
** A version of printf() that understands %lld.  Used for debugging.
** The printf() built into some versions of windows does not understand %lld
** and segfaults if you give it a long long int.
*/
static void sqlite3DebugPrintf(const char *zFormat, ...){
SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  extern int getpid(void);
  va_list ap;
  char zBuf[500];
  va_start(ap, zFormat);
  base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap);
  va_end(ap);
  fprintf(stdout,"%s", zBuf);
9149
9150
9151
9152
9153
9154
9155
9156

9157
9158
9159
9160
9161
9162
9163
9190
9191
9192
9193
9194
9195
9196

9197
9198
9199
9200
9201
9202
9203
9204







-
+







*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for SQLite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


/*
** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
** must be held while executing this routine.
**
9222
9223
9224
9225
9226
9227
9228
9229

9230
9231
9232
9233
9234
9235
9236
9263
9264
9265
9266
9267
9268
9269

9270
9271
9272
9273
9274
9275
9276
9277







-
+







  t += prng.s[prng.i];
  return prng.s[t];
}

/*
** Return N random bytes.
*/
static void sqlite3Randomness(int N, void *pBuf){
SQLITE_PRIVATE void sqlite3Randomness(int N, void *pBuf){
  unsigned char *zBuf = pBuf;
  sqlite3OsEnterMutex();
  while( N-- ){
    *(zBuf++) = randomByte();
  }
  sqlite3OsLeaveMutex();
}
9247
9248
9249
9250
9251
9252
9253
9254

9255
9256
9257
9258
9259
9260
9261
9288
9289
9290
9291
9292
9293
9294

9295
9296
9297
9298
9299
9300
9301
9302







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used to translate between UTF-8, 
** UTF-16, UTF-16BE, and UTF-16LE.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
**
** Notes on UTF-8:
**
**   Byte-0    Byte-1    Byte-2    Byte-3    Value
**  0xxxxxxx                                 00000000 00000000 0xxxxxxx
**  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
**  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
9617
9618
9619
9620
9621
9622
9623

9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641

9642
9643

9644
9645

9646
9647
9648
9649
9650
9651





9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684































9685
9686
9687


9688
9689

9690
9691
9692


9693
9694
9695
9696
9697
9698





9699
9700
9701

9702
9703
9704
9705
9706
9707
9708
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682

9683
9684

9685
9686

9687
9688





9689
9690
9691
9692
9693
9694
9695































9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727


9728
9729
9730

9731
9732


9733
9734
9735





9736
9737
9738
9739
9740
9741
9742

9743
9744
9745
9746
9747
9748
9749
9750







+

















-
+

-
+

-
+

-
-
-
-
-
+
+
+
+
+


-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
+
+

-
+

-
-
+
+

-
-
-
-
-
+
+
+
+
+


-
+







  int nChange;            /* Number of db changes made since last reset */
  i64 startTime;          /* Time when query started - used for profiling */
  int nSql;             /* Number of bytes in zSql */
  char *zSql;           /* Text of the SQL statement that generated this */
#ifdef SQLITE_DEBUG
  FILE *trace;        /* Write an execution trace here, if not NULL */
#endif
  int openedStatement;  /* True if this VM has opened a statement journal */
#ifdef SQLITE_SSE
  int fetchId;          /* Statement number used by sqlite3_fetch_statement */
  int lru;              /* Counter used for LRU cache replacement */
#endif
};

/*
** The following are allowed values for Vdbe.magic
*/
#define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
#define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
#define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
#define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */

/*
** Function prototypes
*/
static void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, Cursor*);
void sqliteVdbePopStack(Vdbe*,int);
static int sqlite3VdbeCursorMoveto(Cursor*);
SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor*);
#if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
static void sqlite3VdbePrintOp(FILE*, int, Op*);
SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
#endif
static int sqlite3VdbeSerialTypeLen(u32);
static u32 sqlite3VdbeSerialType(Mem*, int);
static int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
static int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
static void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32);
SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
SQLITE_PRIVATE int sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
SQLITE_PRIVATE int sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);

int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
static int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
static int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
static int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
static int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
static int sqlite3VdbeIdxRowidLen(const u8*);
static int sqlite3VdbeExec(Vdbe*);
static int sqlite3VdbeList(Vdbe*);
static int sqlite3VdbeHalt(Vdbe*);
static int sqlite3VdbeChangeEncoding(Mem *, int);
static int sqlite3VdbeMemTooBig(Mem*);
static int sqlite3VdbeMemCopy(Mem*, const Mem*);
static void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
static int sqlite3VdbeMemMove(Mem*, Mem*);
static int sqlite3VdbeMemNulTerminate(Mem*);
static int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
static void sqlite3VdbeMemSetInt64(Mem*, i64);
static void sqlite3VdbeMemSetDouble(Mem*, double);
static void sqlite3VdbeMemSetNull(Mem*);
static void sqlite3VdbeMemSetZeroBlob(Mem*,int);
static int sqlite3VdbeMemMakeWriteable(Mem*);
static int sqlite3VdbeMemDynamicify(Mem*);
static int sqlite3VdbeMemStringify(Mem*, int);
static i64 sqlite3VdbeIntValue(Mem*);
static int sqlite3VdbeMemIntegerify(Mem*);
static double sqlite3VdbeRealValue(Mem*);
static void sqlite3VdbeIntegerAffinity(Mem*);
static int sqlite3VdbeMemRealify(Mem*);
static int sqlite3VdbeMemNumerify(Mem*);
static int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
static void sqlite3VdbeMemRelease(Mem *p);
static int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(Cursor*, int , const unsigned char*, int*);
SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *, i64 *);
SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(void*,int,const void*,int, const void*);
SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8*);
SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem*, Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
#ifndef NDEBUG
static   void sqlite3VdbeMemSanity(Mem*);
static   int sqlite3VdbeOpcodeNoPush(u8);
SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
SQLITE_PRIVATE   int sqlite3VdbeOpcodeNoPush(u8);
#endif
static int sqlite3VdbeMemTranslate(Mem*, u8);
SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
#ifdef SQLITE_DEBUG
static   void sqlite3VdbePrintSql(Vdbe*);
static   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
#endif
static int sqlite3VdbeMemHandleBom(Mem *pMem);
static void sqlite3VdbeFifoInit(Fifo*);
static int sqlite3VdbeFifoPush(Fifo*, i64);
static int sqlite3VdbeFifoPop(Fifo*, i64*);
static void sqlite3VdbeFifoClear(Fifo*);
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo*);
SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo*, i64);
SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo*, i64*);
SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo*);

#ifndef SQLITE_OMIT_INCRBLOB
static   int sqlite3VdbeMemExpandBlob(Mem *);
SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
#else
  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
#endif

#endif /* !defined(_VDBEINT_H_) */

/************** End of vdbeInt.h *********************************************/
9803
9804
9805
9806
9807
9808
9809
9810

9811
9812
9813
9814
9815
9816
9817
9845
9846
9847
9848
9849
9850
9851

9852
9853
9854
9855
9856
9857
9858
9859







-
+








#ifndef SQLITE_OMIT_UTF16
/*
** This routine transforms the internal text encoding used by pMem to
** desiredEnc. It is an error if the string is already of the desired
** encoding, or if *pMem does not contain a string value.
*/
static int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  unsigned char zShort[NBFS]; /* Temporary short output buffer */
  int len;                    /* Maximum length of output string in bytes */
  unsigned char *zOut;                  /* Output buffer */
  unsigned char *zIn;                   /* Input iterator */
  unsigned char *zTerm;                 /* End of input */
  unsigned char *z;                     /* Output iterator */
  unsigned int c;
10014
10015
10016
10017
10018
10019
10020
10021

10022
10023
10024
10025
10026
10027
10028
10056
10057
10058
10059
10060
10061
10062

10063
10064
10065
10066
10067
10068
10069
10070







-
+







** UTF-16 string stored in *pMem. If one is present, it is removed and
** the encoding of the Mem adjusted. This routine does not do any
** byte-swapping, it just sets Mem.enc appropriately.
**
** The allocation (static, dynamic etc.) and encoding of the Mem may be
** changed by this function.
*/
static int sqlite3VdbeMemHandleBom(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  int rc = SQLITE_OK;
  u8 bom = 0;

  if( pMem->n<0 || pMem->n>1 ){
    u8 b1 = *(u8 *)pMem->z;
    u8 b2 = *(((u8 *)pMem->z) + 1);
    if( b1==0xFE && b2==0xFF ){
10060
10061
10062
10063
10064
10065
10066
10067

10068
10069
10070
10071
10072
10073
10074
10102
10103
10104
10105
10106
10107
10108

10109
10110
10111
10112
10113
10114
10115
10116







-
+







/*
** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
** return the number of unicode characters in pZ up to (but not including)
** the first 0x00 byte. If nByte is not less than zero, return the
** number of unicode characters in the first nByte of pZ (or up to 
** the first 0x00, whichever comes first).
*/
static int sqlite3Utf8CharLen(const char *zIn, int nByte){
SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  int r = 0;
  const u8 *z = (const u8*)zIn;
  const u8 *zTerm;
  if( nByte>=0 ){
    zTerm = &z[nByte];
  }else{
    zTerm = (const u8*)(-1);
10085
10086
10087
10088
10089
10090
10091
10092

10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109

10110
10111
10112
10113
10114
10115
10116
10127
10128
10129
10130
10131
10132
10133

10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150

10151
10152
10153
10154
10155
10156
10157
10158







-
+
















-
+







/*
** Convert a UTF-16 string in the native encoding into a UTF-8 string.
** Memory to hold the UTF-8 string is obtained from malloc and must be
** freed by the calling function.
**
** NULL is returned if there is an allocation error.
*/
static char *sqlite3Utf16to8(const void *z, int nByte){
SQLITE_PRIVATE char *sqlite3Utf16to8(const void *z, int nByte){
  Mem m;
  memset(&m, 0, sizeof(m));
  sqlite3VdbeMemSetStr(&m, z, nByte, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  assert( (m.flags & MEM_Term)!=0 || sqlite3MallocFailed() );
  assert( (m.flags & MEM_Str)!=0 || sqlite3MallocFailed() );
  return (m.flags & MEM_Dyn)!=0 ? m.z : sqliteStrDup(m.z);
}

/*
** pZ is a UTF-16 encoded unicode string. If nChar is less than zero,
** return the number of bytes up to (but not including), the first pair
** of consecutive 0x00 bytes in pZ. If nChar is not less than zero,
** then return the number of bytes in the first nChar unicode characters
** in pZ (or up until the first pair of 0x00 bytes, whichever comes first).
*/
static int sqlite3Utf16ByteLen(const void *zIn, int nChar){
SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  unsigned int c = 1;
  char const *z = zIn;
  int n = 0;
  if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
    /* Using an "if (SQLITE_UTF16NATIVE==SQLITE_UTF16BE)" construct here
    ** and in other parts of this file means that at one branch will
    ** not be covered by coverage testing on any single host. But coverage
10139
10140
10141
10142
10143
10144
10145
10146

10147
10148
10149
10150
10151
10152
10153
10181
10182
10183
10184
10185
10186
10187

10188
10189
10190
10191
10192
10193
10194
10195







-
+







**
** This has the effect of making sure that the string is well-formed
** UTF-8.  Miscoded characters are removed.
**
** The translation is done in-place (since it is impossible for the
** correct UTF-8 encoding to be longer than a malformed encoding).
*/
static int sqlite3Utf8To8(unsigned char *zIn){
SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  unsigned char *zOut = zIn;
  unsigned char *zStart = zIn;
  int c;

  while(1){
    SQLITE_READ_UTF8(zIn, c);
    if( c==0 ) break;
10162
10163
10164
10165
10166
10167
10168
10169

10170
10171
10172
10173
10174
10175
10176
10204
10205
10206
10207
10208
10209
10210

10211
10212
10213
10214
10215
10216
10217
10218







-
+








#if defined(SQLITE_TEST)
/*
** This routine is called from the TCL test function "translate_selftest".
** It checks that the primitives for serializing and deserializing
** characters in each encoding are inverses of each other.
*/
static void sqlite3UtfSelfTest(){
SQLITE_PRIVATE void sqlite3UtfSelfTest(){
  unsigned int i, t;
  unsigned char zBuf[20];
  unsigned char *z;
  int n;
  unsigned int c;

  for(i=0; i<0x00110000; i++){
10226
10227
10228
10229
10230
10231
10232
10233

10234
10235
10236
10237
10238
10239
10240
10268
10269
10270
10271
10272
10273
10274

10275
10276
10277
10278
10279
10280
10281
10282







-
+







**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


/*
** Set the most recent error code and error string for the sqlite
** handle "db". The error code is set to "err_code".
**
10251
10252
10253
10254
10255
10256
10257
10258

10259
10260
10261
10262
10263
10264
10265
10293
10294
10295
10296
10297
10298
10299

10300
10301
10302
10303
10304
10305
10306
10307







-
+







** zFormat and any string tokens that follow it are assumed to be
** encoded in UTF-8.
**
** To clear the most recent error for sqlite handle "db", sqlite3Error
** should be called with err_code set to SQLITE_OK and zFormat set
** to NULL.
*/
static void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  if( db && (db->pErr || (db->pErr = sqlite3ValueNew())!=0) ){
    db->errCode = err_code;
    if( zFormat ){
      char *z;
      va_list ap;
      va_start(ap, zFormat);
      z = sqlite3VMPrintf(zFormat, ap);
10284
10285
10286
10287
10288
10289
10290
10291

10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306

10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322

10323
10324
10325
10326
10327
10328
10329
10326
10327
10328
10329
10330
10331
10332

10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347

10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363

10364
10365
10366
10367
10368
10369
10370
10371







-
+














-
+















-
+







** This function should be used to report any error that occurs whilst
** compiling an SQL statement (i.e. within sqlite3_prepare()). The
** last thing the sqlite3_prepare() function does is copy the error
** stored by this function into the database handle using sqlite3Error().
** Function sqlite3Error() should be used during statement execution
** (sqlite3_step() etc.).
*/
static void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  pParse->nErr++;
  sqliteFree(pParse->zErrMsg);
  va_start(ap, zFormat);
  pParse->zErrMsg = sqlite3VMPrintf(zFormat, ap);
  va_end(ap);
  if( pParse->rc==SQLITE_OK ){
    pParse->rc = SQLITE_ERROR;
  }
}

/*
** Clear the error message in pParse, if any
*/
static void sqlite3ErrorClear(Parse *pParse){
SQLITE_PRIVATE void sqlite3ErrorClear(Parse *pParse){
  sqliteFree(pParse->zErrMsg);
  pParse->zErrMsg = 0;
  pParse->nErr = 0;
}

/*
** Convert an SQL-style quoted string into a normal string by removing
** the quote characters.  The conversion is done in-place.  If the
** input does not begin with a quote character, then this routine
** is a no-op.
**
** 2002-Feb-14: This routine is extended to remove MS-Access style
** brackets from around identifers.  For example:  "[a-b-c]" becomes
** "a-b-c".
*/
static void sqlite3Dequote(char *z){
SQLITE_PRIVATE void sqlite3Dequote(char *z){
  int quote;
  int i, j;
  if( z==0 ) return;
  quote = z[0];
  switch( quote ){
    case '\'':  break;
    case '"':   break;
10388
10389
10390
10391
10392
10393
10394
10395

10396
10397
10398
10399
10400
10401
10402

10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418

10419
10420
10421
10422
10423
10424
10425
10430
10431
10432
10433
10434
10435
10436

10437
10438
10439
10440
10441
10442
10443

10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459

10460
10461
10462
10463
10464
10465
10466
10467







-
+






-
+















-
+







};
#define UpperToLower sqlite3UpperToLower

/*
** Some systems have stricmp().  Others have strcasecmp().  Because
** there is no consistency, we will define our own.
*/
static int sqlite3StrICmp(const char *zLeft, const char *zRight){
SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return UpperToLower[*a] - UpperToLower[*b];
}
static int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
SQLITE_PRIVATE int sqlite3StrNICmp(const char *zLeft, const char *zRight, int N){
  register unsigned char *a, *b;
  a = (unsigned char *)zLeft;
  b = (unsigned char *)zRight;
  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
}

/*
** Return TRUE if z is a pure numeric string.  Return FALSE if the
** string contains any character which is not part of a number. If
** the string is numeric and contains the '.' character, set *realnum
** to TRUE (otherwise FALSE).
**
** An empty string is considered non-numeric.
*/
static int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
  int incr = (enc==SQLITE_UTF8?1:2);
  if( enc==SQLITE_UTF16BE ) z++;
  if( *z=='-' || *z=='+' ) z += incr;
  if( !isdigit(*(u8*)z) ){
    return 0;
  }
  z += incr;
10449
10450
10451
10452
10453
10454
10455
10456

10457
10458
10459
10460
10461
10462
10463
10491
10492
10493
10494
10495
10496
10497

10498
10499
10500
10501
10502
10503
10504
10505







-
+







** is not, the result is undefined.
**
** This routine is used instead of the library atof() function because
** the library atof() might want to use "," as the decimal point instead
** of "." depending on how locale is set.  But that would cause problems
** for SQL.  So this routine always uses "." regardless of locale.
*/
static int sqlite3AtoF(const char *z, double *pResult){
SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
#ifndef SQLITE_OMIT_FLOATING_POINT
  int sign = 1;
  const char *zBegin = z;
  LONGDOUBLE_TYPE v1 = 0.0;
  while( isspace(*(u8*)z) ) z++;
  if( *z=='-' ){
    sign = -1;
10506
10507
10508
10509
10510
10511
10512























10513
10514
10515
10516
10517
10518

10519
10520
10521
10522
10523
10524
10525

10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538

10539
10540
10541
10542



10543
10544


10545
10546

10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565





10566
10567
10568
10569
10570
10571
10572

10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588

10589

10590









10591











10592


















10593



10594













10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605

10606
10607
10608
10609
10610
10611
10612
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582

10583

10584
10585
10586
10587
10588

10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610


10611
10612


10613



















10614
10615
10616
10617
10618







10619
10620

10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633

10634
10635
10636

10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657

10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679

10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702

10703
10704
10705
10706
10707
10708
10709
10710







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+





-
+
-





-
+













+




+
+
+
-
-
+
+
-
-
+
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
-
-
-
-
-
-
-
+

-













-
+

+
-
+
+
+
+
+
+
+
+
+

+
+
+
+
+
+
+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+










-
+







  }
  *pResult = sign<0 ? -v1 : v1;
  return z - zBegin;
#else
  return sqlite3Atoi64(z, pResult);
#endif /* SQLITE_OMIT_FLOATING_POINT */
}

/*
** Compare the 19-character string zNum against the text representation
** value 2^63:  9223372036854775808.  Return negative, zero, or positive
** if zNum is less than, equal to, or greater than the string.
**
** Unlike memcmp() this routine is guaranteed to return the difference
** in the values of the last digit if the only difference is in the
** last digit.  So, for example,
**
**      compare2pow63("9223372036854775800")
**
** will return -8.
*/
static int compare2pow63(const char *zNum){
  int c;
  c = memcmp(zNum,"922337203685477580",18);
  if( c==0 ){
    c = zNum[18] - '8';
  }
  return c;
}


/*
** Return TRUE if zNum is a 64-bit signed integer and write
** the value of the integer into *pNum.  If zNum is not an integer
** or is an integer that is too large to be expressed with 64 bits,
** then return false.  If n>0 and the integer is string is not
** then return false.
** exactly n bytes long, return false.
**
** When this routine was originally written it dealt with only
** 32-bit numbers.  At that time, it was much faster than the
** atoi() library routine in RedHat 7.2.
*/
static int sqlite3Atoi64(const char *zNum, i64 *pNum){
SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;
  while( isspace(*(u8*)zNum) ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{
    neg = 0;
  }
  while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
    v = v*10 + c - '0';
  }
  *pNum = neg ? -v : v;
  if( c!=0 || i==0 || i>19 ){
    /* zNum is empty or contains non-numeric text or is longer
    ** than 19 digits (thus guaranting that it is too large) */
  return c==0 && i>0 && 
      (i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0));
    return 0;
  }else if( i<19 ){
}

    /* Less than 19 digits, so we know that it fits in 64 bits */
/*
** The string zNum represents an integer.  There might be some other
** information following the integer too, but that part is ignored.
** If the integer that the prefix of zNum represents will fit in a
** 32-bit signed integer, return TRUE.  Otherwise return FALSE.
**
** This routine returns FALSE for the string -2147483648 even that
** that number will in fact fit in a 32-bit integer.  But positive
** 2147483648 will not fit in 32 bits.  So it seems safer to return
** false.
*/
static int sqlite3FitsIn32Bits(const char *zNum){
  int i, c;
  if( *zNum=='-' || *zNum=='+' ) zNum++;
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
}

/*
    return 1;
  }else{
    /* 19-digit numbers must be no larger than 9223372036854775807 if positive
    ** or 9223372036854775808 if negative.  Note that 9223372036854665808
    ** is 2^63. */
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
*/
static int sqlite3GetInt32(const char *zNum, int *pValue){
  if( sqlite3FitsIn32Bits(zNum) ){
    *pValue = atoi(zNum);
    return 1;
    return compare2pow63(zNum)<neg;
  }
  return 0;
}

/*
** The string zNum represents an integer.  There might be some other
** information following the integer too, but that part is ignored.
** If the integer that the prefix of zNum represents will fit in a
** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
**
** This routine returns FALSE for the string -9223372036854775808 even that
** that number will, in theory fit in a 64-bit integer.  Positive
** 9223373036854775808 will not fit in 64 bits.  So it seems safer to return
** false.
*/
static int sqlite3FitsIn64Bits(const char *zNum){
SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum){
  int i, c;
  int neg = 0;
  if( *zNum=='-' || *zNum=='+' ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    zNum++;
  }
  while( *zNum=='0' ){
    zNum++;   /* Skip leading zeros.  Ticket #2454 */
  }
  for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  if( i<19 ){
    /* Guaranteed to fit if less than 19 digits */
    return 1;
  }else if( i>19 ){
    /* Guaranteed to be too big if greater than 19 digits */
    return 0;
  }else{
    /* Compare against 2^63. */
    return compare2pow63(zNum)<neg;
  }
}
  return i<19 || (i==19 && memcmp(zNum,"9223372036854775807",19)<=0);

/*
** If zNum represents an integer that will fit in 32-bits, then set
** *pValue to that integer and return true.  Otherwise return false.
**
** Any non-numeric characters that following zNum are ignored.
** This is different from sqlite3Atoi64() which requires the
** input number to be zero-terminated.
*/
SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  sqlite_int64 v = 0;
  int i, c;
  int neg = 0;
  if( zNum[0]=='-' ){
    neg = 1;
    zNum++;
  }else if( zNum[0]=='+' ){
    zNum++;
}
  while( zNum[0]=='0' ) zNum++;
  for(i=0; i<10 && (c = zNum[i] - '0')>=0 && c<=9; i++){
    v = v*10 + c;

  }
  if( i>9 ){
    return 0;
  }
  if( v-neg>2147483647 ){
    return 0;
  }
  if( neg ){
    v = -v;
  }
  *pValue = (int)v;
  return 1;
}

/*
** Check to make sure we have a valid db pointer.  This test is not
** foolproof but it does provide some measure of protection against
** misuse of the interface such as passing in db pointers that are
** NULL or which have been previously closed.  If this routine returns
** TRUE it means that the db pointer is invalid and should not be
** dereferenced for any reason.  The calling function should invoke
** SQLITE_MISUSE immediately.
*/
static int sqlite3SafetyCheck(sqlite3 *db){
SQLITE_PRIVATE int sqlite3SafetyCheck(sqlite3 *db){
  int magic;
  if( db==0 ) return 1;
  magic = db->magic;
  if( magic!=SQLITE_MAGIC_CLOSED &&
         magic!=SQLITE_MAGIC_OPEN &&
         magic!=SQLITE_MAGIC_BUSY ) return 1;
  return 0;
10637
10638
10639
10640
10641
10642
10643
10644

10645
10646
10647
10648
10649
10650
10651
10735
10736
10737
10738
10739
10740
10741

10742
10743
10744
10745
10746
10747
10748
10749







-
+







** of bytes written is returned.
**
** A variable-length integer consists of the lower 7 bits of each byte
** for all bytes that have the 8th bit set and one byte with the 8th
** bit clear.  Except, if we get to the 9th byte, it stores the full
** 8 bits and is the last byte.
*/
static int sqlite3PutVarint(unsigned char *p, u64 v){
SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  int i, j, n;
  u8 buf[10];
  if( v & (((u64)0xff000000)<<32) ){
    p[8] = v;
    v >>= 8;
    for(i=7; i>=0; i--){
      p[i] = (v & 0x7f) | 0x80;
10666
10667
10668
10669
10670
10671
10672
10673

10674
10675
10676
10677
10678
10679
10680
10764
10765
10766
10767
10768
10769
10770

10771
10772
10773
10774
10775
10776
10777
10778







-
+







  return n;
}

/*
** Read a 64-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
*/
static int sqlite3GetVarint(const unsigned char *p, u64 *v){
SQLITE_PRIVATE int sqlite3GetVarint(const unsigned char *p, u64 *v){
  u32 x;
  u64 x64;
  int n;
  unsigned char c;
  if( ((c = p[0]) & 0x80)==0 ){
    *v = c;
    return 1;
10708
10709
10710
10711
10712
10713
10714
10715

10716
10717
10718
10719
10720
10721
10722
10806
10807
10808
10809
10810
10811
10812

10813
10814
10815
10816
10817
10818
10819
10820







-
+







  return n;
}

/*
** Read a 32-bit variable-length integer from memory starting at p[0].
** Return the number of bytes read.  The value is stored in *v.
*/
static int sqlite3GetVarint32(const unsigned char *p, u32 *v){
SQLITE_PRIVATE int sqlite3GetVarint32(const unsigned char *p, u32 *v){
  u32 x;
  int n;
  unsigned char c;
  if( ((signed char*)p)[0]>=0 ){
    *v = p[0];
    return 1;
  }
10734
10735
10736
10737
10738
10739
10740
10741

10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754

10755
10756
10757

10758
10759
10760
10761
10762
10763
10764
10832
10833
10834
10835
10836
10837
10838

10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851

10852
10853
10854

10855
10856
10857
10858
10859
10860
10861
10862







-
+












-
+


-
+







  return n;
}

/*
** Return the number of bytes that will be needed to store the given
** 64-bit integer.
*/
static int sqlite3VarintLen(u64 v){
SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  int i = 0;
  do{
    i++;
    v >>= 7;
  }while( v!=0 && i<9 );
  return i;
}


/*
** Read or write a four-byte big-endian integer value.
*/
static u32 sqlite3Get4byte(const u8 *p){
SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
}
static void sqlite3Put4byte(unsigned char *p, u32 v){
SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  p[0] = v>>24;
  p[1] = v>>16;
  p[2] = v>>8;
  p[3] = v;
}


10783
10784
10785
10786
10787
10788
10789
10790

10791
10792
10793
10794
10795
10796
10797
10881
10882
10883
10884
10885
10886
10887

10888
10889
10890
10891
10892
10893
10894
10895







-
+







#if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
/*
** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
** value.  Return a pointer to its binary value.  Space to hold the
** binary value has been obtained from malloc and must be freed by
** the calling routine.
*/
static void *sqlite3HexToBlob(const char *z){
SQLITE_PRIVATE void *sqlite3HexToBlob(const char *z){
  char *zBlob;
  int i;
  int n = strlen(z);
  if( n%2 ) return 0;

  zBlob = (char *)sqliteMalloc(n/2);
  if( zBlob ){
10825
10826
10827
10828
10829
10830
10831
10832

10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848

10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862

10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875

10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886

10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906

10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921

10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941

10942
10943
10944
10945
10946
10947
10948
10923
10924
10925
10926
10927
10928
10929

10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945

10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959

10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972

10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983

10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003

11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018

11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038

11039
11040
11041
11042
11043
11044
11045
11046







-
+















-
+













-
+












-
+










-
+



















-
+














-
+



















-
+







**
** Ticket #202:  If db->magic is not a valid open value, take care not
** to modify the db structure at all.  It could be that db is a stale
** pointer.  In other words, it could be that there has been a prior
** call to sqlite3_close(db) and db has been deallocated.  And we do
** not want to write into deallocated memory.
*/
static int sqlite3SafetyOn(sqlite3 *db){
SQLITE_PRIVATE int sqlite3SafetyOn(sqlite3 *db){
  if( db->magic==SQLITE_MAGIC_OPEN ){
    db->magic = SQLITE_MAGIC_BUSY;
    return 0;
  }else if( db->magic==SQLITE_MAGIC_BUSY ){
    db->magic = SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
  }
  return 1;
}

/*
** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
** when this routine is called.
*/
static int sqlite3SafetyOff(sqlite3 *db){
SQLITE_PRIVATE int sqlite3SafetyOff(sqlite3 *db){
  if( db->magic==SQLITE_MAGIC_BUSY ){
    db->magic = SQLITE_MAGIC_OPEN;
    return 0;
  }else {
    db->magic = SQLITE_MAGIC_ERROR;
    db->u1.isInterrupted = 1;
    return 1;
  }
}

/*
** Return a pointer to the ThreadData associated with the calling thread.
*/
static ThreadData *sqlite3ThreadData(){
SQLITE_PRIVATE ThreadData *sqlite3ThreadData(){
  ThreadData *p = (ThreadData*)sqlite3OsThreadSpecificData(1);
  if( !p ){
    sqlite3FailedMalloc();
  }
  return p;
}

/*
** Return a pointer to the ThreadData associated with the calling thread.
** If no ThreadData has been allocated to this thread yet, return a pointer
** to a substitute ThreadData structure that is all zeros. 
*/
static const ThreadData *sqlite3ThreadDataReadOnly(){
SQLITE_PRIVATE const ThreadData *sqlite3ThreadDataReadOnly(){
  static const ThreadData zeroData = {0};  /* Initializer to silence warnings
                                           ** from broken compilers */
  const ThreadData *pTd = sqlite3OsThreadSpecificData(0);
  return pTd ? pTd : &zeroData;
}

/*
** Check to see if the ThreadData for this thread is all zero.  If it
** is, then deallocate it. 
*/
static void sqlite3ReleaseThreadData(){
SQLITE_PRIVATE void sqlite3ReleaseThreadData(){
  sqlite3OsThreadSpecificData(-1);
}

/************** End of util.c ************************************************/
/************** Begin file hash.c ********************************************/
/*
** 2001 September 22
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This is the implementation of generic hash-tables
** used in SQLite.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/* Turn bulk memory into a hash table object by initializing the
** fields of the Hash structure.
**
** "pNew" is a pointer to the hash table that is to be initialized.
** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING.  The value of keyClass 
** determines what kind of key the hash table will use.  "copyKey" is
** true if the hash table should make its own private copy of keys and
** false if it should just use the supplied pointer.  CopyKey only makes
** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
** for other key classes.
*/
static void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew, int keyClass, int copyKey){
  assert( pNew!=0 );
  assert( keyClass>=SQLITE_HASH_STRING && keyClass<=SQLITE_HASH_BINARY );
  pNew->keyClass = keyClass;
#if 0
  if( keyClass==SQLITE_HASH_POINTER || keyClass==SQLITE_HASH_INT ) copyKey = 0;
#endif
  pNew->copyKey = copyKey;
  pNew->first = 0;
  pNew->count = 0;
  pNew->htsize = 0;
  pNew->ht = 0;
  pNew->xMalloc = sqlite3MallocX;
  pNew->xFree = sqlite3FreeX;
}

/* Remove all entries from a hash table.  Reclaim all memory.
** Call this routine to delete a hash table or to reset a hash table
** to the empty state.
*/
static void sqlite3HashClear(Hash *pH){
SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  HashElem *elem;         /* For looping over all elements of the table */

  assert( pH!=0 );
  elem = pH->first;
  pH->first = 0;
  if( pH->ht ) pH->xFree(pH->ht);
  pH->ht = 0;
11192
11193
11194
11195
11196
11197
11198
11199

11200
11201
11202
11203
11204
11205
11206
11290
11291
11292
11293
11294
11295
11296

11297
11298
11299
11300
11301
11302
11303
11304







-
+







  }
}

/* Attempt to locate an element of the hash table pH with a key
** that matches pKey,nKey.  Return the data for this element if it is
** found, or NULL if there is no match.
*/
static void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const void *pKey, int nKey){
  int h;             /* A hash on key */
  HashElem *elem;    /* The element that matches key */
  int (*xHash)(const void*,int);  /* The hash function */

  if( pH==0 || pH->ht==0 ) return 0;
  xHash = hashFunction(pH->keyClass);
  assert( xHash!=0 );
11221
11222
11223
11224
11225
11226
11227
11228

11229
11230
11231
11232
11233
11234
11235
11319
11320
11321
11322
11323
11324
11325

11326
11327
11328
11329
11330
11331
11332
11333







-
+







** new data replaces the old data and the old data is returned.
** The key is not copied in this instance.  If a malloc fails, then
** the new data is returned and the hash table is unchanged.
**
** If the "data" parameter to this function is NULL, then the
** element corresponding to "key" is removed from the hash table.
*/
static void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  int hraw;             /* Raw hash value of the key */
  int h;                /* the hash of the key modulo hash table size */
  HashElem *elem;       /* Used to loop thru the element list */
  HashElem *new_elem;   /* New element added to the pH */
  int (*xHash)(const void*,int);  /* The hash function */

  assert( pH!=0 );
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
































11353
11354
11355
11356
11357



11358
11359
11360
11361
11362
11363
11364
11365
11366

11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377

11378
11379

11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417




































11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429










11430
11431
11432
11433
11434
11435
11436
11412
11413
11414
11415
11416
11417
11418
































11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452



11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463

11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474

11475
11476

11477
11478
11479




































11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517










11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534







-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
+
+
+








-
+










-
+

-
+


-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+







 /*  21 */ "Noop",
 /*  22 */ "Return",
 /*  23 */ "NewRowid",
 /*  24 */ "IfMemNeg",
 /*  25 */ "Variable",
 /*  26 */ "String",
 /*  27 */ "RealAffinity",
 /*  28 */ "ParseSchema",
 /*  29 */ "VOpen",
 /*  30 */ "Close",
 /*  31 */ "CreateIndex",
 /*  32 */ "IsUnique",
 /*  33 */ "NotFound",
 /*  34 */ "Int64",
 /*  35 */ "MustBeInt",
 /*  36 */ "Halt",
 /*  37 */ "Rowid",
 /*  38 */ "IdxLT",
 /*  39 */ "AddImm",
 /*  40 */ "Statement",
 /*  41 */ "RowData",
 /*  42 */ "MemMax",
 /*  43 */ "Push",
 /*  44 */ "NotExists",
 /*  45 */ "MemIncr",
 /*  46 */ "Gosub",
 /*  47 */ "Integer",
 /*  48 */ "MemInt",
 /*  49 */ "Prev",
 /*  50 */ "VColumn",
 /*  51 */ "CreateTable",
 /*  52 */ "Last",
 /*  53 */ "IncrVacuum",
 /*  54 */ "IdxRowid",
 /*  55 */ "MakeIdxRec",
 /*  56 */ "ResetCount",
 /*  57 */ "FifoWrite",
 /*  58 */ "Callback",
 /*  59 */ "ContextPush",
 /*  28 */ "VRename",
 /*  29 */ "ParseSchema",
 /*  30 */ "VOpen",
 /*  31 */ "Close",
 /*  32 */ "CreateIndex",
 /*  33 */ "IsUnique",
 /*  34 */ "NotFound",
 /*  35 */ "Int64",
 /*  36 */ "MustBeInt",
 /*  37 */ "Halt",
 /*  38 */ "Rowid",
 /*  39 */ "IdxLT",
 /*  40 */ "AddImm",
 /*  41 */ "Statement",
 /*  42 */ "RowData",
 /*  43 */ "MemMax",
 /*  44 */ "Push",
 /*  45 */ "NotExists",
 /*  46 */ "MemIncr",
 /*  47 */ "Gosub",
 /*  48 */ "Integer",
 /*  49 */ "MemInt",
 /*  50 */ "Prev",
 /*  51 */ "VColumn",
 /*  52 */ "CreateTable",
 /*  53 */ "Last",
 /*  54 */ "IncrVacuum",
 /*  55 */ "IdxRowid",
 /*  56 */ "MakeIdxRec",
 /*  57 */ "ResetCount",
 /*  58 */ "FifoWrite",
 /*  59 */ "Callback",
 /*  60 */ "Or",
 /*  61 */ "And",
 /*  62 */ "DropTrigger",
 /*  63 */ "DropIndex",
 /*  64 */ "IdxGE",
 /*  62 */ "ContextPush",
 /*  63 */ "DropTrigger",
 /*  64 */ "DropIndex",
 /*  65 */ "IsNull",
 /*  66 */ "NotNull",
 /*  67 */ "Ne",
 /*  68 */ "Eq",
 /*  69 */ "Gt",
 /*  70 */ "Le",
 /*  71 */ "Lt",
 /*  72 */ "Ge",
 /*  73 */ "IdxDelete",
 /*  73 */ "IdxGE",
 /*  74 */ "BitAnd",
 /*  75 */ "BitOr",
 /*  76 */ "ShiftLeft",
 /*  77 */ "ShiftRight",
 /*  78 */ "Add",
 /*  79 */ "Subtract",
 /*  80 */ "Multiply",
 /*  81 */ "Divide",
 /*  82 */ "Remainder",
 /*  83 */ "Concat",
 /*  84 */ "Vacuum",
 /*  84 */ "IdxDelete",
 /*  85 */ "Negative",
 /*  86 */ "MoveLe",
 /*  86 */ "Vacuum",
 /*  87 */ "BitNot",
 /*  88 */ "String8",
 /*  89 */ "IfNot",
 /*  90 */ "DropTable",
 /*  91 */ "MakeRecord",
 /*  92 */ "Delete",
 /*  93 */ "AggFinal",
 /*  94 */ "Dup",
 /*  95 */ "Goto",
 /*  96 */ "TableLock",
 /*  97 */ "FifoRead",
 /*  98 */ "Clear",
 /*  99 */ "IdxGT",
 /* 100 */ "MoveLt",
 /* 101 */ "VerifyCookie",
 /* 102 */ "AggStep",
 /* 103 */ "Pull",
 /* 104 */ "SetNumColumns",
 /* 105 */ "AbsValue",
 /* 106 */ "Transaction",
 /* 107 */ "VFilter",
 /* 108 */ "VDestroy",
 /* 109 */ "ContextPop",
 /* 110 */ "Next",
 /* 111 */ "IdxInsert",
 /* 112 */ "Distinct",
 /* 113 */ "Insert",
 /* 114 */ "Destroy",
 /* 115 */ "ReadCookie",
 /* 116 */ "ForceInt",
 /* 117 */ "LoadAnalysis",
 /* 118 */ "Explain",
 /* 119 */ "IfMemZero",
 /* 120 */ "OpenPseudo",
 /* 121 */ "OpenEphemeral",
 /* 122 */ "Null",
 /* 123 */ "Blob",
 /* 124 */ "MemStore",
 /*  89 */ "MoveLe",
 /*  90 */ "IfNot",
 /*  91 */ "DropTable",
 /*  92 */ "MakeRecord",
 /*  93 */ "Delete",
 /*  94 */ "AggFinal",
 /*  95 */ "Dup",
 /*  96 */ "Goto",
 /*  97 */ "TableLock",
 /*  98 */ "FifoRead",
 /*  99 */ "Clear",
 /* 100 */ "IdxGT",
 /* 101 */ "MoveLt",
 /* 102 */ "VerifyCookie",
 /* 103 */ "AggStep",
 /* 104 */ "Pull",
 /* 105 */ "SetNumColumns",
 /* 106 */ "AbsValue",
 /* 107 */ "Transaction",
 /* 108 */ "VFilter",
 /* 109 */ "VDestroy",
 /* 110 */ "ContextPop",
 /* 111 */ "Next",
 /* 112 */ "IdxInsert",
 /* 113 */ "Distinct",
 /* 114 */ "Insert",
 /* 115 */ "Destroy",
 /* 116 */ "ReadCookie",
 /* 117 */ "ForceInt",
 /* 118 */ "LoadAnalysis",
 /* 119 */ "Explain",
 /* 120 */ "IfMemZero",
 /* 121 */ "OpenPseudo",
 /* 122 */ "OpenEphemeral",
 /* 123 */ "Null",
 /* 124 */ "Blob",
 /* 125 */ "Real",
 /* 126 */ "HexBlob",
 /* 127 */ "Rewind",
 /* 128 */ "MoveGe",
 /* 129 */ "VBegin",
 /* 130 */ "VUpdate",
 /* 131 */ "VCreate",
 /* 132 */ "MemMove",
 /* 133 */ "MemNull",
 /* 134 */ "Found",
 /* 135 */ "NullRow",
 /* 136 */ "NotUsed_136",
 /* 127 */ "MemStore",
 /* 128 */ "Rewind",
 /* 129 */ "MoveGe",
 /* 130 */ "VBegin",
 /* 131 */ "VUpdate",
 /* 132 */ "VCreate",
 /* 133 */ "MemMove",
 /* 134 */ "MemNull",
 /* 135 */ "Found",
 /* 136 */ "NullRow",
 /* 137 */ "NotUsed_137",
 /* 138 */ "ToText",
 /* 139 */ "ToBlob",
 /* 140 */ "ToNumeric",
 /* 141 */ "ToInt",
 /* 142 */ "ToReal",
};
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11547
11548
11549
11550
11551
11552
11553





11554
11555
11556
11557
11558
11559
11560







-
-
-
-
-







**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to OS/2.
*/

#if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
/* os2safe.h has to be included before os2.h, needed for high mem */
#include <os2safe.h>
#endif


#if OS_OS2

/*
** Macros used to determine whether or not to use threads.
*/
#if defined(THREADSAFE) && THREADSAFE
11616
11617
11618
11619
11620
11621
11622
11623

11624
11625
11626
11627
11628
11629
11630
11631
11632
11633

11634
11635
11636
11637
11638
11639
11640
11641
11642
11643

11644
11645
11646
11647

11648
11649
11650
11651

11652
11653
11654
11655

11656
11657
11658
11659
11660

11661
11662
11663
11664
11665

11666
11667
11668
11669
11670
11671
11672
11709
11710
11711
11712
11713
11714
11715

11716
11717
11718
11719
11720
11721
11722
11723
11724
11725

11726
11727
11728
11729
11730
11731
11732
11733
11734
11735

11736
11737
11738
11739

11740
11741
11742
11743

11744
11745
11746
11747

11748
11749
11750
11751
11752

11753
11754
11755
11756
11757

11758
11759
11760
11761
11762
11763
11764
11765







-
+









-
+









-
+



-
+



-
+



-
+




-
+




-
+







** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n+8);
  assert(n>0);
  assert(sizeof(int)<=8);
  if( p ){
    *(int *)p = n;
    p += 8;
  }
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  char *p2 = ((char *)p - 8);
  assert(n>0);
  p2 = (char*)realloc(p2, n+8);
  if( p2 ){
    *(int *)p2 = n;
    p2 += 8;
  }
  return (void *)p2;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free((void *)((char *)p - 8));
}
static int sqlite3GenericAllocationSize(void *p){
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){
  return p ? *(int *)((char *)p - 8) : 0;
}
#else
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n);
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  assert(n>0);
  p = realloc(p, n);
  return p;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free(p);
}
/* Never actually used, but needed for the linker */
static int sqlite3GenericAllocationSize(void *p){ return 0; }
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){ return 0; }
#endif

/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
11694
11695
11696
11697
11698
11699
11700
11701

11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712

11713
11714
11715
11716
11717
11718
11719
11787
11788
11789
11790
11791
11792
11793

11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804

11805
11806
11807
11808
11809
11810
11811
11812







-
+










-
+







** will be in-memory only)
*/
#ifndef SQLITE_OMIT_DISKIO

/*
** Delete the named file
*/
static int sqlite3Os2Delete( const char *zFilename ){
SQLITE_PRIVATE int sqlite3Os2Delete( const char *zFilename ){
  APIRET rc = NO_ERROR;

  rc = DosDelete( (PSZ)zFilename );
  OSTRACE2( "DELETE \"%s\"\n", zFilename );
  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
}

/*
** Return TRUE if the named file exists.
*/
static int sqlite3Os2FileExists( const char *zFilename ){
SQLITE_PRIVATE int sqlite3Os2FileExists( const char *zFilename ){
  FILESTATUS3 fsts3ConfigInfo;
  memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
  return DosQueryPathInfo( (PSZ)zFilename, FIL_STANDARD,
        &fsts3ConfigInfo, sizeof(FILESTATUS3) ) == NO_ERROR;
}

/* Forward declaration */
11728
11729
11730
11731
11732
11733
11734
11735

11736
11737
11738
11739
11740
11741
11742
11821
11822
11823
11824
11825
11826
11827

11828
11829
11830
11831
11832
11833
11834
11835







-
+







** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** SQLITE_OK.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
static int sqlite3Os2OpenReadWrite(
SQLITE_PRIVATE int sqlite3Os2OpenReadWrite(
  const char *zFilename,
  OsFile **pld,
  int *pReadonly
){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
11782
11783
11784
11785
11786
11787
11788
11789

11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809

11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821

11822
11823
11824
11825
11826
11827
11828
11875
11876
11877
11878
11879
11880
11881

11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901

11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913

11914
11915
11916
11917
11918
11919
11920
11921







-
+



















-
+











-
+







** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
static int sqlite3Os2OpenExclusive( const char *zFilename, OsFile **pld, int delFlag ){
SQLITE_PRIVATE int sqlite3Os2OpenExclusive( const char *zFilename, OsFile **pld, int delFlag ){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
  APIRET   rc = NO_ERROR;

  assert( *pld == 0 );
  rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L, FILE_NORMAL,
            OPEN_ACTION_CREATE_IF_NEW | OPEN_ACTION_REPLACE_IF_EXISTS,
            OPEN_FLAGS_FAIL_ON_ERROR | OPEN_FLAGS_RANDOM |
                OPEN_SHARE_DENYREADWRITE | OPEN_ACCESS_READWRITE, (PEAOP2)NULL );
  if( rc != NO_ERROR ){
    return SQLITE_CANTOPEN;
  }

  f.h = hf;
  f.locktype = NO_LOCK;
  f.delOnClose = delFlag ? 1 : 0;
  f.pathToDel = delFlag ? sqlite3OsFullPathname( zFilename ) : NULL;
  OpenCounter( +1 );
  if( delFlag ) DosForceDelete( sqlite3OsFullPathname( zFilename ) );
  if( delFlag ) DosForceDelete( (PSZ)sqlite3OsFullPathname( zFilename ) );
  OSTRACE3( "OPEN EX %d \"%s\"\n", hf, sqlite3OsFullPathname ( zFilename ) );
  return allocateOs2File( &f, pld );
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
static int sqlite3Os2OpenReadOnly( const char *zFilename, OsFile **pld ){
SQLITE_PRIVATE int sqlite3Os2OpenReadOnly( const char *zFilename, OsFile **pld ){
  os2File  f;
  HFILE    hf;
  ULONG    ulAction;
  APIRET   rc = NO_ERROR;

  assert( *pld == 0 );
  rc = DosOpen( (PSZ)zFilename, &hf, &ulAction, 0L,
11864
11865
11866
11867
11868
11869
11870
11871

11872
11873
11874
11875
11876
11877
11878
11879
11880



11881
11882
11883

11884
11885
11886
11887
11888
11889
11890
11957
11958
11959
11960
11961
11962
11963

11964
11965
11966
11967
11968
11969
11970



11971
11972
11973
11974
11975

11976
11977
11978
11979
11980
11981
11982
11983







-
+






-
-
-
+
+
+


-
+







  return SQLITE_OK;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at least SQLITE_TEMPNAME_SIZE characters.
*/
static int sqlite3Os2TempFileName( char *zBuf ){
SQLITE_PRIVATE int sqlite3Os2TempFileName( char *zBuf ){
  static const unsigned char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  int i, j;
  PSZ zTempPath = 0;
  if( DosScanEnv( "TEMP", &zTempPath ) ){
    if( DosScanEnv( "TMP", &zTempPath ) ){
      if( DosScanEnv( "TMPDIR", &zTempPath ) ){
  if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
    if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
      if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
           ULONG ulDriveNum = 0, ulDriveMap = 0;
           DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
           sprintf( zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
           sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
      }
    }
  }
  for(;;){
      sprintf( zBuf, "%s\\"TEMP_FILE_PREFIX, zTempPath );
      j = strlen( zBuf );
      sqlite3Randomness( 15, &zBuf[j] );
11905
11906
11907
11908
11909
11910
11911
11912

11913
11914
11915
11916
11917
11918
11919
11998
11999
12000
12001
12002
12003
12004

12005
12006
12007
12008
12009
12010
12011
12012







-
+







  os2File *pFile;
  APIRET rc = NO_ERROR;
  if( pld && (pFile = (os2File*)*pld) != 0 ){
    OSTRACE2( "CLOSE %d\n", pFile->h );
    rc = DosClose( pFile->h );
    pFile->locktype = NO_LOCK;
    if( pFile->delOnClose != 0 ){
        rc = DosForceDelete( pFile->pathToDel );
        rc = DosForceDelete( (PSZ)pFile->pathToDel );
    }
    *pld = 0;
    OpenCounter( -1 );
  }

  return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
}
11927
11928
11929
11930
11931
11932
11933
11934

11935
11936
11937
11938
11939
11940
11941
12020
12021
12022
12023
12024
12025
12026

12027
12028
12029
12030
12031
12032
12033
12034







-
+







  ULONG got;
  assert( id!=0 );
  SimulateIOError( return SQLITE_IOERR );
  OSTRACE3( "READ %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
  DosRead( ((os2File*)id)->h, pBuf, amt, &got );
  if (got == (ULONG)amt)
    return SQLITE_OK;
  else if (got < 0)
  else if (got == 0)
    return SQLITE_IOERR_READ;
  else {
    memset(&((char*)pBuf)[got], 0, amt-got);
    return SQLITE_IOERR_SHORT_READ;
  }
}

11980
11981
11982
11983
11984
11985
11986
11987

11988
11989
11990
11991
11992
11993
11994
12073
12074
12075
12076
12077
12078
12079

12080
12081
12082
12083
12084
12085
12086
12087







-
+







  return DosResetBuffer( ((os2File*)id)->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
}

/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
*/
static int sqlite3Os2SyncDirectory( const char *zDirname ){
SQLITE_PRIVATE int sqlite3Os2SyncDirectory( const char *zDirname ){
  SimulateIOError( return SQLITE_IOERR );
  return SQLITE_OK;
}

/*
** Truncate an open file to a specified size
*/
12056
12057
12058
12059
12060
12061
12062
12063

12064
12065
12066
12067
12068
12069
12070
12149
12150
12151
12152
12153
12154
12155

12156
12157
12158
12159
12160
12161
12162
12163







-
+







}

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
/*
** Check that a given pathname is a directory and is writable
**
*/
static int sqlite3Os2IsDirWritable( char *zDirname ){
SQLITE_PRIVATE int sqlite3Os2IsDirWritable( char *zDirname ){
  FILESTATUS3 fsts3ConfigInfo;
  APIRET rc = NO_ERROR;
  memset(&fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo));
  if( zDirname==0 ) return 0;
  if( strlen(zDirname)>CCHMAXPATH ) return 0;
  rc = DosQueryPathInfo( (PSZ)zDirname, FIL_STANDARD, &fsts3ConfigInfo, sizeof(FILESTATUS3) );
  if( rc != NO_ERROR ) return 0;
12318
12319
12320
12321
12322
12323
12324
12325

12326
12327
12328
12329
12330
12331
12332
12333
12334






12335
12336

12337
12338
12339





12340
12341
12342
12343
12344
12345
12346
12411
12412
12413
12414
12415
12416
12417

12418
12419
12420
12421
12422



12423
12424
12425
12426
12427
12428
12429
12430
12431

12432

12433

12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445







-
+




-
-
-


+
+
+
+
+
+

-
+
-

-
+
+
+
+
+








/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
static char *sqlite3Os2FullPathname( const char *zRelative ){
SQLITE_PRIVATE char *sqlite3Os2FullPathname( const char *zRelative ){
  char *zFull = 0;
  if( strchr(zRelative, ':') ){
    sqlite3SetString( &zFull, zRelative, (char*)0 );
  }else{
    char zBuff[SQLITE_TEMPNAME_SIZE - 2] = {0};
    char zDrive[1] = {0};
    ULONG cbzFullLen = SQLITE_TEMPNAME_SIZE;
    ULONG ulDriveNum = 0;
    ULONG ulDriveMap = 0;
    ULONG cbzBufLen = SQLITE_TEMPNAME_SIZE;
    char zDrive[2];
    char *zBuff;

    zBuff = sqliteMalloc( cbzBufLen );
    if( zBuff != 0 ){
    DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
    DosQueryCurrentDir( 0L, zBuff, &cbzFullLen );
      if( DosQueryCurrentDir( ulDriveNum, (PBYTE)zBuff, &cbzBufLen ) == NO_ERROR ){
    zFull = sqliteMalloc( cbzFullLen );
    sprintf( zDrive, "%c", (char)('A' + ulDriveNum - 1) );
    sqlite3SetString( &zFull, zDrive, ":\\", zBuff, "\\", zRelative, (char*)0 );
        sqlite3SetString( &zFull, zDrive, ":\\", zBuff,
                          "\\", zRelative, (char*)0 );
      }
      sqliteFree( zBuff );
    }
  }
  return zFull;
}

/*
** The fullSync option is meaningless on os2, or correct me if I'm wrong.  This is a no-op.
** From os_unix.c: Change the value of the fullsync flag in the given file descriptor.
12430
12431
12432
12433
12434
12435
12436
12437

12438
12439
12440
12441

12442
12443
12444
12445

12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458

12459
12460

12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471

12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492

12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513

12514
12515

12516
12517
12518
12519
12520
12521
12522
12523


12524

12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541

12542
12543
12544
12545
12546
12547
12548
12529
12530
12531
12532
12533
12534
12535

12536
12537
12538
12539

12540
12541
12542
12543

12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556

12557
12558

12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569

12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590

12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611

12612

12613
12614
12615
12616
12617
12618
12619
12620
12621

12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641

12642
12643
12644
12645
12646
12647
12648
12649







-
+



-
+



-
+












-
+

-
+










-
+




















-
+




















-
+
-

+







-
+
+

+
















-
+







****************************************************************************/

#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
static void *sqlite3Os2Dlopen(const char *zFilename){
SQLITE_PRIVATE void *sqlite3Os2Dlopen(const char *zFilename){
  UCHAR loadErr[256];
  HMODULE hmod;
  APIRET rc;
  rc = DosLoadModule(loadErr, sizeof(loadErr), zFilename, &hmod);
  rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilename, &hmod);
  if (rc != NO_ERROR) return 0;
  return (void*)hmod;
}
static void *sqlite3Os2Dlsym(void *pHandle, const char *zSymbol){
SQLITE_PRIVATE void *sqlite3Os2Dlsym(void *pHandle, const char *zSymbol){
  PFN pfn;
  APIRET rc;
  rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
  if (rc != NO_ERROR) {
    /* if the symbol itself was not found, search again for the same
     * symbol with an extra underscore, that might be needed depending
     * on the calling convention */
    char _zSymbol[256] = "_";
    strncat(_zSymbol, zSymbol, 255);
    rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
  }
  if (rc != NO_ERROR) return 0;
  return pfn;
  return (void *)pfn;
}
static int sqlite3Os2Dlclose(void *pHandle){
SQLITE_PRIVATE int sqlite3Os2Dlclose(void *pHandle){
  return DosFreeModule((HMODULE)pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */


/*
** Get information to seed the random number generator.  The seed
** is written into the buffer zBuf[256].  The calling function must
** supply a sufficiently large buffer.
*/
static int sqlite3Os2RandomSeed( char *zBuf ){
SQLITE_PRIVATE int sqlite3Os2RandomSeed( char *zBuf ){
  /* We have to initialize zBuf to prevent valgrind from reporting
  ** errors.  The reports issued by valgrind are incorrect - we would
  ** prefer that the randomness be increased by making use of the
  ** uninitialized space in zBuf - but valgrind errors tend to worry
  ** some users.  Rather than argue, it seems easier just to initialize
  ** the whole array and silence valgrind, even if that means less randomness
  ** in the random seed.
  **
  ** When testing, initializing zBuf[] to zero is all we do.  That means
  ** that we always use the same random number sequence. This makes the
  ** tests repeatable.
  */
  memset( zBuf, 0, 256 );
  DosGetDateTime( (PDATETIME)zBuf );
  return SQLITE_OK;
}

/*
** Sleep for a little while.  Return the amount of time slept.
*/
static int sqlite3Os2Sleep( int ms ){
SQLITE_PRIVATE int sqlite3Os2Sleep( int ms ){
  DosSleep( ms );
  return ms;
}

/*
** Static variables used for thread synchronization
*/
static int inMutex = 0;
#ifdef SQLITE_OS2_THREADS
static ULONG mutexOwner;
#endif

/*
** The following pair of routines implement mutual exclusion for
** multi-threaded processes.  Only a single thread is allowed to
** executed code that is surrounded by EnterMutex() and LeaveMutex().
**
** SQLite uses only a single Mutex.  There is not much critical
** code and what little there is executes quickly and without blocking.
*/
static void sqlite3Os2EnterMutex(){
SQLITE_PRIVATE void sqlite3Os2EnterMutex(){
  PTIB ptib;
#ifdef SQLITE_OS2_THREADS
  PTIB ptib;
  DosEnterCritSec();
  DosGetInfoBlocks( &ptib, NULL );
  mutexOwner = ptib->tib_ptib2->tib2_ultid;
#endif
  assert( !inMutex );
  inMutex = 1;
}
static void sqlite3Os2LeaveMutex(){
SQLITE_PRIVATE void sqlite3Os2LeaveMutex(){
#ifdef SQLITE_OS2_THREADS
  PTIB ptib;
#endif
  assert( inMutex );
  inMutex = 0;
#ifdef SQLITE_OS2_THREADS
  DosGetInfoBlocks( &ptib, NULL );
  assert( mutexOwner == ptib->tib_ptib2->tib2_ultid );
  DosExitCritSec();
#endif
}

/*
** Return TRUE if the mutex is currently held.
**
** If the thisThreadOnly parameter is true, return true if and only if the
** calling thread holds the mutex.  If the parameter is false, return
** true if any thread holds the mutex.
*/
static int sqlite3Os2InMutex( int thisThreadOnly ){
SQLITE_PRIVATE int sqlite3Os2InMutex( int thisThreadOnly ){
#ifdef SQLITE_OS2_THREADS
  PTIB ptib;
  DosGetInfoBlocks( &ptib, NULL );
  return inMutex>0 && (thisThreadOnly==0 || mutexOwner==ptib->tib_ptib2->tib2_ultid);
#else
  return inMutex>0;
#endif
12557
12558
12559
12560
12561
12562
12563
12564

12565
12566
12567
12568
12569
12570
12571
12658
12659
12660
12661
12662
12663
12664

12665
12666
12667
12668
12669
12670
12671
12672







-
+







#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
static int sqlite3Os2CurrentTime( double *prNow ){
SQLITE_PRIVATE int sqlite3Os2CurrentTime( double *prNow ){
  double now;
  USHORT second, minute, hour,
         day, month, year;
  DATETIME dt;
  DosGetDateTime( &dt );
  second = (USHORT)dt.seconds;
  minute = (USHORT)dt.minutes + dt.timezone;
12619
12620
12621
12622
12623
12624
12625
12626

12627
12628
12629
12630
12631
12632
12633
12720
12721
12722
12723
12724
12725
12726

12727
12728
12729
12730
12731
12732
12733
12734







-
+







** then return NULL.
**
** If called with allocateFlag<0, check to see if the thread specific
** data is allocated and is all zero.  If it is then deallocate it.
** Return a pointer to the thread specific data or NULL if it is
** unallocated or gets deallocated.
*/
static ThreadData *sqlite3Os2ThreadSpecificData( int allocateFlag ){
SQLITE_PRIVATE ThreadData *sqlite3Os2ThreadSpecificData( int allocateFlag ){
  static ThreadData **s_ppTsd = NULL;
  static const ThreadData zeroData = {0, 0, 0};
  ThreadData *pTsd;

  if( !s_ppTsd ){
    sqlite3OsEnterMutex();
    if( !s_ppTsd ){
12927
12928
12929
12930
12931
12932
12933
12934

12935
12936
12937
12938
12939
12940
12941
12942
12943
12944

12945
12946
12947
12948
12949
12950
12951
12952
12953
12954

12955
12956
12957
12958

12959
12960
12961
12962

12963
12964
12965
12966

12967
12968
12969
12970
12971

12972
12973
12974
12975
12976

12977
12978
12979
12980
12981
12982
12983
13028
13029
13030
13031
13032
13033
13034

13035
13036
13037
13038
13039
13040
13041
13042
13043
13044

13045
13046
13047
13048
13049
13050
13051
13052
13053
13054

13055
13056
13057
13058

13059
13060
13061
13062

13063
13064
13065
13066

13067
13068
13069
13070
13071

13072
13073
13074
13075
13076

13077
13078
13079
13080
13081
13082
13083
13084







-
+









-
+









-
+



-
+



-
+



-
+




-
+




-
+







** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n+8);
  assert(n>0);
  assert(sizeof(int)<=8);
  if( p ){
    *(int *)p = n;
    p += 8;
  }
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  char *p2 = ((char *)p - 8);
  assert(n>0);
  p2 = (char*)realloc(p2, n+8);
  if( p2 ){
    *(int *)p2 = n;
    p2 += 8;
  }
  return (void *)p2;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free((void *)((char *)p - 8));
}
static int sqlite3GenericAllocationSize(void *p){
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){
  return p ? *(int *)((char *)p - 8) : 0;
}
#else
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n);
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  assert(n>0);
  p = realloc(p, n);
  return p;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free(p);
}
/* Never actually used, but needed for the linker */
static int sqlite3GenericAllocationSize(void *p){ return 0; }
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){ return 0; }
#endif

/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
13646
13647
13648
13649
13650
13651
13652
13653

13654
13655
13656
13657
13658
13659
13660
13661
13662

13663
13664
13665
13666
13667
13668
13669
13747
13748
13749
13750
13751
13752
13753

13754
13755
13756
13757
13758
13759
13760
13761
13762

13763
13764
13765
13766
13767
13768
13769
13770







-
+








-
+







  /* On single-threaded builds, ownership transfer is a no-op */
# define transferOwnership(X) SQLITE_OK
#endif

/*
** Delete the named file
*/
static int sqlite3UnixDelete(const char *zFilename){
SQLITE_PRIVATE int sqlite3UnixDelete(const char *zFilename){
  SimulateIOError(return SQLITE_IOERR_DELETE);
  unlink(zFilename);
  return SQLITE_OK;
}

/*
** Return TRUE if the named file exists.
*/
static int sqlite3UnixFileExists(const char *zFilename){
SQLITE_PRIVATE int sqlite3UnixFileExists(const char *zFilename){
  return access(zFilename, 0)==0;
}

/* Forward declaration */
static int allocateUnixFile(
  int h,                    /* File descriptor of the open file */
  OsFile **pId,             /* Write the real file descriptor here */
13680
13681
13682
13683
13684
13685
13686
13687

13688
13689
13690
13691
13692
13693
13694
13781
13782
13783
13784
13785
13786
13787

13788
13789
13790
13791
13792
13793
13794
13795







-
+







** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** SQLITE_OK.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
static int sqlite3UnixOpenReadWrite(
SQLITE_PRIVATE int sqlite3UnixOpenReadWrite(
  const char *zFilename,
  OsFile **pId,
  int *pReadonly
){
  int h;
  
  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadWrite, zFilename, pId, pReadonly);
13723
13724
13725
13726
13727
13728
13729
13730

13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751

13752
13753
13754
13755
13756
13757
13758
13824
13825
13826
13827
13828
13829
13830

13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851

13852
13853
13854
13855
13856
13857
13858
13859







-
+




















-
+







** If delFlag is true, then make arrangements to automatically delete
** the file when it is closed.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
static int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
SQLITE_PRIVATE int sqlite3UnixOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
  int h;

  CRASH_TEST_OVERRIDE(sqlite3CrashOpenExclusive, zFilename, pId, delFlag);
  assert( 0==*pId );
  h = open(zFilename,
                O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY,
                delFlag ? 0600 : SQLITE_DEFAULT_FILE_PERMISSIONS);
  if( h<0 ){
    return SQLITE_CANTOPEN;
  }
  return allocateUnixFile(h, pId, zFilename, delFlag);
}

/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
static int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
SQLITE_PRIVATE int sqlite3UnixOpenReadOnly(const char *zFilename, OsFile **pId){
  int h;
  
  CRASH_TEST_OVERRIDE(sqlite3CrashOpenReadOnly, zFilename, pId, 0);
  assert( 0==*pId );
  h = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  if( h<0 ){
    return SQLITE_CANTOPEN;
13779
13780
13781
13782
13783
13784
13785

13786
13787
13788
13789
13790
13791


13792
13793



13794

13795
13796
13797
13798
13799
13800
13801
13802

13803
13804
13805
13806
13807
13808
13809
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891


13892
13893
13894
13895
13896
13897
13898

13899
13900
13901
13902
13903
13904
13905
13906

13907
13908
13909
13910
13911
13912
13913
13914







+




-
-
+
+


+
+
+
-
+







-
+







** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id unchanged.
*/
static int unixOpenDirectory(
  OsFile *id,
  const char *zDirname
){
  int h;
  unixFile *pFile = (unixFile*)id;
  assert( pFile!=0 );
  SET_THREADID(pFile);
  assert( pFile->dirfd<0 );
  pFile->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0);
  if( pFile->dirfd<0 ){
  pFile->dirfd = h = open(zDirname, O_RDONLY|O_BINARY, 0);
  if( h<0 ){
    return SQLITE_CANTOPEN; 
  }
#ifdef FD_CLOEXEC
  fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
#endif
  OSTRACE3("OPENDIR %-3d %s\n", pFile->dirfd, zDirname);
  OSTRACE3("OPENDIR %-3d %s\n", h, zDirname);
  return SQLITE_OK;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at least SQLITE_TEMPNAME_SIZE characters.
*/
static int sqlite3UnixTempFileName(char *zBuf){
SQLITE_PRIVATE int sqlite3UnixTempFileName(char *zBuf){
  static const char *azDirs[] = {
     0,
     "/var/tmp",
     "/usr/tmp",
     "/tmp",
     ".",
  };
13835
13836
13837
13838
13839
13840
13841
13842

13843
13844
13845
13846
13847
13848
13849
13940
13941
13942
13943
13944
13945
13946

13947
13948
13949
13950
13951
13952
13953
13954







-
+







  return SQLITE_OK; 
}

/*
** Check that a given pathname is a directory and is writable 
**
*/
static int sqlite3UnixIsDirWritable(char *zBuf){
SQLITE_PRIVATE int sqlite3UnixIsDirWritable(char *zBuf){
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
  struct stat buf;
  if( zBuf==0 ) return 0;
  if( zBuf[0]==0 ) return 0;
  if( stat(zBuf, &buf) ) return 0;
  if( !S_ISDIR(buf.st_mode) ) return 0;
  if( access(zBuf, 07) ) return 0;
14104
14105
14106
14107
14108
14109
14110
14111

14112
14113
14114
14115
14116
14117
14118
14209
14210
14211
14212
14213
14214
14215

14216
14217
14218
14219
14220
14221
14222
14223







-
+







** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
**
** This is used to make sure the master journal file has truely been deleted
** before making changes to individual journals on a multi-database commit.
** The F_FULLFSYNC option is not needed here.
*/
static int sqlite3UnixSyncDirectory(const char *zDirname){
SQLITE_PRIVATE int sqlite3UnixSyncDirectory(const char *zDirname){
#ifdef SQLITE_DISABLE_DIRSYNC
  return SQLITE_OK;
#else
  int fd;
  int r;
  fd = open(zDirname, O_RDONLY|O_BINARY, 0);
  OSTRACE3("DIRSYNC %-3d (%s)\n", fd, zDirname);
14132
14133
14134
14135
14136
14137
14138
14139

14140
14141
14142
14143
14144
14145
14146
14237
14238
14239
14240
14241
14242
14243

14244
14245
14246
14247
14248
14249
14250
14251







-
+








/*
** Truncate an open file to a specified size
*/
static int unixTruncate(OsFile *id, i64 nByte){
  int rc;
  assert( id );
  rc = ftruncate(((unixFile*)id)->h, nByte);
  rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
  SimulateIOError( rc=1 );
  if( rc ){
    return SQLITE_IOERR_TRUNCATE;
  }else{
    return SQLITE_OK;
  }
}
15129
15130
15131
15132
15133
15134
15135
15136

15137
15138
15139
15140
15141
15142
15143
15234
15235
15236
15237
15238
15239
15240

15241
15242
15243
15244
15245
15246
15247
15248







-
+








/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
static char *sqlite3UnixFullPathname(const char *zRelative){
SQLITE_PRIVATE char *sqlite3UnixFullPathname(const char *zRelative){
  char *zFull = 0;
  if( zRelative[0]=='/' ){
    sqlite3SetString(&zFull, zRelative, (char*)0);
  }else{
    char *zBuf = sqliteMalloc(5000);
    if( zBuf==0 ){
      return 0;
15438
15439
15440
15441
15442
15443
15444



15445
15446
15447
15448
15449
15450
15451
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559







+
+
+







  const char *zFilename, /* Name of the file being opened */
  int delFlag            /* If true, delete the file on or before closing */
){
  unixFile *pNew;
  unixFile f;
  int rc;

#ifdef FD_CLOEXEC
  fcntl(h, F_SETFD, fcntl(h, F_GETFD, 0) | FD_CLOEXEC);
#endif
  memset(&f, 0, sizeof(f));
  sqlite3OsEnterMutex();
  rc = findLockInfo(h, &f.pLock, &f.pOpen);
  sqlite3OsLeaveMutex();
  if( delFlag ){
    unlink(zFilename);
  }
15485
15486
15487
15488
15489
15490
15491
15492

15493
15494
15495

15496
15497
15498

15499
15500
15501
15502
15503
15504
15505
15506
15507
15508

15509
15510
15511
15512
15513
15514
15515
15593
15594
15595
15596
15597
15598
15599

15600
15601
15602

15603
15604
15605

15606
15607
15608
15609
15610
15611
15612
15613
15614
15615

15616
15617
15618
15619
15620
15621
15622
15623







-
+


-
+


-
+









-
+








#ifndef SQLITE_OMIT_LOAD_EXTENSION
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
#include <dlfcn.h>
static void *sqlite3UnixDlopen(const char *zFilename){
SQLITE_PRIVATE void *sqlite3UnixDlopen(const char *zFilename){
  return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
}
static void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
SQLITE_PRIVATE void *sqlite3UnixDlsym(void *pHandle, const char *zSymbol){
  return dlsym(pHandle, zSymbol);
}
static int sqlite3UnixDlclose(void *pHandle){
SQLITE_PRIVATE int sqlite3UnixDlclose(void *pHandle){
  return dlclose(pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */

/*
** Get information to seed the random number generator.  The seed
** is written into the buffer zBuf[256].  The calling function must
** supply a sufficiently large buffer.
*/
static int sqlite3UnixRandomSeed(char *zBuf){
SQLITE_PRIVATE int sqlite3UnixRandomSeed(char *zBuf){
  /* We have to initialize zBuf to prevent valgrind from reporting
  ** errors.  The reports issued by valgrind are incorrect - we would
  ** prefer that the randomness be increased by making use of the
  ** uninitialized space in zBuf - but valgrind errors tend to worry
  ** some users.  Rather than argue, it seems easier just to initialize
  ** the whole array and silence valgrind, even if that means less randomness
  ** in the random seed.
15538
15539
15540
15541
15542
15543
15544
15545

15546
15547
15548
15549
15550
15551
15552
15646
15647
15648
15649
15650
15651
15652

15653
15654
15655
15656
15657
15658
15659
15660







-
+







  return SQLITE_OK;
}

/*
** Sleep for a little while.  Return the amount of time slept.
** The argument is the number of milliseconds we want to sleep.
*/
static int sqlite3UnixSleep(int ms){
SQLITE_PRIVATE int sqlite3UnixSleep(int ms){
#if defined(HAVE_USLEEP) && HAVE_USLEEP
  usleep(ms*1000);
  return ms;
#else
  sleep((ms+999)/1000);
  return 1000*((ms+999)/1000);
#endif
15597
15598
15599
15600
15601
15602
15603
15604

15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622

15623
15624
15625
15626
15627
15628
15629
15705
15706
15707
15708
15709
15710
15711

15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729

15730
15731
15732
15733
15734
15735
15736
15737







-
+

















-
+







** executed code that is surrounded by EnterMutex() and LeaveMutex().
**
** SQLite uses only a single Mutex.  There is not much critical
** code and what little there is executes quickly and without blocking.
**
** As of version 3.3.2, this mutex must be recursive.
*/
static void sqlite3UnixEnterMutex(){
SQLITE_PRIVATE void sqlite3UnixEnterMutex(){
#ifdef SQLITE_UNIX_THREADS
  pthread_mutex_lock(&mutexAux);
  if( !mutexOwnerValid || !pthread_equal(mutexOwner, pthread_self()) ){
    pthread_mutex_unlock(&mutexAux);
    pthread_mutex_lock(&mutexMain);
    assert( inMutex==0 );
    assert( !mutexOwnerValid );
    pthread_mutex_lock(&mutexAux);
    mutexOwner = pthread_self();
    mutexOwnerValid = 1;
  }
  inMutex++;
  pthread_mutex_unlock(&mutexAux);
#else
  inMutex++;
#endif
}
static void sqlite3UnixLeaveMutex(){
SQLITE_PRIVATE void sqlite3UnixLeaveMutex(){
  assert( inMutex>0 );
#ifdef SQLITE_UNIX_THREADS
  pthread_mutex_lock(&mutexAux);
  inMutex--;
  assert( pthread_equal(mutexOwner, pthread_self()) );
  if( inMutex==0 ){
    assert( mutexOwnerValid );
15639
15640
15641
15642
15643
15644
15645
15646

15647
15648
15649
15650
15651
15652
15653
15747
15748
15749
15750
15751
15752
15753

15754
15755
15756
15757
15758
15759
15760
15761







-
+







/*
** Return TRUE if the mutex is currently held.
**
** If the thisThrd parameter is true, return true only if the
** calling thread holds the mutex.  If the parameter is false, return
** true if any thread holds the mutex.
*/
static int sqlite3UnixInMutex(int thisThrd){
SQLITE_PRIVATE int sqlite3UnixInMutex(int thisThrd){
#ifdef SQLITE_UNIX_THREADS
  int rc;
  pthread_mutex_lock(&mutexAux);
  rc = inMutex>0 && (thisThrd==0 || pthread_equal(mutexOwner,pthread_self()));
  pthread_mutex_unlock(&mutexAux);
  return rc;
#else
15685
15686
15687
15688
15689
15690
15691
15692

15693
15694
15695
15696
15697
15698
15699
15793
15794
15795
15796
15797
15798
15799

15800
15801
15802
15803
15804
15805
15806
15807







-
+







** then return NULL.
**
** If called with allocateFlag<0, check to see if the thread specific
** data is allocated and is all zero.  If it is then deallocate it.
** Return a pointer to the thread specific data or NULL if it is
** unallocated or gets deallocated.
*/
static ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
SQLITE_PRIVATE ThreadData *sqlite3UnixThreadSpecificData(int allocateFlag){
  static const ThreadData zeroData = {0};  /* Initializer to silence warnings
                                           ** from broken compilers */
#ifdef SQLITE_UNIX_THREADS
  static pthread_key_t key;
  static int keyInit = 0;
  ThreadData *pTsd;

15768
15769
15770
15771
15772
15773
15774
15775

15776
15777
15778
15779
15780
15781
15782
15876
15877
15878
15879
15880
15881
15882

15883
15884
15885
15886
15887
15888
15889
15890







-
+







#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
static int sqlite3UnixCurrentTime(double *prNow){
SQLITE_PRIVATE int sqlite3UnixCurrentTime(double *prNow){
#ifdef NO_GETTOD
  time_t t;
  time(&t);
  *prNow = t/86400.0 + 2440587.5;
#else
  struct timeval sNow;
  gettimeofday(&sNow, 0);
15971
15972
15973
15974
15975
15976
15977
15978

15979
15980
15981
15982
15983
15984
15985
15986
15987
15988

15989
15990
15991
15992
15993
15994
15995
15996
15997
15998

15999
16000
16001
16002

16003
16004
16005
16006

16007
16008
16009
16010

16011
16012
16013
16014
16015

16016
16017
16018
16019
16020

16021
16022
16023
16024
16025
16026
16027
16079
16080
16081
16082
16083
16084
16085

16086
16087
16088
16089
16090
16091
16092
16093
16094
16095

16096
16097
16098
16099
16100
16101
16102
16103
16104
16105

16106
16107
16108
16109

16110
16111
16112
16113

16114
16115
16116
16117

16118
16119
16120
16121
16122

16123
16124
16125
16126
16127

16128
16129
16130
16131
16132
16133
16134
16135







-
+









-
+









-
+



-
+



-
+



-
+




-
+




-
+







** enabled. This version allocates an extra 8-bytes at the beginning of each
** block and stores the size of the allocation there.
**
** If neither memory-management or debugging is enabled, the second
** set of implementations is used instead.
*/
#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || defined (SQLITE_MEMDEBUG)
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n+8);
  assert(n>0);
  assert(sizeof(int)<=8);
  if( p ){
    *(int *)p = n;
    p += 8;
  }
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  char *p2 = ((char *)p - 8);
  assert(n>0);
  p2 = (char*)realloc(p2, n+8);
  if( p2 ){
    *(int *)p2 = n;
    p2 += 8;
  }
  return (void *)p2;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free((void *)((char *)p - 8));
}
static int sqlite3GenericAllocationSize(void *p){
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){
  return p ? *(int *)((char *)p - 8) : 0;
}
#else
static void *sqlite3GenericMalloc(int n){
SQLITE_PRIVATE void *sqlite3GenericMalloc(int n){
  char *p = (char *)malloc(n);
  return (void *)p;
}
static void *sqlite3GenericRealloc(void *p, int n){
SQLITE_PRIVATE void *sqlite3GenericRealloc(void *p, int n){
  assert(n>0);
  p = realloc(p, n);
  return p;
}
static void sqlite3GenericFree(void *p){
SQLITE_PRIVATE void sqlite3GenericFree(void *p){
  assert(p);
  free(p);
}
/* Never actually used, but needed for the linker */
static int sqlite3GenericAllocationSize(void *p){ return 0; }
SQLITE_PRIVATE int sqlite3GenericAllocationSize(void *p){ return 0; }
#endif

/*
** The default size of a disk sector
*/
#ifndef PAGER_SECTOR_SIZE
# define PAGER_SECTOR_SIZE 512
16586
16587
16588
16589
16590
16591
16592
16593

16594
16595
16596
16597
16598
16599
16600
16694
16695
16696
16697
16698
16699
16700

16701
16702
16703
16704
16705
16706
16707
16708







-
+







** whatever it is it does.  While this other process is holding the
** file open, we will be unable to delete it.  To work around this
** problem, we delay 100 milliseconds and try to delete again.  Up
** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
** up and returning an error.
*/
#define MX_DELETION_ATTEMPTS 3
static int sqlite3WinDelete(const char *zFilename){
SQLITE_PRIVATE int sqlite3WinDelete(const char *zFilename){
  int cnt = 0;
  int rc;
  void *zConverted = convertUtf8Filename(zFilename);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
  SimulateIOError(return SQLITE_IOERR_DELETE);
16617
16618
16619
16620
16621
16622
16623
16624

16625
16626
16627
16628
16629
16630
16631
16725
16726
16727
16728
16729
16730
16731

16732
16733
16734
16735
16736
16737
16738
16739







-
+







  OSTRACE2("DELETE \"%s\"\n", zFilename);
  return rc!=0 ? SQLITE_OK : SQLITE_IOERR;
}

/*
** Return TRUE if the named file exists.
*/
static int sqlite3WinFileExists(const char *zFilename){
SQLITE_PRIVATE int sqlite3WinFileExists(const char *zFilename){
  int exists = 0;
  void *zConverted = convertUtf8Filename(zFilename);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
  if( isNT() ){
    exists = GetFileAttributesW((WCHAR*)zConverted) != 0xffffffff;
16652
16653
16654
16655
16656
16657
16658
16659

16660
16661
16662
16663
16664
16665
16666
16760
16761
16762
16763
16764
16765
16766

16767
16768
16769
16770
16771
16772
16773
16774







-
+







** and *pReadonly is set to 0 if the file was opened for reading and
** writing or 1 if the file was opened read-only.  The function returns
** SQLITE_OK.
**
** On failure, the function returns SQLITE_CANTOPEN and leaves
** *id and *pReadonly unchanged.
*/
static int sqlite3WinOpenReadWrite(
SQLITE_PRIVATE int sqlite3WinOpenReadWrite(
  const char *zFilename,
  OsFile **pId,
  int *pReadonly
){
  winFile f;
  HANDLE h;
  void *zConverted = convertUtf8Filename(zFilename);
16761
16762
16763
16764
16765
16766
16767
16768

16769
16770
16771
16772
16773
16774
16775
16869
16870
16871
16872
16873
16874
16875

16876
16877
16878
16879
16880
16881
16882
16883







-
+







**
** Sometimes if we have just deleted a prior journal file, windows
** will fail to open a new one because there is a "pending delete".
** To work around this bug, we pause for 100 milliseconds and attempt
** a second open after the first one fails.  The whole operation only
** fails if both open attempts are unsuccessful.
*/
static int sqlite3WinOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
SQLITE_PRIVATE int sqlite3WinOpenExclusive(const char *zFilename, OsFile **pId, int delFlag){
  winFile f;
  HANDLE h;
  DWORD fileflags;
  void *zConverted = convertUtf8Filename(zFilename);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
16828
16829
16830
16831
16832
16833
16834
16835

16836
16837
16838
16839
16840
16841
16842
16936
16937
16938
16939
16940
16941
16942

16943
16944
16945
16946
16947
16948
16949
16950







-
+







/*
** Attempt to open a new file for read-only access.
**
** On success, write the file handle into *id and return SQLITE_OK.
**
** On failure, return SQLITE_CANTOPEN.
*/
static int sqlite3WinOpenReadOnly(const char *zFilename, OsFile **pId){
SQLITE_PRIVATE int sqlite3WinOpenReadOnly(const char *zFilename, OsFile **pId){
  winFile f;
  HANDLE h;
  void *zConverted = convertUtf8Filename(zFilename);
  if( zConverted==0 ){
    return SQLITE_NOMEM;
  }
  assert( *pId==0 );
16899
16900
16901
16902
16903
16904
16905
16906

16907
16908
16909
16910
16911
16912
16913
17007
17008
17009
17010
17011
17012
17013

17014
17015
17016
17017
17018
17019
17020
17021







-
+







  return SQLITE_OK;
}

/*
** Create a temporary file name in zBuf.  zBuf must be big enough to
** hold at least SQLITE_TEMPNAME_SIZE characters.
*/
static int sqlite3WinTempFileName(char *zBuf){
SQLITE_PRIVATE int sqlite3WinTempFileName(char *zBuf){
  static char zChars[] =
    "abcdefghijklmnopqrstuvwxyz"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "0123456789";
  int i, j;
  char zTempPath[SQLITE_TEMPNAME_SIZE];
  if( sqlite3_temp_directory ){
17068
17069
17070
17071
17072
17073
17074
17075

17076
17077
17078
17079
17080
17081
17082
17176
17177
17178
17179
17180
17181
17182

17183
17184
17185
17186
17187
17188
17189
17190







-
+







  }
}

/*
** Sync the directory zDirname. This is a no-op on operating systems other
** than UNIX.
*/
static int sqlite3WinSyncDirectory(const char *zDirname){
SQLITE_PRIVATE int sqlite3WinSyncDirectory(const char *zDirname){
  SimulateIOError(return SQLITE_IOERR_READ);
  return SQLITE_OK;
}

/*
** Truncate an open file to a specified size
*/
17145
17146
17147
17148
17149
17150
17151
17152

17153
17154
17155
17156
17157
17158
17159
17253
17254
17255
17256
17257
17258
17259

17260
17261
17262
17263
17264
17265
17266
17267







-
+







}

#ifndef SQLITE_OMIT_PAGER_PRAGMAS
/*
** Check that a given pathname is a directory and is writable 
**
*/
static int sqlite3WinIsDirWritable(char *zDirname){
SQLITE_PRIVATE int sqlite3WinIsDirWritable(char *zDirname){
  int fileAttr;
  void *zConverted;
  if( zDirname==0 ) return 0;
  if( !isNT() && strlen(zDirname)>MAX_PATH ) return 0;

  zConverted = convertUtf8Filename(zDirname);
  if( zConverted==0 ){
17376
17377
17378
17379
17380
17381
17382
17383

17384
17385
17386
17387
17388
17389
17390
17484
17485
17486
17487
17488
17489
17490

17491
17492
17493
17494
17495
17496
17497
17498







-
+








/*
** Turn a relative pathname into a full pathname.  Return a pointer
** to the full pathname stored in space obtained from sqliteMalloc().
** The calling function is responsible for freeing this space once it
** is no longer needed.
*/
static char *sqlite3WinFullPathname(const char *zRelative){
SQLITE_PRIVATE char *sqlite3WinFullPathname(const char *zRelative){
  char *zFull;
#if defined(__CYGWIN__)
  int nByte;
  nByte = strlen(zRelative) + MAX_PATH + 1001;
  zFull = sqliteMalloc( nByte );
  if( zFull==0 ) return 0;
  if( cygwin_conv_to_full_win32_path(zRelative, zFull) ) return 0;
17516
17517
17518
17519
17520
17521
17522
17523

17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542

17543
17544
17545
17546
17547
17548
17549
17550
17551
17552

17553
17554
17555
17556
17557
17558
17559
17560
17561
17562

17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583

17584
17585
17586
17587
17588
17589
17590
17624
17625
17626
17627
17628
17629
17630

17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649

17650
17651
17652
17653
17654
17655
17656
17657
17658
17659

17660
17661
17662
17663
17664
17665
17666
17667
17668
17669

17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690

17691
17692
17693
17694
17695
17696
17697
17698







-
+


















-
+









-
+









-
+




















-
+







****************************************************************************/

#if !defined(SQLITE_OMIT_LOAD_EXTENSION)
/*
** Interfaces for opening a shared library, finding entry points
** within the shared library, and closing the shared library.
*/
static void *sqlite3WinDlopen(const char *zFilename){
SQLITE_PRIVATE void *sqlite3WinDlopen(const char *zFilename){
  HANDLE h;
  void *zConverted = convertUtf8Filename(zFilename);
  if( zConverted==0 ){
    return 0;
  }
  if( isNT() ){
    h = LoadLibraryW((WCHAR*)zConverted);
  }else{
#if OS_WINCE
    return 0;
#else
    h = LoadLibraryA((char*)zConverted);
#endif
  }
  sqliteFree(zConverted);
  return (void*)h;
  
}
static void *sqlite3WinDlsym(void *pHandle, const char *zSymbol){
SQLITE_PRIVATE void *sqlite3WinDlsym(void *pHandle, const char *zSymbol){
#if OS_WINCE
  /* The GetProcAddressA() routine is only available on wince. */
  return GetProcAddressA((HANDLE)pHandle, zSymbol);
#else
  /* All other windows platforms expect GetProcAddress() to take
  ** an Ansi string regardless of the _UNICODE setting */
  return GetProcAddress((HANDLE)pHandle, zSymbol);
#endif
}
static int sqlite3WinDlclose(void *pHandle){
SQLITE_PRIVATE int sqlite3WinDlclose(void *pHandle){
  return FreeLibrary((HANDLE)pHandle);
}
#endif /* !SQLITE_OMIT_LOAD_EXTENSION */

/*
** Get information to seed the random number generator.  The seed
** is written into the buffer zBuf[256].  The calling function must
** supply a sufficiently large buffer.
*/
static int sqlite3WinRandomSeed(char *zBuf){
SQLITE_PRIVATE int sqlite3WinRandomSeed(char *zBuf){
  /* We have to initialize zBuf to prevent valgrind from reporting
  ** errors.  The reports issued by valgrind are incorrect - we would
  ** prefer that the randomness be increased by making use of the
  ** uninitialized space in zBuf - but valgrind errors tend to worry
  ** some users.  Rather than argue, it seems easier just to initialize
  ** the whole array and silence valgrind, even if that means less randomness
  ** in the random seed.
  **
  ** When testing, initializing zBuf[] to zero is all we do.  That means
  ** that we always use the same random number sequence.* This makes the
  ** tests repeatable.
  */
  memset(zBuf, 0, 256);
  GetSystemTime((LPSYSTEMTIME)zBuf);
  return SQLITE_OK;
}

/*
** Sleep for a little while.  Return the amount of time slept.
*/
static int sqlite3WinSleep(int ms){
SQLITE_PRIVATE int sqlite3WinSleep(int ms){
  Sleep(ms);
  return ms;
}

/*
** Static variables used for thread synchronization
*/
17601
17602
17603
17604
17605
17606
17607
17608

17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625

17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641

17642
17643
17644
17645
17646
17647
17648
17709
17710
17711
17712
17713
17714
17715

17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732

17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748

17749
17750
17751
17752
17753
17754
17755
17756







-
+
















-
+















-
+







**
** SQLite uses only a single Mutex.  There is not much critical
** code and what little there is executes quickly and without blocking.
**
** Version 3.3.1 and earlier used a simple mutex.  Beginning with
** version 3.3.2, a recursive mutex is required.
*/
static void sqlite3WinEnterMutex(){
SQLITE_PRIVATE void sqlite3WinEnterMutex(){
#ifdef SQLITE_W32_THREADS
  static int isInit = 0;
  while( !isInit ){
    static long lock = 0;
    if( InterlockedIncrement(&lock)==1 ){
      InitializeCriticalSection(&cs);
      isInit = 1;
    }else{
      Sleep(1);
    }
  }
  EnterCriticalSection(&cs);
  mutexOwner = GetCurrentThreadId();
#endif
  inMutex++;
}
static void sqlite3WinLeaveMutex(){
SQLITE_PRIVATE void sqlite3WinLeaveMutex(){
  assert( inMutex );
  inMutex--;
#ifdef SQLITE_W32_THREADS
  assert( mutexOwner==GetCurrentThreadId() );
  LeaveCriticalSection(&cs);
#endif
}

/*
** Return TRUE if the mutex is currently held.
**
** If the thisThreadOnly parameter is true, return true if and only if the
** calling thread holds the mutex.  If the parameter is false, return
** true if any thread holds the mutex.
*/
static int sqlite3WinInMutex(int thisThreadOnly){
SQLITE_PRIVATE int sqlite3WinInMutex(int thisThreadOnly){
#ifdef SQLITE_W32_THREADS
  return inMutex>0 && (thisThreadOnly==0 || mutexOwner==GetCurrentThreadId());
#else
  return inMutex>0;
#endif
}

17656
17657
17658
17659
17660
17661
17662
17663

17664
17665
17666
17667
17668
17669
17670
17764
17765
17766
17767
17768
17769
17770

17771
17772
17773
17774
17775
17776
17777
17778







-
+







#endif

/*
** Find the current time (in Universal Coordinated Time).  Write the
** current time and date as a Julian Day number into *prNow and
** return 0.  Return 1 if the time and date cannot be found.
*/
static int sqlite3WinCurrentTime(double *prNow){
SQLITE_PRIVATE int sqlite3WinCurrentTime(double *prNow){
  FILETIME ft;
  /* FILETIME structure is a 64-bit value representing the number of 
     100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
  */
  double now;
#if OS_WINCE
  SYSTEMTIME time;
17709
17710
17711
17712
17713
17714
17715
17716

17717
17718
17719
17720
17721
17722
17723
17817
17818
17819
17820
17821
17822
17823

17824
17825
17826
17827
17828
17829
17830
17831







-
+







** then return NULL.
**
** If called with allocateFlag<0, check to see if the thread specific
** data is allocated and is all zero.  If it is then deallocate it.
** Return a pointer to the thread specific data or NULL if it is
** unallocated or gets deallocated.
*/
static ThreadData *sqlite3WinThreadSpecificData(int allocateFlag){
SQLITE_PRIVATE ThreadData *sqlite3WinThreadSpecificData(int allocateFlag){
  static int key;
  static int keyInit = 0;
  static const ThreadData zeroData = {0};
  ThreadData *pTsd;

  if( !keyInit ){
    sqlite3OsEnterMutex();
17770
17771
17772
17773
17774
17775
17776
17777

17778
17779
17780
17781
17782
17783
17784
17878
17879
17880
17881
17882
17883
17884

17885
17886
17887
17888
17889
17890
17891
17892







-
+







** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef SQLITE_OMIT_DISKIO

/*
** Macros for troubleshooting.  Normally turned off
*/
#if 0
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18404
18405
18406
18407
18408
18409
18410











18411
18412
18413
18414
18415
18416
18417







-
-
-
-
-
-
-
-
-
-
-







** on success or an error code is something goes wrong.
*/
static int write32bits(OsFile *fd, u32 val){
  char ac[4];
  put32bits(ac, val);
  return sqlite3OsWrite(fd, ac, 4);
}

/*
** Read a 32-bit integer at offset 'offset' from the page identified by
** page header 'p'.
*/
static u32 retrieve32bits(PgHdr *p, int offset){
  unsigned char *ac;
  ac = &((unsigned char*)PGHDR_TO_DATA(p))[offset];
  return sqlite3Get4byte(ac);
}


/*
** This function should be called when an error occurs within the pager
** code. The first argument is a pointer to the pager structure, the
** second the error-code about to be returned by a pager API function. 
** The value returned is a copy of the second argument to this function. 
**
19381
19382
19383
19384
19385
19386
19387
19388

19389
19390
19391
19392
19393
19394
19395
19478
19479
19480
19481
19482
19483
19484

19485
19486
19487
19488
19489
19490
19491
19492







-
+







  }
  return rc;
}

/*
** Change the maximum number of in-memory pages that are allowed.
*/
static void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  if( mxPage>10 ){
    pPager->mxPage = mxPage;
  }else{
    pPager->mxPage = 10;
  }
}

19416
19417
19418
19419
19420
19421
19422
19423

19424
19425
19426
19427
19428
19429
19430
19513
19514
19515
19516
19517
19518
19519

19520
19521
19522
19523
19524
19525
19526
19527







-
+







**              assurance that the journal will not be corrupted to the
**              point of causing damage to the database during rollback.
**
** Numeric values associated with these states are OFF==1, NORMAL=2,
** and FULL=3.
*/
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
static void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int full_fsync){
  pPager->noSync =  level==1 || pPager->tempFile;
  pPager->fullSync = level==3 && !pPager->tempFile;
  pPager->full_fsync = full_fsync;
  if( pPager->noSync ) pPager->needSync = 0;
}
#endif

19473
19474
19475
19476
19477
19478
19479
19480

19481
19482
19483
19484
19485
19486
19487
19570
19571
19572
19573
19574
19575
19576

19577
19578
19579
19580
19581
19582
19583
19584







-
+







** and used as the file to be cached.  The file will be deleted
** automatically when it is closed.
**
** If zFilename is ":memory:" then all information is held in cache.
** It is never written to disk.  This can be used to implement an
** in-memory database.
*/
static int sqlite3PagerOpen(
SQLITE_PRIVATE int sqlite3PagerOpen(
  Pager **ppPager,         /* Return the Pager structure here */
  const char *zFilename,   /* Name of the database file to open */
  int nExtra,              /* Extra bytes append to each in-memory page */
  int flags                /* flags controlling this file */
){
  Pager *pPager = 0;
  char *zFullPathname = 0;
19624
19625
19626
19627
19628
19629
19630
19631

19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643

19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654

19655
19656
19657
19658
19659
19660
19661
19662
19663

19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680

19681
19682
19683
19684
19685
19686
19687
19721
19722
19723
19724
19725
19726
19727

19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739

19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750

19751
19752
19753
19754
19755
19756
19757
19758
19759

19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776

19777
19778
19779
19780
19781
19782
19783
19784







-
+











-
+










-
+








-
+
















-
+







#endif
  return SQLITE_OK;
}

/*
** Set the busy handler function.
*/
static void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *pPager, BusyHandler *pBusyHandler){
  pPager->pBusyHandler = pBusyHandler;
}

/*
** Set the destructor for this pager.  If not NULL, the destructor is called
** when the reference count on each page reaches zero.  The destructor can
** be used to clean up information in the extra segment appended to each page.
**
** The destructor is not called as a result sqlite3PagerClose().  
** Destructors are only called by sqlite3PagerUnref().
*/
static void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
SQLITE_PRIVATE void sqlite3PagerSetDestructor(Pager *pPager, void (*xDesc)(DbPage*,int)){
  pPager->xDestructor = xDesc;
}

/*
** Set the reinitializer for this pager.  If not NULL, the reinitializer
** is called when the content of a page in cache is restored to its original
** value as a result of a rollback.  The callback gives higher-level code
** an opportunity to restore the EXTRA section to agree with the restored
** page data.
*/
static void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*,int)){
  pPager->xReiniter = xReinit;
}

/*
** Set the page size.  Return the new size.  If the suggest new page
** size is inappropriate, then an alternative page size is selected
** and returned.
*/
static int sqlite3PagerSetPagesize(Pager *pPager, int pageSize){
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, int pageSize){
  assert( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE );
  if( !pPager->memDb && pPager->nRef==0 ){
    pager_reset(pPager);
    pPager->pageSize = pageSize;
    pPager->pTmpSpace = sqlite3ReallocOrFree(pPager->pTmpSpace, pageSize);
  }
  return pPager->pageSize;
}

/*
** Attempt to set the maximum database page count if mxPage is positive. 
** Make no changes if mxPage is zero or negative.  And never reduce the
** maximum page count below the current size of the database.
**
** Regardless of mxPage, return the current maximum page count.
*/
static int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  if( mxPage>0 ){
    pPager->mxPgno = mxPage;
  }
  sqlite3PagerPagecount(pPager);
  return pPager->mxPgno;
}

19715
19716
19717
19718
19719
19720
19721
19722

19723
19724
19725
19726
19727
19728
19729
19812
19813
19814
19815
19816
19817
19818

19819
19820
19821
19822
19823
19824
19825
19826







-
+







**
** No error checking is done. The rational for this is that this function 
** may be called even if the file does not exist or contain a header. In 
** these cases sqlite3OsRead() will return an error, to which the correct 
** response is to zero the memory at pDest and continue.  A real IO error 
** will presumably recur and be picked up later (Todo: Think about this).
*/
static int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  int rc = SQLITE_OK;
  memset(pDest, 0, N);
  if( MEMDB==0 ){
    disable_simulated_io_errors();
    sqlite3OsSeek(pPager->fd, 0);
    enable_simulated_io_errors();
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
19740
19741
19742
19743
19744
19745
19746
19747

19748
19749
19750
19751
19752
19753
19754
19837
19838
19839
19840
19841
19842
19843

19844
19845
19846
19847
19848
19849
19850
19851







-
+







** pPager. 
**
** If the PENDING_BYTE lies on the page directly after the end of the
** file, then consider this page part of the file too. For example, if
** PENDING_BYTE is byte 4096 (the first byte of page 5) and the size of the
** file is 4096 bytes, 5 is returned instead of 4.
*/
static int sqlite3PagerPagecount(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager){
  i64 n;
  int rc;
  assert( pPager!=0 );
  if( pPager->errCode ){
    return 0;
  }
  if( pPager->dbSize>=0 ){
19925
19926
19927
19928
19929
19930
19931
19932

19933
19934
19935
19936
19937
19938
19939
20022
20023
20024
20025
20026
20027
20028

20029
20030
20031
20032
20033
20034
20035
20036







-
+







  }
  return rc;
}

/*
** Truncate the file to the number of pages specified.
*/
static int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
SQLITE_PRIVATE int sqlite3PagerTruncate(Pager *pPager, Pgno nPage){
  int rc;
  assert( pPager->state>=PAGER_SHARED || MEMDB );
  sqlite3PagerPagecount(pPager);
  if( pPager->errCode ){
    rc = pPager->errCode;
    return rc;
  }
19970
19971
19972
19973
19974
19975
19976
19977

19978
19979
19980
19981
19982
19983
19984
20067
20068
20069
20070
20071
20072
20073

20074
20075
20076
20077
20078
20079
20080
20081







-
+







** result in a coredump.
**
** This function always succeeds. If a transaction is active an attempt
** is made to roll it back. If an error occurs during the rollback 
** a hot journal may be left in the filesystem but no error is returned
** to the caller.
*/
static int sqlite3PagerClose(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  /* A malloc() cannot fail in sqlite3ThreadData() as one or more calls to 
  ** malloc() must have already been made by this thread before it gets
  ** to this point. This means the ThreadData must have been allocated already
  ** so that ThreadData.nAlloc can be set.
  */
  ThreadData *pTsd = sqlite3ThreadData();
20027
20028
20029
20030
20031
20032
20033
20034

20035
20036
20037
20038
20039
20040
20041
20124
20125
20126
20127
20128
20129
20130

20131
20132
20133
20134
20135
20136
20137
20138







-
+







  return SQLITE_OK;
}

#if !defined(NDEBUG) || defined(SQLITE_TEST)
/*
** Return the page number for the given page data.
*/
static Pgno sqlite3PagerPagenumber(DbPage *p){
SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
  return p->pgno;
}
#endif

/*
** The page_ref() function increments the reference count for a page.
** If the page is currently on the freelist (the reference count is zero) then
20081
20082
20083
20084
20085
20086
20087
20088

20089
20090
20091
20092
20093
20094
20095
20178
20179
20180
20181
20182
20183
20184

20185
20186
20187
20188
20189
20190
20191
20192







-
+







# define page_ref(P)   ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
#endif

/*
** Increment the reference count for a page.  The input pointer is
** a reference to the page data.
*/
static int sqlite3PagerRef(DbPage *pPg){
SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
  page_ref(pPg);
  return SQLITE_OK;
}

/*
** Sync the journal.  In other words, make sure all the pages that have
** been written to the journal have actually reached the surface of the
20459
20460
20461
20462
20463
20464
20465
20466

20467
20468
20469
20470
20471
20472
20473
20556
20557
20558
20559
20560
20561
20562

20563
20564
20565
20566
20567
20568
20569
20570







-
+







**
** nReq is the number of bytes of memory required. Once this much has
** been released, the function returns. A negative value for nReq means
** free as much memory as possible. The return value is the total number 
** of bytes of memory released.
*/
#if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) && !defined(SQLITE_OMIT_DISKIO)
static int sqlite3PagerReleaseMemory(int nReq){
SQLITE_PRIVATE int sqlite3PagerReleaseMemory(int nReq){
  const ThreadData *pTsdro = sqlite3ThreadDataReadOnly();
  int nReleased = 0;
  int i;

  /* If the the global mutex is held, this subroutine becomes a
  ** o-op; zero bytes of memory are freed.  This is because
  ** some of the code invoked by this function may also
20840
20841
20842
20843
20844
20845
20846
20847

20848
20849
20850
20851
20852
20853
20854
20937
20938
20939
20940
20941
20942
20943

20944
20945
20946
20947
20948
20949
20950
20951







-
+







** of the page at this time, so do not do a disk read.  Just fill in the
** page content with zeros.  But mark the fact that we have not read the
** content by setting the PgHdr.needRead flag.  Later on, if 
** sqlite3PagerWrite() is called on this page or if this routine is
** called again with noContent==0, that means that the content is needed
** and the disk read should occur at that point.
*/
static int sqlite3PagerAcquire(
SQLITE_PRIVATE int sqlite3PagerAcquire(
  Pager *pPager,      /* The pager open on the database file */
  Pgno pgno,          /* Page number to fetch */
  DbPage **ppPage,    /* Write a pointer to the page here */
  int noContent       /* Do not bother reading content from disk if true */
){
  PgHdr *pPg;
  int rc;
20975
20976
20977
20978
20979
20980
20981
20982

20983
20984
20985
20986
20987
20988
20989
21072
21073
21074
21075
21076
21077
21078

21079
21080
21081
21082
21083
21084
21085
21086







-
+







**
** See also sqlite3PagerGet().  The difference between this routine
** and sqlite3PagerGet() is that _get() will go to the disk and read
** in the page if the page is not already in cache.  This routine
** returns NULL if the page is not in cache or if a disk I/O error 
** has ever happened.
*/
static DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  PgHdr *pPg;

  assert( pPager!=0 );
  assert( pgno!=0 );

  if( pPager->state==PAGER_UNLOCK ){
    assert( !pPager->pAll || pPager->exclusiveMode );
21002
21003
21004
21005
21006
21007
21008
21009

21010
21011
21012
21013
21014
21015
21016
21099
21100
21101
21102
21103
21104
21105

21106
21107
21108
21109
21110
21111
21112
21113







-
+







** Release a page.
**
** If the number of references to the page drop to zero, then the
** page is added to the LRU list.  When all references to all pages
** are released, a rollback occurs and the lock on the database is
** removed.
*/
static int sqlite3PagerUnref(DbPage *pPg){
SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){

  /* Decrement the reference count for this page
  */
  assert( pPg->nRef>0 );
  pPg->nRef--;
  REFINFO(pPg);

21137
21138
21139
21140
21141
21142
21143
21144

21145
21146
21147
21148
21149
21150
21151
21234
21235
21236
21237
21238
21239
21240

21241
21242
21243
21244
21245
21246
21247
21248







-
+







**
** If the database is already reserved for writing, this routine is a no-op.
**
** If exFlag is true, go ahead and get an EXCLUSIVE lock on the file
** immediately instead of waiting until we try to flush the cache.  The
** exFlag is ignored if a transaction is already active.
*/
static int sqlite3PagerBegin(DbPage *pPg, int exFlag){
SQLITE_PRIVATE int sqlite3PagerBegin(DbPage *pPg, int exFlag){
  Pager *pPager = pPg->pPager;
  int rc = SQLITE_OK;
  assert( pPg->nRef>0 );
  assert( pPager->state!=PAGER_UNLOCK );
  if( pPager->state==PAGER_SHARED ){
    assert( pPager->aInJournal==0 );
    if( MEMDB ){
21419
21420
21421
21422
21423
21424
21425
21426

21427
21428
21429
21430
21431
21432
21433
21516
21517
21518
21519
21520
21521
21522

21523
21524
21525
21526
21527
21528
21529
21530







-
+







** and write the page *pData to the journal.
**
** The difference between this function and pager_write() is that this
** function also deals with the special case where 2 or more pages
** fit on a single disk sector. In this case all co-resident pages
** must have been written to the journal file before returning.
*/
static int sqlite3PagerWrite(DbPage *pDbPage){
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  int rc = SQLITE_OK;

  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);

  if( !MEMDB && nPagePerSector>1 ){
21486
21487
21488
21489
21490
21491
21492
21493

21494
21495
21496
21497
21498
21499
21500
21501
21502
21503

21504
21505
21506
21507
21508
21509
21510
21583
21584
21585
21586
21587
21588
21589

21590
21591
21592
21593
21594
21595
21596
21597
21598
21599

21600
21601
21602
21603
21604
21605
21606
21607







-
+









-
+








/*
** Return TRUE if the page given in the argument was previously passed
** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
** to change the content of the page.
*/
#ifndef NDEBUG
static int sqlite3PagerIswriteable(DbPage *pPg){
SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  return pPg->dirty;
}
#endif

#ifndef SQLITE_OMIT_VACUUM
/*
** Replace the content of a single page with the information in the third
** argument.
*/
static int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
SQLITE_PRIVATE int sqlite3PagerOverwrite(Pager *pPager, Pgno pgno, void *pData){
  PgHdr *pPg;
  int rc;

  rc = sqlite3PagerGet(pPager, pgno, &pPg);
  if( rc==SQLITE_OK ){
    rc = sqlite3PagerWrite(pPg);
    if( rc==SQLITE_OK ){
21536
21537
21538
21539
21540
21541
21542
21543

21544
21545
21546
21547
21548
21549
21550
21633
21634
21635
21636
21637
21638
21639

21640
21641
21642
21643
21644
21645
21646
21647







-
+







** a transaction then removed from the freelist during a later part
** of the same transaction and reused for some other purpose.  When it
** is first added to the freelist, this routine is called.  When reused,
** the sqlite3PagerDontRollback() routine is called.  But because the
** page contains critical data, we still need to be sure it gets
** rolled back in spite of the sqlite3PagerDontRollback() call.
*/
static void sqlite3PagerDontWrite(DbPage *pDbPage){
SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *pDbPage){
  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;

  if( MEMDB ) return;
  pPg->alwaysRollback = 1;
  if( pPg->dirty && !pPager->stmtInUse ){
    assert( pPager->state>=PAGER_SHARED );
21575
21576
21577
21578
21579
21580
21581
21582

21583
21584
21585
21586
21587
21588
21589
21672
21673
21674
21675
21676
21677
21678

21679
21680
21681
21682
21683
21684
21685
21686







-
+







** rollback journal.
**
** If we have not yet actually read the content of this page (if
** the PgHdr.needRead flag is set) then this routine acts as a promise
** that we will never need to read the page content in the future.
** so the needRead flag can be cleared at this point.
*/
static void sqlite3PagerDontRollback(DbPage *pPg){
SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
  Pager *pPager = pPg->pPager;

  assert( pPager->state>=PAGER_RESERVED );
  if( pPager->journalOpen==0 ) return;
  if( pPg->alwaysRollback || pPager->alwaysRollback || MEMDB ) return;
  if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
    assert( pPager->aInJournal!=0 );
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629

21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21716
21717
21718
21719
21720
21721
21722



21723
21724
21725
21726

21727
21728
21729
21730
21731
21732
21733







-
-
-

+


-







  if( !pPager->changeCountDone ){
    /* Open page 1 of the file for writing. */
    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
    if( rc!=SQLITE_OK ) return rc;
    rc = sqlite3PagerWrite(pPgHdr);
    if( rc!=SQLITE_OK ) return rc;
  
    /* Read the current value at byte 24. */
    change_counter = retrieve32bits(pPgHdr, 24);
  
    /* Increment the value just read and write it back to byte 24. */
    change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
    change_counter++;
    put32bits(((char*)PGHDR_TO_DATA(pPgHdr))+24, change_counter);
  
    /* Release the page reference. */
    sqlite3PagerUnref(pPgHdr);
    pPager->changeCountDone = 1;
  }
  return SQLITE_OK;
}

21650
21651
21652
21653
21654
21655
21656
21657

21658
21659
21660
21661
21662
21663
21664
21744
21745
21746
21747
21748
21749
21750

21751
21752
21753
21754
21755
21756
21757
21758







-
+







**
** Note that if zMaster==NULL, this does not overwrite a previous value
** passed to an sqlite3PagerCommitPhaseOne() call.
**
** If parameter nTrunc is non-zero, then the pager file is truncated to
** nTrunc pages (this is used by auto-vacuum databases).
*/
static int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager *pPager, const char *zMaster, Pgno nTrunc){
  int rc = SQLITE_OK;

  PAGERTRACE4("DATABASE SYNC: File=%s zMaster=%s nTrunc=%d\n", 
      pPager->zFilename, zMaster, nTrunc);

  /* If this is an in-memory db, or no pages have been written to, or this
  ** function has already been called, it is a no-op.
21741
21742
21743
21744
21745
21746
21747
21748

21749
21750
21751
21752
21753
21754
21755
21835
21836
21837
21838
21839
21840
21841

21842
21843
21844
21845
21846
21847
21848
21849







-
+







/*
** Commit all changes to the database and release the write lock.
**
** If the commit fails for any reason, a rollback attempt is made
** and an error code is returned.  If the commit worked, SQLITE_OK
** is returned.
*/
static int sqlite3PagerCommitPhaseTwo(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  int rc;
  PgHdr *pPg;

  if( pPager->errCode ){
    return pPager->errCode;
  }
  if( pPager->state<PAGER_RESERVED ){
21795
21796
21797
21798
21799
21800
21801
21802

21803
21804
21805
21806
21807
21808
21809
21889
21890
21891
21892
21893
21894
21895

21896
21897
21898
21899
21900
21901
21902
21903







-
+







** This routine cannot fail unless some other process is not following
** the correct locking protocol or unless some other
** process is writing trash into the journal file (SQLITE_CORRUPT) or
** unless a prior malloc() failed (SQLITE_NOMEM).  Appropriate error
** codes are returned for all these occasions.  Otherwise,
** SQLITE_OK is returned.
*/
static int sqlite3PagerRollback(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  int rc;
  PAGERTRACE2("ROLLBACK %d\n", PAGERID(pPager));
  if( MEMDB ){
    PgHdr *p;
    for(p=pPager->pAll; p; p=p->pNextAll){
      PgHistory *pHist;
      assert( !p->alwaysRollback );
21869
21870
21871
21872
21873
21874
21875
21876

21877
21878
21879
21880
21881
21882
21883

21884
21885
21886
21887
21888
21889
21890
21891

21892
21893
21894
21895
21896
21897
21898
21963
21964
21965
21966
21967
21968
21969

21970
21971
21972
21973
21974
21975
21976

21977
21978
21979
21980
21981
21982
21983
21984

21985
21986
21987
21988
21989
21990
21991
21992







-
+






-
+







-
+







  return pager_error(pPager, rc);
}

/*
** Return TRUE if the database file is opened read-only.  Return FALSE
** if the database is (in theory) writable.
*/
static int sqlite3PagerIsreadonly(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerIsreadonly(Pager *pPager){
  return pPager->readOnly;
}

/*
** Return the number of references to the pager.
*/
static int sqlite3PagerRefcount(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  return pPager->nRef;
}

#ifdef SQLITE_TEST
/*
** This routine is used for testing and analysis only.
*/
static int *sqlite3PagerStats(Pager *pPager){
SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  static int a[11];
  a[0] = pPager->nRef;
  a[1] = pPager->nPage;
  a[2] = pPager->mxPage;
  a[3] = pPager->dbSize;
  a[4] = pPager->state;
  a[5] = pPager->errCode;
21908
21909
21910
21911
21912
21913
21914
21915

21916
21917
21918
21919
21920
21921
21922
22002
22003
22004
22005
22006
22007
22008

22009
22010
22011
22012
22013
22014
22015
22016







-
+







/*
** Set the statement rollback point.
**
** This routine should be called with the transaction journal already
** open.  A new statement journal is created that can be used to rollback
** changes of a single SQL command within a larger transaction.
*/
static int sqlite3PagerStmtBegin(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerStmtBegin(Pager *pPager){
  int rc;
  assert( !pPager->stmtInUse );
  assert( pPager->state>=PAGER_SHARED );
  assert( pPager->dbSize>=0 );
  PAGERTRACE2("STMT-BEGIN %d\n", PAGERID(pPager));
  if( MEMDB ){
    pPager->stmtInUse = 1;
21958
21959
21960
21961
21962
21963
21964
21965

21966
21967
21968
21969
21970
21971
21972
22052
22053
22054
22055
22056
22057
22058

22059
22060
22061
22062
22063
22064
22065
22066







-
+







  }
  return rc;
}

/*
** Commit a statement.
*/
static int sqlite3PagerStmtCommit(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerStmtCommit(Pager *pPager){
  if( pPager->stmtInUse ){
    PgHdr *pPg, *pNext;
    PAGERTRACE2("STMT-COMMIT %d\n", PAGERID(pPager));
    if( !MEMDB ){
      sqlite3OsSeek(pPager->stfd, 0);
      /* sqlite3OsTruncate(pPager->stfd, 0); */
      sqliteFree( pPager->aInStmt );
21989
21990
21991
21992
21993
21994
21995
21996

21997
21998
21999
22000
22001
22002
22003
22083
22084
22085
22086
22087
22088
22089

22090
22091
22092
22093
22094
22095
22096
22097







-
+







  pPager->stmtAutoopen = 0;
  return SQLITE_OK;
}

/*
** Rollback a statement.
*/
static int sqlite3PagerStmtRollback(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerStmtRollback(Pager *pPager){
  int rc;
  if( pPager->stmtInUse ){
    PAGERTRACE2("STMT-ROLLBACK %d\n", PAGERID(pPager));
    if( MEMDB ){
      PgHdr *pPg;
      PgHistory *pHist;
      for(pPg=pPager->pStmt; pPg; pPg=pHist->pNextStmt){
22021
22022
22023
22024
22025
22026
22027
22028

22029
22030
22031
22032
22033
22034
22035

22036
22037
22038
22039
22040
22041
22042

22043
22044
22045
22046
22047
22048
22049
22050

22051
22052
22053
22054
22055
22056
22057
22058

22059
22060
22061
22062
22063
22064
22065
22115
22116
22117
22118
22119
22120
22121

22122
22123
22124
22125
22126
22127
22128

22129
22130
22131
22132
22133
22134
22135

22136
22137
22138
22139
22140
22141
22142
22143

22144
22145
22146
22147
22148
22149
22150
22151

22152
22153
22154
22155
22156
22157
22158
22159







-
+






-
+






-
+







-
+







-
+







  pPager->stmtAutoopen = 0;
  return rc;
}

/*
** Return the full pathname of the database file.
*/
static const char *sqlite3PagerFilename(Pager *pPager){
SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
  return pPager->zFilename;
}

/*
** Return the directory of the database file.
*/
static const char *sqlite3PagerDirname(Pager *pPager){
SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
  return pPager->zDirectory;
}

/*
** Return the full pathname of the journal file.
*/
static const char *sqlite3PagerJournalname(Pager *pPager){
SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  return pPager->zJournal;
}

/*
** Return true if fsync() calls are disabled for this pager.  Return FALSE
** if fsync()s are executed normally.
*/
static int sqlite3PagerNosync(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  return pPager->noSync;
}

#ifdef SQLITE_HAS_CODEC
/*
** Set the codec for this pager
*/
static void sqlite3PagerSetCodec(
SQLITE_PRIVATE void sqlite3PagerSetCodec(
  Pager *pPager,
  void *(*xCodec)(void*,void*,Pgno,int),
  void *pCodecArg
){
  pPager->xCodec = xCodec;
  pPager->pCodecArg = pCodecArg;
}
22079
22080
22081
22082
22083
22084
22085
22086

22087
22088
22089
22090
22091
22092
22093
22173
22174
22175
22176
22177
22178
22179

22180
22181
22182
22183
22184
22185
22186
22187







-
+







** allocated along with the page) is the responsibility of the caller.
**
** A transaction must be active when this routine is called. It used to be
** required that a statement transaction was not active, but this restriction
** has been removed (CREATE INDEX needs to move a page when a statement
** transaction is active).
*/
static int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno){
  PgHdr *pPgOld;  /* The page being overwritten. */
  int h;
  Pgno needSyncPgno = 0;

  assert( pPg->nRef>0 );

  PAGERTRACE5("MOVE %d page %d (needSync=%d) moves to %d\n", 
22167
22168
22169
22170
22171
22172
22173
22174

22175
22176
22177
22178
22179
22180
22181
22182

22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197

22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215

22216
22217
22218
22219
22220
22221
22222
22223
22224

22225
22226
22227
22228
22229
22230
22231
22261
22262
22263
22264
22265
22266
22267

22268
22269
22270
22271
22272
22273
22274
22275

22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290

22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308

22309
22310
22311
22312
22313
22314
22315
22316
22317

22318
22319
22320
22321
22322
22323
22324
22325







-
+







-
+














-
+

















-
+








-
+







  return SQLITE_OK;
}
#endif

/*
** Return a pointer to the data for the specified page.
*/
static void *sqlite3PagerGetData(DbPage *pPg){
SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  return PGHDR_TO_DATA(pPg);
}

/*
** Return a pointer to the Pager.nExtra bytes of "extra" space 
** allocated along with the specified page.
*/
static void *sqlite3PagerGetExtra(DbPage *pPg){
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  Pager *pPager = pPg->pPager;
  return (pPager?PGHDR_TO_EXTRA(pPg, pPager):0);
}

/*
** Get/set the locking-mode for this pager. Parameter eMode must be one
** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
** the locking-mode is set to the value specified.
**
** The returned value is either PAGER_LOCKINGMODE_NORMAL or
** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
** locking-mode.
*/
static int sqlite3PagerLockingMode(Pager *pPager, int eMode){
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  assert( eMode==PAGER_LOCKINGMODE_QUERY
            || eMode==PAGER_LOCKINGMODE_NORMAL
            || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  assert( PAGER_LOCKINGMODE_QUERY<0 );
  assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  if( eMode>=0 && !pPager->tempFile ){
    pPager->exclusiveMode = eMode;
  }
  return (int)pPager->exclusiveMode;
}

#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
/*
** Return the current state of the file lock for the given pager.
** The return value is one of NO_LOCK, SHARED_LOCK, RESERVED_LOCK,
** PENDING_LOCK, or EXCLUSIVE_LOCK.
*/
static int sqlite3PagerLockstate(Pager *pPager){
SQLITE_PRIVATE int sqlite3PagerLockstate(Pager *pPager){
  return sqlite3OsLockState(pPager->fd);
}
#endif

#ifdef SQLITE_DEBUG
/*
** Print a listing of all referenced pages and their ref count.
*/
static void sqlite3PagerRefdump(Pager *pPager){
SQLITE_PRIVATE void sqlite3PagerRefdump(Pager *pPager){
  PgHdr *pPg;
  for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
    if( pPg->nRef<=0 ) continue;
    sqlite3DebugPrintf("PAGE %3d addr=%p nRef=%d\n", 
       pPg->pgno, PGHDR_TO_DATA(pPg), pPg->nRef);
  }
}
22242
22243
22244
22245
22246
22247
22248
22249

22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268

22269
22270
22271
22272
22273
22274
22275
22336
22337
22338
22339
22340
22341
22342

22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361

22362
22363
22364
22365
22366
22367
22368
22369







-
+


















-
+







** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
**
** This file implements a external (disk-based) database using BTrees.
** See the header comment on "btreeInt.h" for additional information.
** Including a description of file format and an overview of operation.
*/
/************** Include btreeInt.h in the middle of btree.c ******************/
/************** Begin file btreeInt.h ****************************************/
/*
** 2004 April 6
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
**
** This file implements a external (disk-based) database using BTrees.
** For a detailed discussion of BTrees, refer to
**
**     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
**     "Sorting And Searching", pages 473-480. Addison-Wesley
**     Publishing Company, Reading, Massachusetts.
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839










22840
22841
22842
22843
22844
22845
22846
22917
22918
22919
22920
22921
22922
22923










22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940







-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+







#define put2byte(p,v) ((p)[0] = (v)>>8, (p)[1] = (v))
#define get4byte sqlite3Get4byte
#define put4byte sqlite3Put4byte

/*
** Internal routines that should be accessed by the btree layer only.
*/
static int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
static int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
static void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
static void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
static u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
static int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
static void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
static void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
static int sqlite3BtreeIsRootPage(MemPage *pPage);
static void sqlite3BtreeMoveToParent(BtCursor *pCur);
SQLITE_PRIVATE int sqlite3BtreeGetPage(BtShared*, Pgno, MemPage**, int);
SQLITE_PRIVATE int sqlite3BtreeInitPage(MemPage *pPage, MemPage *pParent);
SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(MemPage*, u8*, CellInfo*);
SQLITE_PRIVATE void sqlite3BtreeParseCell(MemPage*, int, CellInfo*);
SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell);
SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur);
SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur);
SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur);
SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage);
SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur);

/************** End of btreeInt.h ********************************************/
/************** Continuing where we left off in btree.c **********************/

/*
** The header string that appears at the beginning of every
** SQLite database.
23118
23119
23120
23121
23122
23123
23124
23125

23126
23127
23128
23129
23130
23131
23132
23212
23213
23214
23215
23216
23217
23218

23219
23220
23221
23222
23223
23224
23225
23226







-
+







** at most one effective restoreOrClearCursorPosition() call after each 
** saveCursorPosition().
**
** If the second argument argument - doSeek - is false, then instead of 
** returning the cursor to it's saved position, any saved position is deleted
** and the cursor state set to CURSOR_INVALID.
*/
static int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
SQLITE_PRIVATE int sqlite3BtreeRestoreOrClearCursorPosition(BtCursor *pCur){
  int rc;
  assert( pCur->eState==CURSOR_REQUIRESEEK );
#ifndef SQLITE_OMIT_INCRBLOB
  if( pCur->isIncrblobHandle ){
    return SQLITE_ABORT;
  }
#endif
23241
23242
23243
23244
23245
23246
23247
23248

23249
23250
23251

23252
23253
23254
23255
23256
23257
23258
23335
23336
23337
23338
23339
23340
23341

23342

23343

23344
23345
23346
23347
23348
23349
23350
23351







-
+
-

-
+







** the page, 1 means the second cell, and so forth) return a pointer
** to the cell content.
**
** This routine works only for pages that do not contain overflow cells.
*/
#define findCell(pPage, iCell) \
  ((pPage)->aData + get2byte(&(pPage)->aData[(pPage)->cellOffset+2*(iCell)]))
static u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
SQLITE_PRIVATE u8 *sqlite3BtreeFindCell(MemPage *pPage, int iCell){
  u8 *data = pPage->aData;
  assert( iCell>=0 );
  assert( iCell<get2byte(&data[pPage->hdrOffset+3]) );
  assert( iCell<get2byte(&pPage->aData[pPage->hdrOffset+3]) );
  return findCell(pPage, iCell);
}

/*
** This a more complex version of sqlite3BtreeFindCell() that works for
** pages that do contain overflow cells.  See insert
*/
23278
23279
23280
23281
23282
23283
23284
23285

23286
23287
23288
23289
23290
23291
23292
23371
23372
23373
23374
23375
23376
23377

23378
23379
23380
23381
23382
23383
23384
23385







-
+







** are two versions of this function.  sqlite3BtreeParseCell() takes a 
** cell index as the second argument and sqlite3BtreeParseCellPtr() 
** takes a pointer to the body of the cell as its second argument.
**
** Within this file, the parseCell() macro can be called instead of
** sqlite3BtreeParseCellPtr(). Using some compilers, this will be faster.
*/
static void sqlite3BtreeParseCellPtr(
SQLITE_PRIVATE void sqlite3BtreeParseCellPtr(
  MemPage *pPage,         /* Page containing the cell */
  u8 *pCell,              /* Pointer to the cell text. */
  CellInfo *pInfo         /* Fill in this structure */
){
  int n;                  /* Number bytes in cell content header */
  u32 nPayload;           /* Number of bytes of cell payload */

23346
23347
23348
23349
23350
23351
23352
23353

23354
23355
23356
23357
23358
23359
23360
23439
23440
23441
23442
23443
23444
23445

23446
23447
23448
23449
23450
23451
23452
23453







-
+







    }
    pInfo->iOverflow = pInfo->nLocal + n;
    pInfo->nSize = pInfo->iOverflow + 4;
  }
}
#define parseCell(pPage, iCell, pInfo) \
  sqlite3BtreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
static void sqlite3BtreeParseCell(
SQLITE_PRIVATE void sqlite3BtreeParseCell(
  MemPage *pPage,         /* Page containing the cell */
  int iCell,              /* The cell index.  First cell is 0 */
  CellInfo *pInfo         /* Fill in this structure */
){
  parseCell(pPage, iCell, pInfo);
}

23631
23632
23633
23634
23635
23636
23637
23638

23639
23640
23641
23642
23643
23644
23645
23724
23725
23726
23727
23728
23729
23730

23731
23732
23733
23734
23735
23736
23737
23738







-
+







**
** Return SQLITE_OK on success.  If we see that the page does
** not contain a well-formed database page, then return 
** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
** guarantee that the page is well-formed.  It only shows that
** we failed to detect any corruption.
*/
static int sqlite3BtreeInitPage(
SQLITE_PRIVATE int sqlite3BtreeInitPage(
  MemPage *pPage,        /* The page to be initialized */
  MemPage *pParent       /* The parent.  Might be NULL */
){
  int pc;            /* Address of a freeblock within pPage->aData[] */
  int hdr;           /* Offset to beginning of page header */
  u8 *data;          /* Equal to pPage->aData */
  BtShared *pBt;        /* The main btree structure */
23744
23745
23746
23747
23748
23749
23750
23751

23752
23753
23754
23755
23756
23757
23758
23837
23838
23839
23840
23841
23842
23843

23844
23845
23846
23847
23848
23849
23850
23851







-
+







** If the noContent flag is set, it means that we do not care about
** the content of the page at this time.  So do not go to the disk
** to fetch the content.  Just fill in the content with zeros for now.
** If in the future we call sqlite3PagerWrite() on this page, that
** means we have started to be concerned about content and the disk
** read should occur at that point.
*/
static int sqlite3BtreeGetPage(
SQLITE_PRIVATE int sqlite3BtreeGetPage(
  BtShared *pBt,       /* The btree */
  Pgno pgno,           /* Number of the page to fetch */
  MemPage **ppPage,    /* Return the page in this parameter */
  int noContent        /* Do not load page content if true */
){
  int rc;
  MemPage *pPage;
23843
23844
23845
23846
23847
23848
23849
23850

23851
23852
23853
23854
23855
23856
23857
23936
23937
23938
23939
23940
23941
23942

23943
23944
23945
23946
23947
23948
23949
23950







-
+







/*
** Open a database file.
** 
** zFilename is the name of the database file.  If zFilename is NULL
** a new database with a random name is created.  This randomly named
** database file will be deleted when sqlite3BtreeClose() is called.
*/
static int sqlite3BtreeOpen(
SQLITE_PRIVATE int sqlite3BtreeOpen(
  const char *zFilename,  /* Name of the file containing the BTree database */
  sqlite3 *pSqlite,       /* Associated database handle */
  Btree **ppBtree,        /* Pointer to new Btree object written here */
  int flags               /* Options */
){
  BtShared *pBt;          /* Shared part of btree structure */
  Btree *p;               /* Handle to return */
23959
23960
23961
23962
23963
23964
23965

23966
23967
23968
23969
23970
23971
23972
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066







+







    nReserve = zDbHeader[20];
    pBt->maxEmbedFrac = zDbHeader[21];
    pBt->minEmbedFrac = zDbHeader[22];
    pBt->minLeafFrac = zDbHeader[23];
    pBt->pageSizeFixed = 1;
#ifndef SQLITE_OMIT_AUTOVACUUM
    pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
    pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
#endif
  }
  pBt->usableSize = pBt->pageSize - nReserve;
  assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
  sqlite3PagerSetPagesize(pBt->pPager, pBt->pageSize);

#if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
23994
23995
23996
23997
23998
23999
24000
24001

24002
24003
24004
24005
24006
24007
24008
24088
24089
24090
24091
24092
24093
24094

24095
24096
24097
24098
24099
24100
24101
24102







-
+







  }
  return rc;
}

/*
** Close an open database and invalidate all cursors.
*/
static int sqlite3BtreeClose(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  BtShared *pBt = p->pBt;
  BtCursor *pCur;

#ifndef SQLITE_OMIT_SHARED_CACHE
  ThreadData *pTsd;
#endif

24062
24063
24064
24065
24066
24067
24068
24069

24070
24071
24072
24073
24074
24075
24076
24156
24157
24158
24159
24160
24161
24162

24163
24164
24165
24166
24167
24168
24169
24170







-
+







  sqliteFree(pBt);
  return SQLITE_OK;
}

/*
** Change the busy handler callback function.
*/
static int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
SQLITE_PRIVATE int sqlite3BtreeSetBusyHandler(Btree *p, BusyHandler *pHandler){
  BtShared *pBt = p->pBt;
  pBt->pBusyHandler = pHandler;
  sqlite3PagerSetBusyhandler(pBt->pPager, pHandler);
  return SQLITE_OK;
}

/*
24084
24085
24086
24087
24088
24089
24090
24091

24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106

24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117

24118
24119
24120
24121
24122
24123
24124
24178
24179
24180
24181
24182
24183
24184

24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199

24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210

24211
24212
24213
24214
24215
24216
24217
24218







-
+














-
+










-
+







** and the database cannot be corrupted if this program
** crashes.  But if the operating system crashes or there is
** an abrupt power failure when synchronous is off, the database
** could be left in an inconsistent and unrecoverable state.
** Synchronous is on by default so database corruption is not
** normally a worry.
*/
static int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  BtShared *pBt = p->pBt;
  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  return SQLITE_OK;
}

/*
** Change the way data is synced to disk in order to increase or decrease
** how well the database resists damage due to OS crashes and power
** failures.  Level 1 is the same as asynchronous (no syncs() occur and
** there is a high probability of damage)  Level 2 is the default.  There
** is a very low but non-zero probability of damage.  Level 3 reduces the
** probability of damage to near zero but with a write performance reduction.
*/
#ifndef SQLITE_OMIT_PAGER_PRAGMAS
static int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
  BtShared *pBt = p->pBt;
  sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
  return SQLITE_OK;
}
#endif

/*
** Return TRUE if the given btree is set to safety level 1.  In other
** words, return TRUE if no sync() occurs on the disk files.
*/
static int sqlite3BtreeSyncDisabled(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  BtShared *pBt = p->pBt;
  assert( pBt && pBt->pPager );
  return sqlite3PagerNosync(pBt->pPager);
}

#if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
/*
24132
24133
24134
24135
24136
24137
24138
24139

24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160

24161
24162
24163

24164
24165
24166
24167
24168
24169
24170
24171
24172

24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183

24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203

24204
24205
24206
24207
24208
24209
24210
24226
24227
24228
24229
24230
24231
24232

24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253

24254
24255
24256

24257
24258
24259
24260
24261
24262
24263
24264
24265

24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276

24277
24278
24279
24280
24281
24282

24283
24284
24285
24286

24287
24288
24289
24290
24291
24292
24293
24294

24295
24296
24297
24298
24299
24300
24301
24302







-
+




















-
+


-
+








-
+










-
+





-




-








-
+







** of the database file used for locking (beginning at PENDING_BYTE,
** the first byte past the 1GB boundary, 0x40000000) needs to occur
** at the beginning of a page.
**
** If parameter nReserve is less than zero, then the number of reserved
** bytes per page is left unchanged.
*/
static int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve){
  BtShared *pBt = p->pBt;
  if( pBt->pageSizeFixed ){
    return SQLITE_READONLY;
  }
  if( nReserve<0 ){
    nReserve = pBt->pageSize - pBt->usableSize;
  }
  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
        ((pageSize-1)&pageSize)==0 ){
    assert( (pageSize & 7)==0 );
    assert( !pBt->pPage1 && !pBt->pCursor );
    pBt->pageSize = sqlite3PagerSetPagesize(pBt->pPager, pageSize);
  }
  pBt->usableSize = pBt->pageSize - nReserve;
  return SQLITE_OK;
}

/*
** Return the currently defined page size
*/
static int sqlite3BtreeGetPageSize(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  return p->pBt->pageSize;
}
static int sqlite3BtreeGetReserve(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  return p->pBt->pageSize - p->pBt->usableSize;
}

/*
** Set the maximum page count for a database if mxPage is positive.
** No changes are made if mxPage is 0 or negative.
** Regardless of the value of mxPage, return the maximum page count.
*/
static int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  return sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
}
#endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */

/*
** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
** is disabled. The default value for the auto-vacuum property is 
** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
*/
static int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
#ifdef SQLITE_OMIT_AUTOVACUUM
  return SQLITE_READONLY;
#else
  BtShared *pBt = p->pBt;
  int av = (autoVacuum?1:0);
  int iv = (autoVacuum==BTREE_AUTOVACUUM_INCR?1:0);
  if( pBt->pageSizeFixed && av!=pBt->autoVacuum ){
    return SQLITE_READONLY;
  }
  pBt->autoVacuum = av;
  pBt->incrVacuum = iv;
  return SQLITE_OK;
#endif
}

/*
** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
** enabled 1 is returned. Otherwise 0.
*/
static int sqlite3BtreeGetAutoVacuum(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
#ifdef SQLITE_OMIT_AUTOVACUUM
  return BTREE_AUTOVACUUM_NONE;
#else
  return (
    (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
    (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
    BTREE_AUTOVACUUM_INCR
24256
24257
24258
24259
24260
24261
24262

24263
24264
24265
24266
24267
24268
24269
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362







+







      goto page1_init_failed;
    }
    pBt->maxEmbedFrac = page1[21];
    pBt->minEmbedFrac = page1[22];
    pBt->minLeafFrac = page1[23];
#ifndef SQLITE_OMIT_AUTOVACUUM
    pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
    pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
#endif
  }

  /* maxLocal is the maximum amount of payload to store locally for
  ** a cell.  Make sure it is small enough so that at least minFanout
  ** cells can will fit on one page.  We assume a 10-byte page header.
  ** Besides the payload, the cell must store:
24364
24365
24366
24367
24368
24369
24370

24371

24372
24373
24374
24375
24376
24377
24378
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473







+

+







  data[22] = pBt->minEmbedFrac;
  data[23] = pBt->minLeafFrac;
  memset(&data[24], 0, 100-24);
  zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  pBt->pageSizeFixed = 1;
#ifndef SQLITE_OMIT_AUTOVACUUM
  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  put4byte(&data[36 + 4*4], pBt->autoVacuum);
  put4byte(&data[36 + 7*4], pBt->incrVacuum);
#endif
  return SQLITE_OK;
}

/*
** Attempt to start a new transaction. A write-transaction
** is started if the second argument is nonzero, otherwise a read-
24404
24405
24406
24407
24408
24409
24410
24411

24412
24413
24414
24415
24416
24417
24418
24499
24500
24501
24502
24503
24504
24505

24506
24507
24508
24509
24510
24511
24512
24513







-
+







** a reserved lock.  B tries to promote to exclusive but is blocked because
** of A's read lock.  A tries to promote to reserved but is blocked by B.
** One or the other of the two processes must give way or there can be
** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
** when A already has a read lock, we encourage A to give up and let B
** proceed.
*/
static int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  BtShared *pBt = p->pBt;
  int rc = SQLITE_OK;

  btreeIntegrity(p);

  /* If the btree is already in a write-transaction, or it
  ** is already in a read-transaction and a read-transaction
24767
24768
24769
24770
24771
24772
24773
24774

24775
24776
24777
24778
24779
24780
24781
24862
24863
24864
24865
24866
24867
24868

24869
24870
24871
24872
24873
24874
24875
24876







-
+







** A write-transaction must be opened before calling this function.
** It performs a single unit of work towards an incremental vacuum.
**
** If the incremental vacuum is finished after this function has run,
** SQLITE_DONE is returned. If it is not finished, but no error occured,
** SQLITE_OK is returned. Otherwise an SQLite error code. 
*/
static int sqlite3BtreeIncrVacuum(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  BtShared *pBt = p->pBt;
  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  if( !pBt->autoVacuum ){
    return SQLITE_DONE;
  }
  invalidateAllOverflowCache(pBt);
  return incrVacuumStep(pBt, 0);
24875
24876
24877
24878
24879
24880
24881
24882

24883
24884
24885
24886
24887
24888
24889
24970
24971
24972
24973
24974
24975
24976

24977
24978
24979
24980
24981
24982
24983
24984







-
+







**
** When this is called, the master journal should already have been
** created, populated with this journal pointer and synced to disk.
**
** Once this is routine has returned, the only thing required to commit
** the write-transaction for this database file is to delete the journal.
*/
static int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  int rc = SQLITE_OK;
  if( p->inTrans==TRANS_WRITE ){
    BtShared *pBt = p->pBt;
    Pgno nTrunc = 0;
#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum ){
      rc = autoVacuumCommit(pBt, &nTrunc); 
24907
24908
24909
24910
24911
24912
24913
24914

24915
24916
24917
24918
24919
24920
24921
25002
25003
25004
25005
25006
25007
25008

25009
25010
25011
25012
25013
25014
25015
25016







-
+







** contents so that they are written onto the disk platter.  All this
** routine has to do is delete or truncate the rollback journal
** (which causes the transaction to commit) and drop locks.
**
** This will release the write lock on the database file.  If there
** are no active cursors, it also releases the read lock.
*/
static int sqlite3BtreeCommitPhaseTwo(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
  BtShared *pBt = p->pBt;

  btreeIntegrity(p);

  /* If the handle has a write-transaction open, commit the shared-btrees 
  ** transaction and set the shared state to TRANS_READ.
  */
24953
24954
24955
24956
24957
24958
24959
24960

24961
24962
24963
24964
24965
24966
24967
25048
25049
25050
25051
25052
25053
25054

25055
25056
25057
25058
25059
25060
25061
25062







-
+







  btreeIntegrity(p);
  return SQLITE_OK;
}

/*
** Do both phases of a commit.
*/
static int sqlite3BtreeCommit(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  int rc;
  rc = sqlite3BtreeCommitPhaseOne(p, 0);
  if( rc==SQLITE_OK ){
    rc = sqlite3BtreeCommitPhaseTwo(p);
  }
  return rc;
}
24987
24988
24989
24990
24991
24992
24993
24994

24995
24996
24997
24998
24999
25000
25001
25082
25083
25084
25085
25086
25087
25088

25089
25090
25091
25092
25093
25094
25095
25096







-
+







** invalided by this operation.  Any attempt to use a cursor
** that was open at the beginning of this operation will result
** in an error.
**
** This will release the write lock on the database file.  If there
** are no active cursors, it also releases the read lock.
*/
static int sqlite3BtreeRollback(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
  int rc;
  BtShared *pBt = p->pBt;
  MemPage *pPage1;

  rc = saveAllCursors(pBt, 0, 0);
#ifndef SQLITE_OMIT_SHARED_CACHE
  if( rc!=SQLITE_OK ){
25067
25068
25069
25070
25071
25072
25073
25074

25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091

25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111

25112
25113
25114
25115
25116
25117
25118
25162
25163
25164
25165
25166
25167
25168

25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185

25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205

25206
25207
25208
25209
25210
25211
25212
25213







-
+
















-
+



















-
+







** to start a new subtransaction if another subtransaction is already active.
**
** Statement subtransactions are used around individual SQL statements
** that are contained within a BEGIN...COMMIT block.  If a constraint
** error occurs within the statement, the effect of that one statement
** can be rolled back without having to rollback the entire transaction.
*/
static int sqlite3BtreeBeginStmt(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p){
  int rc;
  BtShared *pBt = p->pBt;
  if( (p->inTrans!=TRANS_WRITE) || pBt->inStmt ){
    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  }
  assert( pBt->inTransaction==TRANS_WRITE );
  rc = pBt->readOnly ? SQLITE_OK : sqlite3PagerStmtBegin(pBt->pPager);
  pBt->inStmt = 1;
  return rc;
}


/*
** Commit the statment subtransaction currently in progress.  If no
** subtransaction is active, this is a no-op.
*/
static int sqlite3BtreeCommitStmt(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeCommitStmt(Btree *p){
  int rc;
  BtShared *pBt = p->pBt;
  if( pBt->inStmt && !pBt->readOnly ){
    rc = sqlite3PagerStmtCommit(pBt->pPager);
  }else{
    rc = SQLITE_OK;
  }
  pBt->inStmt = 0;
  return rc;
}

/*
** Rollback the active statement subtransaction.  If no subtransaction
** is active this routine is a no-op.
**
** All cursors will be invalidated by this operation.  Any attempt
** to use a cursor that was open at the beginning of this operation
** will result in an error.
*/
static int sqlite3BtreeRollbackStmt(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeRollbackStmt(Btree *p){
  int rc = SQLITE_OK;
  BtShared *pBt = p->pBt;
  sqlite3MallocDisallow();
  if( pBt->inStmt && !pBt->readOnly ){
    rc = sqlite3PagerStmtRollback(pBt->pPager);
    assert( countWriteCursors(pBt)==0 );
    pBt->inStmt = 0;
25167
25168
25169
25170
25171
25172
25173
25174

25175
25176
25177
25178
25179
25180
25181
25262
25263
25264
25265
25266
25267
25268

25269
25270
25271
25272
25273
25274
25275
25276







-
+







**
** The comparison function must be logically the same for every cursor
** on a particular table.  Changing the comparison function will result
** in incorrect operations.  If the comparison function is NULL, a
** default comparison function is used.  The comparison function is
** always ignored for INTKEY tables.
*/
static int sqlite3BtreeCursor(
SQLITE_PRIVATE int sqlite3BtreeCursor(
  Btree *p,                                   /* The btree */
  int iTable,                                 /* Root page of table to open */
  int wrFlag,                                 /* 1 to write. 0 read-only */
  int (*xCmp)(void*,int,const void*,int,const void*), /* Key Comparison func */
  void *pArg,                                 /* First arg to xCompare() */
  BtCursor **ppCur                            /* Write new cursor here */
){
25243
25244
25245
25246
25247
25248
25249
25250

25251
25252
25253
25254
25255
25256
25257
25338
25339
25340
25341
25342
25343
25344

25345
25346
25347
25348
25349
25350
25351
25352







-
+







  return rc;
}

/*
** Close a cursor.  The read lock on the database file is released
** when the last cursor is closed.
*/
static int sqlite3BtreeCloseCursor(BtCursor *pCur){
SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  BtShared *pBt = pCur->pBtree->pBt;
  clearCursorPosition(pCur);
  if( pCur->pPrev ){
    pCur->pPrev->pNext = pCur->pNext;
  }else{
    pBt->pCursor = pCur->pNext;
  }
25265
25266
25267
25268
25269
25270
25271
25272

25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285

25286
25287
25288
25289
25290
25291
25292
25293
25294


25295
25296
25297
25298







25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309







25310
25311
25312






25313
25314
25315
25316




25317
25318
25319
25320
25321
25322
25323
25324
25325
25326

25327
25328
25329
25330
25331
25332
25333

25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347

25348
25349
25350
25351
25352
25353
25354
25355

25356
25357
25358
25359
25360
25361
25362
25360
25361
25362
25363
25364
25365
25366

25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379

25380
25381
25382
25383
25384
25385
25386



25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417



25418
25419
25420
25421
25422
25423
25424



25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437

25438
25439
25440
25441
25442
25443
25444

25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458

25459
25460
25461
25462
25463
25464
25465
25466

25467
25468
25469
25470
25471
25472
25473
25474







-
+












-
+






-
-
-
+
+




+
+
+
+
+
+
+











+
+
+
+
+
+
+
-
-
-
+
+
+
+
+
+

-
-
-
+
+
+
+









-
+






-
+













-
+







-
+







  return SQLITE_OK;
}

/*
** Make a temporary cursor by filling in the fields of pTempCur.
** The temporary cursor is not on the cursor list for the Btree.
*/
static void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
SQLITE_PRIVATE void sqlite3BtreeGetTempCursor(BtCursor *pCur, BtCursor *pTempCur){
  memcpy(pTempCur, pCur, sizeof(*pCur));
  pTempCur->pNext = 0;
  pTempCur->pPrev = 0;
  if( pTempCur->pPage ){
    sqlite3PagerRef(pTempCur->pPage->pDbPage);
  }
}

/*
** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
** function above.
*/
static void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
SQLITE_PRIVATE void sqlite3BtreeReleaseTempCursor(BtCursor *pCur){
  if( pCur->pPage ){
    sqlite3PagerUnref(pCur->pPage->pDbPage);
  }
}

/*
** The GET_CELL_INFO() macro. Takes one argument, a pointer to a valid
** btree cursor (type BtCursor*).  This macro makes sure the BtCursor.info
** field of the given cursor is valid.  If it is not already valid, call
** Make sure the BtCursor* given in the argument has a valid
** BtCursor.info structure.  If it is not already valid, call
** sqlite3BtreeParseCell() to fill it in.
**
** BtCursor.info is a cache of the information in the current cell.
** Using this cache reduces the number of calls to sqlite3BtreeParseCell().
**
** 2007-06-25:  There is a bug in some versions of MSVC that cause the
** compiler to crash when getCellInfo() is implemented as a macro.
** But there is a measureable speed advantage to using the macro on gcc
** (when less compiler optimizations like -Os or -O0 are used and the
** compiler is not doing agressive inlining.)  So we use a real function
** for MSVC and a macro for everything else.  Ticket #2457.
*/
#ifndef NDEBUG
  static void assertCellInfo(BtCursor *pCur){
    CellInfo info;
    memset(&info, 0, sizeof(info));
    sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &info);
    assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  }
#else
  #define assertCellInfo(x)
#endif
#ifdef _MSC_VER
  /* Use a real function in MSVC to work around bugs in that compiler. */
  static void getCellInfo(BtCursor *pCur){
    if( pCur->info.nSize==0 ){
      sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);
    }else{
      assertCellInfo(pCur);

#define GET_CELL_INFO(pCur)                                             \
  if( pCur->info.nSize==0 )                                             \
    }
  }
#else /* if not _MSC_VER */
  /* Use a macro in all other compilers so that the function is inlined */
#define getCellInfo(pCur)                                               \
  if( pCur->info.nSize==0 ){                                            \
    sqlite3BtreeParseCell(pCur->pPage, pCur->idx, &pCur->info);         \
  else                                                                  \
    assertCellInfo(pCur);
   
  }else{                                                                \
    assertCellInfo(pCur);                                               \
  }
#endif /* _MSC_VER */

/*
** Set *pSize to the size of the buffer needed to hold the value of
** the key for the current entry.  If the cursor is not pointing
** to a valid entry, *pSize is set to 0. 
**
** For a table with the INTKEY flag set, this routine returns the key
** itself, not the number of bytes in the key.
*/
static int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  int rc = restoreOrClearCursorPosition(pCur);
  if( rc==SQLITE_OK ){
    assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
    if( pCur->eState==CURSOR_INVALID ){
      *pSize = 0;
    }else{
      GET_CELL_INFO(pCur);
      getCellInfo(pCur);
      *pSize = pCur->info.nKey;
    }
  }
  return rc;
}

/*
** Set *pSize to the number of bytes of data in the entry the
** cursor currently points to.  Always return SQLITE_OK.
** Failure is not possible.  If the cursor is not currently
** pointing to an entry (which can happen, for example, if
** the database is empty) then *pSize is set to 0.
*/
static int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  int rc = restoreOrClearCursorPosition(pCur);
  if( rc==SQLITE_OK ){
    assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
    if( pCur->eState==CURSOR_INVALID ){
      /* Not pointing at a valid entry - set *pSize to 0. */
      *pSize = 0;
    }else{
      GET_CELL_INFO(pCur);
      getCellInfo(pCur);
      *pSize = pCur->info.nData;
    }
  }
  return rc;
}

/*
25521
25522
25523
25524
25525
25526
25527
25528

25529
25530
25531
25532
25533
25534
25535
25633
25634
25635
25636
25637
25638
25639

25640
25641
25642
25643
25644
25645
25646
25647







-
+







  BtShared *pBt = pCur->pBtree->pBt;   /* Btree this cursor belongs to */

  assert( pPage );
  assert( pCur->eState==CURSOR_VALID );
  assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  assert( offset>=0 );

  GET_CELL_INFO(pCur);
  getCellInfo(pCur);
  aPayload = pCur->info.pCell + pCur->info.nHeader;
  nKey = (pPage->intKey ? 0 : pCur->info.nKey);

  if( skipKey ){
    offset += nKey;
  }
  if( offset+amt > nKey+pCur->info.nData ){
25642
25643
25644
25645
25646
25647
25648
25649

25650
25651
25652
25653
25654
25655
25656
25754
25755
25756
25757
25758
25759
25760

25761
25762
25763
25764
25765
25766
25767
25768







-
+







** "amt" bytes will be transfered into pBuf[].  The transfer
** begins at "offset".
**
** Return SQLITE_OK on success or an error code if anything goes
** wrong.  An error is returned if "offset+amt" is larger than
** the available payload.
*/
static int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  int rc = restoreOrClearCursorPosition(pCur);
  if( rc==SQLITE_OK ){
    assert( pCur->eState==CURSOR_VALID );
    assert( pCur->pPage!=0 );
    if( pCur->pPage->intKey ){
      return SQLITE_CORRUPT_BKPT;
    }
25666
25667
25668
25669
25670
25671
25672
25673

25674
25675
25676
25677
25678
25679
25680
25778
25779
25780
25781
25782
25783
25784

25785
25786
25787
25788
25789
25790
25791
25792







-
+







** "amt" bytes will be transfered into pBuf[].  The transfer
** begins at "offset".
**
** Return SQLITE_OK on success or an error code if anything goes
** wrong.  An error is returned if "offset+amt" is larger than
** the available payload.
*/
static int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  int rc = restoreOrClearCursorPosition(pCur);
  if( rc==SQLITE_OK ){
    assert( pCur->eState==CURSOR_VALID );
    assert( pCur->pPage!=0 );
    assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
    rc = accessPayload(pCur, offset, amt, pBuf, 1, 0);
  }
25710
25711
25712
25713
25714
25715
25716
25717

25718
25719
25720
25721
25722
25723
25724
25822
25823
25824
25825
25826
25827
25828

25829
25830
25831
25832
25833
25834
25835
25836







-
+







  u32 nKey;
  int nLocal;

  assert( pCur!=0 && pCur->pPage!=0 );
  assert( pCur->eState==CURSOR_VALID );
  pPage = pCur->pPage;
  assert( pCur->idx>=0 && pCur->idx<pPage->nCell );
  GET_CELL_INFO(pCur);
  getCellInfo(pCur);
  aPayload = pCur->info.pCell;
  aPayload += pCur->info.nHeader;
  if( pPage->intKey ){
    nKey = 0;
  }else{
    nKey = pCur->info.nKey;
  }
25743
25744
25745
25746
25747
25748
25749
25750

25751
25752
25753
25754
25755
25756

25757
25758
25759
25760
25761
25762
25763
25855
25856
25857
25858
25859
25860
25861

25862
25863
25864
25865
25866
25867

25868
25869
25870
25871
25872
25873
25874
25875







-
+





-
+







**
** The pointer returned is ephemeral.  The key/data may move
** or be destroyed on the next call to any Btree routine.
**
** These routines is used to get quick access to key and data
** in the common case where no overflow pages are used.
*/
static const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  if( pCur->eState==CURSOR_VALID ){
    return (const void*)fetchPayload(pCur, pAmt, 0);
  }
  return 0;
}
static const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  if( pCur->eState==CURSOR_VALID ){
    return (const void*)fetchPayload(pCur, pAmt, 1);
  }
  return 0;
}


25792
25793
25794
25795
25796
25797
25798
25799

25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815

25816
25817
25818
25819
25820
25821
25822
25904
25905
25906
25907
25908
25909
25910

25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926

25927
25928
25929
25930
25931
25932
25933
25934







-
+















-
+







**
** The virtual root page is the root page for most tables.  But
** for the table rooted on page 1, sometime the real root page
** is empty except for the right-pointer.  In such cases the
** virtual root page is the page that the right-pointer of page
** 1 is pointing to.
*/
static int sqlite3BtreeIsRootPage(MemPage *pPage){
SQLITE_PRIVATE int sqlite3BtreeIsRootPage(MemPage *pPage){
  MemPage *pParent = pPage->pParent;
  if( pParent==0 ) return 1;
  if( pParent->pgno>1 ) return 0;
  if( get2byte(&pParent->aData[pParent->hdrOffset+3])==0 ) return 1;
  return 0;
}

/*
** Move the cursor up to the parent page.
**
** pCur->idx is set to the cell index that contains the pointer
** to the page we are coming from.  If we are coming from the
** right-most child page then pCur->idx is set to one more than
** the largest cell index.
*/
static void sqlite3BtreeMoveToParent(BtCursor *pCur){
SQLITE_PRIVATE void sqlite3BtreeMoveToParent(BtCursor *pCur){
  MemPage *pParent;
  MemPage *pPage;
  int idxParent;

  assert( pCur->eState==CURSOR_VALID );
  pPage = pCur->pPage;
  assert( pPage!=0 );
25919
25920
25921
25922
25923
25924
25925
25926

25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945

25946
25947
25948
25949
25950
25951
25952
26031
26032
26033
26034
26035
26036
26037

26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056

26057
26058
26059
26060
26061
26062
26063
26064







-
+


















-
+







  return SQLITE_OK;
}

/* Move the cursor to the first entry in the table.  Return SQLITE_OK
** on success.  Set *pRes to 0 if the cursor actually points to something
** or set *pRes to 1 if the table is empty.
*/
static int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  int rc;
  rc = moveToRoot(pCur);
  if( rc ) return rc;
  if( pCur->eState==CURSOR_INVALID ){
    assert( pCur->pPage->nCell==0 );
    *pRes = 1;
    return SQLITE_OK;
  }
  assert( pCur->pPage->nCell>0 );
  *pRes = 0;
  rc = moveToLeftmost(pCur);
  return rc;
}

/* Move the cursor to the last entry in the table.  Return SQLITE_OK
** on success.  Set *pRes to 0 if the cursor actually points to something
** or set *pRes to 1 if the table is empty.
*/
static int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  int rc;
  rc = moveToRoot(pCur);
  if( rc ) return rc;
  if( CURSOR_INVALID==pCur->eState ){
    assert( pCur->pPage->nCell==0 );
    *pRes = 1;
    return SQLITE_OK;
25980
25981
25982
25983
25984
25985
25986
25987

25988
25989
25990
25991
25992
25993
25994
26092
26093
26094
26095
26096
26097
26098

26099
26100
26101
26102
26103
26104
26105
26106







-
+







**
**     *pRes==0     The cursor is left pointing at an entry that
**                  exactly matches pKey.
**
**     *pRes>0      The cursor is left pointing at an entry that
**                  is larger than pKey.
*/
static int sqlite3BtreeMoveto(
SQLITE_PRIVATE int sqlite3BtreeMoveto(
  BtCursor *pCur,        /* The cursor to be moved */
  const void *pKey,      /* The key content for indices.  Not used by tables */
  i64 nKey,              /* Size of pKey.  Or the key for tables */
  int biasRight,         /* If true, bias the search to the high end */
  int *pRes              /* Search result flag */
){
  int rc;
26097
26098
26099
26100
26101
26102
26103
26104

26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118

26119
26120
26121
26122
26123
26124
26125
26209
26210
26211
26212
26213
26214
26215

26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229

26230
26231
26232
26233
26234
26235
26236
26237







-
+













-
+







/*
** Return TRUE if the cursor is not pointing at an entry of the table.
**
** TRUE will be returned after a call to sqlite3BtreeNext() moves
** past the last entry in the table or sqlite3BtreePrev() moves past
** the first entry.  TRUE is also returned if the table is empty.
*/
static int sqlite3BtreeEof(BtCursor *pCur){
SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  ** have been deleted? This API will need to change to return an error code
  ** as well as the boolean result value.
  */
  return (CURSOR_VALID!=pCur->eState);
}

/*
** Advance the cursor to the next entry in the database.  If
** successful then set *pRes=0.  If the cursor
** was already pointing to the last entry in the database before
** this routine was called, then set *pRes=1.
*/
static int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  int rc;
  MemPage *pPage;

  rc = restoreOrClearCursorPosition(pCur);
  if( rc!=SQLITE_OK ){
    return rc;
  }
26176
26177
26178
26179
26180
26181
26182
26183

26184
26185
26186
26187
26188
26189
26190
26288
26289
26290
26291
26292
26293
26294

26295
26296
26297
26298
26299
26300
26301
26302







-
+








/*
** Step the cursor to the back to the previous entry in the database.  If
** successful then set *pRes=0.  If the cursor
** was already pointing to the first entry in the database before
** this routine was called, then set *pRes=1.
*/
static int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  int rc;
  Pgno pgno;
  MemPage *pPage;

  rc = restoreOrClearCursorPosition(pCur);
  if( rc!=SQLITE_OK ){
    return rc;
27907
27908
27909
27910
27911
27912
27913
27914

27915
27916
27917
27918
27919
27920
27921
28019
28020
28021
28022
28023
28024
28025

28026
28027
28028
28029
28030
28031
28032
28033







-
+







** and the data is given by (pData,nData).  The cursor is used only to
** define what table the record should be inserted into.  The cursor
** is left pointing at a random location.
**
** For an INTKEY table, only the nKey value of the key is used.  pKey is
** ignored.  For a ZERODATA table, the pData and nData are both ignored.
*/
static int sqlite3BtreeInsert(
SQLITE_PRIVATE int sqlite3BtreeInsert(
  BtCursor *pCur,                /* Insert data into the table of this cursor */
  const void *pKey, i64 nKey,    /* The key of the new record */
  const void *pData, int nData,  /* The data of the new record */
  int nZero,                     /* Number of extra 0 bytes to append to data */
  int appendBias                 /* True if this is likely an append */
){
  int rc;
27993
27994
27995
27996
27997
27998
27999
28000

28001
28002
28003
28004
28005
28006
28007
28105
28106
28107
28108
28109
28110
28111

28112
28113
28114
28115
28116
28117
28118
28119







-
+







  return rc;
}

/*
** Delete the entry that the cursor is pointing to.  The cursor
** is left pointing at a random location.
*/
static int sqlite3BtreeDelete(BtCursor *pCur){
SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  MemPage *pPage = pCur->pPage;
  unsigned char *pCell;
  int rc;
  Pgno pgnoChild = 0;
  BtShared *pBt = pCur->pBtree->pBt;

  assert( pPage->isInit );
28109
28110
28111
28112
28113
28114
28115
28116

28117
28118
28119
28120
28121
28122
28123
28221
28222
28223
28224
28225
28226
28227

28228
28229
28230
28231
28232
28233
28234
28235







-
+







** The type of type is determined by the flags parameter.  Only the
** following values of flags are currently in use.  Other values for
** flags might not work:
**
**     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
**     BTREE_ZERODATA                  Used for SQL indices
*/
static int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  BtShared *pBt = p->pBt;
  MemPage *pRoot;
  Pgno pgnoRoot;
  int rc;
  if( pBt->inTransaction!=TRANS_WRITE ){
    /* Must start a transaction first */
    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
28288
28289
28290
28291
28292
28293
28294
28295

28296
28297
28298
28299
28300
28301
28302
28400
28401
28402
28403
28404
28405
28406

28407
28408
28409
28410
28411
28412
28413
28414







-
+







** the page number of the root of the table.  After this routine returns,
** the root page is empty, but still exists.
**
** This routine will fail with SQLITE_LOCKED if there are any open
** read cursors on the table.  Open write cursors are moved to the
** root of the table.
*/
static int sqlite3BtreeClearTable(Btree *p, int iTable){
SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable){
  int rc;
  BtShared *pBt = p->pBt;
  if( p->inTrans!=TRANS_WRITE ){
    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  }
  rc = checkReadLocks(p, iTable, 0);
  if( rc ){
28327
28328
28329
28330
28331
28332
28333
28334

28335
28336
28337
28338
28339
28340
28341
28439
28440
28441
28442
28443
28444
28445

28446
28447
28448
28449
28450
28451
28452
28453







-
+







** root pages are kept at the beginning of the database file, which
** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
** page number that used to be the last root page in the file before
** the move.  If no page gets moved, *piMoved is set to 0.
** The last root page is recorded in meta[3] and the value of
** meta[3] is updated by this procedure.
*/
static int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  int rc;
  MemPage *pPage = 0;
  BtShared *pBt = p->pBt;

  if( p->inTrans!=TRANS_WRITE ){
    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  }
28445
28446
28447
28448
28449
28450
28451
28452

28453
28454
28455
28456
28457
28458
28459
28557
28558
28559
28560
28561
28562
28563

28564
28565
28566
28567
28568
28569
28570
28571







-
+







** through meta[15] are available for use by higher layers.  Meta[0]
** is read-only, the others are read/write.
** 
** The schema layer numbers meta values differently.  At the schema
** layer (and the SetCookie and ReadCookie opcodes) the number of
** free pages is not visible.  So Cookie[0] is the same as Meta[1].
*/
static int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
SQLITE_PRIVATE int sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  DbPage *pDbPage;
  int rc;
  unsigned char *pP1;
  BtShared *pBt = p->pBt;

  /* Reading a meta-data value requires a read-lock on page 1 (and hence
  ** the sqlite_master table. We grab this lock regardless of whether or
28484
28485
28486
28487
28488
28489
28490
28491

28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503





28504
28505
28506
28507
28508
28509
28510
28511

28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524

28525
28526
28527
28528
28529
28530
28531
28596
28597
28598
28599
28600
28601
28602

28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627

28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640

28641
28642
28643
28644
28645
28646
28647
28648







-
+












+
+
+
+
+







-
+












-
+







  return rc;
}

/*
** Write meta-information back into the database.  Meta[0] is
** read-only and may not be written.
*/
static int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  BtShared *pBt = p->pBt;
  unsigned char *pP1;
  int rc;
  assert( idx>=1 && idx<=15 );
  if( p->inTrans!=TRANS_WRITE ){
    return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  }
  assert( pBt->pPage1!=0 );
  pP1 = pBt->pPage1->aData;
  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  if( rc ) return rc;
  put4byte(&pP1[36 + idx*4], iMeta);
  if( idx==7 ){
    assert( pBt->autoVacuum || iMeta==0 );
    assert( iMeta==0 || iMeta==1 );
    pBt->incrVacuum = iMeta;
  }
  return SQLITE_OK;
}

/*
** Return the flag byte at the beginning of the page that the cursor
** is currently pointing to.
*/
static int sqlite3BtreeFlags(BtCursor *pCur){
SQLITE_PRIVATE int sqlite3BtreeFlags(BtCursor *pCur){
  /* TODO: What about CURSOR_REQUIRESEEK state? Probably need to call
  ** restoreOrClearCursorPosition() here.
  */
  MemPage *pPage = pCur->pPage;
  return pPage ? pPage->aData[pPage->hdrOffset] : 0;
}


/*
** Return the pager associated with a BTree.  This routine is used for
** testing and debugging only.
*/
static Pager *sqlite3BtreePager(Btree *p){
SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  return p->pBt->pPager;
}

#ifndef SQLITE_OMIT_INTEGRITY_CHECK
/*
** Append a message to the error message string.
*/
28852
28853
28854
28855
28856
28857
28858
28859

28860
28861
28862
28863
28864
28865
28866
28969
28970
28971
28972
28973
28974
28975

28976
28977
28978
28979
28980
28981
28982
28983







-
+







** a table.  nRoot is the number of entries in aRoot.
**
** If everything checks out, this routine returns NULL.  If something is
** amiss, an error message is written into memory obtained from malloc()
** and a pointer to that error message is returned.  The calling function
** is responsible for freeing the error message when it is done.
*/
static char *sqlite3BtreeIntegrityCheck(
SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  Btree *p,     /* The btree to be checked */
  int *aRoot,   /* An array of root pages numbers for individual trees */
  int nRoot,    /* Number of entries in aRoot[] */
  int mxErr,    /* Stop reporting errors after this many */
  int *pnErr    /* Write number of errors seen to this variable */
){
  int i;
28957
28958
28959
28960
28961
28962
28963
28964

28965
28966
28967
28968
28969
28970
28971
28972

28973
28974
28975
28976
28977
28978
28979
28980
28981
28982

28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995

28996
28997
28998
28999
29000
29001
29002
29074
29075
29076
29077
29078
29079
29080

29081
29082
29083
29084
29085
29086
29087
29088

29089
29090
29091
29092
29093
29094
29095
29096
29097
29098

29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111

29112
29113
29114
29115
29116
29117
29118
29119







-
+







-
+









-
+












-
+







  return sCheck.zErrMsg;
}
#endif /* SQLITE_OMIT_INTEGRITY_CHECK */

/*
** Return the full pathname of the underlying database file.
*/
static const char *sqlite3BtreeGetFilename(Btree *p){
SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerFilename(p->pBt->pPager);
}

/*
** Return the pathname of the directory that contains the database file.
*/
static const char *sqlite3BtreeGetDirname(Btree *p){
SQLITE_PRIVATE const char *sqlite3BtreeGetDirname(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerDirname(p->pBt->pPager);
}

/*
** Return the pathname of the journal file for this database. The return
** value of this routine is the same regardless of whether the journal file
** has been created or not.
*/
static const char *sqlite3BtreeGetJournalname(Btree *p){
SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerJournalname(p->pBt->pPager);
}

#ifndef SQLITE_OMIT_VACUUM
/*
** Copy the complete content of pBtFrom into pBtTo.  A transaction
** must be active for both files.
**
** The size of file pBtFrom may be reduced by this operation.
** If anything goes wrong, the transaction on pBtFrom is rolled back.
*/
static int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  int rc = SQLITE_OK;
  Pgno i, nPage, nToPage, iSkip;

  BtShared *pBtTo = pTo->pBt;
  BtShared *pBtFrom = pFrom->pBt;

  if( pTo->inTrans!=TRANS_WRITE || pFrom->inTrans!=TRANS_WRITE ){
29045
29046
29047
29048
29049
29050
29051
29052

29053
29054
29055
29056
29057
29058
29059

29060
29061
29062
29063
29064
29065
29066

29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086

29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099

29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110

29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129

29130
29131
29132
29133
29134
29135
29136
29162
29163
29164
29165
29166
29167
29168

29169
29170
29171
29172
29173
29174
29175

29176
29177
29178
29179
29180
29181
29182

29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202

29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215

29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226

29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245

29246
29247
29248
29249
29250
29251
29252
29253







-
+






-
+






-
+



















-
+












-
+










-
+


















-
+







  return rc;  
}
#endif /* SQLITE_OMIT_VACUUM */

/*
** Return non-zero if a transaction is active.
*/
static int sqlite3BtreeIsInTrans(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  return (p && (p->inTrans==TRANS_WRITE));
}

/*
** Return non-zero if a statement transaction is active.
*/
static int sqlite3BtreeIsInStmt(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeIsInStmt(Btree *p){
  return (p->pBt && p->pBt->inStmt);
}

/*
** Return non-zero if a read (or write) transaction is active.
*/
static int sqlite3BtreeIsInReadTrans(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  return (p && (p->inTrans!=TRANS_NONE));
}

/*
** This function returns a pointer to a blob of memory associated with
** a single shared-btree. The memory is used by client code for it's own
** purposes (for example, to store a high-level schema associated with 
** the shared-btree). The btree layer manages reference counting issues.
**
** The first time this is called on a shared-btree, nBytes bytes of memory
** are allocated, zeroed, and returned to the caller. For each subsequent 
** call the nBytes parameter is ignored and a pointer to the same blob
** of memory returned. 
**
** Just before the shared-btree is closed, the function passed as the 
** xFree argument when the memory allocation was made is invoked on the 
** blob of allocated memory. This function should not call sqliteFree()
** on the memory, the btree layer does that.
*/
static void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  BtShared *pBt = p->pBt;
  if( !pBt->pSchema ){
    pBt->pSchema = sqliteMalloc(nBytes);
    pBt->xFreeSchema = xFree;
  }
  return pBt->pSchema;
}

/*
** Return true if another user of the same shared btree as the argument
** handle holds an exclusive lock on the sqlite_master table.
*/
static int sqlite3BtreeSchemaLocked(Btree *p){
SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  return (queryTableLock(p, MASTER_ROOT, READ_LOCK)!=SQLITE_OK);
}


#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** Obtain a lock on the table whose root page is iTab.  The
** lock is a write lock if isWritelock is true or a read lock
** if it is false.
*/
static int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  int rc = SQLITE_OK;
  u8 lockType = (isWriteLock?WRITE_LOCK:READ_LOCK);
  rc = queryTableLock(p, iTab, lockType);
  if( rc==SQLITE_OK ){
    rc = lockTable(p, iTab, lockType);
  }
  return rc;
}
#endif

#ifndef SQLITE_OMIT_INCRBLOB
/*
** Argument pCsr must be a cursor opened for writing on an 
** INTKEY table currently pointing at a valid table entry. 
** This function modifies the data stored as part of that entry.
** Only the data content may only be modified, it is not possible
** to change the length of the data stored.
*/
static int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){

  assert(pCsr->isIncrblobHandle);
  if( pCsr->eState==CURSOR_REQUIRESEEK ){
    return SQLITE_ABORT;
  }

  /* Check some preconditions: 
29159
29160
29161
29162
29163
29164
29165
29166

29167
29168
29169
29170
29171
29172
29173
29276
29277
29278
29279
29280
29281
29282

29283
29284
29285
29286
29287
29288
29289
29290







-
+







** for incremental blob IO only.
**
** This function sets a flag only. The actual page location cache
** (stored in BtCursor.aOverflow[]) is allocated and used by function
** accessPayload() (the worker function for sqlite3BtreeData() and
** sqlite3BtreePutData()).
*/
static void sqlite3BtreeCacheOverflow(BtCursor *pCur){
SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  assert(!pCur->isIncrblobHandle);
  assert(!pCur->aOverflow);
  pCur->isIncrblobHandle = 1;
}
#endif

/************** End of btree.c ***********************************************/
29205
29206
29207
29208
29209
29210
29211
29212

29213
29214
29215
29216
29217
29218
29219
29220
29221

29222
29223
29224
29225
29226
29227
29228
29322
29323
29324
29325
29326
29327
29328

29329
29330
29331
29332
29333
29334
29335
29336
29337

29338
29339
29340
29341
29342
29343
29344
29345







-
+








-
+







  }
  return pPage;
}

/*
** Initialize a Fifo structure.
*/
static void sqlite3VdbeFifoInit(Fifo *pFifo){
SQLITE_PRIVATE void sqlite3VdbeFifoInit(Fifo *pFifo){
  memset(pFifo, 0, sizeof(*pFifo));
}

/*
** Push a single 64-bit integer value into the Fifo.  Return SQLITE_OK
** normally.   SQLITE_NOMEM is returned if we are unable to allocate
** memory.
*/
static int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
SQLITE_PRIVATE int sqlite3VdbeFifoPush(Fifo *pFifo, i64 val){
  FifoPage *pPage;
  pPage = pFifo->pLast;
  if( pPage==0 ){
    pPage = pFifo->pLast = pFifo->pFirst = allocateFifoPage(20);
    if( pPage==0 ){
      return SQLITE_NOMEM;
    }
29239
29240
29241
29242
29243
29244
29245
29246

29247
29248
29249
29250
29251
29252
29253
29356
29357
29358
29359
29360
29361
29362

29363
29364
29365
29366
29367
29368
29369
29370







-
+







}

/*
** Extract a single 64-bit integer value from the Fifo.  The integer
** extracted is the one least recently inserted.  If the Fifo is empty
** return SQLITE_DONE.
*/
static int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
SQLITE_PRIVATE int sqlite3VdbeFifoPop(Fifo *pFifo, i64 *pVal){
  FifoPage *pPage;
  if( pFifo->nEntry==0 ){
    return SQLITE_DONE;
  }
  assert( pFifo->nEntry>0 );
  pPage = pFifo->pFirst;
  assert( pPage!=0 );
29272
29273
29274
29275
29276
29277
29278
29279

29280
29281
29282
29283
29284
29285
29286
29389
29390
29391
29392
29393
29394
29395

29396
29397
29398
29399
29400
29401
29402
29403







-
+







  return SQLITE_OK;
}

/*
** Delete all information from a Fifo object.   Free all memory held
** by the Fifo.
*/
static void sqlite3VdbeFifoClear(Fifo *pFifo){
SQLITE_PRIVATE void sqlite3VdbeFifoClear(Fifo *pFifo){
  FifoPage *pPage, *pNextPage;
  for(pPage=pFifo->pFirst; pPage; pPage=pNextPage){
    pNextPage = pPage->pNext;
    sqliteFree(pPage);
  }
  sqlite3VdbeFifoInit(pFifo);
}
29320
29321
29322
29323
29324
29325
29326
29327

29328
29329
29330
29331
29332
29333
29334
29437
29438
29439
29440
29441
29442
29443

29444
29445
29446
29447
29448
29449
29450
29451







-
+







** representation is already stored using the requested encoding, then this
** routine is a no-op.
**
** SQLITE_OK is returned if the conversion is successful (or not required).
** SQLITE_NOMEM may be returned if a malloc() fails during conversion
** between formats.
*/
static int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  int rc;
  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
    return SQLITE_OK;
  }
#ifdef SQLITE_OMIT_UTF16
  return SQLITE_ERROR;
#else
29346
29347
29348
29349
29350
29351
29352
29353

29354
29355
29356
29357
29358
29359
29360
29463
29464
29465
29466
29467
29468
29469

29470
29471
29472
29473
29474
29475
29476
29477







-
+







}

/*
** Make the given Mem object MEM_Dyn.
**
** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
*/
static int sqlite3VdbeMemDynamicify(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemDynamicify(Mem *pMem){
  int n;
  u8 *z;
  expandBlob(pMem);
  if( (pMem->flags & (MEM_Ephem|MEM_Static|MEM_Short))==0 ){
    return SQLITE_OK;
  }
  assert( (pMem->flags & MEM_Dyn)==0 );
29375
29376
29377
29378
29379
29380
29381
29382

29383
29384
29385
29386
29387
29388
29389
29492
29493
29494
29495
29496
29497
29498

29499
29500
29501
29502
29503
29504
29505
29506







-
+







}

/*
** If the given Mem* has a zero-filled tail, turn it into an ordinary
** blob stored in dynamically allocated space.
*/
#ifndef SQLITE_OMIT_INCRBLOB
static int sqlite3VdbeMemExpandBlob(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  if( pMem->flags & MEM_Zero ){
    char *pNew;
    int nByte;
    assert( (pMem->flags & MEM_Blob)!=0 );
    nByte = pMem->n + pMem->u.i;
    if( nByte<=0 ) nByte = 1;
    pNew = sqliteMalloc(nByte);
29406
29407
29408
29409
29410
29411
29412
29413

29414
29415
29416
29417
29418
29419
29420
29523
29524
29525
29526
29527
29528
29529

29530
29531
29532
29533
29534
29535
29536
29537







-
+








/*
** Make the given Mem object either MEM_Short or MEM_Dyn so that bytes
** of the Mem.z[] array can be modified.
**
** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
*/
static int sqlite3VdbeMemMakeWriteable(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  int n;
  u8 *z;
  expandBlob(pMem);
  if( (pMem->flags & (MEM_Ephem|MEM_Static))==0 ){
    return SQLITE_OK;
  }
  assert( (pMem->flags & MEM_Dyn)==0 );
29438
29439
29440
29441
29442
29443
29444
29445

29446
29447
29448
29449
29450
29451
29452
29555
29556
29557
29558
29559
29560
29561

29562
29563
29564
29565
29566
29567
29568
29569







-
+







  assert(0==(1&(int)pMem->z));
  return SQLITE_OK;
}

/*
** Make sure the given Mem is \u0000 terminated.
*/
static int sqlite3VdbeMemNulTerminate(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
    return SQLITE_OK;   /* Nothing to do */
  }
  if( pMem->flags & (MEM_Static|MEM_Ephem) ){
    return sqlite3VdbeMemMakeWriteable(pMem);
  }else{
    char *z; 
29478
29479
29480
29481
29482
29483
29484
29485

29486
29487
29488
29489
29490
29491
29492
29595
29596
29597
29598
29599
29600
29601

29602
29603
29604
29605
29606
29607
29608
29609







-
+







**
** A MEM_Null value will never be passed to this function. This function is
** used for converting values to text for returning to the user (i.e. via
** sqlite3_value_text()), or for ensuring that values to be used as btree
** keys are strings. In the former case a NULL pointer is returned the
** user and the later is an internal programming error.
*/
static int sqlite3VdbeMemStringify(Mem *pMem, int enc){
SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  int rc = SQLITE_OK;
  int fg = pMem->flags;
  char *z = pMem->zShort;

  assert( !(fg&MEM_Zero) );
  assert( !(fg&(MEM_Str|MEM_Blob)) );
  assert( fg&(MEM_Int|MEM_Real) );
29515
29516
29517
29518
29519
29520
29521
29522

29523
29524
29525
29526
29527
29528
29529
29632
29633
29634
29635
29636
29637
29638

29639
29640
29641
29642
29643
29644
29645
29646







-
+







** Memory cell pMem contains the context of an aggregate function.
** This routine calls the finalize method for that function.  The
** result of the aggregate is stored back into pMem.
**
** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
** otherwise.
*/
static int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  int rc = SQLITE_OK;
  if( pFunc && pFunc->xFinalize ){
    sqlite3_context ctx;
    assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
    ctx.s.flags = MEM_Null;
    ctx.s.z = pMem->zShort;
    ctx.pMem = pMem;
29545
29546
29547
29548
29549
29550
29551
29552

29553
29554
29555
29556
29557
29558
29559
29662
29663
29664
29665
29666
29667
29668

29669
29670
29671
29672
29673
29674
29675
29676







-
+







}

/*
** Release any memory held by the Mem. This may leave the Mem in an
** inconsistent state, for example with (Mem.z==0) and
** (Mem.type==SQLITE_TEXT).
*/
static void sqlite3VdbeMemRelease(Mem *p){
SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  if( p->flags & (MEM_Dyn|MEM_Agg) ){
    if( p->xDel ){
      if( p->flags & MEM_Agg ){
        sqlite3VdbeMemFinalize(p, p->u.pDef);
        assert( (p->flags & MEM_Agg)==0 );
        sqlite3VdbeMemRelease(p);
      }else{
29573
29574
29575
29576
29577
29578
29579
29580

29581
29582
29583
29584
29585
29586
29587
29690
29691
29692
29693
29694
29695
29696

29697
29698
29699
29700
29701
29702
29703
29704







-
+







** If pMem is an integer, then the value is exact.  If pMem is
** a floating-point then the value returned is the integer part.
** If pMem is a string or blob, then we make an attempt to convert
** it into a integer and return that.  If pMem is NULL, return 0.
**
** If pMem is a string, its encoding might be changed.
*/
static i64 sqlite3VdbeIntValue(Mem *pMem){
SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  int flags = pMem->flags;
  if( flags & MEM_Int ){
    return pMem->u.i;
  }else if( flags & MEM_Real ){
    return (i64)pMem->r;
  }else if( flags & (MEM_Str|MEM_Blob) ){
    i64 value;
29600
29601
29602
29603
29604
29605
29606
29607

29608
29609
29610
29611
29612
29613
29614
29717
29718
29719
29720
29721
29722
29723

29724
29725
29726
29727
29728
29729
29730
29731







-
+








/*
** Return the best representation of pMem that we can get into a
** double.  If pMem is already a double or an integer, return its
** value.  If it is a string or blob, try to convert it to a double.
** If it is a NULL, return 0.0.
*/
static double sqlite3VdbeRealValue(Mem *pMem){
SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  if( pMem->flags & MEM_Real ){
    return pMem->r;
  }else if( pMem->flags & MEM_Int ){
    return (double)pMem->u.i;
  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
    double val = 0.0;
    pMem->flags |= MEM_Str;
29624
29625
29626
29627
29628
29629
29630
29631

29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642

29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653

29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664

29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685

29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696

29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711

29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723


29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737

29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754

29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768

29769
29770
29771
29772
29773
29774
29775
29741
29742
29743
29744
29745
29746
29747

29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758

29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769

29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780

29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801

29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812

29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827

29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838


29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853

29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870

29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884

29885
29886
29887
29888
29889
29890
29891
29892







-
+










-
+










-
+










-
+




















-
+










-
+














-
+










-
-
+
+













-
+
















-
+













-
+







  }
}

/*
** The MEM structure is already a MEM_Real.  Try to also make it a
** MEM_Int if we can.
*/
static void sqlite3VdbeIntegerAffinity(Mem *pMem){
SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  assert( pMem->flags & MEM_Real );
  pMem->u.i = pMem->r;
  if( ((double)pMem->u.i)==pMem->r ){
    pMem->flags |= MEM_Int;
  }
}

/*
** Convert pMem to type integer.  Invalidate any prior representations.
*/
static int sqlite3VdbeMemIntegerify(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  pMem->u.i = sqlite3VdbeIntValue(pMem);
  sqlite3VdbeMemRelease(pMem);
  pMem->flags = MEM_Int;
  return SQLITE_OK;
}

/*
** Convert pMem so that it is of type MEM_Real.
** Invalidate any prior representations.
*/
static int sqlite3VdbeMemRealify(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  pMem->r = sqlite3VdbeRealValue(pMem);
  sqlite3VdbeMemRelease(pMem);
  pMem->flags = MEM_Real;
  return SQLITE_OK;
}

/*
** Convert pMem so that it has types MEM_Real or MEM_Int or both.
** Invalidate any prior representations.
*/
static int sqlite3VdbeMemNumerify(Mem *pMem){
SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  double r1, r2;
  i64 i;
  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  r1 = sqlite3VdbeRealValue(pMem);
  i = (i64)r1;
  r2 = (double)i;
  if( r1==r2 ){
    sqlite3VdbeMemIntegerify(pMem);
  }else{
    pMem->r = r1;
    pMem->flags = MEM_Real;
    sqlite3VdbeMemRelease(pMem);
  }
  return SQLITE_OK;
}

/*
** Delete any previous value and set the value stored in *pMem to NULL.
*/
static void sqlite3VdbeMemSetNull(Mem *pMem){
SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  sqlite3VdbeMemRelease(pMem);
  pMem->flags = MEM_Null;
  pMem->type = SQLITE_NULL;
  pMem->n = 0;
}

/*
** Delete any previous value and set the value to be a BLOB of length
** n containing all zeros.
*/
static void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  sqlite3VdbeMemRelease(pMem);
  pMem->flags = MEM_Blob|MEM_Zero|MEM_Short;
  pMem->type = SQLITE_BLOB;
  pMem->n = 0;
  if( n<0 ) n = 0;
  pMem->u.i = n;
  pMem->z = pMem->zShort;
  pMem->enc = SQLITE_UTF8;
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type INTEGER.
*/
static void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  sqlite3VdbeMemRelease(pMem);
  pMem->u.i = val;
  pMem->flags = MEM_Int;
  pMem->type = SQLITE_INTEGER;
}

/*
** Delete any previous value and set the value stored in *pMem to val,
** manifest type REAL.
*/
static void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  if( isnan(val) ){
SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  if( sqlite3_isnan(val) ){
    sqlite3VdbeMemSetNull(pMem);
  }else{
    sqlite3VdbeMemRelease(pMem);
    pMem->r = val;
    pMem->flags = MEM_Real;
    pMem->type = SQLITE_FLOAT;
  }
}

/*
** Return true if the Mem object contains a TEXT or BLOB that is
** too large - whose size exceeds SQLITE_MAX_LENGTH.
*/
static int sqlite3VdbeMemTooBig(Mem *p){
SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  if( p->flags & (MEM_Str|MEM_Blob) ){
    int n = p->n;
    if( p->flags & MEM_Zero ){
      n += p->u.i;
    }
    return n>SQLITE_MAX_LENGTH;
  }
  return 0; 
}

/*
** Make an shallow copy of pFrom into pTo.  Prior contents of
** pTo are overwritten.  The pFrom->z field is not duplicated.  If
** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
** and flags gets srcType (either MEM_Ephem or MEM_Static).
*/
static void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  memcpy(pTo, pFrom, sizeof(*pFrom)-sizeof(pFrom->zShort));
  pTo->xDel = 0;
  if( pTo->flags & (MEM_Str|MEM_Blob) ){
    pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short|MEM_Ephem);
    assert( srcType==MEM_Ephem || srcType==MEM_Static );
    pTo->flags |= srcType;
  }
}

/*
** Make a full copy of pFrom into pTo.  Prior contents of pTo are
** freed before the copy is made.
*/
static int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  int rc;
  if( pTo->flags & MEM_Dyn ){
    sqlite3VdbeMemRelease(pTo);
  }
  sqlite3VdbeMemShallowCopy(pTo, pFrom, MEM_Ephem);
  if( pTo->flags & MEM_Ephem ){
    rc = sqlite3VdbeMemMakeWriteable(pTo);
29783
29784
29785
29786
29787
29788
29789
29790

29791
29792
29793
29794
29795
29796
29797
29900
29901
29902
29903
29904
29905
29906

29907
29908
29909
29910
29911
29912
29913
29914







-
+







** Transfer the contents of pFrom to pTo. Any existing value in pTo is
** freed. If pFrom contains ephemeral data, a copy is made.
**
** pFrom contains an SQL NULL when this routine returns.  SQLITE_NOMEM
** might be returned if pFrom held ephemeral data and we were unable
** to allocate enough space to make a copy.
*/
static int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
SQLITE_PRIVATE int sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  int rc;
  if( pTo->flags & MEM_Dyn ){
    sqlite3VdbeMemRelease(pTo);
  }
  memcpy(pTo, pFrom, sizeof(Mem));
  if( pFrom->flags & MEM_Short ){
    pTo->z = pTo->zShort;
29805
29806
29807
29808
29809
29810
29811
29812

29813
29814
29815
29816
29817
29818
29819
29922
29923
29924
29925
29926
29927
29928

29929
29930
29931
29932
29933
29934
29935
29936







-
+







  }
  return rc;
}

/*
** Change the value of a Mem to be a string or a BLOB.
*/
static int sqlite3VdbeMemSetStr(
SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  Mem *pMem,          /* Memory cell to set to string value */
  const char *z,      /* String pointer */
  int n,              /* Bytes in string, or negative */
  u8 enc,             /* Encoding of z.  0 for BLOBs */
  void (*xDel)(void*) /* Destructor function */
){
  sqlite3VdbeMemRelease(pMem);
29877
29878
29879
29880
29881
29882
29883
29884

29885
29886
29887
29888
29889
29890
29891
29994
29995
29996
29997
29998
29999
30000

30001
30002
30003
30004
30005
30006
30007
30008







-
+







** negative, zero or positive if pMem1 is less than, equal to, or greater
** than pMem2. Sorting order is NULL's first, followed by numbers (integers
** and reals) sorted numerically, followed by text ordered by the collating
** sequence pColl and finally blob's ordered by memcmp().
**
** Two NULL values are considered equal by this function.
*/
static int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  int rc;
  int f1, f2;
  int combined_flags;

  /* Interchange pMem1 and pMem2 if the collating sequence specifies
  ** DESC order.
  */
30002
30003
30004
30005
30006
30007
30008
30009

30010
30011
30012
30013
30014
30015
30016
30119
30120
30121
30122
30123
30124
30125

30126
30127
30128
30129
30130
30131
30132
30133







-
+







**
** The pMem structure is assumed to be uninitialized.  Any prior content
** is overwritten without being freed.
**
** If this routine fails for any reason (malloc returns NULL or unable
** to read from the disk) then the pMem is left in an inconsistent state.
*/
static int sqlite3VdbeMemFromBtree(
SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
  int offset,       /* Offset from the start of data to return bytes from. */
  int amt,          /* Number of bytes to return. */
  int key,          /* If true, retrieve from the btree key, not data. */
  Mem *pMem         /* OUT: Return data in this Mem structure. */
){
  char *zData;       /* Data from the btree layer */
30068
30069
30070
30071
30072
30073
30074
30075

30076
30077
30078
30079
30080
30081
30082
30185
30186
30187
30188
30189
30190
30191

30192
30193
30194
30195
30196
30197
30198
30199







-
+







}

#ifndef NDEBUG
/*
** Perform various checks on the memory cell pMem. An assert() will
** fail if pMem is internally inconsistent.
*/
static void sqlite3VdbeMemSanity(Mem *pMem){
SQLITE_PRIVATE void sqlite3VdbeMemSanity(Mem *pMem){
  int flags = pMem->flags;
  assert( flags!=0 );  /* Must define some type */
  if( flags & (MEM_Str|MEM_Blob) ){
    int x = flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
    assert( x!=0 );            /* Strings must define a string subtype */
    assert( (x & (x-1))==0 );  /* Only one string subtype can be defined */
    assert( pMem->z!=0 );      /* Strings must have a value */
30122
30123
30124
30125
30126
30127
30128
30129

30130
30131
30132
30133
30134
30135
30136
30239
30240
30241
30242
30243
30244
30245

30246
30247
30248
30249
30250
30251
30252
30253







-
+







** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
** SQLITE_UTF8.
**
** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
** If that is the case, then the result must be aligned on an even byte
** boundary.
*/
static const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  if( !pVal ) return 0;
  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );

  if( pVal->flags&MEM_Null ){
    return 0;
  }
  assert( (MEM_Blob>>3) == MEM_Str );
30157
30158
30159
30160
30161
30162
30163
30164

30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183

30184
30185
30186
30187
30188
30189
30190
30274
30275
30276
30277
30278
30279
30280

30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299

30300
30301
30302
30303
30304
30305
30306
30307







-
+


















-
+







    return 0;
  }
}

/*
** Create a new sqlite3_value object.
*/
static sqlite3_value *sqlite3ValueNew(void){
SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(void){
  Mem *p = sqliteMalloc(sizeof(*p));
  if( p ){
    p->flags = MEM_Null;
    p->type = SQLITE_NULL;
  }
  return p;
}

/*
** Create a new sqlite3_value object, containing the value of pExpr.
**
** This only works for very simple expressions that consist of one constant
** token (i.e. "5", "5.1", "NULL", "'a string'"). If the expression can
** be converted directly into a value, then the value is allocated and
** a pointer written to *ppVal. The caller is responsible for deallocating
** the value by passing it to sqlite3ValueFree() later on. If the expression
** cannot be converted to a value, then *ppVal is set to NULL.
*/
static int sqlite3ValueFromExpr(
SQLITE_PRIVATE int sqlite3ValueFromExpr(
  Expr *pExpr, 
  u8 enc, 
  u8 affinity,
  sqlite3_value **ppVal
){
  int op;
  char *zVal = 0;
30235
30236
30237
30238
30239
30240
30241
30242

30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255

30256
30257
30258
30259
30260
30261
30262
30263
30264
30265

30266
30267
30268
30269
30270
30271
30272
30352
30353
30354
30355
30356
30357
30358

30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371

30372
30373
30374
30375
30376
30377
30378
30379
30380
30381

30382
30383
30384
30385
30386
30387
30388
30389







-
+












-
+









-
+







  *ppVal = 0;
  return SQLITE_NOMEM;
}

/*
** Change the string value of an sqlite3_value object
*/
static void sqlite3ValueSetStr(
SQLITE_PRIVATE void sqlite3ValueSetStr(
  sqlite3_value *v, 
  int n, 
  const void *z, 
  u8 enc,
  void (*xDel)(void*)
){
  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
}

/*
** Free an sqlite3_value object
*/
static void sqlite3ValueFree(sqlite3_value *v){
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  if( !v ) return;
  sqlite3ValueSetStr(v, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  sqliteFree(v);
}

/*
** Return the number of bytes in the sqlite3_value object assuming
** that it uses the encoding "enc"
*/
static int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  Mem *p = (Mem*)pVal;
  if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
    if( p->flags & MEM_Zero ){
      return p->n+p->u.i;
    }else{
      return p->n;
    }
30303
30304
30305
30306
30307
30308
30309
30310

30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328

30329
30330
30331
30332
30333
30334
30335
30336
30337

30338
30339
30340
30341
30342
30343
30344

30345
30346
30347
30348
30349
30350
30351
30420
30421
30422
30423
30424
30425
30426

30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444

30445
30446
30447
30448
30449
30450
30451
30452
30453

30454
30455
30456
30457
30458
30459
30460

30461
30462
30463
30464
30465
30466
30467
30468







-
+

















-
+








-
+






-
+







int sqlite3_vdbe_addop_trace = 0;
#endif


/*
** Create a new virtual database engine.
*/
static Vdbe *sqlite3VdbeCreate(sqlite3 *db){
SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  Vdbe *p;
  p = sqliteMalloc( sizeof(Vdbe) );
  if( p==0 ) return 0;
  p->db = db;
  if( db->pVdbe ){
    db->pVdbe->pPrev = p;
  }
  p->pNext = db->pVdbe;
  p->pPrev = 0;
  db->pVdbe = p;
  p->magic = VDBE_MAGIC_INIT;
  return p;
}

/*
** Remember the SQL string for a prepared statement.
*/
static void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n){
  if( p==0 ) return;
  assert( p->zSql==0 );
  p->zSql = sqlite3StrNDup(z, n);
}

/*
** Return the SQL associated with a prepared statement
*/
static const char *sqlite3VdbeGetSql(Vdbe *p){
SQLITE_PRIVATE const char *sqlite3VdbeGetSql(Vdbe *p){
  return p->zSql;
}

/*
** Swap all content between two VDBE structures.
*/
static void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  Vdbe tmp, *pTmp;
  char *zTmp;
  int nTmp;
  tmp = *pA;
  *pA = *pB;
  *pB = tmp;
  pTmp = pA->pNext;
30362
30363
30364
30365
30366
30367
30368
30369

30370
30371
30372
30373
30374
30375
30376
30479
30480
30481
30482
30483
30484
30485

30486
30487
30488
30489
30490
30491
30492
30493







-
+







  pB->nSql = nTmp;
}

#ifdef SQLITE_DEBUG
/*
** Turn tracing on or off
*/
static void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  p->trace = trace;
}
#endif

/*
** Resize the Vdbe.aOp array so that it contains at least N
** elements. If the Vdbe is in VDBE_MAGIC_RUN state, then
30412
30413
30414
30415
30416
30417
30418
30419

30420
30421
30422
30423
30424
30425
30426
30529
30530
30531
30532
30533
30534
30535

30536
30537
30538
30539
30540
30541
30542
30543







-
+







**
**    p1, p2          First two of the three possible operands.
**
** Use the sqlite3VdbeResolveLabel() function to fix an address and
** the sqlite3VdbeChangeP3() function to change the value of the P3
** operand.
*/
static int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
SQLITE_PRIVATE int sqlite3VdbeAddOp(Vdbe *p, int op, int p1, int p2){
  int i;
  VdbeOp *pOp;

  i = p->nOp;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( p->nOpAlloc<=i ){
    resizeOpArray(p, i+1);
30441
30442
30443
30444
30445
30446
30447
30448

30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468

30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488

30489
30490
30491
30492
30493
30494
30495
30558
30559
30560
30561
30562
30563
30564

30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584

30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604

30605
30606
30607
30608
30609
30610
30611
30612







-
+



















-
+



















-
+







#endif
  return i;
}

/*
** Add an opcode that includes the p3 value.
*/
static int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
SQLITE_PRIVATE int sqlite3VdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3,int p3type){
  int addr = sqlite3VdbeAddOp(p, op, p1, p2);
  sqlite3VdbeChangeP3(p, addr, zP3, p3type);
  return addr;
}

/*
** Create a new symbolic label for an instruction that has yet to be
** coded.  The symbolic label is really just a negative number.  The
** label can be used as the P2 value of an operation.  Later, when
** the label is resolved to a specific address, the VDBE will scan
** through its operation list and change all values of P2 which match
** the label into the resolved address.
**
** The VDBE knows that a P2 value is a label because labels are
** always negative and P2 values are suppose to be non-negative.
** Hence, a negative P2 value is a label that has yet to be resolved.
**
** Zero is returned if a malloc() fails.
*/
static int sqlite3VdbeMakeLabel(Vdbe *p){
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  int i;
  i = p->nLabel++;
  assert( p->magic==VDBE_MAGIC_INIT );
  if( i>=p->nLabelAlloc ){
    p->nLabelAlloc = p->nLabelAlloc*2 + 10;
    p->aLabel = sqliteReallocOrFree(p->aLabel,
                                    p->nLabelAlloc*sizeof(p->aLabel[0]));
  }
  if( p->aLabel ){
    p->aLabel[i] = -1;
  }
  return -1-i;
}

/*
** Resolve label "x" to be the address of the next instruction to
** be inserted.  The parameter "x" must have been obtained from
** a prior call to sqlite3VdbeMakeLabel().
*/
static void sqlite3VdbeResolveLabel(Vdbe *p, int x){
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  int j = -1-x;
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( j>=0 && j<p->nLabel );
  if( p->aLabel ){
    p->aLabel[j] = p->nOp;
  }
}
30527
30528
30529
30530
30531
30532
30533
30534

30535
30536
30537
30538
30539
30540
30541
30644
30645
30646
30647
30648
30649
30650

30651
30652
30653
30654
30655
30656
30657
30658







-
+







    NOPUSH_MASK_8 + (((unsigned)NOPUSH_MASK_9)<<16)
  };
  assert( op<32*5 );
  return (masks[op>>5] & (1<<(op&0x1F)));
}

#ifndef NDEBUG
static int sqlite3VdbeOpcodeNoPush(u8 op){
SQLITE_PRIVATE int sqlite3VdbeOpcodeNoPush(u8 op){
  return opcodeNoPush(op);
}
#endif

/*
** Loop through the program looking for P2 values that are negative.
** Each such value is a label.  Resolve the label by setting the P2
30569
30570
30571
30572
30573
30574
30575

30576

30577
30578
30579
30580
30581



30582
30583
30584
30585
30586
30587

30588
30589
30590
30591
30592
30593
30594
30686
30687
30688
30689
30690
30691
30692
30693

30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716







+
-
+





+
+
+






+








    if( opcode==OP_Function || opcode==OP_AggStep 
#ifndef SQLITE_OMIT_VIRTUALTABLE
        || opcode==OP_VUpdate
#endif
    ){
      if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
    }
    }else if( opcode==OP_Halt ){
    if( opcode==OP_Halt ){
      if( pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort ){
        doesStatementRollback = 1;
      }
    }else if( opcode==OP_Statement ){
      hasStatementBegin = 1;
#ifndef SQLITE_OMIT_VIRTUALTABLE
    }else if( opcode==OP_VUpdate || opcode==OP_VRename ){
      doesStatementRollback = 1;
    }else if( opcode==OP_VFilter ){
      int n;
      assert( p->nOp - i >= 3 );
      assert( pOp[-2].opcode==OP_Integer );
      n = pOp[-2].p1;
      if( n>nMaxArgs ) nMaxArgs = n;
#endif
    }
    if( opcodeNoPush(opcode) ){
      nMaxStack--;
    }

    if( pOp->p2>=0 ) continue;
    assert( -1-pOp->p2<p->nLabel );
30613
30614
30615
30616
30617
30618
30619
30620

30621
30622
30623
30624
30625
30626
30627
30628
30629

30630
30631
30632
30633
30634
30635
30636
30735
30736
30737
30738
30739
30740
30741

30742
30743
30744
30745
30746
30747
30748
30749
30750

30751
30752
30753
30754
30755
30756
30757
30758







-
+








-
+







    }
  }
}

/*
** Return the address of the next instruction to be inserted.
*/
static int sqlite3VdbeCurrentAddr(Vdbe *p){
SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  assert( p->magic==VDBE_MAGIC_INIT );
  return p->nOp;
}

/*
** Add a whole list of operations to the operation stack.  Return the
** address of the first operation added.
*/
static int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  int addr;
  assert( p->magic==VDBE_MAGIC_INIT );
  resizeOpArray(p, p->nOp + nOp);
  if( sqlite3MallocFailed() ){
    return 0;
  }
  addr = p->nOp;
30658
30659
30660
30661
30662
30663
30664
30665

30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676

30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688

30689
30690
30691
30692
30693
30694
30695
30780
30781
30782
30783
30784
30785
30786

30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797

30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809

30810
30811
30812
30813
30814
30815
30816
30817







-
+










-
+











-
+








/*
** Change the value of the P1 operand for a specific instruction.
** This routine is useful when a large program is loaded from a
** static array using sqlite3VdbeAddOpList but we want to make a
** few minor changes to the program.
*/
static void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  if( p && addr>=0 && p->nOp>addr && p->aOp ){
    p->aOp[addr].p1 = val;
  }
}

/*
** Change the value of the P2 operand for a specific instruction.
** This routine is useful for setting a jump destination.
*/
static void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
  assert( val>=0 );
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  if( p && addr>=0 && p->nOp>addr && p->aOp ){
    p->aOp[addr].p2 = val;
  }
}

/*
** Change the P2 operand of instruction addr so that it points to
** the address of the next instruction to be coded.
*/
static void sqlite3VdbeJumpHere(Vdbe *p, int addr){
SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  sqlite3VdbeChangeP2(p, addr, p->nOp);
}


/*
** If the input FuncDef structure is ephemeral, then free it.  If
** the FuncDef is not ephermal, then do nothing.
30735
30736
30737
30738
30739
30740
30741
30742

30743
30744
30745
30746
30747
30748
30749
30857
30858
30859
30860
30861
30862
30863

30864
30865
30866
30867
30868
30869
30870
30871







-
+







  }
}


/*
** Change N opcodes starting at addr to No-ops.
*/
static void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
  if( p && p->aOp ){
    VdbeOp *pOp = &p->aOp[addr];
    while( N-- ){
      freeP3(pOp->p3type, pOp->p3);
      memset(pOp, 0, sizeof(pOp[0]));
      pOp->opcode = OP_Noop;
      pOp++;
30772
30773
30774
30775
30776
30777
30778
30779

30780
30781
30782
30783
30784
30785
30786
30894
30895
30896
30897
30898
30899
30900

30901
30902
30903
30904
30905
30906
30907
30908







-
+







** 
** Other values of n (P3_STATIC, P3_COLLSEQ etc.) indicate that zP3 points
** to a string or structure that is guaranteed to exist for the lifetime of
** the Vdbe. In these cases we can just copy the pointer.
**
** If addr<0 then change P3 on the most recently inserted instruction.
*/
static void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
  Op *pOp;
  assert( p==0 || p->magic==VDBE_MAGIC_INIT );
  if( p==0 || p->aOp==0 || sqlite3MallocFailed() ){
    if (n != P3_KEYINFO) {
      freeP3(n, (void*)*(char**)&zP3);
    }
    return;
30829
30830
30831
30832
30833
30834
30835
30836

30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849

30850
30851
30852
30853
30854
30855
30856
30951
30952
30953
30954
30955
30956
30957

30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970

30971
30972
30973
30974
30975
30976
30977
30978







-
+












-
+







}

#ifndef NDEBUG
/*
** Replace the P3 field of the most recently coded instruction with
** comment text.
*/
static void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  va_list ap;
  assert( p->nOp>0 || p->aOp==0 );
  assert( p->aOp==0 || p->aOp[p->nOp-1].p3==0 || sqlite3MallocFailed() );
  va_start(ap, zFormat);
  sqlite3VdbeChangeP3(p, -1, sqlite3VMPrintf(zFormat, ap), P3_DYNAMIC);
  va_end(ap);
}
#endif

/*
** Return the opcode for a given address.
*/
static VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  assert( p->magic==VDBE_MAGIC_INIT );
  assert( (addr>=0 && addr<p->nOp) || sqlite3MallocFailed() );
  return ((addr>=0 && addr<p->nOp)?(&p->aOp[addr]):0);
}

#if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
     || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
30925
30926
30927
30928
30929
30930
30931
30932

30933
30934
30935
30936
30937
30938
30939
31047
31048
31049
31050
31051
31052
31053

31054
31055
31056
31057
31058
31059
31060
31061







-
+







#endif


#if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
/*
** Print a single opcode.  This routine is used for debugging only.
*/
static void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  char *zP3;
  char zPtr[50];
  static const char *zFormat1 = "%4d %-13s %4d %4d %s\n";
  if( pOut==0 ) pOut = stdout;
  zP3 = displayP3(pOp, zPtr, sizeof(zPtr));
  fprintf(pOut, zFormat1,
      pc, sqlite3OpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3);
30956
30957
30958
30959
30960
30961
30962
30963

30964
30965
30966
30967
30968
30969
30970
31078
31079
31080
31081
31082
31083
31084

31085
31086
31087
31088
31089
31090
31091
31092







-
+







/*
** Give a listing of the program in the virtual machine.
**
** The interface is the same as sqlite3VdbeExec().  But instead of
** running the code, it invokes the callback once for each instruction.
** This feature is used to implement "EXPLAIN".
*/
static int sqlite3VdbeList(
SQLITE_PRIVATE int sqlite3VdbeList(
  Vdbe *p                   /* The VDBE */
){
  sqlite3 *db = p->db;
  int i;
  int rc = SQLITE_OK;

  assert( p->explain );
31034
31035
31036
31037
31038
31039
31040
31041

31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058

31059
31060
31061
31062
31063
31064
31065
31156
31157
31158
31159
31160
31161
31162

31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179

31180
31181
31182
31183
31184
31185
31186
31187







-
+
















-
+







}
#endif /* SQLITE_OMIT_EXPLAIN */

#ifdef SQLITE_DEBUG
/*
** Print the SQL that was used to generate a VDBE program.
*/
static void sqlite3VdbePrintSql(Vdbe *p){
SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( nOp<1 ) return;
  pOp = &p->aOp[nOp-1];
  if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
    const char *z = pOp->p3;
    while( isspace(*(u8*)z) ) z++;
    printf("SQL: [%s]\n", z);
  }
}
#endif

#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
static void sqlite3VdbeIOTraceSql(Vdbe *p){
SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( sqlite3_io_trace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[nOp-1];
  if( pOp->opcode==OP_Noop && pOp->p3!=0 ){
    char *z = sqlite3StrDup(pOp->p3);
31087
31088
31089
31090
31091
31092
31093
31094

31095
31096
31097
31098
31099
31100
31101
31209
31210
31211
31212
31213
31214
31215

31216
31217
31218
31219
31220
31221
31222
31223







-
+







** as allocating stack space and initializing the program counter.
** After the VDBE has be prepped, it can be executed by one or more
** calls to sqlite3VdbeExec().  
**
** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
** VDBE_MAGIC_RUN.
*/
static void sqlite3VdbeMakeReady(
SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  Vdbe *p,                       /* The VDBE */
  int nVar,                      /* Number of '?' see in the SQL statement */
  int nMem,                      /* Number of memory cells to allocate */
  int nCursor,                   /* Number of cursors to allocate */
  int isExplain                  /* True if the EXPLAIN keywords is present */
){
  int n;
31168
31169
31170
31171
31172
31173
31174

31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190

31191
31192
31193
31194
31195
31196
31197
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312

31313
31314
31315
31316
31317
31318
31319
31320







+















-
+







  p->errorAction = OE_Abort;
  p->popStack =  0;
  p->explain |= isExplain;
  p->magic = VDBE_MAGIC_RUN;
  p->nChange = 0;
  p->cacheCtr = 1;
  p->minWriteFileFormat = 255;
  p->openedStatement = 0;
#ifdef VDBE_PROFILE
  {
    int i;
    for(i=0; i<p->nOp; i++){
      p->aOp[i].cnt = 0;
      p->aOp[i].cycles = 0;
    }
  }
#endif
}

/*
** Close a cursor and release all the resources that cursor happens
** to hold.
*/
static void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, Cursor *pCx){
  if( pCx==0 ){
    return;
  }
  if( pCx->pCursor ){
    sqlite3BtreeCloseCursor(pCx->pCursor);
  }
  if( pCx->pBt ){
31250
31251
31252
31253
31254
31255
31256

31257
31258
31259
31260
31261
31262
31263
31264
31265

31266
31267
31268
31269
31270
31271
31272
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388

31389
31390
31391
31392
31393
31394
31395
31396







+








-
+







    sqliteFree(p->contextStack);
  }
  p->contextStack = 0;
  p->contextStackDepth = 0;
  p->contextStackTop = 0;
  sqliteFree(p->zErrMsg);
  p->zErrMsg = 0;
  p->resOnStack = 0;
}

/*
** Set the number of result columns that will be returned by this SQL
** statement. This is now set at compile time, rather than during
** execution of the vdbe program so that sqlite3_column_count() can
** be called on an SQL statement before sqlite3_step().
*/
static void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  Mem *pColName;
  int n;
  releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  sqliteFree(p->aColName);
  n = nResColumn*COLNAME_N;
  p->nResColumn = nResColumn;
  p->aColName = pColName = (Mem*)sqliteMalloc( sizeof(Mem)*n );
31283
31284
31285
31286
31287
31288
31289
31290

31291
31292
31293
31294
31295
31296
31297
31407
31408
31409
31410
31411
31412
31413

31414
31415
31416
31417
31418
31419
31420
31421







-
+







** This call must be made after a call to sqlite3VdbeSetNumCols().
**
** If N==P3_STATIC  it means that zName is a pointer to a constant static
** string and we can just copy the pointer. If it is P3_DYNAMIC, then 
** the string is freed using sqliteFree() when the vdbe is finished with
** it. Otherwise, N bytes of zName are copied.
*/
static int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *p, int idx, int var, const char *zName, int N){
  int rc;
  Mem *pColName;
  assert( idx<p->nResColumn );
  assert( var<COLNAME_N );
  if( sqlite3MallocFailed() ) return SQLITE_NOMEM;
  assert( p->aColName!=0 );
  pColName = &(p->aColName[idx+var*p->nResColumn]);
31551
31552
31553
31554
31555
31556
31557
31558

31559
31560
31561
31562
31563
31564
31565
31675
31676
31677
31678
31679
31680
31681

31682
31683
31684
31685
31686
31687
31688
31689







-
+







/*
** Find every active VM other than pVdbe and change its status to
** aborted.  This happens when one VM causes a rollback due to an
** ON CONFLICT ROLLBACK clause (for example).  The other VMs must be
** aborted so that they do not have data rolled out from underneath
** them leading to a segfault.
*/
static void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
SQLITE_PRIVATE void sqlite3AbortOtherActiveVdbes(sqlite3 *db, Vdbe *pExcept){
  Vdbe *pOther;
  for(pOther=db->pVdbe; pOther; pOther=pOther->pNext){
    if( pOther==pExcept ) continue;
    if( pOther->magic!=VDBE_MAGIC_RUN || pOther->pc<0 ) continue;
    checkActiveVdbeCnt(db);
    closeAllCursors(pOther);
    checkActiveVdbeCnt(db);
31575
31576
31577
31578
31579
31580
31581
31582

31583
31584
31585
31586
31587
31588
31589
31699
31700
31701
31702
31703
31704
31705

31706
31707
31708
31709
31710
31711
31712
31713







-
+







** This routine is the only way to move the state of a VM from
** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.
**
** Return an error code.  If the commit could not complete because of
** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
** means the close did not happen and needs to be repeated.
*/
static int sqlite3VdbeHalt(Vdbe *p){
SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  sqlite3 *db = p->db;
  int i;
  int (*xFunc)(Btree *pBt) = 0;  /* Function to call on each btree backend */
  int isSpecialError;            /* Set to true if SQLITE_NOMEM or IOERR */

  /* This function contains the logic that determines if a statement or
  ** transaction will be committed or rolled back as a result of the
31716
31717
31718
31719
31720
31721
31722

31723

31724
31725
31726
31727
31728
31729
31730
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856







+

+







          sqlite3CommitInternalChanges(db);
        }
      }else{
        sqlite3RollbackAll(db);
      }
    }else if( !xFunc ){
      if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
        if( p->openedStatement ){
        xFunc = sqlite3BtreeCommitStmt;
        } 
      }else if( p->errorAction==OE_Abort ){
        xFunc = sqlite3BtreeRollbackStmt;
      }else{
        sqlite3AbortOtherActiveVdbes(db, p);
        sqlite3RollbackAll(db);
        db->autoCommit = 1;
      }
31780
31781
31782
31783
31784
31785
31786
31787

31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802

31803
31804
31805
31806
31807
31808
31809
31906
31907
31908
31909
31910
31911
31912

31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927

31928
31929
31930
31931
31932
31933
31934
31935







-
+














-
+







  return SQLITE_OK;
}

/*
** Each VDBE holds the result of the most recent sqlite3_step() call
** in p->rc.  This routine sets that result back to SQLITE_OK.
*/
static void sqlite3VdbeResetStepResult(Vdbe *p){
SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  p->rc = SQLITE_OK;
}

/*
** Clean up a VDBE after execution but do not delete the VDBE just yet.
** Write any error messages into *pzErrMsg.  Return the result code.
**
** After this routine is run, the VDBE should be ready to be executed
** again.
**
** To look at it another way, this routine resets the state of the
** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
** VDBE_MAGIC_INIT.
*/
static int sqlite3VdbeReset(Vdbe *p){
SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  sqlite3 *db;
  db = p->db;

  /* If the VM did not run to completion or if it encountered an
  ** error, then it might not have been halted properly.  So halt
  ** it now.
  */
31871
31872
31873
31874
31875
31876
31877
31878

31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896

31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912

31913
31914
31915
31916
31917
31918
31919
31997
31998
31999
32000
32001
32002
32003

32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021

32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037

32038
32039
32040
32041
32042
32043
32044
32045







-
+

















-
+















-
+







  return p->rc & db->errMask;
}
 
/*
** Clean up and delete a VDBE after execution.  Return an integer which is
** the result code.  Write any error message text into *pzErrMsg.
*/
static int sqlite3VdbeFinalize(Vdbe *p){
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  int rc = SQLITE_OK;
  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
    rc = sqlite3VdbeReset(p);
    assert( (rc & p->db->errMask)==rc );
  }else if( p->magic!=VDBE_MAGIC_INIT ){
    return SQLITE_MISUSE;
  }
  sqlite3VdbeDelete(p);
  return rc;
}

/*
** Call the destructor for each auxdata entry in pVdbeFunc for which
** the corresponding bit in mask is clear.  Auxdata entries beyond 31
** are always destroyed.  To destroy all auxdata entries, call this
** routine with mask==0.
*/
static void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
  int i;
  for(i=0; i<pVdbeFunc->nAux; i++){
    struct AuxData *pAux = &pVdbeFunc->apAux[i];
    if( (i>31 || !(mask&(1<<i))) && pAux->pAux ){
      if( pAux->xDelete ){
        pAux->xDelete(pAux->pAux);
      }
      pAux->pAux = 0;
    }
  }
}

/*
** Delete an entire VDBE.
*/
static void sqlite3VdbeDelete(Vdbe *p){
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  int i;
  if( p==0 ) return;
  Cleanup(p);
  if( p->pPrev ){
    p->pPrev->pNext = p->pNext;
  }else{
    assert( p->db->pVdbe==p );
31940
31941
31942
31943
31944
31945
31946
31947

31948
31949
31950
31951
31952
31953
31954
32066
32067
32068
32069
32070
32071
32072

32073
32074
32075
32076
32077
32078
32079
32080







-
+







}

/*
** If a MoveTo operation is pending on the given cursor, then do that
** MoveTo now.  Return an error code.  If no MoveTo is pending, this
** routine does nothing and returns SQLITE_OK.
*/
static int sqlite3VdbeCursorMoveto(Cursor *p){
SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(Cursor *p){
  if( p->deferredMoveto ){
    int res, rc;
#ifdef SQLITE_TEST
    extern int sqlite3_search_count;
#endif
    assert( p->isTable );
    rc = sqlite3BtreeMoveto(p->pCursor, 0, p->movetoTarget, 0, &res);
32010
32011
32012
32013
32014
32015
32016
32017

32018
32019
32020
32021
32022
32023
32024
32136
32137
32138
32139
32140
32141
32142

32143
32144
32145
32146
32147
32148
32149
32150







-
+







** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
** of SQLite will not understand those serial types.
*/

/*
** Return the serial-type for the value stored in pMem.
*/
static u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  int flags = pMem->flags;
  int n;

  if( flags&MEM_Null ){
    return 0;
  }
  if( flags&MEM_Int ){
32048
32049
32050
32051
32052
32053
32054
32055

32056
32057
32058
32059
32060
32061
32062
32174
32175
32176
32177
32178
32179
32180

32181
32182
32183
32184
32185
32186
32187
32188







-
+







  assert( n>=0 );
  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
}

/*
** Return the length of the data corresponding to the supplied serial-type.
*/
static int sqlite3VdbeSerialTypeLen(u32 serial_type){
SQLITE_PRIVATE int sqlite3VdbeSerialTypeLen(u32 serial_type){
  if( serial_type>=12 ){
    return (serial_type-12)/2;
  }else{
    static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
    return aSize[serial_type];
  }
}
32115
32116
32117
32118
32119
32120
32121
32122

32123
32124
32125
32126
32127
32128
32129
32241
32242
32243
32244
32245
32246
32247

32248
32249
32250
32251
32252
32253
32254
32255







-
+







** prefix and the tail then write the prefix and set the tail to all
** zeros.
**
** Return the number of bytes actually written into buf[].  The number
** of bytes in the zero-filled tail is included in the return value only
** if those bytes were zeroed in buf[].
*/ 
static int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
SQLITE_PRIVATE int sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  int len;

  /* Integer and Real */
  if( serial_type<=7 && serial_type>0 ){
    u64 v;
    int i;
32164
32165
32166
32167
32168
32169
32170
32171

32172
32173
32174
32175
32176
32177
32178
32290
32291
32292
32293
32294
32295
32296

32297
32298
32299
32300
32301
32302
32303
32304







-
+







  return 0;
}

/*
** Deserialize the data blob pointed to by buf as serial type serial_type
** and store the result in pMem.  Return the number of bytes read.
*/ 
static int sqlite3VdbeSerialGet(
SQLITE_PRIVATE int sqlite3VdbeSerialGet(
  const unsigned char *buf,     /* Buffer to deserialize from */
  u32 serial_type,              /* Serial type to deserialize */
  Mem *pMem                     /* Memory cell to write value into */
){
  switch( serial_type ){
    case 10:   /* Reserved for future use */
    case 11:   /* Reserved for future use */
32281
32282
32283
32284
32285
32286
32287
32288

32289
32290
32291
32292
32293
32294
32295
32407
32408
32409
32410
32411
32412
32413

32414
32415
32416
32417
32418
32419
32420
32421







-
+







/*
** This function compares the two table rows or index records specified by 
** {nKey1, pKey1} and {nKey2, pKey2}, returning a negative, zero
** or positive integer if {nKey1, pKey1} is less than, equal to or 
** greater than {nKey2, pKey2}.  Both Key1 and Key2 must be byte strings
** composed by the OP_MakeRecord opcode of the VDBE.
*/
static int sqlite3VdbeRecordCompare(
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  void *userData,
  int nKey1, const void *pKey1, 
  int nKey2, const void *pKey2
){
  KeyInfo *pKeyInfo = (KeyInfo*)userData;
  u32 d1, d2;          /* Offset into aKey[] of next data element */
  u32 idx1, idx2;      /* Offset into aKey[] of next header element */
32358
32359
32360
32361
32362
32363
32364
32365

32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380

32381
32382
32383
32384
32385
32386
32387
32484
32485
32486
32487
32488
32489
32490

32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505

32506
32507
32508
32509
32510
32511
32512
32513







-
+














-
+








/*
** The argument is an index entry composed using the OP_MakeRecord opcode.
** The last entry in this record should be an integer (specifically
** an integer rowid).  This routine returns the number of bytes in
** that integer.
*/
static int sqlite3VdbeIdxRowidLen(const u8 *aKey){
SQLITE_PRIVATE int sqlite3VdbeIdxRowidLen(const u8 *aKey){
  u32 szHdr;        /* Size of the header */
  u32 typeRowid;    /* Serial type of the rowid */

  sqlite3GetVarint32(aKey, &szHdr);
  sqlite3GetVarint32(&aKey[szHdr-1], &typeRowid);
  return sqlite3VdbeSerialTypeLen(typeRowid);
}
  

/*
** pCur points at an index entry created using the OP_MakeRecord opcode.
** Read the rowid (the last field in the record) and store it in *rowid.
** Return SQLITE_OK if everything works, or an error code otherwise.
*/
static int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
SQLITE_PRIVATE int sqlite3VdbeIdxRowid(BtCursor *pCur, i64 *rowid){
  i64 nCellKey = 0;
  int rc;
  u32 szHdr;        /* Size of the header */
  u32 typeRowid;    /* Serial type of the rowid */
  u32 lenRowid;     /* Size of the rowid */
  Mem m, v;

32408
32409
32410
32411
32412
32413
32414
32415

32416
32417
32418
32419
32420
32421
32422
32534
32535
32536
32537
32538
32539
32540

32541
32542
32543
32544
32545
32546
32547
32548







-
+







** that is negative, zero, or positive if pC is less than, equal to,
** or greater than pKey.  Return SQLITE_OK on success.
**
** pKey is either created without a rowid or is truncated so that it
** omits the rowid at the end.  The rowid at the end of the index entry
** is ignored as well.
*/
static int sqlite3VdbeIdxKeyCompare(
SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  Cursor *pC,                 /* The cursor to compare against */
  int nKey, const u8 *pKey,   /* The key to compare */
  int *res                    /* Write the comparison result here */
){
  i64 nCellKey = 0;
  int rc;
  BtCursor *pCur = pC->pCursor;
32438
32439
32440
32441
32442
32443
32444
32445

32446
32447
32448
32449
32450
32451
32452
32453
32454

32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468

32469
32470
32471
32472
32473
32474
32475
32476
32477
32478

32479
32480
32481
32482
32483
32484
32485
32564
32565
32566
32567
32568
32569
32570

32571
32572
32573
32574
32575
32576
32577
32578
32579

32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593

32594
32595
32596
32597
32598
32599
32600
32601
32602
32603

32604
32605
32606
32607
32608
32609
32610
32611







-
+








-
+













-
+









-
+







  return SQLITE_OK;
}

/*
** This routine sets the value to be returned by subsequent calls to
** sqlite3_changes() on the database handle 'db'. 
*/
static void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  db->nChange = nChange;
  db->nTotalChange += nChange;
}

/*
** Set a flag in the vdbe to update the change counter when it is finalised
** or reset.
*/
static void sqlite3VdbeCountChanges(Vdbe *v){
SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  v->changeCntOn = 1;
}

/*
** Mark every prepared statement associated with a database connection
** as expired.
**
** An expired statement means that recompilation of the statement is
** recommend.  Statements expire when things happen that make their
** programs obsolete.  Removing user-defined functions or collating
** sequences, or changing an authorization function are the types of
** things that make prepared statements obsolete.
*/
static void sqlite3ExpirePreparedStatements(sqlite3 *db){
SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  Vdbe *p;
  for(p = db->pVdbe; p; p=p->pNext){
    p->expired = 1;
  }
}

/*
** Return the database associated with the Vdbe.
*/
static sqlite3 *sqlite3VdbeDb(Vdbe *v){
SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  return v->db;
}

/************** End of vdbeaux.c *********************************************/
/************** Begin file vdbeapi.c *****************************************/
/*
** 2004 May 26
32501
32502
32503
32504
32505
32506
32507
32508

32509
32510
32511
32512
32513
32514
32515
32627
32628
32629
32630
32631
32632
32633

32634
32635
32636
32637
32638
32639
32640
32641







-
+







** Return TRUE (non-zero) of the statement supplied as an argument needs
** to be recompiled.  A statement needs to be recompiled whenever the
** execution environment changes in a way that would alter the program
** that sqlite3_prepare() generates.  For example, if new functions or
** collating sequences are registered or if an authorizer function is
** added or changed.
*/
int sqlite3_expired(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  Vdbe *p = (Vdbe*)pStmt;
  return p==0 || p->expired;
}

/**************************** sqlite3_value_  *******************************
** The following routines extract information from a Mem or sqlite3_value
** structure.
32751
32752
32753
32754
32755
32756
32757

32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772

32773
32774
32775
32776

32777
32778
32779
32780
32781
32782
32783
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898

32899
32900
32901
32902

32903
32904
32905
32906
32907
32908
32909
32910







+














-
+



-
+







  sqlite3Error(p->db, rc, 0);
  p->rc = sqlite3ApiExit(p->db, p->rc);
end_of_step:
  assert( (rc&0xff)==rc );
  if( p->zSql && (rc&0xff)<SQLITE_ROW ){
    /* This behavior occurs if sqlite3_prepare_v2() was used to build
    ** the prepared statement.  Return error codes directly */
    sqlite3Error(p->db, p->rc, 0);
    return p->rc;
  }else{
    /* This is for legacy sqlite3_prepare() builds and when the code
    ** is SQLITE_ROW or SQLITE_DONE */
    return rc;
  }
}

/*
** This is the top-level implementation of sqlite3_step().  Call
** sqlite3Step() to do most of the work.  If a schema error occurs,
** call sqlite3Reprepare() and try again.
*/
#ifdef SQLITE_OMIT_PARSER
int sqlite3_step(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  return sqlite3Step((Vdbe*)pStmt);
}
#else
int sqlite3_step(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  int cnt = 0;
  int rc;
  Vdbe *v = (Vdbe*)pStmt;
  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
         && cnt++ < 5
         && sqlite3Reprepare(v) ){
    sqlite3_reset(pStmt);
32800
32801
32802
32803
32804
32805
32806
32807

32808
32809
32810
32811
32812
32813
32814
32927
32928
32929
32930
32931
32932
32933

32934
32935
32936
32937
32938
32939
32940
32941







-
+







** The following is the implementation of an SQL function that always
** fails with an error message stating that the function is used in the
** wrong context.  The sqlite3_overload_function() API might construct
** SQL function that use this routine so that the functions will exist
** for name resolution but are actually overloaded by the xFindFunction
** method of virtual tables.
*/
static void sqlite3InvalidFunction(
SQLITE_PRIVATE void sqlite3InvalidFunction(
  sqlite3_context *context,  /* The function calling context */
  int argc,                  /* Number of arguments to the function */
  sqlite3_value **argv       /* Value of each argument */
){
  const char *zName = context->pFunc->zName;
  char *zErr;
  zErr = sqlite3MPrintf(
32929
32930
32931
32932
32933
32934
32935
32936

32937
32938
32939
32940
32941
32942
32943
33056
33057
33058
33059
33060
33061
33062

33063
33064
33065
33066
33067
33068
33069
33070







-
+







** it is, return a pointer to the Mem for the value of that column.
** If iCol is not valid, return a pointer to a Mem which has a value
** of NULL.
*/
static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  Vdbe *pVm = (Vdbe *)pStmt;
  int vals = sqlite3_data_count(pStmt);
  if( i>=vals || i<0 ){
  if( pVm==0 || pVm->resOnStack==0 || i>=pVm->nResColumn || i<0 ){
    static const Mem nullMem = {{0}, 0.0, "", 0, MEM_Null, SQLITE_NULL };
    sqlite3Error(pVm->db, SQLITE_RANGE, 0);
    return (Mem*)&nullMem;
  }
  return &pVm->pTos[(1-vals)+i];
}

33435
33436
33437
33438
33439
33440
33441
33442

33443
33444
33445
33446
33447
33448
33449
33562
33563
33564
33565
33566
33567
33568

33569
33570
33571
33572
33573
33574
33575
33576







-
+







**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The following global variable is incremented every time a cursor
** moves, either by the OP_MoveXX, OP_Next, or OP_Prev opcodes.  The test
** procedures use this information to make sure that indices are
** working correctly.  This variable has no function other than to
33682
33683
33684
33685
33686
33687
33688
33689

33690
33691
33692
33693
33694
33695
33696
33697
33698

33699
33700
33701
33702
33703
33704
33705
33809
33810
33811
33812
33813
33814
33815

33816
33817
33818
33819
33820
33821
33822
33823
33824

33825
33826
33827
33828
33829
33830
33831
33832







-
+








-
+







  return pMem->type;
}

/*
** Exported version of applyAffinity(). This one works on sqlite3_value*, 
** not the internal Mem* type.
*/
static void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *pVal, u8 affinity, u8 enc){
  applyAffinity((Mem *)pVal, affinity, enc);
}

#ifdef SQLITE_DEBUG
/*
** Write a nice string representation of the contents of cell pMem
** into buffer zBuf, length nBuf.
*/
static void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  char *zCsr = zBuf;
  int f = pMem->flags;

  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};

  if( f&MEM_Blob ){
    int i;
33831
33832
33833
33834
33835
33836
33837
33838

33839
33840
33841
33842
33843
33844
33845
33958
33959
33960
33961
33962
33963
33964

33965
33966
33967
33968
33969
33970
33971
33972







-
+







** routine to return SQLITE_ERROR.
**
** Other fatal errors return SQLITE_ERROR.
**
** After this routine has finished, sqlite3VdbeFinalize() should be
** used to clean up the mess that was left behind.
*/
static int sqlite3VdbeExec(
SQLITE_PRIVATE int sqlite3VdbeExec(
  Vdbe *p                    /* The VDBE */
){
  int pc;                    /* The program counter */
  Op *pOp;                   /* Current operation */
  int rc = SQLITE_OK;        /* Value to return */
  sqlite3 *db = p->db;       /* The database */
  u8 encoding = ENC(db);     /* The database encoding */
34540
34541
34542
34543
34544
34545
34546








34547
34548
34549
34550
34551

34552
34553
34554
34555
34556
34557
34558
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694







+
+
+
+
+
+
+
+





+







    b = pNos->u.i;
    switch( pOp->opcode ){
      case OP_Add:         b += a;       break;
      case OP_Subtract:    b -= a;       break;
      case OP_Multiply:    b *= a;       break;
      case OP_Divide: {
        if( a==0 ) goto divide_by_zero;
        /* Dividing the largest possible negative 64-bit integer (1<<63) by 
        ** -1 returns an integer to large to store in a 64-bit data-type. On
        ** some architectures, the value overflows to (1<<63). On others,
        ** a SIGFPE is issued. The following statement normalizes this
        ** behaviour so that all architectures behave as if integer 
        ** overflow occured.
        */
        if( a==-1 && b==(((i64)1)<<63) ) a = 1;
        b /= a;
        break;
      }
      default: {
        if( a==0 ) goto divide_by_zero;
        if( a==-1 ) a = 1;
        b %= a;
        break;
      }
    }
    Release(pTos);
    pTos--;
    Release(pTos);
34571
34572
34573
34574
34575
34576
34577

34578
34579
34580
34581
34582

34583
34584
34585
34586
34587
34588
34589
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718

34719
34720
34721
34722
34723
34724
34725
34726







+




-
+







        b /= a;
        break;
      }
      default: {
        i64 ia = (i64)a;
        i64 ib = (i64)b;
        if( ia==0 ) goto divide_by_zero;
        if( ia==-1 ) ia = 1;
        b = ib % ia;
        break;
      }
    }
    if( isnan(b) ){
    if( sqlite3_isnan(b) ){
      goto divide_by_zero;
    }
    Release(pTos);
    pTos--;
    Release(pTos);
    pTos->r = b;
    pTos->flags = MEM_Real;
35785
35786
35787
35788
35789
35790
35791

35792
35793
35794
35795
35796
35797
35798
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936







+







case OP_Statement: {       /* no-push */
  int i = pOp->p1;
  Btree *pBt;
  if( i>=0 && i<db->nDb && (pBt = db->aDb[i].pBt)!=0 && !(db->autoCommit) ){
    assert( sqlite3BtreeIsInTrans(pBt) );
    if( !sqlite3BtreeIsInStmt(pBt) ){
      rc = sqlite3BtreeBeginStmt(pBt);
      p->openedStatement = 1;
    }
  }
  break;
}

/* Opcode: AutoCommit P1 P2 *
**
35896
35897
35898
35899
35900
35901
35902





35903
35904
35905
35906
35907
35908



35909




35910
35911


35912
35913
35914
35915
35916
35917
35918
35919

35920
35921
35922
35923
35924
35925
35926
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059


36060
36061
36062
36063
36064
36065
36066
36067
36068

36069
36070
36071
36072
36073
36074
36075
36076







+
+
+
+
+






+
+
+

+
+
+
+
-
-
+
+







-
+







**
** Read cookie number P2 from database P1 and push it onto the stack.
** P2==0 is the schema version.  P2==1 is the database format.
** P2==2 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.
**
** If P1 is negative, then this is a request to read the size of a
** databases free-list. P2 must be set to 1 in this case. The actual
** database accessed is ((P1+1)*-1). For example, a P1 parameter of -1
** corresponds to database 0 ("main"), a P1 of -2 is database 1 ("temp").
**
** There must be a read-lock on the database (either a transaction
** must be started or there must be an open cursor) before
** executing this instruction.
*/
case OP_ReadCookie: {
  int iMeta;
  int iDb = pOp->p1;
  int iCookie = pOp->p2;

  assert( pOp->p2<SQLITE_N_BTREE_META );
  if( iDb<0 ){
    iDb = (-1*(iDb+1));
    iCookie *= -1;
  }
  assert( pOp->p1>=0 && pOp->p1<db->nDb );
  assert( db->aDb[pOp->p1].pBt!=0 );
  assert( iDb>=0 && iDb<db->nDb );
  assert( db->aDb[iDb].pBt!=0 );
  /* The indexing of meta values at the schema layer is off by one from
  ** the indexing in the btree layer.  The btree considers meta[0] to
  ** be the number of free pages in the database (a read-only value)
  ** and meta[1] to be the schema cookie.  The schema layer considers
  ** meta[1] to be the schema cookie.  So we have to shift the index
  ** by one in the following statement.
  */
  rc = sqlite3BtreeGetMeta(db->aDb[pOp->p1].pBt, 1 + pOp->p2, (u32 *)&iMeta);
  rc = sqlite3BtreeGetMeta(db->aDb[iDb].pBt, 1 + iCookie, (u32 *)&iMeta);
  pTos++;
  pTos->u.i = iMeta;
  pTos->flags = MEM_Int;
  break;
}

/* Opcode: SetCookie P1 P2 *
37670
37671
37672
37673
37674
37675
37676
37677
37678

37679
37680
37681
37682
37683
37684
37685
37820
37821
37822
37823
37824
37825
37826


37827
37828
37829
37830
37831
37832
37833
37834







-
-
+







  aRoot = sqliteMallocRaw( sizeof(int*)*(nRoot+1) );
  if( aRoot==0 ) goto no_mem;
  j = pOp->p1;
  assert( j>=0 && j<p->nMem );
  pnErr = &p->aMem[j];
  assert( (pnErr->flags & MEM_Int)!=0 );
  for(j=0; j<nRoot; j++){
    Mem *pMem = &pTos[-j];
    aRoot[j] = pMem->u.i;
    aRoot[j] = pTos[-j].u.i;
  }
  aRoot[j] = 0;
  popStack(&pTos, nRoot);
  pTos++;
  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot,
                                 pnErr->u.i, &nErr);
  pnErr->u.i -= nErr;
38364
38365
38366
38367
38368
38369
38370
























38371
38372
38373
38374
38375
38376
38377
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







    }
  }

  break;
}
#endif /* SQLITE_OMIT_VIRTUALTABLE */

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VRename * * P3
**
** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
** This opcode invokes the corresponding xRename method. The value
** on the top of the stack is popped and passed as the zName argument
** to the xRename method.
*/
case OP_VRename: {   /* no-push */
  sqlite3_vtab *pVtab = (sqlite3_vtab *)(pOp->p3);
  assert( pVtab->pModule->xRename );

  Stringify(pTos, encoding);

  if( sqlite3SafetyOff(db) ) goto abort_due_to_misuse;
  sqlite3VtabLock(pVtab);
  rc = pVtab->pModule->xRename(pVtab, pTos->z);
  sqlite3VtabUnlock(db, pVtab);
  if( sqlite3SafetyOn(db) ) goto abort_due_to_misuse;

  popStack(&pTos, 1);
  break;
}
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Opcode: VUpdate P1 P2 P3
**
** P3 is a pointer to a virtual table object, an sqlite3_vtab structure.
** This opcode invokes the corresponding xUpdate method. P2 values
** are taken from the stack to pass to the xUpdate invocation. The
38581
38582
38583
38584
38585
38586
38587
38588

38589
38590
38591
38592
38593
38594
38595
38754
38755
38756
38757
38758
38759
38760

38761
38762
38763
38764
38765
38766
38767
38768







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to implement incremental BLOB I/O.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


#ifndef SQLITE_OMIT_INCRBLOB

/*
** Valid sqlite3_blob* handles point to Incrblob structures.
38845
38846
38847
38848
38849
38850
38851

38852
38853
38854
38855
38856
38857
38858
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032







+







  */
  db = v->db;
  rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  if( rc==SQLITE_ABORT ){
    sqlite3VdbeFinalize(v);
    p->pStmt = 0;
  }else{
    db->errCode = rc;
    v->rc = rc;
  }

  return sqlite3ApiExit(db, rc);
}

/*
38891
38892
38893
38894
38895
38896
38897
38898

38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917

38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937

38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952

38953
38954

38955
38956


38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971

38972
38973
38974
38975
38976
38977
38978
39065
39066
39067
39068
39069
39070
39071

39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090

39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110

39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125

39126
39127
39128
39129
39130

39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146

39147
39148
39149
39150
39151
39152
39153
39154







-
+


















-
+



















-
+














-
+


+

-
+
+














-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains routines used for analyzing expressions and
** for generating VDBE code that evaluates expressions in SQLite.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** Return the 'affinity' of the expression pExpr if any.
**
** If pExpr is a column, a reference to a column via an 'AS' alias,
** or a sub-select with a column as the return value, then the 
** affinity of that column is returned. Otherwise, 0x00 is returned,
** indicating no affinity for the expression.
**
** i.e. the WHERE clause expresssions in the following statements all
** have an affinity:
**
** CREATE TABLE t1(a);
** SELECT * FROM t1 WHERE a;
** SELECT a AS b FROM t1 WHERE b;
** SELECT * FROM t1 WHERE (select a from t1);
*/
static char sqlite3ExprAffinity(Expr *pExpr){
SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  int op = pExpr->op;
  if( op==TK_SELECT ){
    return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
  }
#ifndef SQLITE_OMIT_CAST
  if( op==TK_CAST ){
    return sqlite3AffinityType(&pExpr->token);
  }
#endif
  return pExpr->affinity;
}

/*
** Set the collating sequence for expression pExpr to be the collating
** sequence named by pToken.   Return a pointer to the revised expression.
** The collating sequence is marked as "explicit" using the EP_ExpCollate
** flag.  An explicit collating sequence will override implicit
** collating sequences.
*/
static Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
  CollSeq *pColl;
  if( pExpr==0 ) return 0;
  pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
  if( pColl ){
    pExpr->pColl = pColl;
    pExpr->flags |= EP_ExpCollate;
  }
  return pExpr;
}

/*
** Return the default collation sequence for the expression pExpr. If
** there is no default collation type, return 0.
*/
static CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  CollSeq *pColl = 0;
  if( pExpr ){
    int op;
    pColl = pExpr->pColl;
    if( pExpr->op==TK_CAST && !pColl ){
    op = pExpr->op;
    if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
      return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
    }
  }
  if( sqlite3CheckCollSeq(pParse, pColl) ){ 
    pColl = 0;
  }
  return pColl;
}

/*
** pExpr is an operand of a comparison operator.  aff2 is the
** type affinity of the other operand.  This routine returns the
** type affinity that should be used for the comparison operator.
*/
static char sqlite3CompareAffinity(Expr *pExpr, char aff2){
SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  char aff1 = sqlite3ExprAffinity(pExpr);
  if( aff1 && aff2 ){
    /* Both sides of the comparison are columns. If one has numeric
    ** affinity, use that. Otherwise use no affinity.
    */
    if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
      return SQLITE_AFF_NUMERIC;
39016
39017
39018
39019
39020
39021
39022
39023

39024
39025
39026
39027
39028
39029
39030
39192
39193
39194
39195
39196
39197
39198

39199
39200
39201
39202
39203
39204
39205
39206







-
+








/*
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
** idx_affinity is the affinity of an indexed column. Return true
** if the index with affinity idx_affinity may be used to implement
** the comparison in pExpr.
*/
static int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  char aff = comparisonAffinity(pExpr);
  switch( aff ){
    case SQLITE_AFF_NONE:
      return 1;
    case SQLITE_AFF_TEXT:
      return idx_affinity==SQLITE_AFF_TEXT;
    default:
39095
39096
39097
39098
39099
39100
39101
39102

39103
39104
39105
39106
39107
39108
39109
39271
39272
39273
39274
39275
39276
39277

39278
39279
39280
39281
39282
39283
39284
39285







-
+







}

/*
** Construct a new expression node and return a pointer to it.  Memory
** for this node is obtained from sqliteMalloc().  The calling function
** is responsible for making sure the node eventually gets freed.
*/
static Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
SQLITE_PRIVATE Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
  Expr *pNew;
  pNew = sqliteMalloc( sizeof(Expr) );
  if( pNew==0 ){
    /* When malloc fails, delete pLeft and pRight. Expressions passed to 
    ** this function must always be allocated with sqlite3Expr() for this 
    ** reason. 
    */
39136
39137
39138
39139
39140
39141
39142
39143

39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163

39164
39165
39166
39167
39168
39169
39170
39312
39313
39314
39315
39316
39317
39318

39319
39320
39321
39322
39323
39324
39325
39326
39327
39328
39329
39330
39331
39332
39333
39334
39335
39336
39337
39338

39339
39340
39341
39342
39343
39344
39345
39346







-
+



















-
+







  return pNew;
}

/*
** Works like sqlite3Expr() but frees its pLeft and pRight arguments
** if it fails due to a malloc problem.
*/
static Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
SQLITE_PRIVATE Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
  Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
  if( pNew==0 ){
    sqlite3ExprDelete(pLeft);
    sqlite3ExprDelete(pRight);
  }
  return pNew;
}

/*
** When doing a nested parse, you can include terms in an expression
** that look like this:   #0 #1 #2 ...  These terms refer to elements
** on the stack.  "#0" means the top of the stack.
** "#1" means the next down on the stack.  And so forth.
**
** This routine is called by the parser to deal with on of those terms.
** It immediately generates code to store the value in a memory location.
** The returns an expression that will code to extract the value from
** that memory location as needed.
*/
static Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
SQLITE_PRIVATE Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
  Vdbe *v = pParse->pVdbe;
  Expr *p;
  int depth;
  if( pParse->nested==0 ){
    sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
    return sqlite3Expr(TK_NULL, 0, 0, 0);
  }
39180
39181
39182
39183
39184
39185
39186
39187

39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201

39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219

39220
39221
39222
39223
39224
39225
39226
39356
39357
39358
39359
39360
39361
39362

39363
39364
39365
39366
39367
39368
39369
39370
39371
39372
39373
39374
39375
39376

39377
39378
39379
39380
39381
39382
39383
39384
39385
39386
39387
39388
39389
39390
39391
39392
39393
39394

39395
39396
39397
39398
39399
39400
39401
39402







-
+













-
+

















-
+







  return p;
}

/*
** Join two expressions using an AND operator.  If either expression is
** NULL, then just return the other expression.
*/
static Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
SQLITE_PRIVATE Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
  if( pLeft==0 ){
    return pRight;
  }else if( pRight==0 ){
    return pLeft;
  }else{
    return sqlite3Expr(TK_AND, pLeft, pRight, 0);
  }
}

/*
** Set the Expr.span field of the given expression to span all
** text between the two given tokens.
*/
static void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
SQLITE_PRIVATE void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
  assert( pRight!=0 );
  assert( pLeft!=0 );
  if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
    assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
    if( pLeft->dyn==0 && pRight->dyn==0 ){
      pExpr->span.z = pLeft->z;
      pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
    }else{
      pExpr->span.z = 0;
    }
  }
}

/*
** Construct a new expression node for a function with multiple
** arguments.
*/
static Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
SQLITE_PRIVATE Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
  Expr *pNew;
  assert( pToken );
  pNew = sqliteMalloc( sizeof(Expr) );
  if( pNew==0 ){
    sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
    return 0;
  }
39246
39247
39248
39249
39250
39251
39252
39253

39254
39255
39256
39257
39258
39259
39260
39422
39423
39424
39425
39426
39427
39428

39429
39430
39431
39432
39433
39434
39435
39436







-
+







** the SQL statement comes from an external source.
**
** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
** as the previous instance of the same wildcard.  Or if this is the first
** instance of the wildcard, the next sequenial variable number is
** assigned.
*/
static void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  Token *pToken;
  if( pExpr==0 ) return;
  pToken = &pExpr->token;
  assert( pToken->n>=1 );
  assert( pToken->z!=0 );
  assert( pToken->z[0]!=0 );
  if( pToken->n==1 ){
39305
39306
39307
39308
39309
39310
39311
39312

39313
39314
39315
39316
39317
39318
39319
39320
39321
39322
39323
39324
39325
39326
39327

39328
39329
39330
39331
39332
39333
39334
39481
39482
39483
39484
39485
39486
39487

39488
39489
39490
39491
39492
39493
39494
39495
39496
39497
39498
39499
39500
39501
39502

39503
39504
39505
39506
39507
39508
39509
39510







-
+














-
+







    sqlite3ErrorMsg(pParse, "too many SQL variables");
  }
}

/*
** Recursively delete an expression tree.
*/
static void sqlite3ExprDelete(Expr *p){
SQLITE_PRIVATE void sqlite3ExprDelete(Expr *p){
  if( p==0 ) return;
  if( p->span.dyn ) sqliteFree((char*)p->span.z);
  if( p->token.dyn ) sqliteFree((char*)p->token.z);
  sqlite3ExprDelete(p->pLeft);
  sqlite3ExprDelete(p->pRight);
  sqlite3ExprListDelete(p->pList);
  sqlite3SelectDelete(p->pSelect);
  sqliteFree(p);
}

/*
** The Expr.token field might be a string literal that is quoted.
** If so, remove the quotation marks.
*/
static void sqlite3DequoteExpr(Expr *p){
SQLITE_PRIVATE void sqlite3DequoteExpr(Expr *p){
  if( ExprHasAnyProperty(p, EP_Dequoted) ){
    return;
  }
  ExprSetProperty(p, EP_Dequoted);
  if( p->token.dyn==0 ){
    sqlite3TokenCopy(&p->token, &p->token);
  }
39344
39345
39346
39347
39348
39349
39350
39351

39352
39353
39354
39355
39356
39357
39358
39359
39360
39361
39362
39363
39364
39365
39366
39367
39368
39369
39370

39371
39372
39373
39374
39375
39376
39377
39378
39379
39380

39381
39382
39383
39384
39385
39386
39387
39520
39521
39522
39523
39524
39525
39526

39527
39528
39529
39530
39531
39532
39533
39534
39535
39536
39537
39538
39539
39540
39541
39542
39543
39544
39545

39546
39547
39548
39549
39550
39551
39552
39553
39554
39555

39556
39557
39558
39559
39560
39561
39562
39563







-
+


















-
+









-
+







**
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
** by subsequent calls to sqlite*ListAppend() routines.
**
** Any tables that the SrcList might point to are not duplicated.
*/
static Expr *sqlite3ExprDup(Expr *p){
SQLITE_PRIVATE Expr *sqlite3ExprDup(Expr *p){
  Expr *pNew;
  if( p==0 ) return 0;
  pNew = sqliteMallocRaw( sizeof(*p) );
  if( pNew==0 ) return 0;
  memcpy(pNew, p, sizeof(*pNew));
  if( p->token.z!=0 ){
    pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
    pNew->token.dyn = 1;
  }else{
    assert( pNew->token.z==0 );
  }
  pNew->span.z = 0;
  pNew->pLeft = sqlite3ExprDup(p->pLeft);
  pNew->pRight = sqlite3ExprDup(p->pRight);
  pNew->pList = sqlite3ExprListDup(p->pList);
  pNew->pSelect = sqlite3SelectDup(p->pSelect);
  return pNew;
}
static void sqlite3TokenCopy(Token *pTo, Token *pFrom){
SQLITE_PRIVATE void sqlite3TokenCopy(Token *pTo, Token *pFrom){
  if( pTo->dyn ) sqliteFree((char*)pTo->z);
  if( pFrom->z ){
    pTo->n = pFrom->n;
    pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
    pTo->dyn = 1;
  }else{
    pTo->z = 0;
  }
}
static ExprList *sqlite3ExprListDup(ExprList *p){
SQLITE_PRIVATE ExprList *sqlite3ExprListDup(ExprList *p){
  ExprList *pNew;
  struct ExprList_item *pItem, *pOldItem;
  int i;
  if( p==0 ) return 0;
  pNew = sqliteMalloc( sizeof(*pNew) );
  if( pNew==0 ) return 0;
  pNew->nExpr = pNew->nAlloc = p->nExpr;
39415
39416
39417
39418
39419
39420
39421
39422

39423
39424
39425
39426
39427
39428
39429
39591
39592
39593
39594
39595
39596
39597

39598
39599
39600
39601
39602
39603
39604
39605







-
+







** If cursors, triggers, views and subqueries are all omitted from
** the build, then none of the following routines, except for 
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
** called with a NULL argument.
*/
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
 || !defined(SQLITE_OMIT_SUBQUERY)
static SrcList *sqlite3SrcListDup(SrcList *p){
SQLITE_PRIVATE SrcList *sqlite3SrcListDup(SrcList *p){
  SrcList *pNew;
  int i;
  int nByte;
  if( p==0 ) return 0;
  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  pNew = sqliteMallocRaw( nByte );
  if( pNew==0 ) return 0;
39445
39446
39447
39448
39449
39450
39451
39452

39453
39454
39455
39456
39457
39458
39459
39460
39461
39462
39463
39464
39465
39466
39467
39468
39469
39470
39471
39472

39473
39474
39475
39476
39477
39478
39479
39621
39622
39623
39624
39625
39626
39627

39628
39629
39630
39631
39632
39633
39634
39635
39636
39637
39638
39639
39640
39641
39642
39643
39644
39645
39646
39647

39648
39649
39650
39651
39652
39653
39654
39655







-
+



















-
+







    pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
    pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
    pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
    pNewItem->colUsed = pOldItem->colUsed;
  }
  return pNew;
}
static IdList *sqlite3IdListDup(IdList *p){
SQLITE_PRIVATE IdList *sqlite3IdListDup(IdList *p){
  IdList *pNew;
  int i;
  if( p==0 ) return 0;
  pNew = sqliteMallocRaw( sizeof(*pNew) );
  if( pNew==0 ) return 0;
  pNew->nId = pNew->nAlloc = p->nId;
  pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
  if( pNew->a==0 ){
    sqliteFree(pNew);
    return 0;
  }
  for(i=0; i<p->nId; i++){
    struct IdList_item *pNewItem = &pNew->a[i];
    struct IdList_item *pOldItem = &p->a[i];
    pNewItem->zName = sqliteStrDup(pOldItem->zName);
    pNewItem->idx = pOldItem->idx;
  }
  return pNew;
}
static Select *sqlite3SelectDup(Select *p){
SQLITE_PRIVATE Select *sqlite3SelectDup(Select *p){
  Select *pNew;
  if( p==0 ) return 0;
  pNew = sqliteMallocRaw( sizeof(*p) );
  if( pNew==0 ) return 0;
  pNew->isDistinct = p->isDistinct;
  pNew->pEList = sqlite3ExprListDup(p->pEList);
  pNew->pSrc = sqlite3SrcListDup(p->pSrc);
39494
39495
39496
39497
39498
39499
39500
39501

39502
39503
39504
39505
39506
39507
39508
39509
39510
39511
39512

39513
39514
39515
39516
39517
39518
39519
39670
39671
39672
39673
39674
39675
39676

39677
39678
39679
39680
39681
39682
39683
39684
39685
39686
39687

39688
39689
39690
39691
39692
39693
39694
39695







-
+










-
+







  pNew->pRightmost = 0;
  pNew->addrOpenEphm[0] = -1;
  pNew->addrOpenEphm[1] = -1;
  pNew->addrOpenEphm[2] = -1;
  return pNew;
}
#else
static Select *sqlite3SelectDup(Select *p){
SQLITE_PRIVATE Select *sqlite3SelectDup(Select *p){
  assert( p==0 );
  return 0;
}
#endif


/*
** Add a new element to the end of an expression list.  If pList is
** initially NULL, then create a new expression list.
*/
static ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
  if( pList==0 ){
    pList = sqliteMalloc( sizeof(ExprList) );
    if( pList==0 ){
      goto no_mem;
    }
    assert( pList->nAlloc==0 );
  }
39543
39544
39545
39546
39547
39548
39549
39550

39551
39552
39553
39554
39555
39556
39557
39719
39720
39721
39722
39723
39724
39725

39726
39727
39728
39729
39730
39731
39732
39733







-
+







  return 0;
}

/*
** If the expression list pEList contains more than iLimit elements,
** leave an error message in pParse.
*/
static void sqlite3ExprListCheckLength(
SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  Parse *pParse,
  ExprList *pEList,
  int iLimit,
  const char *zObject
){
  if( pEList && pEList->nExpr>iLimit ){
    sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
39600
39601
39602
39603
39604
39605
39606
39607

39608
39609
39610
39611
39612
39613
39614
39615
39616
39617
39618
39619
39620

39621
39622
39623
39624
39625
39626
39627
39628
39629
39630

39631
39632
39633
39634
39635
39636
39637
39776
39777
39778
39779
39780
39781
39782

39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
39795

39796
39797
39798
39799
39800
39801
39802
39803
39804
39805

39806
39807
39808
39809
39810
39811
39812
39813







-
+












-
+









-
+







/*
** Set the Expr.nHeight variable in the structure passed as an 
** argument. An expression with no children, Expr.pList or 
** Expr.pSelect member has a height of 1. Any other expression
** has a height equal to the maximum height of any other 
** referenced Expr plus one.
*/
static void sqlite3ExprSetHeight(Expr *p){
SQLITE_PRIVATE void sqlite3ExprSetHeight(Expr *p){
  int nHeight = 0;
  heightOfExpr(p->pLeft, &nHeight);
  heightOfExpr(p->pRight, &nHeight);
  heightOfExprList(p->pList, &nHeight);
  heightOfSelect(p->pSelect, &nHeight);
  p->nHeight = nHeight + 1;
}

/*
** Return the maximum height of any expression tree referenced
** by the select statement passed as an argument.
*/
static int sqlite3SelectExprHeight(Select *p){
SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  int nHeight = 0;
  heightOfSelect(p, &nHeight);
  return nHeight;
}
#endif

/*
** Delete an entire expression list.
*/
static void sqlite3ExprListDelete(ExprList *pList){
SQLITE_PRIVATE void sqlite3ExprListDelete(ExprList *pList){
  int i;
  struct ExprList_item *pItem;
  if( pList==0 ) return;
  assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  assert( pList->nExpr<=pList->nAlloc );
  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
    sqlite3ExprDelete(pItem->pExpr);
39753
39754
39755
39756
39757
39758
39759
39760

39761
39762
39763
39764
39765
39766
39767
39768
39769
39770
39771
39772

39773
39774
39775
39776
39777
39778
39779
39780
39781
39782
39783
39784
39785
39786
39787

39788
39789
39790
39791
39792
39793
39794
39795
39796
39797
39798
39799

39800
39801
39802
39803
39804
39805
39806
39929
39930
39931
39932
39933
39934
39935

39936
39937
39938
39939
39940
39941
39942
39943
39944
39945
39946
39947

39948
39949
39950
39951
39952
39953
39954
39955
39956
39957
39958
39959
39960
39961
39962

39963
39964
39965
39966
39967
39968
39969
39970
39971
39972
39973
39974

39975
39976
39977
39978
39979
39980
39981
39982







-
+











-
+














-
+











-
+







** Walk an expression tree.  Return 1 if the expression is constant
** and 0 if it involves variables or function calls.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
static int sqlite3ExprIsConstant(Expr *p){
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  int isConst = 1;
  walkExprTree(p, exprNodeIsConstant, &isConst);
  return isConst;
}

/*
** Walk an expression tree.  Return 1 if the expression is constant
** that does no originate from the ON or USING clauses of a join.
** Return 0 if it involves variables or function calls or terms from
** an ON or USING clause.
*/
static int sqlite3ExprIsConstantNotJoin(Expr *p){
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  int isConst = 3;
  walkExprTree(p, exprNodeIsConstant, &isConst);
  return isConst!=0;
}

/*
** Walk an expression tree.  Return 1 if the expression is constant
** or a function call with constant arguments.  Return and 0 if there
** are any variables.
**
** For the purposes of this function, a double-quoted string (ex: "abc")
** is considered a variable but a single-quoted string (ex: 'abc') is
** a constant.
*/
static int sqlite3ExprIsConstantOrFunction(Expr *p){
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  int isConst = 2;
  walkExprTree(p, exprNodeIsConstant, &isConst);
  return isConst!=0;
}

/*
** If the expression p codes a constant integer that is small enough
** to fit in a 32-bit integer, return 1 and put the value of the integer
** in *pValue.  If the expression is not an integer or if it is too big
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
*/
static int sqlite3ExprIsInteger(Expr *p, int *pValue){
SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  switch( p->op ){
    case TK_INTEGER: {
      if( sqlite3GetInt32((char*)p->token.z, pValue) ){
        return 1;
      }
      break;
    }
39819
39820
39821
39822
39823
39824
39825
39826

39827
39828
39829
39830
39831
39832
39833
39995
39996
39997
39998
39999
40000
40001

40002
40003
40004
40005
40006
40007
40008
40009







-
+







  }
  return 0;
}

/*
** Return TRUE if the given string is a row-id column name.
*/
static int sqlite3IsRowid(const char *z){
SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  return 0;
}

/*
40029
40030
40031
40032
40033
40034
40035

40036
40037
40038
40039
40040
40041
40042
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216
40217
40218
40219







+







            pDup->flags |= EP_ExpCollate;
          }
          if( pExpr->span.dyn ) sqliteFree((char*)pExpr->span.z);
          if( pExpr->token.dyn ) sqliteFree((char*)pExpr->token.z);
          memcpy(pExpr, pDup, sizeof(*pExpr));
          sqliteFree(pDup);
          cnt = 1;
          pMatch = 0;
          assert( zTab==0 && zDb==0 );
          goto lookupname_end_2;
        }
      } 
    }

    /* Advance to the next name context.  The loop will exit when either
40318
40319
40320
40321
40322
40323
40324
40325

40326
40327
40328
40329
40330
40331
40332
40495
40496
40497
40498
40499
40500
40501

40502
40503
40504
40505
40506
40507
40508
40509







-
+







** usage.  Make sure all function names are recognized and all functions
** have the correct number of arguments.  Leave an error message
** in pParse->zErrMsg if anything is amiss.  Return the number of errors.
**
** If the expression contains aggregate functions then set the EP_Agg
** property on the expression.
*/
static int sqlite3ExprResolveNames( 
SQLITE_PRIVATE int sqlite3ExprResolveNames( 
  NameContext *pNC,       /* Namespace to resolve expressions in. */
  Expr *pExpr             /* The expression to be analyzed. */
){
  int savedHasAgg;
  if( pExpr==0 ) return 0;
#if SQLITE_MAX_EXPR_DEPTH>0
  if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
40375
40376
40377
40378
40379
40380
40381
40382

40383
40384
40385
40386
40387
40388
40389
40552
40553
40554
40555
40556
40557
40558

40559
40560
40561
40562
40563
40564
40565
40566







-
+







**     x IN (4,5,11)              -- IN operator with list on right-hand side
**     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
**
** The pExpr parameter describes the expression that contains the IN
** operator or subquery.
*/
#ifndef SQLITE_OMIT_SUBQUERY
static void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
  int testAddr = 0;                       /* One-time test address */
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v==0 ) return;


  /* This code must be run in its entirety every time it is encountered
  ** if any of the following is true:
40548
40549
40550
40551
40552
40553
40554
40555

40556
40557
40558
40559
40560
40561
40562
40725
40726
40727
40728
40729
40730
40731

40732
40733
40734
40735
40736
40737
40738
40739







-
+








/*
** Generate code that will extract the iColumn-th column from
** table pTab and push that column value on the stack.  There
** is an open cursor to pTab in iTable.  If iColumn<0 then
** code is generated that extracts the rowid.
*/
static void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
SQLITE_PRIVATE void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
  if( iColumn<0 ){
    int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
    sqlite3VdbeAddOp(v, op, iTable, 0);
  }else if( pTab==0 ){
    sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
  }else{
    int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
40576
40577
40578
40579
40580
40581
40582
40583

40584
40585
40586
40587
40588
40589
40590
40753
40754
40755
40756
40757
40758
40759

40760
40761
40762
40763
40764
40765
40766
40767







-
+







**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align.  Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
static void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
  Vdbe *v = pParse->pVdbe;
  int op;
  int stackChng = 1;    /* Amount of change to stack depth */

  if( v==0 ) return;
  if( pExpr==0 ){
    sqlite3VdbeAddOp(v, OP_Null, 0, 0);
40964
40965
40966
40967
40968
40969
40970
40971

40972
40973
40974
40975
40976
40977
40978
41141
41142
41143
41144
41145
41146
41147

41148
41149
41150
41151
41152
41153
41154
41155







-
+







**
** This routine might also cache the result and modify the pExpr tree
** so that it will make use of the cached result on subsequent evaluations
** rather than evaluate the whole expression again.  Trivial expressions are
** not cached.  If the expression is cached, its result is stored in a 
** memory location.
*/
static void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
  Vdbe *v = pParse->pVdbe;
  int iMem;
  int addr1, addr2;
  if( v==0 ) return;
  addr1 = sqlite3VdbeCurrentAddr(v);
  sqlite3ExprCode(pParse, pExpr);
  addr2 = sqlite3VdbeCurrentAddr(v);
40986
40987
40988
40989
40990
40991
40992
40993

40994
40995
40996
40997
40998
40999
41000
41163
41164
41165
41166
41167
41168
41169

41170
41171
41172
41173
41174
41175
41176
41177







-
+








/*
** Generate code that pushes the value of every element of the given
** expression list onto the stack.
**
** Return the number of elements pushed onto the stack.
*/
static int sqlite3ExprCodeExprList(
SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  Parse *pParse,     /* Parsing context */
  ExprList *pList    /* The expression list to be coded */
){
  struct ExprList_item *pItem;
  int i, n;
  if( pList==0 ) return 0;
  n = pList->nExpr;
41014
41015
41016
41017
41018
41019
41020
41021

41022
41023
41024
41025
41026
41027
41028
41191
41192
41193
41194
41195
41196
41197

41198
41199
41200
41201
41202
41203
41204
41205







-
+







**
** This code depends on the fact that certain token values (ex: TK_EQ)
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
** the make process cause these values to align.  Assert()s in the code
** below verify that the numbers are aligned correctly.
*/
static void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  Vdbe *v = pParse->pVdbe;
  int op = 0;
  int ckOffset = pParse->ckOffset;
  if( v==0 || pExpr==0 ) return;
  op = pExpr->op;
  switch( op ){
    case TK_AND: {
41103
41104
41105
41106
41107
41108
41109
41110

41111
41112
41113
41114
41115
41116
41117
41280
41281
41282
41283
41284
41285
41286

41287
41288
41289
41290
41291
41292
41293
41294







-
+







** Generate code for a boolean expression such that a jump is made
** to the label "dest" if the expression is false but execution
** continues straight thru if the expression is true.
**
** If the expression evaluates to NULL (neither true nor false) then
** jump if jumpIfNull is true or fall through if jumpIfNull is false.
*/
static void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  Vdbe *v = pParse->pVdbe;
  int op = 0;
  int ckOffset = pParse->ckOffset;
  if( v==0 || pExpr==0 ) return;

  /* The value of pExpr->op and op are related as follows:
  **
41220
41221
41222
41223
41224
41225
41226
41227

41228
41229
41230
41231
41232
41233
41234
41397
41398
41399
41400
41401
41402
41403

41404
41405
41406
41407
41408
41409
41410
41411







-
+







** returns false, then you do not really know for certain if the two
** expressions are the same.  But if you get a TRUE return, then you
** can be sure the expressions are the same.  In the places where
** this routine is used, it does not hurt to get an extra FALSE - that
** just might result in some slightly slower code.  But returning
** an incorrect TRUE could lead to a malfunction.
*/
static int sqlite3ExprCompare(Expr *pA, Expr *pB){
SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
  int i;
  if( pA==0||pB==0 ){
    return pB==pA;
  }
  if( pA->op!=pB->op ) return 0;
  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
  if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
41430
41431
41432
41433
41434
41435
41436
41437

41438
41439
41440
41441
41442
41443
41444
41445
41446
41447
41448
41449

41450
41451
41452
41453
41454
41455
41456
41607
41608
41609
41610
41611
41612
41613

41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625

41626
41627
41628
41629
41630
41631
41632
41633







-
+











-
+







**
** This routine should only be called after the expression has been
** analyzed by sqlite3ExprResolveNames().
**
** If errors are seen, leave an error message in zErrMsg and return
** the number of errors.
*/
static int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
SQLITE_PRIVATE int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  int nErr = pNC->pParse->nErr;
  walkExprTree(pExpr, analyzeAggregate, pNC);
  return pNC->pParse->nErr - nErr;
}

/*
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
** expression list.  Return the number of errors.
**
** If an error is found, the analysis is cut short.
*/
static int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
SQLITE_PRIVATE int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  struct ExprList_item *pItem;
  int i;
  int nErr = 0;
  if( pList ){
    for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
      nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
    }
41470
41471
41472
41473
41474
41475
41476
41477

41478
41479
41480
41481
41482
41483
41484
41647
41648
41649
41650
41651
41652
41653

41654
41655
41656
41657
41658
41659
41660
41661







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE
41509
41510
41511
41512
41513
41514
41515
41516

41517
41518
41519
41520
41521
41522
41523
41524
41525
41526
41527
41528
41529
41530
41531
41532
41533
41534
41535
41536
41537

41538
41539
41540
41541
41542
41543
41544
41686
41687
41688
41689
41690
41691
41692

41693
41694
41695
41696
41697
41698
41699
41700
41701
41702
41703
41704
41705
41706
41707
41708
41709
41710
41711
41712
41713

41714
41715
41716
41717
41718
41719
41720
41721







-
+




















-
+







  Token tname;
  unsigned char const *zCsr = zSql;
  int len = 0;
  char *zRet;

  /* The principle used to locate the table name in the CREATE TABLE 
  ** statement is that the table name is the first token that is immediatedly
  ** followed by a left parenthesis - TK_LP.
  ** followed by a left parenthesis - TK_LP - or "USING" TK_USING.
  */
  if( zSql ){
    do {
      if( !*zCsr ){
        /* Ran out of input before finding an opening bracket. Return NULL. */
        return;
      }

      /* Store the token that zCsr points to in tname. */
      tname.z = zCsr;
      tname.n = len;

      /* Advance zCsr to the next token. Store that token type in 'token',
      ** and it's length in 'len' (to be used next iteration of this loop).
      */
      do {
        zCsr += len;
        len = sqlite3GetToken(zCsr, &token);
      } while( token==TK_SPACE );
      assert( len>0 );
    } while( token!=TK_LP );
    } while( token!=TK_LP && token!=TK_USING );

    zRet = sqlite3MPrintf("%.*s%Q%s", tname.z - zSql, zSql, 
       zTableName, tname.z+tname.n);
    sqlite3_result_text(context, zRet, -1, sqlite3FreeX);
  }
}

41615
41616
41617
41618
41619
41620
41621
41622

41623
41624
41625
41626
41627
41628
41629
41792
41793
41794
41795
41796
41797
41798

41799
41800
41801
41802
41803
41804
41805
41806







-
+







  }
}
#endif   /* !SQLITE_OMIT_TRIGGER */

/*
** Register built-in functions used to help implement ALTER TABLE
*/
static void sqlite3AlterFunctions(sqlite3 *db){
SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
  static const struct {
     char *zName;
     signed char nArg;
     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
  } aFuncs[] = {
    { "sqlite_rename_table",    2, renameTableFunc},
#ifndef SQLITE_OMIT_TRIGGER
41719
41720
41721
41722
41723
41724
41725
41726

41727
41728
41729
41730
41731
41732
41733
41734
41735
41736
41737
41738
41739
41740
41741

41742
41743
41744
41745
41746
41747
41748
41749
41750
41751
41752
41753
41754
41755
41756
41757
41758
41759
41760
41896
41897
41898
41899
41900
41901
41902

41903
41904
41905
41906
41907
41908
41909
41910
41911
41912
41913
41914
41915
41916
41917
41918
41919
41920
41921
41922
41923
41924
41925






41926
41927
41928
41929
41930
41931
41932







-
+















+






-
-
-
-
-
-







#endif
}

/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
** command. 
*/
static void sqlite3AlterRenameTable(
SQLITE_PRIVATE void sqlite3AlterRenameTable(
  Parse *pParse,            /* Parser context. */
  SrcList *pSrc,            /* The table to rename. */
  Token *pName              /* The new table name. */
){
  int iDb;                  /* Database that contains the table */
  char *zDb;                /* Name of database iDb */
  Table *pTab;              /* Table being renamed */
  char *zName = 0;          /* NULL-terminated version of pName */ 
  sqlite3 *db = pParse->db; /* Database connection */
  int nTabName;             /* Number of UTF-8 characters in zTabName */
  const char *zTabName;     /* Original name of the table */
  Vdbe *v;
#ifndef SQLITE_OMIT_TRIGGER
  char *zWhere = 0;         /* Where clause to locate temp triggers */
#endif
  int isVirtualRename = 0;  /* True if this is a v-table with an xRename() */
  
  if( sqlite3MallocFailed() ) goto exit_rename_table;
  assert( pSrc->nSrc==1 );

  pTab = sqlite3LocateTable(pParse, pSrc->a[0].zName, pSrc->a[0].zDatabase);
  if( !pTab ) goto exit_rename_table;
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( IsVirtual(pTab) ){
    sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
    goto exit_rename_table;
  }
#endif
  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  zDb = db->aDb[iDb].zName;

  /* Get a NULL terminated version of the new table name. */
  zName = sqlite3NameFromToken(pName);
  if( !zName ) goto exit_rename_table;

41780
41781
41782
41783
41784
41785
41786









41787
41788
41789
41790


41791
41792
41793
41794
41795
41796

41797












41798
41799
41800
41801
41802
41803
41804
41952
41953
41954
41955
41956
41957
41958
41959
41960
41961
41962
41963
41964
41965
41966
41967
41968
41969
41970

41971
41972
41973
41974
41975
41976
41977

41978
41979
41980
41981
41982
41983
41984
41985
41986
41987
41988
41989
41990
41991
41992
41993
41994
41995
41996
41997
41998







+
+
+
+
+
+
+
+
+



-
+
+





-
+

+
+
+
+
+
+
+
+
+
+
+
+








#ifndef SQLITE_OMIT_AUTHORIZATION
  /* Invoke the authorization callback. */
  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
    goto exit_rename_table;
  }
#endif

#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
    goto exit_rename_table;
  }
  if( IsVirtual(pTab) && pTab->pMod->pModule->xRename ){
    isVirtualRename = 1;
  }
#endif

  /* Begin a transaction and code the VerifyCookie for database iDb. 
  ** Then modify the schema cookie (since the ALTER TABLE modifies the
  ** schema).
  ** schema). Open a statement transaction if the table is a virtual
  ** table.
  */
  v = sqlite3GetVdbe(pParse);
  if( v==0 ){
    goto exit_rename_table;
  }
  sqlite3BeginWriteOperation(pParse, 0, iDb);
  sqlite3BeginWriteOperation(pParse, isVirtualRename, iDb);
  sqlite3ChangeCookie(db, v, iDb);

  /* If this is a virtual table, invoke the xRename() function if
  ** one is defined. The xRename() callback will modify the names
  ** of any resources used by the v-table implementation (including other
  ** SQLite tables) that are identified by the name of the virtual table.
  */
#ifndef SQLITE_OMIT_VIRTUALTABLE
  if( isVirtualRename ){
    sqlite3VdbeOp3(v, OP_String8, 0, 0, zName, 0);
    sqlite3VdbeOp3(v, OP_VRename, 0, 0, (const char*)pTab->pVtab, P3_VTAB);
  }
#endif

  /* figure out how many UTF-8 characters are in zName */
  zTabName = pTab->zName;
  nTabName = sqlite3Utf8CharLen(zTabName, -1);

  /* Modify the sqlite_master table to use the new table name. */
  sqlite3NestedParse(pParse,
41864
41865
41866
41867
41868
41869
41870
41871

41872
41873
41874
41875
41876
41877
41878
42058
42059
42060
42061
42062
42063
42064

42065
42066
42067
42068
42069
42070
42071
42072







-
+







** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse->pNewTable was extended to include
** the new column during parsing.
*/
static void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  Table *pNew;              /* Copy of pParse->pNewTable */
  Table *pTab;              /* Table being altered */
  int iDb;                  /* Database number */
  const char *zDb;          /* Database name */
  const char *zTab;         /* Table name */
  char *zCol;               /* Null-terminated column definition */
  Column *pCol;             /* The new column */
41977
41978
41979
41980
41981
41982
41983
41984

41985
41986
41987
41988
41989
41990
41991
42171
42172
42173
42174
42175
42176
42177

42178
42179
42180
42181
42182
42183
42184
42185







-
+







** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
** the copy. The copy of the Table structure is deleted by tokenize.c 
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
static void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  Table *pNew;
  Table *pTab;
  Vdbe *v;
  int iDb;
  int i;
  int nAlloc;

42062
42063
42064
42065
42066
42067
42068
42069

42070
42071
42072
42073
42074
42075
42076
42256
42257
42258
42259
42260
42261
42262

42263
42264
42265
42266
42267
42268
42269
42270







-
+







**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code associated with the ANALYZE command.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef SQLITE_OMIT_ANALYZE

/*
** This routine generates code that opens the sqlite_stat1 table on cursor
** iStatCur.
**
42224
42225
42226
42227
42228
42229
42230
42231

42232
42233
42234
42235
42236
42237
42238
42418
42419
42420
42421
42422
42423
42424

42425
42426
42427
42428
42429
42430
42431
42432







-
+







    }
    sqlite3VdbeResolveLabel(v, endOfLoop);
    sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
    sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);

    /* Store the results.  
    **
    ** The result is a single row of the sqlite_stmt1 table.  The first
    ** The result is a single row of the sqlite_stat1 table.  The first
    ** two columns are the names of the table and index.  The third column
    ** is a string composed of a list of integer statistics about the
    ** index.  The first integer in the list is the total number of entires
    ** in the index.  There is one additional integer in the list for each
    ** column of the table.  This additional integer is a guess of how many
    ** rows of the table the index will select.  If D is the count of distinct
    ** values and K is the total number of rows, then the integer is computed
42328
42329
42330
42331
42332
42333
42334
42335

42336
42337
42338
42339
42340
42341
42342
42522
42523
42524
42525
42526
42527
42528

42529
42530
42531
42532
42533
42534
42535
42536







-
+







**        ANALYZE  <database>                -- 2
**        ANALYZE  ?<database>.?<tablename>  -- 3
**
** Form 1 causes all indices in all attached databases to be analyzed.
** Form 2 analyzes all indices the single database named.
** Form 3 analyzes all indices associated with the named table.
*/
static void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  sqlite3 *db = pParse->db;
  int iDb;
  int i;
  char *z, *zDb;
  Table *pTab;
  Token *pTableName;

42426
42427
42428
42429
42430
42431
42432
42433

42434
42435
42436
42437
42438
42439
42440
42620
42621
42622
42623
42624
42625
42626

42627
42628
42629
42630
42631
42632
42633
42634







-
+







  }
  return 0;
}

/*
** Load the content of the sqlite_stat1 table into the index hash tables.
*/
static int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  analysisInfo sInfo;
  HashElem *i;
  char *zSql;
  int rc;

  /* Clear any prior statistics */
  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
42474
42475
42476
42477
42478
42479
42480
42481

42482
42483
42484
42485
42486
42487
42488
42668
42669
42670
42671
42672
42673
42674

42675
42676
42677
42678
42679
42680
42681
42682







-
+







**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the ATTACH and DETACH commands.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

#ifndef SQLITE_OMIT_ATTACH
/*
** Resolve an expression that was part of an ATTACH or DETACH statement. This
** is slightly different from resolving a normal SQL expression, because simple
** identifiers are treated as strings, not possible column names or aliases.
42809
42810
42811
42812
42813
42814
42815
42816

42817
42818
42819
42820
42821
42822
42823
42824
42825

42826
42827
42828
42829
42830
42831
42832
42833

42834
42835
42836
42837
42838
42839
42840
42841
42842
42843
42844
42845
42846
42847
42848

42849
42850
42851
42852
42853
42854
42855
43003
43004
43005
43006
43007
43008
43009

43010
43011
43012
43013
43014
43015
43016
43017
43018

43019
43020
43021
43022
43023
43024
43025
43026

43027
43028
43029
43030
43031
43032
43033
43034
43035
43036
43037
43038
43039
43040
43041

43042
43043
43044
43045
43046
43047
43048
43049







-
+








-
+







-
+














-
+







}

/*
** Called by the parser to compile a DETACH statement.
**
**     DETACH pDbname
*/
static void sqlite3Detach(Parse *pParse, Expr *pDbname){
SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  codeAttach(pParse, SQLITE_DETACH, "sqlite_detach", 1, pDbname, 0, 0, pDbname);
}

/*
** Called by the parser to compile an ATTACH statement.
**
**     ATTACH p AS pDbname KEY pKey
*/
static void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  codeAttach(pParse, SQLITE_ATTACH, "sqlite_attach", 3, p, p, pDbname, pKey);
}
#endif /* SQLITE_OMIT_ATTACH */

/*
** Register the functions sqlite_attach and sqlite_detach.
*/
static void sqlite3AttachFunctions(sqlite3 *db){
SQLITE_PRIVATE void sqlite3AttachFunctions(sqlite3 *db){
#ifndef SQLITE_OMIT_ATTACH
  static const int enc = SQLITE_UTF8;
  sqlite3CreateFunc(db, "sqlite_attach", 3, enc, db, attachFunc, 0, 0);
  sqlite3CreateFunc(db, "sqlite_detach", 1, enc, db, detachFunc, 0, 0);
#endif
}

/*
** Initialize a DbFixer structure.  This routine must be called prior
** to passing the structure to one of the sqliteFixAAAA() routines below.
**
** The return value indicates whether or not fixation is required.  TRUE
** means we do need to fix the database references, FALSE means we do not.
*/
static int sqlite3FixInit(
SQLITE_PRIVATE int sqlite3FixInit(
  DbFixer *pFix,      /* The fixer to be initialized */
  Parse *pParse,      /* Error messages will be written here */
  int iDb,            /* This is the database that must be used */
  const char *zType,  /* "view", "trigger", or "index" */
  const Token *pName  /* Name of the view, trigger, or index */
){
  sqlite3 *db;
42874
42875
42876
42877
42878
42879
42880
42881

42882
42883
42884
42885
42886
42887
42888
43068
43069
43070
43071
43072
43073
43074

43075
43076
43077
43078
43079
43080
43081
43082







-
+







** view in one database does not refer to objects in a different database.
** (Exception: indices, triggers, and views in the TEMP database are
** allowed to refer to anything.)  If a reference is explicitly made
** to an object in a different database, an error message is added to
** pParse->zErrMsg and these routines return non-zero.  If everything
** checks out, these routines return 0.
*/
static int sqlite3FixSrcList(
SQLITE_PRIVATE int sqlite3FixSrcList(
  DbFixer *pFix,       /* Context of the fixation */
  SrcList *pList       /* The Source list to check and modify */
){
  int i;
  const char *zDb;
  struct SrcList_item *pItem;

42901
42902
42903
42904
42905
42906
42907
42908

42909
42910
42911
42912
42913
42914
42915
42916
42917
42918
42919
42920
42921
42922
42923
42924
42925
42926
42927
42928
42929

42930
42931
42932
42933
42934
42935
42936
42937
42938
42939
42940
42941
42942
42943
42944
42945
42946
42947

42948
42949
42950
42951
42952
42953
42954
42955
42956
42957
42958
42959
42960
42961
42962
42963
42964

42965
42966
42967
42968
42969
42970
42971
43095
43096
43097
43098
43099
43100
43101

43102
43103
43104
43105
43106
43107
43108
43109
43110
43111
43112
43113
43114
43115
43116
43117
43118
43119
43120
43121
43122

43123
43124
43125
43126
43127
43128
43129
43130
43131
43132
43133
43134
43135
43136
43137
43138
43139
43140

43141
43142
43143
43144
43145
43146
43147
43148
43149
43150
43151
43152
43153
43154
43155
43156
43157

43158
43159
43160
43161
43162
43163
43164
43165







-
+




















-
+

















-
+
















-
+







    if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
    if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
#endif
  }
  return 0;
}
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
static int sqlite3FixSelect(
SQLITE_PRIVATE int sqlite3FixSelect(
  DbFixer *pFix,       /* Context of the fixation */
  Select *pSelect      /* The SELECT statement to be fixed to one database */
){
  while( pSelect ){
    if( sqlite3FixExprList(pFix, pSelect->pEList) ){
      return 1;
    }
    if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
      return 1;
    }
    pSelect = pSelect->pPrior;
  }
  return 0;
}
static int sqlite3FixExpr(
SQLITE_PRIVATE int sqlite3FixExpr(
  DbFixer *pFix,     /* Context of the fixation */
  Expr *pExpr        /* The expression to be fixed to one database */
){
  while( pExpr ){
    if( sqlite3FixSelect(pFix, pExpr->pSelect) ){
      return 1;
    }
    if( sqlite3FixExprList(pFix, pExpr->pList) ){
      return 1;
    }
    if( sqlite3FixExpr(pFix, pExpr->pRight) ){
      return 1;
    }
    pExpr = pExpr->pLeft;
  }
  return 0;
}
static int sqlite3FixExprList(
SQLITE_PRIVATE int sqlite3FixExprList(
  DbFixer *pFix,     /* Context of the fixation */
  ExprList *pList    /* The expression to be fixed to one database */
){
  int i;
  struct ExprList_item *pItem;
  if( pList==0 ) return 0;
  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
    if( sqlite3FixExpr(pFix, pItem->pExpr) ){
      return 1;
    }
  }
  return 0;
}
#endif

#ifndef SQLITE_OMIT_TRIGGER
static int sqlite3FixTriggerStep(
SQLITE_PRIVATE int sqlite3FixTriggerStep(
  DbFixer *pFix,     /* Context of the fixation */
  TriggerStep *pStep /* The trigger step be fixed to one database */
){
  while( pStep ){
    if( sqlite3FixSelect(pFix, pStep->pSelect) ){
      return 1;
    }
42995
42996
42997
42998
42999
43000
43001
43002

43003
43004
43005
43006
43007
43008
43009
43189
43190
43191
43192
43193
43194
43195

43196
43197
43198
43199
43200
43201
43202
43203







-
+







**
*************************************************************************
** This file contains code used to implement the sqlite3_set_authorizer()
** API.  This facility is an optional feature of the library.  Embedded
** systems that do not need this facility may omit it by recompiling
** the library with -DSQLITE_OMIT_AUTHORIZATION=1
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** All of the code in this file may be omitted by defining a single
** macro.
*/
#ifndef SQLITE_OMIT_AUTHORIZATION
43080
43081
43082
43083
43084
43085
43086
43087

43088
43089
43090
43091
43092
43093
43094
43274
43275
43276
43277
43278
43279
43280

43281
43282
43283
43284
43285
43286
43287
43288







-
+







** is in pTabList or else it is the NEW or OLD table of a trigger.  
** Check to see if it is OK to read this particular column.
**
** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
** then generate an error.
*/
static void sqlite3AuthRead(
SQLITE_PRIVATE void sqlite3AuthRead(
  Parse *pParse,        /* The parser context */
  Expr *pExpr,          /* The expression to check authorization on */
  SrcList *pTabList     /* All table that pExpr might refer to */
){
  sqlite3 *db = pParse->db;
  int rc;
  Table *pTab;          /* The table being read */
43151
43152
43153
43154
43155
43156
43157
43158

43159
43160
43161
43162
43163
43164
43165
43345
43346
43347
43348
43349
43350
43351

43352
43353
43354
43355
43356
43357
43358
43359







-
+








/*
** Do an authorization check using the code and arguments given.  Return
** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
** is returned, then the error count and error message in pParse are
** modified appropriately.
*/
static int sqlite3AuthCheck(
SQLITE_PRIVATE int sqlite3AuthCheck(
  Parse *pParse,
  int code,
  const char *zArg1,
  const char *zArg2,
  const char *zArg3
){
  sqlite3 *db = pParse->db;
43187
43188
43189
43190
43191
43192
43193
43194

43195
43196
43197
43198
43199
43200
43201
43202
43203
43204
43205
43206
43207
43208
43209
43210

43211
43212
43213
43214
43215
43216
43217
43381
43382
43383
43384
43385
43386
43387

43388
43389
43390
43391
43392
43393
43394
43395
43396
43397
43398
43399
43400
43401
43402
43403

43404
43405
43406
43407
43408
43409
43410
43411







-
+















-
+







}

/*
** Push an authorization context.  After this routine is called, the
** zArg3 argument to authorization callbacks will be zContext until
** popped.  Or if pParse==0, this routine is a no-op.
*/
static void sqlite3AuthContextPush(
SQLITE_PRIVATE void sqlite3AuthContextPush(
  Parse *pParse,
  AuthContext *pContext, 
  const char *zContext
){
  pContext->pParse = pParse;
  if( pParse ){
    pContext->zAuthContext = pParse->zAuthContext;
    pParse->zAuthContext = zContext;
  }
}

/*
** Pop an authorization context that was previously pushed
** by sqlite3AuthContextPush
*/
static void sqlite3AuthContextPop(AuthContext *pContext){
SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  if( pContext->pParse ){
    pContext->pParse->zAuthContext = pContext->zAuthContext;
    pContext->pParse = 0;
  }
}

#endif /* SQLITE_OMIT_AUTHORIZATION */
43238
43239
43240
43241
43242
43243
43244
43245

43246
43247
43248
43249
43250
43251
43252

43253
43254
43255
43256
43257
43258
43259
43432
43433
43434
43435
43436
43437
43438

43439
43440
43441
43442
43443
43444
43445

43446
43447
43448
43449
43450
43451
43452
43453







-
+






-
+







**     CREATE INDEX
**     DROP INDEX
**     creating ID lists
**     BEGIN TRANSACTION
**     COMMIT
**     ROLLBACK
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** This routine is called when a new SQL statement is beginning to
** be parsed.  Initialize the pParse structure as needed.
*/
static void sqlite3BeginParse(Parse *pParse, int explainFlag){
SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  pParse->explain = explainFlag;
  pParse->nVar = 0;
}

#ifndef SQLITE_OMIT_SHARED_CACHE
/*
** The TableLock structure is only used by the sqlite3TableLock() and
43272
43273
43274
43275
43276
43277
43278
43279

43280
43281
43282
43283
43284
43285
43286
43466
43467
43468
43469
43470
43471
43472

43473
43474
43475
43476
43477
43478
43479
43480







-
+







** The table to be locked has root page iTab and is found in database iDb.
** A read or a write lock can be taken depending on isWritelock.
**
** This routine just records the fact that the lock is desired.  The
** code to make the lock occur is generated by a later call to
** codeTableLocks() which occurs during sqlite3FinishCoding().
*/
static void sqlite3TableLock(
SQLITE_PRIVATE void sqlite3TableLock(
  Parse *pParse,     /* Parsing context */
  int iDb,           /* Index of the database containing the table to lock */
  int iTab,          /* Root page number of the table to be locked */
  u8 isWriteLock,    /* True for a write lock */
  const char *zName  /* Name of the table to be locked */
){
  int i;
43342
43343
43344
43345
43346
43347
43348
43349

43350
43351
43352
43353
43354
43355
43356
43536
43537
43538
43539
43540
43541
43542

43543
43544
43545
43546
43547
43548
43549
43550







-
+







** prepared.  This routine puts the finishing touches on the
** VDBE program and resets the pParse structure for the next
** parse.
**
** Note that if an error occurred, it might be the case that
** no VDBE code was generated.
*/
static void sqlite3FinishCoding(Parse *pParse){
SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( sqlite3MallocFailed() ) return;
  if( pParse->nested ) return;
  if( !pParse->pVdbe ){
    if( pParse->rc==SQLITE_OK && pParse->nErr ){
43439
43440
43441
43442
43443
43444
43445
43446

43447
43448
43449
43450
43451
43452
43453
43633
43634
43635
43636
43637
43638
43639

43640
43641
43642
43643
43644
43645
43646
43647







-
+







** and finalization steps are omitted because those are handling by the
** outermost parser.
**
** Not everything is nestable.  This facility is designed to permit
** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
** care if you decide to try to use this routine for some other purposes.
*/
static void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  va_list ap;
  char *zSql;
# define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
  char saveBuf[SAVE_SZ];

  if( pParse->nErr ) return;
  assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
43474
43475
43476
43477
43478
43479
43480
43481

43482
43483
43484
43485
43486
43487
43488
43668
43669
43670
43671
43672
43673
43674

43675
43676
43677
43678
43679
43680
43681
43682







-
+







** If zDatabase is 0, all databases are searched for the table and the
** first matching table is returned.  (No checking for duplicate table
** names is done.)  The search order is TEMP first, then MAIN, then any
** auxiliary databases added using the ATTACH command.
**
** See also sqlite3LocateTable().
*/
static Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  Table *p = 0;
  int i;
  assert( zName!=0 );
  for(i=OMIT_TEMPDB; i<db->nDb; i++){
    int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
    if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
    p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, strlen(zName)+1);
43497
43498
43499
43500
43501
43502
43503
43504

43505
43506
43507
43508
43509
43510
43511
43691
43692
43693
43694
43695
43696
43697

43698
43699
43700
43701
43702
43703
43704
43705







-
+







** database containing the table.  Return NULL if not found.  Also leave an
** error message in pParse->zErrMsg.
**
** The difference between this routine and sqlite3FindTable() is that this
** routine leaves an error message in pParse->zErrMsg where
** sqlite3FindTable() does not.
*/
static Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
SQLITE_PRIVATE Table *sqlite3LocateTable(Parse *pParse, const char *zName, const char *zDbase){
  Table *p;

  /* Read the database schema. If an error occurs, leave an error message
  ** and code in pParse and return NULL. */
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
    return 0;
  }
43530
43531
43532
43533
43534
43535
43536
43537

43538
43539
43540
43541
43542
43543
43544
43724
43725
43726
43727
43728
43729
43730

43731
43732
43733
43734
43735
43736
43737
43738







-
+







**
** If zDatabase is 0, all databases are searched for the
** table and the first matching index is returned.  (No checking
** for duplicate index names is done.)  The search order is
** TEMP first, then MAIN, then any auxiliary databases added
** using the ATTACH command.
*/
static Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  Index *p = 0;
  int i;
  for(i=OMIT_TEMPDB; i<db->nDb; i++){
    int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
    Schema *pSchema = db->aDb[j].pSchema;
    if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
    assert( pSchema || (j==1 && !db->aDb[1].pBt) );
43577
43578
43579
43580
43581
43582
43583
43584

43585
43586
43587
43588
43589
43590
43591
43771
43772
43773
43774
43775
43776
43777

43778
43779
43780
43781
43782
43783
43784
43785







-
+








/*
** For the index called zIdxName which is found in the database iDb,
** unlike that index from its Table then remove the index from
** the index hash table and free all memory structures associated
** with the index.
*/
static void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  Index *pIndex;
  int len;
  Hash *pHash = &db->aDb[iDb].pSchema->idxHash;

  len = strlen(zIdxName);
  pIndex = sqlite3HashInsert(pHash, zIdxName, len+1, 0);
  if( pIndex ){
43610
43611
43612
43613
43614
43615
43616
43617

43618
43619
43620
43621
43622
43623
43624
43804
43805
43806
43807
43808
43809
43810

43811
43812
43813
43814
43815
43816
43817
43818







-
+







** if there were schema changes during the transaction or if a
** schema-cookie mismatch occurs.
**
** If iDb<=0 then reset the internal schema tables for all database
** files.  If iDb>=2 then reset the internal schema for only the
** single file indicated.
*/
static void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
  int i, j;

  assert( iDb>=0 && iDb<db->nDb );
  for(i=iDb; i<db->nDb; i++){
    Db *pDb = &db->aDb[i];
    if( pDb->pSchema ){
      sqlite3SchemaFree(pDb->pSchema);
43661
43662
43663
43664
43665
43666
43667
43668

43669
43670
43671
43672
43673
43674
43675
43855
43856
43857
43858
43859
43860
43861

43862
43863
43864
43865
43866
43867
43868
43869







-
+







    db->aDb = db->aDbStatic;
  }
}

/*
** This routine is called when a commit occurs.
*/
static void sqlite3CommitInternalChanges(sqlite3 *db){
SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  db->flags &= ~SQLITE_InternChanges;
}

/*
** Clear the column names from a table or view.
*/
static void sqliteResetColumnNames(Table *pTable){
43695
43696
43697
43698
43699
43700
43701
43702

43703
43704
43705
43706
43707
43708
43709
43889
43890
43891
43892
43893
43894
43895

43896
43897
43898
43899
43900
43901
43902
43903







-
+







**
** This routine just deletes the data structure.  It does not unlink
** the table data structure from the hash table.  Nor does it remove
** foreign keys from the sqlite.aFKey hash table.  But it does destroy
** memory structures of the indices and foreign keys associated with 
** the table.
*/
static void sqlite3DeleteTable(Table *pTable){
SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
  Index *pIndex, *pNext;
  FKey *pFKey, *pNextFKey;

  if( pTable==0 ) return;

  /* Do not delete the table until the reference count reaches zero. */
  pTable->nRef--;
43745
43746
43747
43748
43749
43750
43751
43752

43753
43754
43755
43756
43757
43758
43759
43939
43940
43941
43942
43943
43944
43945

43946
43947
43948
43949
43950
43951
43952
43953







-
+







  sqliteFree(pTable);
}

/*
** Unlink the given table from the hash tables and the delete the
** table structure with all its indices and foreign keys.
*/
static void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  Table *p;
  FKey *pF1, *pF2;
  Db *pDb;

  assert( db!=0 );
  assert( iDb>=0 && iDb<db->nDb );
  assert( zTabName && zTabName[0] );
43785
43786
43787
43788
43789
43790
43791
43792

43793
43794
43795
43796
43797
43798
43799
43800
43801
43802
43803
43804
43805
43806
43807

43808
43809
43810
43811
43812
43813
43814
43815
43816
43817
43818
43819
43820
43821

43822
43823
43824
43825
43826
43827
43828
43979
43980
43981
43982
43983
43984
43985

43986
43987
43988
43989
43990
43991
43992
43993
43994
43995
43996
43997
43998
43999
44000

44001
44002
44003
44004
44005
44006
44007
44008
44009
44010
44011
44012
44013
44014

44015
44016
44017
44018
44019
44020
44021
44022







-
+














-
+













-
+







** is obtained from sqliteMalloc() and must be freed by the calling
** function.
**
** Tokens are often just pointers into the original SQL text and so
** are not \000 terminated and are not persistent.  The returned string
** is \000 terminated and is persistent.
*/
static char *sqlite3NameFromToken(Token *pName){
SQLITE_PRIVATE char *sqlite3NameFromToken(Token *pName){
  char *zName;
  if( pName ){
    zName = sqliteStrNDup((char*)pName->z, pName->n);
    sqlite3Dequote(zName);
  }else{
    zName = 0;
  }
  return zName;
}

/*
** Open the sqlite_master table stored in database number iDb for
** writing. The table is opened using cursor 0.
*/
static void sqlite3OpenMasterTable(Parse *p, int iDb){
SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  Vdbe *v = sqlite3GetVdbe(p);
  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
  sqlite3VdbeAddOp(v, OP_OpenWrite, 0, MASTER_ROOT);
  sqlite3VdbeAddOp(v, OP_SetNumColumns, 0, 5); /* sqlite_master has 5 columns */
}

/*
** The token *pName contains the name of a database (either "main" or
** "temp" or the name of an attached db). This routine returns the
** index of the named database in db->aDb[], or -1 if the named db 
** does not exist.
*/
static int sqlite3FindDb(sqlite3 *db, Token *pName){
SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  int i = -1;    /* Database number */
  int n;         /* Number of characters in the name */
  Db *pDb;       /* A database whose name space is being searched */
  char *zName;   /* Name we are searching for */

  zName = sqlite3NameFromToken(pName);
  if( zName ){
43850
43851
43852
43853
43854
43855
43856
43857

43858
43859
43860
43861
43862
43863
43864
44044
44045
44046
44047
44048
44049
44050

44051
44052
44053
44054
44055
44056
44057
44058







-
+







**
** Then pName1 is set to "yyy" and pName2 is "".
**
** This routine sets the *ppUnqual pointer to point at the token (pName1 or
** pName2) that stores the unqualified table name.  The index of the
** database "xxx" is returned.
*/
static int sqlite3TwoPartName(
SQLITE_PRIVATE int sqlite3TwoPartName(
  Parse *pParse,      /* Parsing and code generating context */
  Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
  Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
  Token **pUnqual     /* Write the unqualified object name here */
){
  int iDb;                    /* Database holding the object */
  sqlite3 *db = pParse->db;
43883
43884
43885
43886
43887
43888
43889
43890

43891
43892
43893
43894
43895
43896
43897
44077
44078
44079
44080
44081
44082
44083

44084
44085
44086
44087
44088
44089
44090
44091







-
+







/*
** This routine is used to check if the UTF-8 string zName is a legal
** unqualified name for a new schema object (table, index, view or
** trigger). All names are legal except those that begin with the string
** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
** is reserved for internal use.
*/
static int sqlite3CheckObjectName(Parse *pParse, const char *zName){
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  if( !pParse->db->init.busy && pParse->nested==0 
          && (pParse->db->flags & SQLITE_WriteSchema)==0
          && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
    sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
    return SQLITE_ERROR;
  }
  return SQLITE_OK;
43909
43910
43911
43912
43913
43914
43915
43916

43917
43918
43919
43920
43921
43922
43923
44103
44104
44105
44106
44107
44108
44109

44110
44111
44112
44113
44114
44115
44116
44117







-
+







**
** The new table record is initialized and put in pParse->pNewTable.
** As more of the CREATE TABLE statement is parsed, additional action
** routines will be called to add more information to this record.
** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
** is called to complete the construction of the new table record.
*/
static void sqlite3StartTable(
SQLITE_PRIVATE void sqlite3StartTable(
  Parse *pParse,   /* Parser context */
  Token *pName1,   /* First part of the name of the table or view */
  Token *pName2,   /* Second part of the name of the table or view */
  int isTemp,      /* True if this is a TEMP table */
  int isView,      /* True if this is a VIEW */
  int isVirtual,   /* True if this is a VIRTUAL table */
  int noErr        /* Do nothing if table already exists */
44120
44121
44122
44123
44124
44125
44126
44127

44128
44129
44130
44131
44132
44133
44134
44314
44315
44316
44317
44318
44319
44320

44321
44322
44323
44324
44325
44326
44327
44328







-
+







** Add a new column to the table currently being constructed.
**
** The parser calls this routine once for each column declaration
** in a CREATE TABLE statement.  sqlite3StartTable() gets called
** first to get things going.  Then this routine is called for each
** column.
*/
static void sqlite3AddColumn(Parse *pParse, Token *pName){
SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  Table *p;
  int i;
  char *z;
  Column *pCol;
  if( (p = pParse->pNewTable)==0 ) return;
  if( p->nCol+1>SQLITE_MAX_COLUMN ){
    sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
44166
44167
44168
44169
44170
44171
44172
44173

44174
44175
44176
44177
44178
44179
44180
44360
44361
44362
44363
44364
44365
44366

44367
44368
44369
44370
44371
44372
44373
44374







-
+








/*
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
** been seen on a column.  This routine sets the notNull flag on
** the column currently under construction.
*/
static void sqlite3AddNotNull(Parse *pParse, int onError){
SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  Table *p;
  int i;
  if( (p = pParse->pNewTable)==0 ) return;
  i = p->nCol-1;
  if( i>=0 ) p->aCol[i].notNull = onError;
}

44199
44200
44201
44202
44203
44204
44205
44206

44207
44208
44209
44210
44211
44212
44213
44393
44394
44395
44396
44397
44398
44399

44400
44401
44402
44403
44404
44405
44406
44407







-
+







** 'REAL'        | SQLITE_AFF_REAL
** 'FLOA'        | SQLITE_AFF_REAL
** 'DOUB'        | SQLITE_AFF_REAL
**
** If none of the substrings in the above table are found,
** SQLITE_AFF_NUMERIC is returned.
*/
static char sqlite3AffinityType(const Token *pType){
SQLITE_PRIVATE char sqlite3AffinityType(const Token *pType){
  u32 h = 0;
  char aff = SQLITE_AFF_NUMERIC;
  const unsigned char *zIn = pType->z;
  const unsigned char *zEnd = &pType->z[pType->n];

  while( zIn!=zEnd ){
    h = (h<<8) + sqlite3UpperToLower[*zIn];
44246
44247
44248
44249
44250
44251
44252
44253

44254
44255
44256
44257
44258
44259
44260
44440
44441
44442
44443
44444
44445
44446

44447
44448
44449
44450
44451
44452
44453
44454







-
+







** parsing a CREATE TABLE statement.  The pFirst token is the first
** token in the sequence of tokens that describe the type of the
** column currently under construction.   pLast is the last token
** in the sequence.  Use this information to construct a string
** that contains the typename of the column and store that string
** in zType.
*/ 
static void sqlite3AddColumnType(Parse *pParse, Token *pType){
SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  Table *p;
  int i;
  Column *pCol;

  if( (p = pParse->pNewTable)==0 ) return;
  i = p->nCol-1;
  if( i<0 ) return;
44270
44271
44272
44273
44274
44275
44276
44277

44278
44279
44280
44281
44282
44283
44284
44464
44465
44466
44467
44468
44469
44470

44471
44472
44473
44474
44475
44476
44477
44478







-
+







**
** Default value expressions must be constant.  Raise an exception if this
** is not the case.
**
** This routine is called by the parser while in the middle of
** parsing a CREATE TABLE statement.
*/
static void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){
  Table *p;
  Column *pCol;
  if( (p = pParse->pNewTable)!=0 ){
    pCol = &(p->aCol[p->nCol-1]);
    if( !sqlite3ExprIsConstantOrFunction(pExpr) ){
      sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
          pCol->zName);
44308
44309
44310
44311
44312
44313
44314
44315

44316
44317
44318
44319
44320
44321
44322
44502
44503
44504
44505
44506
44507
44508

44509
44510
44511
44512
44513
44514
44515
44516







-
+







** field of the table under construction to be the index of the
** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
** no INTEGER PRIMARY KEY.
**
** If the key is not an INTEGER PRIMARY KEY, then create a unique
** index for the key.  No index is created for INTEGER PRIMARY KEYs.
*/
static void sqlite3AddPrimaryKey(
SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  Parse *pParse,    /* Parsing context */
  ExprList *pList,  /* List of field names to be indexed */
  int onError,      /* What to do with a uniqueness conflict */
  int autoInc,      /* True if the AUTOINCREMENT keyword is present */
  int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
){
  Table *pTab = pParse->pNewTable;
44367
44368
44369
44370
44371
44372
44373
44374

44375
44376
44377
44378
44379
44380
44381
44382
44383
44384
44385
44386
44387
44388
44389
44390
44391
44392
44393
44394

44395
44396
44397
44398
44399
44400
44401
44561
44562
44563
44564
44565
44566
44567

44568
44569
44570
44571
44572
44573
44574
44575
44576
44577
44578
44579
44580
44581
44582
44583
44584
44585
44586
44587

44588
44589
44590
44591
44592
44593
44594
44595







-
+



















-
+







  sqlite3ExprListDelete(pList);
  return;
}

/*
** Add a new CHECK constraint to the table currently under construction.
*/
static void sqlite3AddCheckConstraint(
SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  Parse *pParse,    /* Parsing context */
  Expr *pCheckExpr  /* The check expression */
){
#ifndef SQLITE_OMIT_CHECK
  Table *pTab = pParse->pNewTable;
  if( pTab && !IN_DECLARE_VTAB ){
    /* The CHECK expression must be duplicated so that tokens refer
    ** to malloced space and not the (ephemeral) text of the CREATE TABLE
    ** statement */
    pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr));
  }
#endif
  sqlite3ExprDelete(pCheckExpr);
}

/*
** Set the collation function of the most recently parsed table column
** to the CollSeq given.
*/
static void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){
  Table *p;
  int i;

  if( (p = pParse->pNewTable)==0 ) return;
  i = p->nCol-1;

  if( sqlite3LocateCollSeq(pParse, zType, nType) ){
44429
44430
44431
44432
44433
44434
44435
44436

44437
44438
44439
44440
44441
44442
44443
44623
44624
44625
44626
44627
44628
44629

44630
44631
44632
44633
44634
44635
44636
44637







-
+







** another error occurs, NULL is returned and an error message written into
** pParse.
**
** This routine is a wrapper around sqlite3FindCollSeq().  This routine
** invokes the collation factory if the named collation cannot be found
** and generates an error message.
*/
static CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){
  sqlite3 *db = pParse->db;
  u8 enc = ENC(db);
  u8 initbusy = db->init.busy;
  CollSeq *pColl;

  pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy);
  if( !initbusy && (!pColl || !pColl->xCmp) ){
44467
44468
44469
44470
44471
44472
44473
44474

44475
44476
44477
44478
44479
44480
44481
44661
44662
44663
44664
44665
44666
44667

44668
44669
44670
44671
44672
44673
44674
44675







-
+







**
** This plan is not completely bullet-proof.  It is possible for
** the schema to change multiple times and for the cookie to be
** set back to prior value.  But schema changes are infrequent
** and the probability of hitting the same cookie value is only
** 1 chance in 2^32.  So we're safe enough.
*/
static void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
SQLITE_PRIVATE void sqlite3ChangeCookie(sqlite3 *db, Vdbe *v, int iDb){
  sqlite3VdbeAddOp(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, 0);
  sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 0);
}

/*
** Measure the number of characters needed to output the given
** identifier.  The number returned includes any quotes used
44583
44584
44585
44586
44587
44588
44589
44590

44591
44592
44593
44594
44595
44596
44597
44777
44778
44779
44780
44781
44782
44783

44784
44785
44786
44787
44788
44789
44790
44791







-
+







** the sqlite_master table.  We do not want to create it again.
**
** If the pSelect argument is not NULL, it means that this routine
** was called to create a table generated from a 
** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
** the new table will match the result set of the SELECT.
*/
static void sqlite3EndTable(
SQLITE_PRIVATE void sqlite3EndTable(
  Parse *pParse,          /* Parse context */
  Token *pCons,           /* The ',' token after the last column defn. */
  Token *pEnd,            /* The final ')' token in the CREATE TABLE */
  Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
){
  Table *p;
  sqlite3 *db = pParse->db;
44792
44793
44794
44795
44796
44797
44798
44799

44800
44801
44802
44803
44804
44805
44806
44986
44987
44988
44989
44990
44991
44992

44993
44994
44995
44996
44997
44998
44999
45000







-
+







  }
}

#ifndef SQLITE_OMIT_VIEW
/*
** The parser calls this routine in order to create a new VIEW
*/
static void sqlite3CreateView(
SQLITE_PRIVATE void sqlite3CreateView(
  Parse *pParse,     /* The parsing context */
  Token *pBegin,     /* The CREATE token that begins the statement */
  Token *pName1,     /* The token that holds the name of the view */
  Token *pName2,     /* The token that holds the name of the view */
  Select *pSelect,   /* A SELECT statement that will become the new view */
  int isTemp,        /* TRUE for a TEMPORARY view */
  int noErr          /* Suppress error messages if VIEW already exists */
44869
44870
44871
44872
44873
44874
44875
44876

44877
44878
44879
44880
44881
44882
44883
45063
45064
45065
45066
45067
45068
45069

45070
45071
45072
45073
45074
45075
45076
45077







-
+








#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
/*
** The Table structure pTable is really a VIEW.  Fill in the names of
** the columns of the view in the pTable structure.  Return the number
** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
*/
static int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  Table *pSelTab;   /* A fake table from which we get the result set */
  Select *pSel;     /* Copy of the SELECT that implements the view */
  int nErr = 0;     /* Number of errors encountered */
  int n;            /* Temporarily holds the number of cursors assigned */

  assert( pTable );

44979
44980
44981
44982
44983
44984
44985
44986

44987
44988
44989
44990
44991
44992
44993
45173
45174
45175
45176
45177
45178
45179

45180
45181
45182
45183
45184
45185
45186
45187







-
+







** because the first match might be for one of the deleted indices
** or tables and not the table/index that is actually being moved.
** We must continue looping until all tables and indices with
** rootpage==iFrom have been converted to have a rootpage of iTo
** in order to be certain that we got the right one.
*/
#ifndef SQLITE_OMIT_AUTOVACUUM
static void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
  HashElem *pElem;
  Hash *pHash;

  pHash = &pDb->pSchema->tblHash;
  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
    Table *pTab = sqliteHashData(pElem);
    if( pTab->tnum==iFrom ){
45087
45088
45089
45090
45091
45092
45093
45094

45095
45096
45097
45098
45099
45100
45101
45281
45282
45283
45284
45285
45286
45287

45288
45289
45290
45291
45292
45293
45294
45295







-
+







#endif
}

/*
** This routine is called to do the work of a DROP TABLE statement.
** pName is the name of the table to be dropped.
*/
static void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  Table *pTab;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  if( pParse->nErr || sqlite3MallocFailed() ){
    goto exit_drop_table;
45255
45256
45257
45258
45259
45260
45261
45262

45263
45264
45265
45266
45267
45268
45269
45449
45450
45451
45452
45453
45454
45455

45456
45457
45458
45459
45460
45461
45462
45463







-
+







** under construction in the pParse->pNewTable field.  The new FKey
** is not linked into db->aFKey at this point - that does not happen
** until sqlite3EndTable().
**
** The foreign key is set for IMMEDIATE processing.  A subsequent call
** to sqlite3DeferForeignKey() might change this to DEFERRED.
*/
static void sqlite3CreateForeignKey(
SQLITE_PRIVATE void sqlite3CreateForeignKey(
  Parse *pParse,       /* Parsing context */
  ExprList *pFromCol,  /* Columns in this table that point to other table */
  Token *pTo,          /* Name of the other table */
  ExprList *pToCol,    /* Columns in the other table */
  int flags            /* Conflict resolution algorithms. */
){
#ifndef SQLITE_OMIT_FOREIGN_KEY
45361
45362
45363
45364
45365
45366
45367
45368

45369
45370
45371
45372
45373
45374
45375
45555
45556
45557
45558
45559
45560
45561

45562
45563
45564
45565
45566
45567
45568
45569







-
+







/*
** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
** clause is seen as part of a foreign key definition.  The isDeferred
** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
** The behavior of the most recently created foreign key is adjusted
** accordingly.
*/
static void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
#ifndef SQLITE_OMIT_FOREIGN_KEY
  Table *pTab;
  FKey *pFKey;
  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  pFKey->isDeferred = isDeferred;
#endif
}
45446
45447
45448
45449
45450
45451
45452
45453

45454
45455
45456
45457
45458
45459
45460

45461
45462
45463
45464
45465
45466
45467
45640
45641
45642
45643
45644
45645
45646

45647
45648
45649
45650
45651
45652
45653

45654
45655
45656
45657
45658
45659
45660
45661







-
+






-
+







** as the table to be indexed.  pParse->pNewTable is a table that is
** currently being constructed by a CREATE TABLE statement.
**
** pList is a list of columns to be indexed.  pList will be NULL if this
** is a primary key or unique-constraint on the most recent column added
** to the table currently under construction.  
*/
static void sqlite3CreateIndex(
SQLITE_PRIVATE void sqlite3CreateIndex(
  Parse *pParse,     /* All information about this parse */
  Token *pName1,     /* First part of index name. May be NULL */
  Token *pName2,     /* Second part of index name. May be NULL */
  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  ExprList *pList,   /* A list of columns to be indexed */
  int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  Token *pStart,     /* The CREATE token that begins a CREATE TABLE statement */
  Token *pStart,     /* The CREATE token that begins this statement */
  Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
  int sortOrder,     /* Sort order of primary key when pList==NULL */
  int ifNotExist     /* Omit error if index already exists */
){
  Table *pTab = 0;     /* Table to be indexed */
  Index *pIndex = 0;   /* The index to be created */
  char *zName = 0;     /* Name of the index */
45875
45876
45877
45878
45879
45880
45881
45882

45883
45884
45885
45886
45887
45888
45889
46069
46070
46071
46072
46073
46074
46075

46076
46077
46078
46079
46080
46081
46082
46083







-
+







  return;
}

/*
** Generate code to make sure the file format number is at least minFormat.
** The generated code will increase the file format number if necessary.
*/
static void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  Vdbe *v;
  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1);
    sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
    sqlite3VdbeAddOp(v, OP_Ge, 0, sqlite3VdbeCurrentAddr(v)+3);
    sqlite3VdbeAddOp(v, OP_Integer, minFormat, 0);
45905
45906
45907
45908
45909
45910
45911
45912

45913
45914
45915
45916
45917
45918
45919
45920
45921
45922
45923
45924
45925
45926
45927
45928
45929
45930
45931
45932
45933

45934
45935
45936
45937
45938
45939
45940
46099
46100
46101
46102
46103
46104
46105

46106
46107
46108
46109
46110
46111
46112
46113
46114
46115
46116
46117
46118
46119
46120
46121
46122
46123
46124
46125
46126

46127
46128
46129
46130
46131
46132
46133
46134







-
+




















-
+







**           aiRowEst[N]<=aiRowEst[N-1]
**           aiRowEst[N]>=1
**
** Apart from that, we have little to go on besides intuition as to
** how aiRowEst[] should be initialized.  The numbers generated here
** are based on typical values found in actual indices.
*/
static void sqlite3DefaultRowEst(Index *pIdx){
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  unsigned *a = pIdx->aiRowEst;
  int i;
  assert( a!=0 );
  a[0] = 1000000;
  for(i=pIdx->nColumn; i>=5; i--){
    a[i] = 5;
  }
  while( i>=1 ){
    a[i] = 11 - i;
    i--;
  }
  if( pIdx->onError!=OE_None ){
    a[pIdx->nColumn] = 1;
  }
}

/*
** This routine will drop an existing named index.  This routine
** implements the DROP INDEX statement.
*/
static void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  Index *pIndex;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  if( pParse->nErr || sqlite3MallocFailed() ){
    goto exit_drop_index;
46001
46002
46003
46004
46005
46006
46007
46008

46009
46010
46011
46012
46013
46014
46015
46195
46196
46197
46198
46199
46200
46201

46202
46203
46204
46205
46206
46207
46208
46209







-
+







**
** The index of the new entry is returned in *pIdx.
**
** This routine returns a pointer to the array of objects.  This
** might be the same as the pArray parameter or it might be a different
** pointer if the array was resized.
*/
static void *sqlite3ArrayAllocate(
SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  void *pArray,     /* Array of objects.  Might be reallocated */
  int szEntry,      /* Size of each object in the array */
  int initSize,     /* Suggested initial allocation, in elements */
  int *pnEntry,     /* Number of objects currently in use */
  int *pnAlloc,     /* Current size of the allocation, in elements */
  int *pIdx         /* Write the index of a new slot here */
){
46035
46036
46037
46038
46039
46040
46041
46042

46043
46044
46045
46046
46047
46048
46049
46229
46230
46231
46232
46233
46234
46235

46236
46237
46238
46239
46240
46241
46242
46243







-
+








/*
** Append a new element to the given IdList.  Create a new IdList if
** need be.
**
** A new IdList is returned, or NULL if malloc() fails.
*/
static IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
SQLITE_PRIVATE IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){
  int i;
  if( pList==0 ){
    pList = sqliteMalloc( sizeof(IdList) );
    if( pList==0 ) return 0;
    pList->nAlloc = 0;
  }
  pList->a = sqlite3ArrayAllocate(
46061
46062
46063
46064
46065
46066
46067
46068

46069
46070
46071
46072
46073
46074
46075
46076
46077
46078
46079
46080
46081
46082

46083
46084
46085
46086
46087
46088
46089
46255
46256
46257
46258
46259
46260
46261

46262
46263
46264
46265
46266
46267
46268
46269
46270
46271
46272
46273
46274
46275

46276
46277
46278
46279
46280
46281
46282
46283







-
+













-
+







  pList->a[i].zName = sqlite3NameFromToken(pToken);
  return pList;
}

/*
** Delete an IdList.
*/
static void sqlite3IdListDelete(IdList *pList){
SQLITE_PRIVATE void sqlite3IdListDelete(IdList *pList){
  int i;
  if( pList==0 ) return;
  for(i=0; i<pList->nId; i++){
    sqliteFree(pList->a[i].zName);
  }
  sqliteFree(pList->a);
  sqliteFree(pList);
}

/*
** Return the index in pList of the identifier named zId.  Return -1
** if not found.
*/
static int sqlite3IdListIndex(IdList *pList, const char *zName){
SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  int i;
  if( pList==0 ) return -1;
  for(i=0; i<pList->nId; i++){
    if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  }
  return -1;
}
46109
46110
46111
46112
46113
46114
46115
46116

46117
46118
46119
46120
46121
46122
46123
46303
46304
46305
46306
46307
46308
46309

46310
46311
46312
46313
46314
46315
46316
46317







-
+







** Then B is a table name and the database name is unspecified.  If called
** like this:
**
**         sqlite3SrcListAppend(A,B,C);
**
** Then C is the table name and B is the database name.
*/
static SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
  struct SrcList_item *pItem;
  if( pList==0 ){
    pList = sqliteMalloc( sizeof(SrcList) );
    if( pList==0 ) return 0;
    pList->nAlloc = 1;
  }
  if( pList->nSrc>=pList->nAlloc ){
46148
46149
46150
46151
46152
46153
46154
46155

46156
46157
46158
46159
46160
46161
46162
46163
46164
46165
46166
46167
46168
46169
46170
46171
46172
46173

46174
46175
46176
46177
46178
46179
46180
46342
46343
46344
46345
46346
46347
46348

46349
46350
46351
46352
46353
46354
46355
46356
46357
46358
46359
46360
46361
46362
46363
46364
46365
46366

46367
46368
46369
46370
46371
46372
46373
46374







-
+

















-
+







  pList->nSrc++;
  return pList;
}

/*
** Assign cursors to all tables in a SrcList
*/
static void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  int i;
  struct SrcList_item *pItem;
  assert(pList || sqlite3MallocFailed() );
  if( pList ){
    for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
      if( pItem->iCursor>=0 ) break;
      pItem->iCursor = pParse->nTab++;
      if( pItem->pSelect ){
        sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
      }
    }
  }
}

/*
** Delete an entire SrcList including all its substructure.
*/
static void sqlite3SrcListDelete(SrcList *pList){
SQLITE_PRIVATE void sqlite3SrcListDelete(SrcList *pList){
  int i;
  struct SrcList_item *pItem;
  if( pList==0 ) return;
  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
    sqliteFree(pItem->zDatabase);
    sqliteFree(pItem->zName);
    sqliteFree(pItem->zAlias);
46198
46199
46200
46201
46202
46203
46204
46205

46206
46207
46208
46209
46210
46211
46212
46392
46393
46394
46395
46396
46397
46398

46399
46400
46401
46402
46403
46404
46405
46406







-
+







** SELECT statement that the subquery encodes.  The pTable and
** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
** parameters are the content of the ON and USING clauses.
**
** Return a new SrcList which encodes is the FROM with the new
** term added.
*/
static SrcList *sqlite3SrcListAppendFromTerm(
SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  SrcList *p,             /* The left part of the FROM clause already seen */
  Token *pTable,          /* Name of the table to add to the FROM clause */
  Token *pDatabase,       /* Name of the database containing pTable */
  Token *pAlias,          /* The right-hand side of the AS subexpression */
  Select *pSubquery,      /* A subquery used in place of a table name */
  Expr *pOn,              /* The ON clause of a join */
  IdList *pUsing          /* The USING clause of a join */
46240
46241
46242
46243
46244
46245
46246
46247

46248
46249
46250
46251
46252
46253
46254
46255
46256
46257
46258
46259
46260

46261
46262
46263
46264
46265
46266
46267
46434
46435
46436
46437
46438
46439
46440

46441
46442
46443
46444
46445
46446
46447
46448
46449
46450
46451
46452
46453

46454
46455
46456
46457
46458
46459
46460
46461







-
+












-
+







**
**           A natural cross join B
**
** The operator is "natural cross join".  The A and B operands are stored
** in p->a[0] and p->a[1], respectively.  The parser initially stores the
** operator with A.  This routine shifts that operator over to B.
*/
static void sqlite3SrcListShiftJoinType(SrcList *p){
SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  if( p && p->a ){
    int i;
    for(i=p->nSrc-1; i>0; i--){
      p->a[i].jointype = p->a[i-1].jointype;
    }
    p->a[0].jointype = 0;
  }
}

/*
** Begin a transaction
*/
static void sqlite3BeginTransaction(Parse *pParse, int type){
SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  sqlite3 *db;
  Vdbe *v;
  int i;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3MallocFailed() ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
46275
46276
46277
46278
46279
46280
46281
46282

46283
46284
46285
46286
46287
46288
46289
46290
46291
46292
46293
46294
46295
46296
46297
46298
46299

46300
46301
46302
46303
46304
46305
46306
46307
46308
46309
46310
46311
46312
46313
46314
46315
46316
46317

46318
46319
46320
46321
46322
46323
46324
46469
46470
46471
46472
46473
46474
46475

46476
46477
46478
46479
46480
46481
46482
46483
46484
46485
46486
46487
46488
46489
46490
46491
46492

46493
46494
46495
46496
46497
46498
46499
46500
46501
46502
46503
46504
46505
46506
46507
46508
46509
46510

46511
46512
46513
46514
46515
46516
46517
46518







-
+
















-
+

















-
+







  }
  sqlite3VdbeAddOp(v, OP_AutoCommit, 0, 0);
}

/*
** Commit a transaction
*/
static void sqlite3CommitTransaction(Parse *pParse){
SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3MallocFailed() ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;

  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 0);
  }
}

/*
** Rollback a transaction
*/
static void sqlite3RollbackTransaction(Parse *pParse){
SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  sqlite3 *db;
  Vdbe *v;

  if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  if( pParse->nErr || sqlite3MallocFailed() ) return;
  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;

  v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_AutoCommit, 1, 1);
  }
}

/*
** Make sure the TEMP database is open and available for use.  Return
** the number of errors.  Leave any error messages in the pParse structure.
*/
static int sqlite3OpenTempDatabase(Parse *pParse){
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  sqlite3 *db = pParse->db;
  if( db->aDb[1].pBt==0 && !pParse->explain ){
    int rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE,
                                 &db->aDb[1].pBt);
    if( rc!=SQLITE_OK ){
      sqlite3ErrorMsg(pParse, "unable to open a temporary database "
        "file for storing temporary tables");
46357
46358
46359
46360
46361
46362
46363
46364

46365
46366
46367
46368
46369
46370
46371
46551
46552
46553
46554
46555
46556
46557

46558
46559
46560
46561
46562
46563
46564
46565







-
+







** will be made to point to that subroutine.  The generation of the
** cookie verification subroutine code happens in sqlite3FinishCoding().
**
** If iDb<0 then code the OP_Goto only - don't set flag to verify the
** schema on any databases.  This can be used to position the OP_Goto
** early in the code, before we know if any database tables will be used.
*/
static void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  sqlite3 *db;
  Vdbe *v;
  int mask;

  v = sqlite3GetVdbe(pParse);
  if( v==0 ) return;  /* This only happens if there was a prior error */
  db = pParse->db;
46401
46402
46403
46404
46405
46406
46407
46408

46409
46410
46411
46412
46413
46414
46415
46595
46596
46597
46598
46599
46600
46601

46602
46603
46604
46605
46606
46607
46608
46609







-
+







** necessary to undo a write and the checkpoint should not be set.
**
** Only database iDb and the temp database are made writable by this call.
** If iDb==0, then the main and temp databases are made writable.   If
** iDb==1 then only the temp database is made writable.  If iDb>1 then the
** specified auxiliary database and the temp database are made writable.
*/
static void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v==0 ) return;
  sqlite3CodeVerifySchema(pParse, iDb);
  pParse->writeMask |= 1<<iDb;
  if( setStatement && pParse->nested==0 ){
    sqlite3VdbeAddOp(v, OP_Statement, iDb, 0);
  }
46486
46487
46488
46489
46490
46491
46492
46493

46494
46495
46496
46497
46498
46499
46500
46680
46681
46682
46683
46684
46685
46686

46687
46688
46689
46690
46691
46692
46693
46694







-
+







**
** Form 1 causes all indices in all attached databases to be rebuilt.
** Form 2 rebuilds all indices in all databases that use the named
** collating function.  Forms 3 and 4 rebuild the named index or all
** indices associated with the named table.
*/
#ifndef SQLITE_OMIT_REINDEX
static void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
  char *z;                    /* Name of a table or index */
  const char *zDb;            /* Name of the database */
  Table *pTab;                /* A table in the database */
  Index *pIndex;              /* An index associated with pTab */
  int iDb;                    /* The database index number */
  sqlite3 *db = pParse->db;   /* The database connection */
46549
46550
46551
46552
46553
46554
46555
46556

46557
46558
46559
46560
46561
46562
46563
46743
46744
46745
46746
46747
46748
46749

46750
46751
46752
46753
46754
46755
46756
46757







-
+







**
** If successful, a pointer to the new structure is returned. In this case
** the caller is responsible for calling sqliteFree() on the returned 
** pointer. If an error occurs (out of memory or missing collation 
** sequence), NULL is returned and the state of pParse updated to reflect
** the error.
*/
static KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  int i;
  int nCol = pIdx->nColumn;
  int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
  KeyInfo *pKey = (KeyInfo *)sqliteMalloc(nBytes);

  if( pKey ){
    pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
46591
46592
46593
46594
46595
46596
46597
46598

46599
46600
46601
46602
46603
46604
46605
46785
46786
46787
46788
46789
46790
46791

46792
46793
46794
46795
46796
46797
46798
46799







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


/*
** Invoke the 'collation needed' callback to request a collation sequence
** in the database text encoding of name zName, length nName.
** If the collation sequence
46660
46661
46662
46663
46664
46665
46666
46667

46668
46669
46670
46671
46672
46673
46674
46854
46855
46856
46857
46858
46859
46860

46861
46862
46863
46864
46865
46866
46867
46868







-
+







** If it is not NULL, then pColl must point to the database native encoding 
** collation sequence with name zName, length nName.
**
** The return value is either the collation sequence to be used in database
** db for collation type name zName, length nName, or NULL, if no collation
** sequence can be found.
*/
static CollSeq *sqlite3GetCollSeq(
SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  sqlite3* db, 
  CollSeq *pColl, 
  const char *zName, 
  int nName
){
  CollSeq *p;

46697
46698
46699
46700
46701
46702
46703
46704

46705
46706
46707
46708
46709
46710
46711
46891
46892
46893
46894
46895
46896
46897

46898
46899
46900
46901
46902
46903
46904
46905







-
+







** that have not been defined by sqlite3_create_collation() etc.
**
** If required, this routine calls the 'collation needed' callback to
** request a definition of the collating sequence. If this doesn't work, 
** an equivalent collating sequence that uses a text encoding different
** from the main database is substituted, if one is available.
*/
static int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  if( pColl ){
    const char *zName = pColl->zName;
    CollSeq *p = sqlite3GetCollSeq(pParse->db, pColl, zName, -1);
    if( !p ){
      if( pParse->nErr==0 ){
        sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
      }
46779
46780
46781
46782
46783
46784
46785
46786

46787
46788
46789
46790
46791
46792
46793
46973
46974
46975
46976
46977
46978
46979

46980
46981
46982
46983
46984
46985
46986
46987







-
+







** new entry.  Otherwise return NULL.
**
** A separate function sqlite3LocateCollSeq() is a wrapper around
** this routine.  sqlite3LocateCollSeq() invokes the collation factory
** if necessary and generates an error message if the collating sequence
** cannot be found.
*/
static CollSeq *sqlite3FindCollSeq(
SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  sqlite3 *db,
  u8 enc,
  const char *zName,
  int nName,
  int create
){
  CollSeq *pColl;
46818
46819
46820
46821
46822
46823
46824
46825

46826
46827
46828
46829
46830
46831
46832
47012
47013
47014
47015
47016
47017
47018

47019
47020
47021
47022
47023
47024
47025
47026







-
+







** function found is returned.  A function is valid if either xFunc
** or xStep is non-zero.
**
** If createFlag is false, then a function with the required name and
** number of arguments may be returned even if the eTextRep flag does not
** match that requested.
*/
static FuncDef *sqlite3FindFunction(
SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  sqlite3 *db,       /* An open database */
  const char *zName, /* Name of the function.  Not null-terminated */
  int nName,         /* Number of characters in the name */
  int nArg,          /* Number of arguments.  -1 means any number */
  u8 enc,            /* Preferred text encoding */
  int createFlag     /* Create new entry if true and does not otherwise exist */
){
46904
46905
46906
46907
46908
46909
46910
46911

46912
46913
46914
46915
46916
46917
46918
47098
47099
47100
47101
47102
47103
47104

47105
47106
47107
47108
47109
47110
47111
47112







-
+








/*
** Free all resources held by the schema structure. The void* argument points
** at a Schema struct. This function does not call sqliteFree() on the 
** pointer itself, it just cleans up subsiduary resources (i.e. the contents
** of the schema hash tables).
*/
static void sqlite3SchemaFree(void *p){
SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
  Hash temp1;
  Hash temp2;
  HashElem *pElem;
  Schema *pSchema = (Schema *)p;

  temp1 = pSchema->tblHash;
  temp2 = pSchema->trigHash;
46933
46934
46935
46936
46937
46938
46939
46940

46941
46942
46943
46944
46945
46946
46947
47127
47128
47129
47130
47131
47132
47133

47134
47135
47136
47137
47138
47139
47140
47141







-
+







  pSchema->flags &= ~DB_SchemaLoaded;
}

/*
** Find and return the schema associated with a BTree.  Create
** a new one if necessary.
*/
static Schema *sqlite3SchemaGet(Btree *pBt){
SQLITE_PRIVATE Schema *sqlite3SchemaGet(Btree *pBt){
  Schema * p;
  if( pBt ){
    p = (Schema *)sqlite3BtreeSchema(pBt,sizeof(Schema),sqlite3SchemaFree);
  }else{
    p = (Schema *)sqliteMalloc(sizeof(Schema));
  }
  if( p && 0==p->file_format ){
46970
46971
46972
46973
46974
46975
46976
46977

46978
46979
46980
46981
46982
46983
46984
47164
47165
47166
47167
47168
47169
47170

47171
47172
47173
47174
47175
47176
47177
47178







-
+







** An tokenizer for SQL
**
** This file contains C code that implements the sqlite3_complete() API.
** This code used to be part of the tokenizer.c source file.  But by
** separating it out, the code will be automatically omitted from
** static links that do not use it.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef SQLITE_OMIT_COMPLETE

/*
** This is defined in tokenize.c.  We just have to import the definition.
*/
extern const char sqlite3IsIdChar[];
47044
47045
47046
47047
47048
47049
47050
47051

47052
47053
47054
47055
47056
47057
47058
47238
47239
47240
47241
47242
47243
47244

47245
47246
47247
47248
47249
47250
47251
47252







-
+







**
** Whitespace never causes a state transition and is always ignored.
**
** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
** to recognize the end of a trigger can be omitted.  All we have to do
** is look for a semicolon that is not part of an string or comment.
*/
int sqlite3_complete(const char *zSql){
SQLITE_API int sqlite3_complete(const char *zSql){
  u8 state = 0;   /* Current state, using numbers defined in header comment */
  u8 token;       /* Value of the next token */

#ifndef SQLITE_OMIT_TRIGGER
  /* A complex statement machine used to detect the end of a CREATE TRIGGER
  ** statement.  This is the normal case.
  */
47198
47199
47200
47201
47202
47203
47204
47205

47206
47207
47208
47209
47210
47211
47212
47392
47393
47394
47395
47396
47397
47398

47399
47400
47401
47402
47403
47404
47405
47406







-
+








#ifndef SQLITE_OMIT_UTF16
/*
** This routine is the same as the sqlite3_complete() routine described
** above, except that the parameter is required to be UTF-16 encoded, not
** UTF-8.
*/
int sqlite3_complete16(const void *zSql){
SQLITE_API int sqlite3_complete16(const void *zSql){
  sqlite3_value *pVal;
  char const *zSql8;
  int rc = 0;

  pVal = sqlite3ValueNew();
  sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
47231
47232
47233
47234
47235
47236
47237
47238

47239
47240
47241
47242
47243
47244
47245
47246

47247
47248
47249
47250
47251
47252
47253
47254
47255
47256
47257
47258
47259
47260
47261
47262
47263
47264
47265
47266

47267
47268
47269
47270
47271
47272
47273
47425
47426
47427
47428
47429
47430
47431

47432
47433
47434
47435
47436
47437
47438
47439

47440
47441
47442
47443
47444
47445
47446
47447
47448
47449
47450
47451
47452
47453
47454
47455
47456
47457
47458
47459

47460
47461
47462
47463
47464
47465
47466
47467







-
+







-
+



















-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** in order to generate code for DELETE FROM statements.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** Look up every table that is named in pSrc.  If any table is not found,
** add an error message to pParse->zErrMsg and return NULL.  If all tables
** are found, return a pointer to the last table.
*/
static Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  Table *pTab = 0;
  int i;
  struct SrcList_item *pItem;
  for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
    pTab = sqlite3LocateTable(pParse, pItem->zName, pItem->zDatabase);
    sqlite3DeleteTable(pItem->pTab);
    pItem->pTab = pTab;
    if( pTab ){
      pTab->nRef++;
    }
  }
  return pTab;
}

/*
** Check to make sure the given table is writable.  If it is not
** writable, generate an error message and return 1.  If it is
** writable return 0;
*/
static int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  if( (pTab->readOnly && (pParse->db->flags & SQLITE_WriteSchema)==0
        && pParse->nested==0) 
#ifndef SQLITE_OMIT_VIRTUALTABLE
      || (pTab->pMod && pTab->pMod->pModule->xUpdate==0)
#endif
  ){
    sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
47281
47282
47283
47284
47285
47286
47287
47288

47289
47290
47291
47292
47293
47294
47295
47475
47476
47477
47478
47479
47480
47481

47482
47483
47484
47485
47486
47487
47488
47489







-
+







#endif
  return 0;
}

/*
** Generate code that will open a table for reading.
*/
static void sqlite3OpenTable(
SQLITE_PRIVATE void sqlite3OpenTable(
  Parse *p,       /* Generate code into this VDBE */
  int iCur,       /* The cursor number of the table */
  int iDb,        /* The database index in sqlite3.aDb[] */
  Table *pTab,    /* The table to be opened */
  int opcode      /* OP_OpenRead or OP_OpenWrite */
){
  Vdbe *v;
47307
47308
47309
47310
47311
47312
47313
47314

47315
47316
47317
47318
47319
47320
47321
47501
47502
47503
47504
47505
47506
47507

47508
47509
47510
47511
47512
47513
47514
47515







-
+







/*
** Generate code for a DELETE FROM statement.
**
**     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
**                 \________/       \________________/
**                  pTabList              pWhere
*/
static void sqlite3DeleteFrom(
SQLITE_PRIVATE void sqlite3DeleteFrom(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table from which we should delete things */
  Expr *pWhere           /* The WHERE clause.  May be null */
){
  Vdbe *v;               /* The virtual database engine */
  Table *pTab;           /* The table from which records will be deleted */
  const char *zDb;       /* Name of database holding pTab */
47607
47608
47609
47610
47611
47612
47613
47614

47615
47616
47617
47618
47619
47620
47621
47801
47802
47803
47804
47805
47806
47807

47808
47809
47810
47811
47812
47813
47814
47815







-
+







**   3.  The record number of the row to be deleted must be on the top
**       of the stack.
**
** This routine pops the top of the stack to remove the record number
** and then generates code to remove both the table record and all index
** entries that point to that record.
*/
static void sqlite3GenerateRowDelete(
SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  sqlite3 *db,       /* The database containing the index */
  Vdbe *v,           /* Generate code into this VDBE */
  Table *pTab,       /* Table containing the row to be deleted */
  int iCur,          /* Cursor number for the table */
  int count          /* Increment the row change counter */
){
  int addr;
47640
47641
47642
47643
47644
47645
47646
47647

47648
47649
47650
47651
47652
47653
47654
47834
47835
47836
47837
47838
47839
47840

47841
47842
47843
47844
47845
47846
47847
47848







-
+







**
**   2.  Read/write cursors for all indices of pTab must be open as
**       cursor number iCur+i for the i-th index.
**
**   3.  The "iCur" cursor must be pointing to the row that is to be
**       deleted.
*/
static void sqlite3GenerateRowIndexDelete(
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  Vdbe *v,           /* Generate code into this VDBE */
  Table *pTab,       /* Table containing the row to be deleted */
  int iCur,          /* Cursor number for the table */
  char *aIdxUsed     /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
){
  int i;
  Index *pIdx;
47662
47663
47664
47665
47666
47667
47668
47669

47670
47671
47672
47673
47674
47675
47676
47856
47857
47858
47859
47860
47861
47862

47863
47864
47865
47866
47867
47868
47869
47870







-
+








/*
** Generate code that will assemble an index key and put it on the top
** of the tack.  The key with be for index pIdx which is an index on pTab.
** iCur is the index of a cursor open on the pTab table and pointing to
** the entry that needs indexing.
*/
static void sqlite3GenerateIndexKey(
SQLITE_PRIVATE void sqlite3GenerateIndexKey(
  Vdbe *v,           /* Generate code into this VDBE */
  Index *pIdx,       /* The index for which to generate a key */
  int iCur           /* Cursor number for the pIdx->pTable table */
){
  int j;
  Table *pTab = pIdx->pTable;

47704
47705
47706
47707
47708
47709
47710
47711

47712
47713
47714
47715
47716
47717
47718
47898
47899
47900
47901
47902
47903
47904

47905
47906
47907
47908
47909
47910
47911
47912







-
+







** This file contains the C functions that implement various SQL
** functions of SQLite.  
**
** There is only one exported symbol in this file - the function
** sqliteRegisterBuildinFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
/* #include <math.h> */

/*
** Return the collating function associated with a function.
*/
static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
48082
48083
48084
48085
48086
48087
48088
48089

48090
48091
48092
48093
48094
48095
48096
48276
48277
48278
48279
48280
48281
48282

48283
48284
48285
48286
48287
48288
48289
48290







-
+







/* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
** is case sensitive causing 'a' LIKE 'A' to be false */
static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };

/*
** Read a single UTF-8 character and return its value.
*/
static u32 sqlite3ReadUtf8(const unsigned char *z){
SQLITE_PRIVATE u32 sqlite3ReadUtf8(const unsigned char *z){
  u32 c;
  SQLITE_READ_UTF8(z, c);
  return c;
}

/*
** Compare two UTF-8 strings for equality where the first string can
48980
48981
48982
48983
48984
48985
48986
48987

48988
48989
48990
48991
48992
48993
48994
49174
49175
49176
49177
49178
49179
49180

49181
49182
49183
49184
49185
49186
49187
49188







-
+









/*
** This function registered all of the above C functions as SQL
** functions.  This should be the only routine in this file with
** external linkage.
*/
static void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  static const struct {
     char *zName;
     signed char nArg;
     u8 argType;           /* ff: db   1: 0, 2: 1, 3: 2,...  N:  N-1. */
     u8 eTextRep;          /* 1: UTF-16.  0: UTF-8 */
     u8 needCollSeq;
     void (*xFunc)(sqlite3_context*,int,sqlite3_value **);
49092
49093
49094
49095
49096
49097
49098

49099






49100
49101
49102
49103
49104
49105
49106
49286
49287
49288
49289
49290
49291
49292
49293

49294
49295
49296
49297
49298
49299
49300
49301
49302
49303
49304
49305
49306







+
-
+
+
+
+
+
+







          strlen(aAggs[i].zName), aAggs[i].nArg, SQLITE_UTF8, 0);
      if( pFunc && aAggs[i].needCollSeq ){
        pFunc->needCollSeq = 1;
      }
    }
  }
  sqlite3RegisterDateTimeFunctions(db);
  if( !sqlite3MallocFailed() ){
  sqlite3_overload_function(db, "MATCH", 2);
    int rc = sqlite3_overload_function(db, "MATCH", 2);
    assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
    if( rc==SQLITE_NOMEM ){
      sqlite3FailedMalloc();
    }
  }
#ifdef SQLITE_SSE
  (void)sqlite3SseFunctions(db);
#endif
#ifdef SQLITE_CASE_SENSITIVE_LIKE
  sqlite3RegisterLikeFunctions(db, 1);
#else
  sqlite3RegisterLikeFunctions(db, 0);
49119
49120
49121
49122
49123
49124
49125
49126

49127
49128
49129
49130
49131
49132
49133
49319
49320
49321
49322
49323
49324
49325

49326
49327
49328
49329
49330
49331
49332
49333







-
+







}

/*
** Register the built-in LIKE and GLOB functions.  The caseSensitive
** parameter determines whether or not the LIKE operator is case
** sensitive.  GLOB is always case sensitive.
*/
static void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  struct compareInfo *pInfo;
  if( caseSensitive ){
    pInfo = (struct compareInfo*)&likeInfoAlt;
  }else{
    pInfo = (struct compareInfo*)&likeInfoNorm;
  }
  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0);
49142
49143
49144
49145
49146
49147
49148
49149

49150
49151
49152
49153
49154
49155
49156
49342
49343
49344
49345
49346
49347
49348

49349
49350
49351
49352
49353
49354
49355
49356







-
+







/*
** pExpr points to an expression which implements a function.  If
** it is appropriate to apply the LIKE optimization to that function
** then set aWc[0] through aWc[2] to the wildcard characters and
** return TRUE.  If the function is not a LIKE-style function then
** return FALSE.
*/
static int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  FuncDef *pDef;
  if( pExpr->op!=TK_FUNCTION || !pExpr->pList ){
    return 0;
  }
  if( pExpr->pList->nExpr!=2 ){
    return 0;
  }
49184
49185
49186
49187
49188
49189
49190
49191

49192
49193
49194
49195
49196
49197
49198
49199
49200
49201
49202
49203
49204
49205
49206
49207

49208
49209
49210
49211
49212
49213
49214
49384
49385
49386
49387
49388
49389
49390

49391
49392
49393
49394
49395
49396
49397
49398
49399
49400
49401
49402
49403
49404
49405
49406

49407
49408
49409
49410
49411
49412
49413
49414







-
+















-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle INSERT statements in SQLite.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** Set P3 of the most recently inserted opcode to a column affinity
** string for index pIdx. A column affinity string has one character
** for each column in the table, according to the affinity of the column:
**
**  Character      Column affinity
**  ------------------------------
**  'a'            TEXT
**  'b'            NONE
**  'c'            NUMERIC
**  'd'            INTEGER
**  'e'            REAL
*/
static void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
SQLITE_PRIVATE void sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  if( !pIdx->zColAff ){
    /* The first time a column affinity string for a particular index is
    ** required, it is allocated and populated here. It is then stored as
    ** a member of the Index structure for subsequent use.
    **
    ** The column affinity string will eventually be deleted by
    ** sqliteDeleteIndex() when the Index structure itself is cleaned
49239
49240
49241
49242
49243
49244
49245
49246

49247
49248
49249
49250
49251
49252
49253
49439
49440
49441
49442
49443
49444
49445

49446
49447
49448
49449
49450
49451
49452
49453







-
+







**  ------------------------------
**  'a'            TEXT
**  'b'            NONE
**  'c'            NUMERIC
**  'd'            INTEGER
**  'e'            REAL
*/
static void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  /* The first time a column affinity string for a particular table
  ** is required, it is allocated and populated here. It is then 
  ** stored as a member of the Table structure for subsequent use.
  **
  ** The column affinity string will eventually be deleted by
  ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  */
49488
49489
49490
49491
49492
49493
49494
49495

49496
49497
49498
49499
49500
49501
49502
49688
49689
49690
49691
49692
49693
49694

49695
49696
49697
49698
49699
49700
49701
49702







-
+







**         goto A
**      D: open write cursor to <table> and its indices
**         loop over the intermediate table
**           transfer values form intermediate table into <table>
**         end the loop
**         cleanup
*/
static void sqlite3Insert(
SQLITE_PRIVATE void sqlite3Insert(
  Parse *pParse,        /* Parser context */
  SrcList *pTabList,    /* Name of table into which we are inserting */
  ExprList *pList,      /* List of values to be inserted */
  Select *pSelect,      /* A SELECT statement to use as the data source */
  IdList *pColumn,      /* Column names corresponding to IDLIST. */
  int onError           /* How to handle constraint errors */
){
49519
49520
49521
49522
49523
49524
49525


49526
49527
49528
49529
49530
49531
49532
49719
49720
49721
49722
49723
49724
49725
49726
49727
49728
49729
49730
49731
49732
49733
49734







+
+







  int iInsertBlock = 0; /* Address of the subroutine used to insert data */
  int iCntMem = 0;      /* Memory cell used for the row counter */
  int newIdx = -1;      /* Cursor for the NEW table */
  Db *pDb;              /* The database containing table being inserted into */
  int counterMem = 0;   /* Memory cell holding AUTOINCREMENT counter */
  int appendFlag = 0;   /* True if the insert is likely to be an append */
  int iDb;

  int nHidden = 0;

#ifndef SQLITE_OMIT_TRIGGER
  int isView;                 /* True if attempting to insert into a view */
  int triggers_exist = 0;     /* True if there are FOR EACH ROW triggers */
#endif

  if( pParse->nErr || sqlite3MallocFailed() ){
49696
49697
49698
49699
49700
49701
49702





49703

49704
49705
49706
49707
49708
49709
49710
49898
49899
49900
49901
49902
49903
49904
49905
49906
49907
49908
49909

49910
49911
49912
49913
49914
49915
49916
49917







+
+
+
+
+
-
+







      }
    }
  }

  /* Make sure the number of columns in the source data matches the number
  ** of columns to be inserted into the table.
  */
  if( IsVirtual(pTab) ){
    for(i=0; i<pTab->nCol; i++){
      nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
    }
  }
  if( pColumn==0 && nColumn && nColumn!=pTab->nCol ){
  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
    sqlite3ErrorMsg(pParse, 
       "table %S has %d columns but %d values were supplied",
       pTabList, 0, pTab->nCol, nColumn);
    goto insert_cleanup;
  }
  if( pColumn!=0 && nColumn!=pColumn->nId ){
    sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
49810
49811
49812
49813
49814
49815
49816





49817
49818
49819
49820
49821
49822
49823
50017
50018
50019
50020
50021
50022
50023
50024
50025
50026
50027
50028
50029
50030
50031
50032
50033
50034
50035







+
+
+
+
+







      assert( pSelect==0 );  /* Otherwise useTempTable is true */
      sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr);
      sqlite3VdbeAddOp(v, OP_NotNull, -1, sqlite3VdbeCurrentAddr(v)+3);
      sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
      sqlite3VdbeAddOp(v, OP_Integer, -1, 0);
      sqlite3VdbeAddOp(v, OP_MustBeInt, 0, 0);
    }

    /* Cannot have triggers on a virtual table. If it were possible,
    ** this block would have to account for hidden column.
    */
    assert(!IsVirtual(pTab));

    /* Create the new column data
    */
    for(i=0; i<pTab->nCol; i++){
      if( pColumn==0 ){
        j = i;
      }else{
49903
49904
49905
49906
49907
49908
49909

49910
49911
49912
49913
49914
49915
49916
49917
49918
49919


49920





49921
49922
49923
49924
49925
49926

49927
49928
49929
49930
49931
49932
49933
50115
50116
50117
50118
50119
50120
50121
50122
50123
50124
50125
50126
50127
50128
50129
50130
50131
50132
50133
50134

50135
50136
50137
50138
50139
50140
50141
50142
50143
50144

50145
50146
50147
50148
50149
50150
50151
50152







+










+
+
-
+
+
+
+
+





-
+







      appendFlag = 1;
    }
    autoIncStep(pParse, counterMem);

    /* Push onto the stack, data for all columns of the new entry, beginning
    ** with the first column.
    */
    nHidden = 0;
    for(i=0; i<pTab->nCol; i++){
      if( i==pTab->iPKey ){
        /* The value of the INTEGER PRIMARY KEY column is always a NULL.
        ** Whenever this column is read, the record number will be substituted
        ** in its place.  So will fill this column with a NULL to avoid
        ** taking up data space with information that will never be used. */
        sqlite3VdbeAddOp(v, OP_Null, 0, 0);
        continue;
      }
      if( pColumn==0 ){
        if( IsHiddenColumn(&pTab->aCol[i]) ){
          assert( IsVirtual(pTab) );
        j = i;
          j = -1;
          nHidden++;
        }else{
          j = i - nHidden;
        }
      }else{
        for(j=0; j<pColumn->nId; j++){
          if( pColumn->a[j].idx==i ) break;
        }
      }
      if( nColumn==0 || (pColumn && j>=pColumn->nId) ){
      if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
        sqlite3ExprCode(pParse, pTab->aCol[i].pDflt);
      }else if( useTempTable ){
        sqlite3VdbeAddOp(v, OP_Column, srcTab, j); 
      }else if( pSelect ){
        sqlite3VdbeAddOp(v, OP_Dup, i+nColumn-j+IsVirtual(pTab), 1);
      }else{
        sqlite3ExprCode(pParse, pList->a[j].pExpr);
50096
50097
50098
50099
50100
50101
50102
50103

50104
50105
50106
50107
50108
50109
50110
50315
50316
50317
50318
50319
50320
50321

50322
50323
50324
50325
50326
50327
50328
50329







-
+







**
** If the isUpdate flag is true, it means that the "base" cursor is
** initially pointing to an entry that is being updated.  The isUpdate
** flag causes extra code to be generated so that the "base" cursor
** is still pointing at the same entry after the routine returns.
** Without the isUpdate flag, the "base" cursor might be moved.
*/
static void sqlite3GenerateConstraintChecks(
SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  Parse *pParse,      /* The parser context */
  Table *pTab,        /* the table into which we are inserting */
  int base,           /* Index of a read/write cursor pointing at pTab */
  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
  int rowidChng,      /* True if the record number will change */
  int isUpdate,       /* True for UPDATE, False for INSERT */
  int overrideError,  /* Override onError to this if not OE_Default */
50350
50351
50352
50353
50354
50355
50356
50357

50358
50359
50360
50361
50362
50363
50364
50569
50570
50571
50572
50573
50574
50575

50576
50577
50578
50579
50580
50581
50582
50583







-
+







** The stack must contain keys for all active indices followed by data
** and the rowid for the new entry.  This routine creates the new
** entries in all indices and in the main table.
**
** The arguments to this routine should be the same as the first six
** arguments to sqlite3GenerateConstraintChecks.
*/
static void sqlite3CompleteInsertion(
SQLITE_PRIVATE void sqlite3CompleteInsertion(
  Parse *pParse,      /* The parser context */
  Table *pTab,        /* the table into which we are inserting */
  int base,           /* Index of a read/write cursor pointing at pTab */
  char *aIdxUsed,     /* Which indices are used.  NULL means all are used */
  int rowidChng,      /* True if the record number will change */
  int isUpdate,       /* True for UPDATE, False for INSERT */
  int newIdx,         /* Index of NEW table for triggers.  -1 if none */
50407
50408
50409
50410
50411
50412
50413
50414

50415
50416
50417
50418
50419
50420
50421
50626
50627
50628
50629
50630
50631
50632

50633
50634
50635
50636
50637
50638
50639
50640







-
+







}

/*
** Generate code that will open cursors for a table and for all
** indices of that table.  The "base" parameter is the cursor number used
** for the table.  Indices are opened on subsequent cursors.
*/
static void sqlite3OpenTableAndIndices(
SQLITE_PRIVATE void sqlite3OpenTableAndIndices(
  Parse *pParse,   /* Parsing context */
  Table *pTab,     /* Table to be opened */
  int base,        /* Cursor number assigned to the table */
  int op           /* OP_OpenRead or OP_OpenWrite */
){
  int i;
  int iDb;
50773
50774
50775
50776
50777
50778
50779
50780

50781
50782
50783
50784
50785
50786
50787
50788
50789
50790
50791
50792
50793
50794

50795
50796
50797
50798
50799
50800
50801
50992
50993
50994
50995
50996
50997
50998

50999
51000
51001
51002
51003
51004
51005
51006
51007
51008
51009
51010
51011
51012

51013
51014
51015
51016
51017
51018
51019
51020







-
+













-
+







**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


/*
** Execute SQL code.  Return one of the SQLITE_ success/failure
** codes.  Also write an error message into memory obtained from
** malloc() and make *pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called.  pArg becomes the first
** argument to xCallback().  If xCallback=NULL then no callback
** is invoked, even for queries.
*/
int sqlite3_exec(
SQLITE_API int sqlite3_exec(
  sqlite3 *db,                /* The database on which the SQL executes */
  const char *zSql,           /* The SQL to be executed */
  sqlite3_callback xCallback, /* Invoke this callback routine */
  void *pArg,                 /* First argument to xCallback() */
  char **pzErrMsg             /* Write error messages here */
){
  int rc = SQLITE_OK;
50925
50926
50927
50928
50929
50930
50931
50932

50933
50934
50935
50936
50937
50938
50939
50940
50941






50942
50943
50944
50945
50946
50947
50948
51144
51145
51146
51147
51148
51149
51150

51151
51152
51153
51154
51155
51156
51157
51158
51159
51160
51161
51162
51163
51164
51165
51166
51167
51168
51169
51170
51171
51172
51173







-
+









+
+
+
+
+
+







*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
**
** @(#) $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** @(#) $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITE3EXT_H_
#define _SQLITE3EXT_H_

typedef struct sqlite3_api_routines sqlite3_api_routines;

/*
** The following structure hold pointers to all of the SQLite API
** routines.
**
** WARNING:  In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only.  If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each others shared
** libraries!
*/
struct sqlite3_api_routines {
  void * (*aggregate_context)(sqlite3_context*,int nBytes);
  int  (*aggregate_count)(sqlite3_context*);
  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  int  (*bind_double)(sqlite3_stmt*,int,double);
  int  (*bind_int)(sqlite3_stmt*,int,int);
51056
51057
51058
51059
51060
51061
51062

51063
51064
51065
51066
51067
51068
51069
51281
51282
51283
51284
51285
51286
51287
51288
51289
51290
51291
51292
51293
51294
51295







+







  const void * (*value_text16le)(sqlite3_value*);
  int  (*value_type)(sqlite3_value*);
  char *(*vmprintf)(const char*,va_list);
  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  int (*clear_bindings)(sqlite3_stmt*);
  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
};

/*
** The following macros redefine the API routines so that they are
** redirected throught the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
51118
51119
51120
51121
51122
51123
51124

51125
51126
51127
51128
51129
51130
51131
51344
51345
51346
51347
51348
51349
51350
51351
51352
51353
51354
51355
51356
51357
51358







+







#define sqlite3_complete               sqlite3_api->complete
#define sqlite3_complete16             sqlite3_api->complete16
#define sqlite3_create_collation       sqlite3_api->create_collation
#define sqlite3_create_collation16     sqlite3_api->create_collation16
#define sqlite3_create_function        sqlite3_api->create_function
#define sqlite3_create_function16      sqlite3_api->create_function16
#define sqlite3_create_module          sqlite3_api->create_module
#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
#define sqlite3_data_count             sqlite3_api->data_count
#define sqlite3_db_handle              sqlite3_api->db_handle
#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
#define sqlite3_errcode                sqlite3_api->errcode
#define sqlite3_errmsg                 sqlite3_api->errmsg
#define sqlite3_errmsg16               sqlite3_api->errmsg16
51256
51257
51258
51259
51260
51261
51262

51263
51264
51265
51266
51267
51268
51269
51483
51484
51485
51486
51487
51488
51489
51490
51491
51492
51493
51494
51495
51496
51497







+








#ifdef SQLITE_OMIT_PROGRESS_CALLBACK
# define sqlite3_progress_handler 0
#endif

#ifdef SQLITE_OMIT_VIRTUALTABLE
# define sqlite3_create_module 0
# define sqlite3_create_module_v2 0
# define sqlite3_declare_vtab 0
#endif

#ifdef SQLITE_OMIT_SHARED_CACHE
# define sqlite3_enable_shared_cache 0
#endif

51420
51421
51422
51423
51424
51425
51426






51427
51428
51429
51430
51431
51432
51433
51648
51649
51650
51651
51652
51653
51654
51655
51656
51657
51658
51659
51660
51661
51662
51663
51664
51665
51666
51667







+
+
+
+
+
+








  /*
  ** Added after 3.3.13
  */
  sqlite3_prepare_v2,
  sqlite3_prepare16_v2,
  sqlite3_clear_bindings,

  /*
  ** Added for 3.4.1
  */
  sqlite3_create_module_v2,

};

/*
** Attempt to load an SQLite extension library contained in the file
** zFile.  The entry point is zProc.  zProc may be 0 in which case a
** default entry point name (sqlite3_extension_init) is used.  Use
** of the default name is recommended.
51507
51508
51509
51510
51511
51512
51513
51514

51515
51516
51517
51518
51519
51520
51521
51741
51742
51743
51744
51745
51746
51747

51748
51749
51750
51751
51752
51753
51754
51755







-
+







  return SQLITE_OK;
}

/*
** Call this routine when the database connection is closing in order
** to clean up loaded extensions
*/
static void sqlite3CloseExtensions(sqlite3 *db){
SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  int i;
  for(i=0; i<db->nExtension; i++){
    sqlite3OsDlclose(db->aExtension[i]);
  }
  sqliteFree(db->aExtension);
}

51579
51580
51581
51582
51583
51584
51585
51586

51587
51588
51589
51590
51591
51592
51593
51813
51814
51815
51816
51817
51818
51819

51820
51821
51822
51823
51824
51825
51826
51827







-
+







  nAutoExtension = 0;
  sqlite3OsLeaveMutex();
}

/*
** Load all automatic extensions.
*/
static int sqlite3AutoLoadExtensions(sqlite3 *db){
SQLITE_PRIVATE int sqlite3AutoLoadExtensions(sqlite3 *db){
  int i;
  int go = 1;
  int rc = SQLITE_OK;
  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);

  if( nAutoExtension==0 ){
    /* Common case: early out without every having to acquire a mutex */
51627
51628
51629
51630
51631
51632
51633
51634

51635
51636
51637
51638
51639
51640
51641
51861
51862
51863
51864
51865
51866
51867

51868
51869
51870
51871
51872
51873
51874
51875







-
+







**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the PRAGMA command.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/* Ignore this whole file if pragmas are disabled
*/
#if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)

#if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
51845
51846
51847
51848
51849
51850
51851
51852

51853
51854
51855
51856
51857
51858
51859
52079
52080
52081
52082
52083
52084
52085

52086
52087
52088
52089
52090
52091
52092
52093







-
+







** identifier, or a number.  If minusFlag is true, then the value is
** a number that was preceded by a minus sign.
**
** If the left side is "database.id" then pId1 is the database name
** and pId2 is the id.  If the left side is just "id" then pId1 is the
** id and pId2 is any empty string.
*/
static void sqlite3Pragma(
SQLITE_PRIVATE void sqlite3Pragma(
  Parse *pParse, 
  Token *pId1,        /* First part of [database.]id field */
  Token *pId2,        /* Second part of [database.]id field, or NULL */
  Token *pValue,      /* Token for <value>, or NULL */
  int minusFlag       /* True if a '-' sign preceded <value> */
){
  char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
52035
52036
52037
52038
52039
52040
52041



52042
52043
52044
52045
52046
52047
52048





52049























52050
52051
52052
52053
52054
52055
52056
52269
52270
52271
52272
52273
52274
52275
52276
52277
52278
52279
52280
52281
52282
52283
52284
52285
52286
52287
52288
52289
52290

52291
52292
52293
52294
52295
52296
52297
52298
52299
52300
52301
52302
52303
52304
52305
52306
52307
52308
52309
52310
52311
52312
52313
52314
52315
52316
52317
52318
52319
52320







+
+
+







+
+
+
+
+
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+







  **  PRAGMA [database.]auto_vacuum=N
  **
  ** Get or set the (boolean) value of the database 'auto-vacuum' parameter.
  */
#ifndef SQLITE_OMIT_AUTOVACUUM
  if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
    Btree *pBt = pDb->pBt;
    if( sqlite3ReadSchema(pParse) ){
      goto pragma_out;
    }
    if( !zRight ){
      int auto_vacuum = 
          pBt ? sqlite3BtreeGetAutoVacuum(pBt) : SQLITE_DEFAULT_AUTOVACUUM;
      returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
    }else{
      int eAuto = getAutoVacuum(zRight);
      if( eAuto>=0 ){
        /* Call SetAutoVacuum() to set initialize the internal auto and
        ** incr-vacuum flags. This is required in case this connection
        ** creates the database file. It is important that it is created
        ** as an auto-vacuum capable db.
        */
        sqlite3BtreeSetAutoVacuum(pBt, eAuto);
        int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
        if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
          /* When setting the auto_vacuum mode to either "full" or 
          ** "incremental", write the value of meta[6] in the database
          ** file. Before writing to meta[6], check that meta[3] indicates
          ** that this really is an auto-vacuum capable database.
          */
          static const VdbeOpList setMeta6[] = {
            { OP_Transaction,    0,               1,        0},    /* 0 */
            { OP_ReadCookie,     0,               3,        0},    /* 1 */
            { OP_If,             0,               0,        0},    /* 2 */
            { OP_Halt,           SQLITE_OK,       OE_Abort, 0},    /* 3 */
            { OP_Integer,        0,               0,        0},    /* 4 */
            { OP_SetCookie,      0,               6,        0},    /* 5 */
          };
          int iAddr;
          iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
          sqlite3VdbeChangeP1(v, iAddr, iDb);
          sqlite3VdbeChangeP1(v, iAddr+1, iDb);
          sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
          sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
          sqlite3VdbeChangeP1(v, iAddr+5, iDb);
        }
      }
    }
  }else
#endif

  /*
  **  PRAGMA [database.]incremental_vacuum(N)
52208
52209
52210
52211
52212
52213
52214

52215
52216
52217
52218
52219
52220
52221
52222
52223
52224
52225




52226

52227
52228
52229
52230
52231
52232
52233
52472
52473
52474
52475
52476
52477
52478
52479
52480
52481
52482
52483
52484
52485
52486
52487
52488
52489
52490
52491
52492
52493
52494

52495
52496
52497
52498
52499
52500
52501
52502







+











+
+
+
+
-
+







  */
  if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
    Table *pTab;
    if( sqlite3ReadSchema(pParse) ) goto pragma_out;
    pTab = sqlite3FindTable(db, zRight, zDb);
    if( pTab ){
      int i;
      int nHidden = 0;
      Column *pCol;
      sqlite3VdbeSetNumCols(v, 6);
      sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", P3_STATIC);
      sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", P3_STATIC);
      sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", P3_STATIC);
      sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", P3_STATIC);
      sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", P3_STATIC);
      sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", P3_STATIC);
      sqlite3ViewGetColumnNames(pParse, pTab);
      for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
        const Token *pDflt;
        if( IsHiddenColumn(pCol) ){
          nHidden++;
          continue;
        }
        sqlite3VdbeAddOp(v, OP_Integer, i, 0);
        sqlite3VdbeAddOp(v, OP_Integer, i-nHidden, 0);
        sqlite3VdbeOp3(v, OP_String8, 0, 0, pCol->zName, 0);
        sqlite3VdbeOp3(v, OP_String8, 0, 0,
           pCol->zType ? pCol->zType : "", 0);
        sqlite3VdbeAddOp(v, OP_Integer, pCol->notNull, 0);
        if( pCol->pDflt && (pDflt = &pCol->pDflt->span)->z ){
          sqlite3VdbeOp3(v, OP_String8, 0, 0, (char*)pDflt->z, pDflt->n);
        }else{
52617
52618
52619
52620
52621
52622
52623
52624
52625




52626
52627
52628


52629




52630



52631

52632
52633
52634

52635
52636
52637
52638
52639
52640
52641
52886
52887
52888
52889
52890
52891
52892


52893
52894
52895
52896
52897
52898

52899
52900
52901
52902
52903
52904
52905

52906
52907
52908
52909
52910
52911
52912

52913
52914
52915
52916
52917
52918
52919
52920







-
-
+
+
+
+


-
+
+

+
+
+
+
-
+
+
+

+


-
+







  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  ** the schema-version is potentially dangerous and may lead to program
  ** crashes or database corruption. Use with caution!
  **
  ** The user-version is not used internally by SQLite. It may be used by
  ** applications for any purpose.
  */
  if( sqlite3StrICmp(zLeft, "schema_version")==0 ||
      sqlite3StrICmp(zLeft, "user_version")==0 ){
  if( sqlite3StrICmp(zLeft, "schema_version")==0 
   || sqlite3StrICmp(zLeft, "user_version")==0 
   || sqlite3StrICmp(zLeft, "freelist_count")==0 
  ){

    int iCookie;   /* Cookie index. 0 for schema-cookie, 6 for user-cookie. */
    if( zLeft[0]=='s' || zLeft[0]=='S' ){
    switch( zLeft[0] ){
      case 's': case 'S':
      iCookie = 0;
        break;
      case 'f': case 'F':
        iCookie = 1;
        iDb = (-1*(iDb+1));
    }else{
        assert(iDb<=0);
        break;
      default:
      iCookie = 5;
        break;
    }

    if( zRight ){
    if( zRight && iDb>=0 ){
      /* Write the specified cookie value */
      static const VdbeOpList setCookie[] = {
        { OP_Transaction,    0,  1,  0},    /* 0 */
        { OP_Integer,        0,  0,  0},    /* 1 */
        { OP_SetCookie,      0,  0,  0},    /* 2 */
      };
      int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
52762
52763
52764
52765
52766
52767
52768
52769

52770
52771
52772
52773
52774
52775
52776
53041
53042
53043
53044
53045
53046
53047

53048
53049
53050
53051
53052
53053
53054
53055







-
+







**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(InitData *pData, const char *zExtra){
52789
52790
52791
52792
52793
52794
52795
52796

52797
52798
52799
52800
52801
52802
52803
53068
53069
53070
53071
53072
53073
53074

53075
53076
53077
53078
53079
53080
53081
53082







-
+







** Each callback contains the following information:
**
**     argv[0] = name of thing being created
**     argv[1] = root page number for table or index. 0 for trigger or view.
**     argv[2] = SQL text for the CREATE statement.
**
*/
static int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **azColName){
  InitData *pData = (InitData*)pInit;
  sqlite3 *db = pData->db;
  int iDb = pData->iDb;

  pData->rc = SQLITE_OK;
  DbClearProperty(db, iDb, DB_Empty);
  if( sqlite3MallocFailed() ){
52959
52960
52961
52962
52963
52964
52965
52966

52967
52968
52969
52970
52971
52972
52973
53238
53239
53240
53241
53242
53243
53244

53245
53246
53247
53248
53249
53250
53251
53252







-
+







  ** Meta values are as follows:
  **    meta[0]   Schema cookie.  Changes with each schema change.
  **    meta[1]   File format of schema layer.
  **    meta[2]   Size of the page cache.
  **    meta[3]   Use freelist if 0.  Autovacuum if greater than zero.
  **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  **    meta[5]   The user cookie. Used by the application.
  **    meta[6]   
  **    meta[6]   Incremental-vacuum flag.
  **    meta[7]
  **    meta[8]
  **    meta[9]
  **
  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  ** the possible values of meta[4].
  */
53081
53082
53083
53084
53085
53086
53087
53088

53089
53090
53091
53092
53093
53094
53095
53360
53361
53362
53363
53364
53365
53366

53367
53368
53369
53370
53371
53372
53373
53374







-
+







** created using ATTACH statements.  Return a success code.  If an
** error occurs, write an error message into *pzErrMsg.
**
** After a database is initialized, the DB_SchemaLoaded bit is set
** bit is set in the flags field of the Db structure. If the database
** file was of zero-length, then the DB_Empty flag is also set.
*/
static int sqlite3Init(sqlite3 *db, char **pzErrMsg){
SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  int i, rc;
  int called_initone = 0;
  
  if( db->init.busy ) return SQLITE_OK;
  rc = SQLITE_OK;
  db->init.busy = 1;
  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
53123
53124
53125
53126
53127
53128
53129
53130

53131
53132
53133
53134
53135
53136
53137
53402
53403
53404
53405
53406
53407
53408

53409
53410
53411
53412
53413
53414
53415
53416







-
+







  return rc; 
}

/*
** This routine is a no-op if the database schema is already initialised.
** Otherwise, the schema is loaded. An error code is returned.
*/
static int sqlite3ReadSchema(Parse *pParse){
SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  int rc = SQLITE_OK;
  sqlite3 *db = pParse->db;
  if( !db->init.busy ){
    rc = sqlite3Init(db, &pParse->zErrMsg);
  }
  if( rc!=SQLITE_OK ){
    pParse->rc = rc;
53171
53172
53173
53174
53175
53176
53177
53178

53179
53180
53181
53182
53183
53184
53185
53450
53451
53452
53453
53454
53455
53456

53457
53458
53459
53460
53461
53462
53463
53464







-
+







/*
** Convert a schema pointer into the iDb index that indicates
** which database file in db->aDb[] the schema refers to.
**
** If the same database is attached more than once, the first
** attached database is returned.
*/
static int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  int i = -1000000;

  /* If pSchema is NULL, then return -1000000. This happens when code in 
  ** expr.c is trying to resolve a reference to a transient table (i.e. one
  ** created by a sub-select). In this case the return value of this 
  ** function should never be used.
  **
53198
53199
53200
53201
53202
53203
53204
53205

53206
53207
53208
53209
53210
53211
53212
53477
53478
53479
53480
53481
53482
53483

53484
53485
53486
53487
53488
53489
53490
53491







-
+







  }
  return i;
}

/*
** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
*/
static int sqlite3Prepare(
SQLITE_PRIVATE int sqlite3Prepare(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
53318
53319
53320
53321
53322
53323
53324
53325

53326
53327
53328
53329
53330
53331
53332
53597
53598
53599
53600
53601
53602
53603

53604
53605
53606
53607
53608
53609
53610
53611







-
+







}

/*
** Rerun the compilation of a statement after a schema change.
** Return true if the statement was recompiled successfully.
** Return false if there is an error of some kind.
*/
static int sqlite3Reprepare(Vdbe *p){
SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  int rc;
  sqlite3_stmt *pNew;
  const char *zSql;
  sqlite3 *db;
  
  zSql = sqlite3VdbeGetSql(p);
  if( zSql==0 ){
53352
53353
53354
53355
53356
53357
53358
53359

53360
53361
53362
53363
53364
53365
53366
53631
53632
53633
53634
53635
53636
53637

53638
53639
53640
53641
53642
53643
53644
53645







-
+







** Two versions of the official API.  Legacy and new use.  In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step().  In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
int sqlite3_prepare(
SQLITE_API int sqlite3_prepare(
  sqlite3 *db,              /* Database handle. */
  const char *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const char **pzTail       /* OUT: End of parsed string */
){
  return sqlite3Prepare(db,zSql,nBytes,0,ppStmt,pzTail);
53421
53422
53423
53424
53425
53426
53427
53428

53429
53430
53431
53432
53433
53434
53435
53700
53701
53702
53703
53704
53705
53706

53707
53708
53709
53710
53711
53712
53713
53714







-
+







** Two versions of the official API.  Legacy and new use.  In the legacy
** version, the original SQL text is not saved in the prepared statement
** and so if a schema change occurs, SQLITE_SCHEMA is returned by
** sqlite3_step().  In the new version, the original SQL text is retained
** and the statement is automatically recompiled if an schema change
** occurs.
*/
int sqlite3_prepare16(
SQLITE_API int sqlite3_prepare16(
  sqlite3 *db,              /* Database handle. */ 
  const void *zSql,         /* UTF-8 encoded SQL statement. */
  int nBytes,               /* Length of zSql in bytes. */
  sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
  const void **pzTail       /* OUT: End of parsed string */
){
  return sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
53458
53459
53460
53461
53462
53463
53464
53465

53466
53467
53468
53469
53470
53471
53472
53737
53738
53739
53740
53741
53742
53743

53744
53745
53746
53747
53748
53749
53750
53751







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle SELECT statements in SQLite.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/


/*
** Delete all the content of a Select structure but do not deallocate
** the select structure itself.
*/
53483
53484
53485
53486
53487
53488
53489
53490

53491
53492
53493
53494
53495
53496
53497
53762
53763
53764
53765
53766
53767
53768

53769
53770
53771
53772
53773
53774
53775
53776







-
+







}


/*
** Allocate a new Select structure and return a pointer to that
** structure.
*/
static Select *sqlite3SelectNew(
SQLITE_PRIVATE Select *sqlite3SelectNew(
  ExprList *pEList,     /* which columns to include in the result */
  SrcList *pSrc,        /* the FROM clause -- which tables to scan */
  Expr *pWhere,         /* the WHERE clause */
  ExprList *pGroupBy,   /* the GROUP BY clause */
  Expr *pHaving,        /* the HAVING clause */
  ExprList *pOrderBy,   /* the ORDER BY clause */
  int isDistinct,       /* true if the DISTINCT keyword is present */
53531
53532
53533
53534
53535
53536
53537
53538

53539
53540
53541
53542
53543
53544
53545
53810
53811
53812
53813
53814
53815
53816

53817
53818
53819
53820
53821
53822
53823
53824







-
+







  }
  return pNew;
}

/*
** Delete the given Select structure and all of its substructures.
*/
static void sqlite3SelectDelete(Select *p){
SQLITE_PRIVATE void sqlite3SelectDelete(Select *p){
  if( p ){
    clearSelect(p);
    sqliteFree(p);
  }
}

/*
53555
53556
53557
53558
53559
53560
53561
53562

53563
53564
53565
53566
53567
53568
53569
53834
53835
53836
53837
53838
53839
53840

53841
53842
53843
53844
53845
53846
53847
53848







-
+







**     JT_RIGHT
**
** A full outer join is the combination of JT_LEFT and JT_RIGHT.
**
** If an illegal or unsupported join type is seen, then still return
** a join type, but put an error in the pParse structure.
*/
static int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  int jointype = 0;
  Token *apAll[3];
  Token *p;
  static const struct {
    const char zKeyword[8];
    u8 nChar;
    u8 code;
53629
53630
53631
53632
53633
53634
53635














53636
53637
53638
53639
53640

53641
53642
53643
53644
53645
53646
53647
53908
53909
53910
53911
53912
53913
53914
53915
53916
53917
53918
53919
53920
53921
53922
53923
53924
53925
53926
53927
53928
53929
53930
53931
53932

53933
53934
53935
53936
53937
53938
53939
53940







+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
+







** Set the value of a token to a '\000'-terminated string.
*/
static void setToken(Token *p, const char *z){
  p->z = (u8*)z;
  p->n = z ? strlen(z) : 0;
  p->dyn = 0;
}

/*
** Set the token to the double-quoted and escaped version of the string pointed
** to by z. For example;
**
**    {a"bc}  ->  {"a""bc"}
*/
static void setQuotedToken(Token *p, const char *z){
  p->z = (u8 *)sqlite3MPrintf("\"%w\"", z);
  p->dyn = 1;
  if( p->z ){
    p->n = strlen((char *)p->z);
  }
}

/*
** Create an expression node for an identifier with the name of zName
*/
static Expr *sqlite3CreateIdExpr(const char *zName){
SQLITE_PRIVATE Expr *sqlite3CreateIdExpr(const char *zName){
  Token dummy;
  setToken(&dummy, zName);
  return sqlite3Expr(TK_ID, 0, 0, &dummy);
}


/*
54502
54503
54504
54505
54506
54507
54508
54509

54510
54511
54512
54513
54514
54515
54516
54795
54796
54797
54798
54799
54800
54801

54802
54803
54804
54805
54806
54807
54808
54809







-
+







*/
static int prepSelectStmt(Parse*, Select*);

/*
** Given a SELECT statement, generate a Table structure that describes
** the result set of that SELECT.
*/
static Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
  Table *pTab;
  int i, j;
  ExprList *pEList;
  Column *aCol, *pCol;

  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  if( prepSelectStmt(pParse, pSelect) ){
54764
54765
54766
54767
54768
54769
54770









54771
54772
54773
54774
54775
54776
54777
54778
54779
54780
54781
54782
54783
54784
54785
54786
54787
54788

54789
54790
54791
54792
54793

54794
54795
54796
54797
54798
54799
54800
54801

54802
54803
54804
54805
54806
54807
54808
55057
55058
55059
55060
55061
55062
55063
55064
55065
55066
55067
55068
55069
55070
55071
55072
55073
55074
55075
55076
55077
55078
55079
55080
55081
55082
55083
55084
55085
55086
55087
55088
55089

55090
55091
55092
55093
55094

55095
55096
55097
55098
55099
55100
55101
55102
55103
55104
55105
55106
55107
55108
55109
55110
55111







+
+
+
+
+
+
+
+
+

















-
+




-
+








+







                 sqlite3StrICmp(zTName, zTabName)!=0) ){
            continue;
          }
          tableSeen = 1;
          for(j=0; j<pTab->nCol; j++){
            Expr *pExpr, *pRight;
            char *zName = pTab->aCol[j].zName;

            /* If a column is marked as 'hidden' (currently only possible
            ** for virtual tables), do not include it in the expanded
            ** result-set list.
            */
            if( IsHiddenColumn(&pTab->aCol[j]) ){
              assert(IsVirtual(pTab));
              continue;
            }

            if( i>0 ){
              struct SrcList_item *pLeft = &pTabList->a[i-1];
              if( (pLeft[1].jointype & JT_NATURAL)!=0 &&
                        columnIndex(pLeft->pTab, zName)>=0 ){
                /* In a NATURAL join, omit the join columns from the 
                ** table on the right */
                continue;
              }
              if( sqlite3IdListIndex(pLeft[1].pUsing, zName)>=0 ){
                /* In a join with a USING clause, omit columns in the
                ** using clause from the table on the right. */
                continue;
              }
            }
            pRight = sqlite3Expr(TK_ID, 0, 0, 0);
            if( pRight==0 ) break;
            setToken(&pRight->token, zName);
            setQuotedToken(&pRight->token, zName);
            if( zTabName && (longNames || pTabList->nSrc>1) ){
              Expr *pLeft = sqlite3Expr(TK_ID, 0, 0, 0);
              pExpr = sqlite3Expr(TK_DOT, pLeft, pRight, 0);
              if( pExpr==0 ) break;
              setToken(&pLeft->token, zTabName);
              setQuotedToken(&pLeft->token, zTabName);
              setToken(&pExpr->span, sqlite3MPrintf("%s.%s", zTabName, zName));
              pExpr->span.dyn = 1;
              pExpr->token.z = 0;
              pExpr->token.n = 0;
              pExpr->token.dyn = 0;
            }else{
              pExpr = pRight;
              pExpr->span = pExpr->token;
              pExpr->span.dyn = 0;
            }
            if( longNames ){
              pNew = sqlite3ExprListAppend(pNew, pExpr, &pExpr->span);
            }else{
              pNew = sqlite3ExprListAppend(pNew, pExpr, &pRight->token);
            }
          }
54820
54821
54822
54823
54824
54825
54826



54827
54828
54829
54830
54831
54832
54833
55123
55124
55125
55126
55127
55128
55129
55130
55131
55132
55133
55134
55135
55136
55137
55138
55139







+
+
+







    }
    sqlite3ExprListDelete(pEList);
    p->pEList = pNew;
  }
  if( p->pEList && p->pEList->nExpr>SQLITE_MAX_COLUMN ){
    sqlite3ErrorMsg(pParse, "too many columns in result set");
    rc = SQLITE_ERROR;
  }
  if( sqlite3MallocFailed() ){
    rc = SQLITE_NOMEM;
  }
  return rc;
}

#ifndef SQLITE_OMIT_COMPOUND_SELECT
/*
** This routine associates entries in an ORDER BY expression list with
54919
54920
54921
54922
54923
54924
54925
54926

54927
54928
54929
54930
54931
54932
54933
55225
55226
55227
55228
55229
55230
55231

55232
55233
55234
55235
55236
55237
55238
55239







-
+







}
#endif /* #ifndef SQLITE_OMIT_COMPOUND_SELECT */

/*
** Get a VDBE for the given parser context.  Create a new one if necessary.
** If an error occurs, return NULL and leave a message in pParse.
*/
static Vdbe *sqlite3GetVdbe(Parse *pParse){
SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  Vdbe *v = pParse->pVdbe;
  if( v==0 ){
    v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  }
  return v;
}

55931
55932
55933
55934
55935
55936
55937










55938
55939
55940
55941
55942
55943
55944
56237
56238
56239
56240
56241
56242
56243
56244
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
56260







+
+
+
+
+
+
+
+
+
+







    sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
    sqlite3VdbeOp3(v, OP_OpenRead, iIdx, pIdx->tnum, 
        (char*)pKey, P3_KEYINFO_HANDOFF);
    if( seekOp==OP_Rewind ){
      sqlite3VdbeAddOp(v, OP_Null, 0, 0);
      sqlite3VdbeAddOp(v, OP_MakeRecord, 1, 0);
      seekOp = OP_MoveGt;
    }
    if( pIdx->aSortOrder[0]==SQLITE_SO_DESC ){
      /* Ticket #2514: invert the seek operator if we are using
      ** a descending index. */
      if( seekOp==OP_Last ){
        seekOp = OP_Rewind;
      }else{
        assert( seekOp==OP_MoveGt );
        seekOp = OP_MoveLt;
      }
    }
    sqlite3VdbeAddOp(v, seekOp, iIdx, 0);
    sqlite3VdbeAddOp(v, OP_IdxRowid, iIdx, 0);
    sqlite3VdbeAddOp(v, OP_Close, iIdx, 0);
    sqlite3VdbeAddOp(v, OP_MoveGe, base, 0);
  }
  eList.nExpr = 1;
56004
56005
56006
56007
56008
56009
56010
56011

56012
56013
56014
56015
56016
56017
56018
56320
56321
56322
56323
56324
56325
56326

56327
56328
56329
56330
56331
56332
56333
56334







-
+








/*
** This routine resolves any names used in the result set of the
** supplied SELECT statement. If the SELECT statement being resolved
** is a sub-select, then pOuterNC is a pointer to the NameContext 
** of the parent SELECT.
*/
static int sqlite3SelectResolve(
SQLITE_PRIVATE int sqlite3SelectResolve(
  Parse *pParse,         /* The parser context */
  Select *p,             /* The SELECT statement being coded. */
  NameContext *pOuterNC  /* The outer name context. May be NULL. */
){
  ExprList *pEList;          /* Result set. */
  int i;                     /* For-loop variable used in multiple places */
  NameContext sNC;           /* Local name-context */
56279
56280
56281
56282
56283
56284
56285
56286

56287
56288
56289
56290
56291
56292
56293
56595
56596
56597
56598
56599
56600
56601

56602
56603
56604
56605
56606
56607
56608
56609







-
+







** This routine is called for the outer query first.   For that call,
** pParent will be NULL.  During the processing of the outer query, this 
** routine is called recursively to handle the subquery.  For the recursive
** call, pParent will point to the outer query.  Because the subquery is
** the second element in a three-way join, the parentTab parameter will
** be 1 (the 2nd value of a 0-indexed array.)
*/
static int sqlite3Select(
SQLITE_PRIVATE int sqlite3Select(
  Parse *pParse,         /* The parser context */
  Select *p,             /* The SELECT statement being coded. */
  int eDest,             /* How to dispose of the results */
  int iParm,             /* A parameter used by the eDest disposal method */
  Select *pParent,       /* Another SELECT for which this is a sub-query */
  int parentTab,         /* Index in pParent->pSrc of this query */
  int *pParentAgg,       /* True if pParent uses aggregate functions */
56831
56832
56833
56834
56835
56836
56837
56838

56839
56840
56841
56842
56843
56844
56845
56846
56847
56848
56849
56850
56851
56852
56853
56854

56855
56856
56857
56858
56859
56860
56861
56862
56863

56864
56865
56866
56867
56868
56869
56870
57147
57148
57149
57150
57151
57152
57153

57154
57155
57156
57157
57158
57159
57160
57161
57162
57163
57164
57165
57166
57167
57168
57169

57170
57171
57172
57173
57174
57175
57176
57177
57178

57179
57180
57181
57182
57183
57184
57185
57186







-
+















-
+








-
+







** for helping to understand what is happening inside the code generator
** during the execution of complex SELECT statements.
**
** These routine are not called anywhere from within the normal
** code base.  Then are intended to be called from within the debugger
** or from temporary "printf" statements inserted for debugging.
*/
static void sqlite3PrintExpr(Expr *p){
SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
  if( p->token.z && p->token.n>0 ){
    sqlite3DebugPrintf("(%.*s", p->token.n, p->token.z);
  }else{
    sqlite3DebugPrintf("(%d", p->op);
  }
  if( p->pLeft ){
    sqlite3DebugPrintf(" ");
    sqlite3PrintExpr(p->pLeft);
  }
  if( p->pRight ){
    sqlite3DebugPrintf(" ");
    sqlite3PrintExpr(p->pRight);
  }
  sqlite3DebugPrintf(")");
}
static void sqlite3PrintExprList(ExprList *pList){
SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
  int i;
  for(i=0; i<pList->nExpr; i++){
    sqlite3PrintExpr(pList->a[i].pExpr);
    if( i<pList->nExpr-1 ){
      sqlite3DebugPrintf(", ");
    }
  }
}
static void sqlite3PrintSelect(Select *p, int indent){
SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
  sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
  sqlite3PrintExprList(p->pEList);
  sqlite3DebugPrintf("\n");
  if( p->pSrc ){
    char *zPrefix;
    int i;
    zPrefix = "FROM";
57130
57131
57132
57133
57134
57135
57136
57137

57138
57139
57140
57141
57142
57143
57144
57446
57447
57448
57449
57450
57451
57452

57453
57454
57455
57456
57457
57458
57459
57460







-
+







*
*/

#ifndef SQLITE_OMIT_TRIGGER
/*
** Delete a linked list of TriggerStep structures.
*/
static void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
SQLITE_PRIVATE void sqlite3DeleteTriggerStep(TriggerStep *pTriggerStep){
  while( pTriggerStep ){
    TriggerStep * pTmp = pTriggerStep;
    pTriggerStep = pTriggerStep->pNext;

    if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
    sqlite3ExprDelete(pTmp->pWhere);
    sqlite3ExprListDelete(pTmp->pExprList);
57153
57154
57155
57156
57157
57158
57159
57160

57161
57162
57163
57164
57165
57166
57167
57469
57470
57471
57472
57473
57474
57475

57476
57477
57478
57479
57480
57481
57482
57483







-
+







** This is called by the parser when it sees a CREATE TRIGGER statement
** up to the point of the BEGIN before the trigger actions.  A Trigger
** structure is generated based on the information available and stored
** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
** sqlite3FinishTrigger() function is called to complete the trigger
** construction process.
*/
static void sqlite3BeginTrigger(
SQLITE_PRIVATE void sqlite3BeginTrigger(
  Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
  Token *pName1,      /* The name of the trigger */
  Token *pName2,      /* The name of the trigger */
  int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
  SrcList *pTableName,/* The name of the table/view the trigger applies to */
57313
57314
57315
57316
57317
57318
57319
57320

57321
57322
57323
57324
57325
57326
57327
57629
57630
57631
57632
57633
57634
57635

57636
57637
57638
57639
57640
57641
57642
57643







-
+







  }
}

/*
** This routine is called after all of the trigger actions have been parsed
** in order to complete the process of building the trigger.
*/
static void sqlite3FinishTrigger(
SQLITE_PRIVATE void sqlite3FinishTrigger(
  Parse *pParse,          /* Parser context */
  TriggerStep *pStepList, /* The triggered program */
  Token *pAll             /* Token that describes the complete CREATE TRIGGER */
){
  Trigger *pTrig = 0;     /* The trigger whose construction is finishing up */
  sqlite3 *db = pParse->db;  /* The database */
  DbFixer sFix;
57439
57440
57441
57442
57443
57444
57445
57446

57447
57448
57449
57450
57451
57452
57453
57755
57756
57757
57758
57759
57760
57761

57762
57763
57764
57765
57766
57767
57768
57769







-
+







/*
** Turn a SELECT statement (that the pSelect parameter points to) into
** a trigger step.  Return a pointer to a TriggerStep structure.
**
** The parser calls this routine when it finds a SELECT statement in
** body of a TRIGGER.  
*/
static TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(Select *pSelect){
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  if( pTriggerStep==0 ) {
    sqlite3SelectDelete(pSelect);
    return 0;
  }

  pTriggerStep->op = TK_SELECT;
57461
57462
57463
57464
57465
57466
57467
57468

57469
57470
57471
57472
57473
57474
57475
57777
57778
57779
57780
57781
57782
57783

57784
57785
57786
57787
57788
57789
57790
57791







-
+







/*
** Build a trigger step out of an INSERT statement.  Return a pointer
** to the new trigger step.
**
** The parser calls this routine when it sees an INSERT inside the
** body of a trigger.
*/
static TriggerStep *sqlite3TriggerInsertStep(
SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  Token *pTableName,  /* Name of the table into which we insert */
  IdList *pColumn,    /* List of columns in pTableName to insert into */
  ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
  Select *pSelect,    /* A SELECT statement that supplies values */
  int orconf          /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
){
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
57495
57496
57497
57498
57499
57500
57501
57502

57503
57504
57505
57506
57507
57508
57509
57811
57812
57813
57814
57815
57816
57817

57818
57819
57820
57821
57822
57823
57824
57825







-
+







}

/*
** Construct a trigger step that implements an UPDATE statement and return
** a pointer to that trigger step.  The parser calls this routine when it
** sees an UPDATE statement inside the body of a CREATE TRIGGER.
*/
static TriggerStep *sqlite3TriggerUpdateStep(
SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  Token *pTableName,   /* Name of the table to be updated */
  ExprList *pEList,    /* The SET clause: list of column and new values */
  Expr *pWhere,        /* The WHERE clause */
  int orconf           /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
){
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  if( pTriggerStep==0 ){
57523
57524
57525
57526
57527
57528
57529
57530

57531
57532
57533
57534
57535
57536
57537
57538
57539
57540
57541
57542
57543
57544
57545
57546
57547
57548
57549

57550
57551
57552
57553
57554
57555
57556
57557
57558
57559
57560
57561
57562
57563
57564
57565
57566
57567
57568

57569
57570
57571
57572
57573
57574
57575
57839
57840
57841
57842
57843
57844
57845

57846
57847
57848
57849
57850
57851
57852
57853
57854
57855
57856
57857
57858
57859
57860
57861
57862
57863
57864

57865
57866
57867
57868
57869
57870
57871
57872
57873
57874
57875
57876
57877
57878
57879
57880
57881
57882
57883

57884
57885
57886
57887
57888
57889
57890
57891







-
+


















-
+


















-
+







}

/*
** Construct a trigger step that implements a DELETE statement and return
** a pointer to that trigger step.  The parser calls this routine when it
** sees a DELETE statement inside the body of a CREATE TRIGGER.
*/
static TriggerStep *sqlite3TriggerDeleteStep(Token *pTableName, Expr *pWhere){
SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(Token *pTableName, Expr *pWhere){
  TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  if( pTriggerStep==0 ){
    sqlite3ExprDelete(pWhere);
    return 0;
  }

  pTriggerStep->op = TK_DELETE;
  pTriggerStep->target  = *pTableName;
  pTriggerStep->pWhere = pWhere;
  pTriggerStep->orconf = OE_Default;
  sqlitePersistTriggerStep(pTriggerStep);

  return pTriggerStep;
}

/* 
** Recursively delete a Trigger structure
*/
static void sqlite3DeleteTrigger(Trigger *pTrigger){
SQLITE_PRIVATE void sqlite3DeleteTrigger(Trigger *pTrigger){
  if( pTrigger==0 ) return;
  sqlite3DeleteTriggerStep(pTrigger->step_list);
  sqliteFree(pTrigger->name);
  sqliteFree(pTrigger->table);
  sqlite3ExprDelete(pTrigger->pWhen);
  sqlite3IdListDelete(pTrigger->pColumns);
  if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
  sqliteFree(pTrigger);
}

/*
** This function is called to drop a trigger from the database schema. 
**
** This may be called directly from the parser and therefore identifies
** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
** same job as this routine except it takes a pointer to the trigger
** instead of the trigger name.
**/
static void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  Trigger *pTrigger = 0;
  int i;
  const char *zDb;
  const char *zName;
  int nName;
  sqlite3 *db = pParse->db;

57609
57610
57611
57612
57613
57614
57615
57616

57617
57618
57619
57620
57621
57622
57623
57925
57926
57927
57928
57929
57930
57931

57932
57933
57934
57935
57936
57937
57938
57939







-
+







  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
}


/*
** Drop a trigger given a pointer to that trigger. 
*/
static void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  Table   *pTable;
  Vdbe *v;
  sqlite3 *db = pParse->db;
  int iDb;

  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  assert( iDb>=0 && iDb<db->nDb );
57663
57664
57665
57666
57667
57668
57669
57670

57671
57672
57673
57674
57675
57676
57677
57979
57980
57981
57982
57983
57984
57985

57986
57987
57988
57989
57990
57991
57992
57993







-
+







    sqlite3VdbeOp3(v, OP_DropTrigger, iDb, 0, pTrigger->name, 0);
  }
}

/*
** Remove a trigger from the hash tables of the sqlite* pointer.
*/
static void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  Trigger *pTrigger;
  int nName = strlen(zName);
  pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
                               zName, nName, 0);
  if( pTrigger ){
    Table *pTable = tableOfTrigger(pTrigger);
    assert( pTable!=0 );
57716
57717
57718
57719
57720
57721
57722
57723

57724
57725
57726
57727
57728
57729
57730
58032
58033
58034
58035
58036
58037
58038

58039
58040
58041
58042
58043
58044
58045
58046







-
+







** "op" on table pTab.  If pChanges is not NULL then it is a list of columns
** that are being updated.  Triggers only match if the ON clause of the
** trigger definition overlaps the set of columns being updated.
**
** The returned bit vector is some combination of TRIGGER_BEFORE and
** TRIGGER_AFTER.
*/
static int sqlite3TriggersExist(
SQLITE_PRIVATE int sqlite3TriggersExist(
  Parse *pParse,          /* Used to check for recursive triggers */
  Table *pTab,            /* The table the contains the triggers */
  int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  ExprList *pChanges      /* Columns that change in an UPDATE statement */
){
  Trigger *pTrigger;
  int mask = 0;
57855
57856
57857
57858
57859
57860
57861
57862

57863
57864
57865
57866
57867
57868
57869
58171
58172
58173
58174
58175
58176
58177

58178
58179
58180
58181
58182
58183
58184
58185







-
+







**
** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
**    a temporary vdbe cursor (index oldIdx) must be open and pointing at
**    a row containing values to be substituted for old.* expressions in the
**    trigger program(s).
**
*/
static int sqlite3CodeRowTrigger(
SQLITE_PRIVATE int sqlite3CodeRowTrigger(
  Parse *pParse,       /* Parse context */
  int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
  int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  Table *pTab,         /* The table to code triggers from */
  int newIdx,          /* The indice of the "new" row to access */
  int oldIdx,          /* The indice of the "old" row to access */
57957
57958
57959
57960
57961
57962
57963
57964

57965
57966
57967
57968
57969
57970
57971
58273
58274
58275
58276
58277
58278
58279

58280
58281
58282
58283
58284
58285
58286
58287







-
+







**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle UPDATE statements.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

#ifndef SQLITE_OMIT_VIRTUALTABLE
/* Forward declaration */
static void updateVirtualTable(
  Parse *pParse,       /* The parsing context */
  SrcList *pSrc,       /* The virtual table to be modified */
57998
57999
58000
58001
58002
58003
58004
58005

58006
58007
58008
58009

58010
58011
58012
58013
58014
58015
58016
58017
58018
58019
58020
58021
58022
58023
58024
58025
58026

58027
58028
58029
58030
58031
58032
58033
58314
58315
58316
58317
58318
58319
58320

58321
58322
58323
58324
58325
58326
58327
58328
58329
58330
58331
58332
58333
58334
58335
58336
58337
58338
58339
58340
58341
58342

58343
58344
58345
58346
58347
58348
58349
58350







-
+




+
















-
+







** into the sqlite_master table.)
**
** Therefore, the P3 parameter is only required if the default value for
** the column is a literal number, string or null. The sqlite3ValueFromExpr()
** function is capable of transforming these types of expressions into
** sqlite3_value objects.
*/
static void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i){
  if( pTab && !pTab->pSelect ){
    sqlite3_value *pValue;
    u8 enc = ENC(sqlite3VdbeDb(v));
    Column *pCol = &pTab->aCol[i];
    assert( i<pTab->nCol );
    sqlite3ValueFromExpr(pCol->pDflt, enc, pCol->affinity, &pValue);
    if( pValue ){
      sqlite3VdbeChangeP3(v, -1, (const char *)pValue, P3_MEM);
    }else{
      VdbeComment((v, "# %s.%s", pTab->zName, pCol->zName));
    }
  }
}

/*
** Process an UPDATE statement.
**
**   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
**          \_______/ \________/     \______/       \________________/
*            onError   pTabList      pChanges             pWhere
*/
static void sqlite3Update(
SQLITE_PRIVATE void sqlite3Update(
  Parse *pParse,         /* The parser context */
  SrcList *pTabList,     /* The table in which we should change things */
  ExprList *pChanges,    /* Things to be changed */
  Expr *pWhere,          /* The WHERE clause.  May be null */
  int onError            /* How to handle constraint errors */
){
  int i, j;              /* Loop counters */
58587
58588
58589
58590
58591
58592
58593
58594

58595
58596
58597
58598
58599
58600
58601
58904
58905
58906
58907
58908
58909
58910

58911
58912
58913
58914
58915
58916
58917
58918







-
+







**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
/*
** Execute zSql on database db. Return an error code.
*/
static int execSql(sqlite3 *db, const char *zSql){
58635
58636
58637
58638
58639
58640
58641
58642

58643
58644
58645
58646
58647
58648
58649
58650
58651
58652
58653

58654
58655
58656
58657
58658
58659
58660
58952
58953
58954
58955
58956
58957
58958

58959
58960
58961
58962
58963
58964
58965
58966
58967
58968
58969

58970
58971
58972
58973
58974
58975
58976
58977







-
+










-
+







** in PostgreSQL.
**
** In version 1.0.x of SQLite, the VACUUM command would call
** gdbm_reorganize() on all the database tables.  But beginning
** with 2.0.0, SQLite no longer uses GDBM so this command has
** become a no-op.
*/
static void sqlite3Vacuum(Parse *pParse){
SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  Vdbe *v = sqlite3GetVdbe(pParse);
  if( v ){
    sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0);
  }
  return;
}

/*
** This routine implements the OP_Vacuum opcode of the VDBE.
*/
static int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  int rc = SQLITE_OK;     /* Return code from service routines */
  Btree *pMain;           /* The database being vacuumed */
  Btree *pTemp;           /* The temporary database we vacuum into */
  char *zSql = 0;         /* SQL statements */
  int saved_flags;        /* Saved value of the db->flags */
  Db *pDb = 0;            /* Database to detach at end of vacuum */

58846
58847
58848
58849
58850
58851
58852
58853

58854
58855



























58856
58857
58858
58859
58860
58861
58862
58863
58864
58865
58866
58867
58868
58869
58870

58871
58872
58873
58874
58875
58876
58877
58878












58879
58880
58881
58882
58883
58884
58885
58886
58887
58888
58889

58890
58891
58892
58893
58894
58895
58896
58897

58898
58899
58900
58901
58902
58903
58904
58905
58906
58907
58908
58909
58910
58911
58912
58913
58914
58915
58916
58917

58918
58919
58920
58921
58922
58923
58924
59163
59164
59165
59166
59167
59168
59169

59170
59171
59172
59173
59174
59175
59176
59177
59178
59179
59180
59181
59182
59183
59184
59185
59186
59187
59188
59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199
59200
59201
59202
59203
59204
59205
59206
59207
59208
59209





59210






59211

59212
59213
59214
59215
59216
59217
59218
59219
59220
59221
59222
59223
59224
59225
59226
59227
59228
59229
59230
59231
59232
59233

59234
59235
59236
59237
59238
59239
59240
59241

59242
59243
59244
59245
59246
59247
59248
59249
59250
59251
59252
59253
59254
59255
59256
59257
59258
59259
59260
59261

59262
59263
59264
59265
59266
59267
59268
59269







-
+


+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+










-
-
-
-
-
+
-
-
-
-
-
-

-
+
+
+
+
+
+
+
+
+
+
+
+










-
+







-
+



















-
+







**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to help implement virtual tables.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef SQLITE_OMIT_VIRTUALTABLE

static int createModule(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
) {
  int nName = strlen(zName);
  Module *pMod = (Module *)sqliteMallocRaw(sizeof(Module) + nName + 1);
  if( pMod ){
    char *zCopy = (char *)(&pMod[1]);
    memcpy(zCopy, zName, nName+1);
    pMod->zName = zCopy;
    pMod->pModule = pModule;
    pMod->pAux = pAux;
    pMod->xDestroy = xDestroy;
    pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
    if( pMod && pMod->xDestroy ){
      pMod->xDestroy(pMod->pAux);
    }
    sqliteFree(pMod);
    sqlite3ResetInternalSchema(db, 0);
  }
  return sqlite3ApiExit(db, SQLITE_OK);
}


/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux                      /* Context pointer for xCreate/xConnect */
){
  int nName = strlen(zName);
  Module *pMod = (Module *)sqliteMallocRaw(sizeof(Module) + nName + 1);
  if( pMod ){
    char *zCopy = (char *)(&pMod[1]);
    memcpy(zCopy, zName, nName+1);
  return createModule(db, zName, pModule, pAux, 0);
    pMod->zName = zCopy;
    pMod->pModule = pModule;
    pMod->pAux = pAux;
    pMod = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
    sqliteFree(pMod);
    sqlite3ResetInternalSchema(db, 0);
  }
  return sqlite3ApiExit(db, SQLITE_OK);

/*
** External API function used to create a new virtual-table module.
*/
int sqlite3_create_module_v2(
  sqlite3 *db,                    /* Database in which module is registered */
  const char *zName,              /* Name assigned to this module */
  const sqlite3_module *pModule,  /* The definition of the module */
  void *pAux,                     /* Context pointer for xCreate/xConnect */
  void (*xDestroy)(void *)        /* Module destructor function */
){
  return createModule(db, zName, pModule, pAux, xDestroy);
}

/*
** Lock the virtual table so that it cannot be disconnected.
** Locks nest.  Every lock should have a corresponding unlock.
** If an unlock is omitted, resources leaks will occur.  
**
** If a disconnect is attempted while a virtual table is locked,
** the disconnect is deferred until all locks have been removed.
*/
static void sqlite3VtabLock(sqlite3_vtab *pVtab){
SQLITE_PRIVATE void sqlite3VtabLock(sqlite3_vtab *pVtab){
  pVtab->nRef++;
}

/*
** Unlock a virtual table.  When the last lock is removed,
** disconnect the virtual table.
*/
static void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
SQLITE_PRIVATE void sqlite3VtabUnlock(sqlite3 *db, sqlite3_vtab *pVtab){
  pVtab->nRef--;
  assert(db);
  assert(!sqlite3SafetyCheck(db));
  if( pVtab->nRef==0 ){
    if( db->magic==SQLITE_MAGIC_BUSY ){
      sqlite3SafetyOff(db);
      pVtab->pModule->xDisconnect(pVtab);
      sqlite3SafetyOn(db);
    } else {
      pVtab->pModule->xDisconnect(pVtab);
    }
  }
}

/*
** Clear any and all virtual-table information from the Table record.
** This routine is called, for example, just before deleting the Table
** record.
*/
static void sqlite3VtabClear(Table *p){
SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
  sqlite3_vtab *pVtab = p->pVtab;
  if( pVtab ){
    assert( p->pMod && p->pMod->pModule );
    sqlite3VtabUnlock(p->pSchema->db, pVtab);
    p->pVtab = 0;
  }
  if( p->azModuleArg ){
58957
58958
58959
58960
58961
58962
58963
58964

58965
58966
58967
58968
58969
58970
58971
59302
59303
59304
59305
59306
59307
59308

59309
59310
59311
59312
59313
59314
59315
59316







-
+







}

/*
** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
** statement.  The module name has been parsed, but the optional list
** of parameters that follow the module name are still pending.
*/
static void sqlite3VtabBeginParse(
SQLITE_PRIVATE void sqlite3VtabBeginParse(
  Parse *pParse,        /* Parsing context */
  Token *pName1,        /* Name of new table, or database name */
  Token *pName2,        /* Name of new table or NULL */
  Token *pModuleName    /* Name of the module for the virtual table */
){
  int iDb;              /* The database the table is being created in */
  Table *pTable;        /* The new virtual table */
59018
59019
59020
59021
59022
59023
59024
59025

59026
59027
59028
59029
59030
59031
59032
59363
59364
59365
59366
59367
59368
59369

59370
59371
59372
59373
59374
59375
59376
59377







-
+







  }
}

/*
** The parser calls this routine after the CREATE VIRTUAL TABLE statement
** has been completely parsed.
*/
static void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  Table *pTab;        /* The table being constructed */
  sqlite3 *db;        /* The database connection */
  char *zModule;      /* The module name of the table: USING modulename */
  Module *pMod = 0;

  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
59106
59107
59108
59109
59110
59111
59112
59113

59114
59115
59116
59117
59118
59119
59120
59121
59122
59123

59124
59125
59126
59127
59128
59129
59130
59451
59452
59453
59454
59455
59456
59457

59458
59459
59460
59461
59462
59463
59464
59465
59466
59467

59468
59469
59470
59471
59472
59473
59474
59475







-
+









-
+







  }
}

/*
** The parser calls this routine when it sees the first token
** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
static void sqlite3VtabArgInit(Parse *pParse){
SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  addArgumentToVtab(pParse);
  pParse->sArg.z = 0;
  pParse->sArg.n = 0;
}

/*
** The parser calls this routine for each token after the first token
** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
*/
static void sqlite3VtabArgExtend(Parse *pParse, Token *p){
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  Token *pArg = &pParse->sArg;
  if( pArg->z==0 ){
    pArg->z = p->z;
    pArg->n = p->n;
  }else{
    assert(pArg->z < p->z);
    pArg->n = (p->z + p->n - pArg->z);
59182
59183
59184
59185
59186
59187
59188






































59189
59190
59191
59192
59193
59194
59195
59196
59197
59198
59199

59200
59201
59202
59203
59204
59205
59206
59527
59528
59529
59530
59531
59532
59533
59534
59535
59536
59537
59538
59539
59540
59541
59542
59543
59544
59545
59546
59547
59548
59549
59550
59551
59552
59553
59554
59555
59556
59557
59558
59559
59560
59561
59562
59563
59564
59565
59566
59567
59568
59569
59570
59571
59572
59573
59574
59575
59576
59577
59578
59579
59580
59581

59582
59583
59584
59585
59586
59587
59588
59589







+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+










-
+







    rc = SQLITE_ERROR;
  } 
  if( rc==SQLITE_OK ){
    rc = rc2;
  }
  db->pVTab = 0;
  sqliteFree(zModuleName);

  /* If everything went according to plan, loop through the columns
  ** of the table to see if any of them contain the token "hidden".
  ** If so, set the Column.isHidden flag and remove the token from
  ** the type string.
  */
  if( rc==SQLITE_OK ){
    int iCol;
    for(iCol=0; iCol<pTab->nCol; iCol++){
      char *zType = pTab->aCol[iCol].zType;
      int nType;
      int i = 0;
      if( !zType ) continue;
      nType = strlen(zType);
      if( sqlite3StrNICmp("hidden", zType, 6) || (zType[6] && zType[6]!=' ') ){
        for(i=0; i<nType; i++){
          if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
           && (zType[i+7]=='\0' || zType[i+7]==' ')
          ){
            i++;
            break;
          }
        }
      }
      if( i<nType ){
        int j;
        int nDel = 6 + (zType[i+6] ? 1 : 0);
        for(j=i; (j+nDel)<=nType; j++){
          zType[j] = zType[j+nDel];
        }
        if( zType[i]=='\0' && i>0 ){
          assert(zType[i-1]==' ');
          zType[i-1] = '\0';
        }
        pTab->aCol[iCol].isHidden = 1;
      }
    }
  }
  return rc;
}

/*
** This function is invoked by the parser to call the xConnect() method
** of the virtual table pTab. If an error occurs, an error code is returned 
** and an error left in pParse.
**
** This call is a no-op if table pTab is not a virtual table.
*/
static int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  Module *pMod;
  int rc = SQLITE_OK;

  if( !pTab || !pTab->isVirtual || pTab->pVtab ){
    return SQLITE_OK;
  }

59250
59251
59252
59253
59254
59255
59256
59257

59258
59259
59260
59261
59262
59263
59264
59633
59634
59635
59636
59637
59638
59639

59640
59641
59642
59643
59644
59645
59646
59647







-
+







** This function is invoked by the vdbe to call the xCreate method
** of the virtual table named zTab in database iDb. 
**
** If an error occurs, *pzErr is set to point an an English language
** description of the error and an SQLITE_XXX error code is returned.
** In this case the caller must call sqliteFree() on *pzErr.
*/
static int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  int rc = SQLITE_OK;
  Table *pTab;
  Module *pMod;
  const char *zModule;

  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  assert(pTab && pTab->isVirtual && !pTab->pVtab);
59334
59335
59336
59337
59338
59339
59340
59341

59342
59343
59344
59345
59346
59347
59348
59717
59718
59719
59720
59721
59722
59723

59724
59725
59726
59727
59728
59729
59730
59731







-
+







/*
** This function is invoked by the vdbe to call the xDestroy method
** of the virtual table named zTab in database iDb. This occurs
** when a DROP TABLE is mentioned.
**
** This call is a no-op if zTab is not a virtual table.
*/
static int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab)
{
  int rc = SQLITE_OK;
  Table *pTab;

  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  assert(pTab);
  if( pTab->pVtab ){
59387
59388
59389
59390
59391
59392
59393
59394

59395
59396
59397
59398
59399
59400
59401
59770
59771
59772
59773
59774
59775
59776

59777
59778
59779
59780
59781
59782
59783
59784







-
+








/*
** If argument rc2 is not SQLITE_OK, then return it and do nothing. 
** Otherwise, invoke the xSync method of all virtual tables in the 
** sqlite3.aVTrans array. Return the error code for the first error 
** that occurs, or SQLITE_OK if all xSync operations are successful.
*/
static int sqlite3VtabSync(sqlite3 *db, int rc2){
SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, int rc2){
  int i;
  int rc = SQLITE_OK;
  int rcsafety;
  sqlite3_vtab **aVTrans = db->aVTrans;
  if( rc2!=SQLITE_OK ) return rc2;

  rc = sqlite3SafetyOff(db);
59417
59418
59419
59420
59421
59422
59423
59424

59425
59426
59427
59428
59429
59430
59431
59432
59433

59434
59435
59436
59437
59438
59439
59440
59441
59442
59443
59444
59445
59446

59447
59448
59449
59450
59451
59452
59453
59800
59801
59802
59803
59804
59805
59806

59807
59808
59809
59810
59811
59812
59813
59814
59815

59816
59817
59818
59819
59820
59821
59822
59823
59824
59825
59826
59827
59828

59829
59830
59831
59832
59833
59834
59835
59836







-
+








-
+












-
+







  return rc;
}

/*
** Invoke the xRollback method of all virtual tables in the 
** sqlite3.aVTrans array. Then clear the array itself.
*/
static int sqlite3VtabRollback(sqlite3 *db){
SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  callFinaliser(db, (int)(&((sqlite3_module *)0)->xRollback));
  return SQLITE_OK;
}

/*
** Invoke the xCommit method of all virtual tables in the 
** sqlite3.aVTrans array. Then clear the array itself.
*/
static int sqlite3VtabCommit(sqlite3 *db){
SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  callFinaliser(db, (int)(&((sqlite3_module *)0)->xCommit));
  return SQLITE_OK;
}

/*
** If the virtual table pVtab supports the transaction interface
** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
** not currently open, invoke the xBegin method now.
**
** If the xBegin call is successful, place the sqlite3_vtab pointer
** in the sqlite3.aVTrans array.
*/
static int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, sqlite3_vtab *pVtab){
  int rc = SQLITE_OK;
  const sqlite3_module *pModule;

  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  ** than zero, then this function is being called from within a
  ** virtual module xSync() callback. It is illegal to write to 
  ** virtual module tables in this case, so return SQLITE_LOCKED.
59491
59492
59493
59494
59495
59496
59497
59498

59499
59500
59501
59502
59503
59504
59505
59874
59875
59876
59877
59878
59879
59880

59881
59882
59883
59884
59885
59886
59887
59888







-
+







** This routine is used to allow virtual table implementations to
** overload MATCH, LIKE, GLOB, and REGEXP operators.
**
** Return either the pDef argument (indicating no change) or a 
** new FuncDef structure that is marked as ephemeral using the
** SQLITE_FUNC_EPHEM flag.
*/
static FuncDef *sqlite3VtabOverloadFunction(
SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  FuncDef *pDef,  /* Function to possibly overload */
  int nArg,       /* Number of arguments to the function */
  Expr *pExpr     /* First argument to the function */
){
  Table *pTab;
  sqlite3_vtab *pVtab;
  sqlite3_module *pMod;
59568
59569
59570
59571
59572
59573
59574
59575

59576
59577
59578
59579
59580
59581
59582
59951
59952
59953
59954
59955
59956
59957

59958
59959
59960
59961
59962
59963
59964
59965







-
+







** This module contains C code that generates VDBE code used to process
** the WHERE clause of SQL statements.  This module is reponsible for
** generating the code that loops through a table looking for applicable
** rows.  Indices are selected and used to speed the search when doing
** so is applicable.  Because this module is responsible for selecting
** indices, you might also think of this module as the "query optimizer".
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
*/
#define BMS  (sizeof(Bitmask)*8)

61490
61491
61492
61493
61494
61495
61496
61497

61498
61499
61500
61501
61502
61503
61504
61873
61874
61875
61876
61877
61878
61879

61880
61881
61882
61883
61884
61885
61886
61887







-
+







** *ppOrderBy is set to NULL.  This is an optimization that prevents an
** unnecessary sort of the result set if an index appropriate for the
** ORDER BY clause already exists.
**
** If the where clause loops cannot be arranged to provide the correct
** output order, then the *ppOrderBy is unchanged.
*/
static WhereInfo *sqlite3WhereBegin(
SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  Parse *pParse,        /* The parser context */
  SrcList *pTabList,    /* A list of all tables to be scanned */
  Expr *pWhere,         /* The WHERE clause */
  ExprList **ppOrderBy  /* An ORDER BY clause, or NULL */
){
  int i;                     /* Loop counter */
  WhereInfo *pWInfo;         /* Will become the return value of this function */
62207
62208
62209
62210
62211
62212
62213
62214

62215
62216
62217
62218
62219
62220
62221
62590
62591
62592
62593
62594
62595
62596

62597
62598
62599
62600
62601
62602
62603
62604







-
+







  return 0;
}

/*
** Generate the end of the WHERE loop.  See comments on 
** sqlite3WhereBegin() for additional information.
*/
static void sqlite3WhereEnd(WhereInfo *pWInfo){
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  Vdbe *v = pWInfo->pParse->pVdbe;
  int i;
  WhereLevel *pLevel;
  SrcList *pTabList = pWInfo->pTabList;

  /* Generate loop termination code.
  */
62485
62486
62487
62488
62489
62490
62491
62492

62493
62494
62495
62496
62497
62498
62499






62500
62501
62502
62503
62504
62505
62506
62507
62508








62509
62510
62511
62512
62513
62514
62515
62516
62517
62518
62519
62520
62521
62522
62523
62524
62525
62526
62527
62528
62529
62530
62531
62532
62533
62534
62535
62536
62537
62538
62539
62540
62541
62542
62543
62544
62545
62546
62547
62548
62549
62550
62551
62552
62553
62554
62555
62556
62557
62558
62559
62560
62561
62562
62563
62564
62565
62566
62567


























































62568
62569
62570
62571
62572
62573
62574
62575
62576
62577
62578
62579
62580
62581
62582
62583
62584
62585
62586
62587
62588
62589
62590
62591
62592
62593
62594
62595
62596
62597
62598
62599
62600
62601
62602
62603
62604
62605
62606
62607
62608
62609
62610
62611
62612
62613
62614
62615
62616
62617
62618
62619
62620
62621
62622
62623
62624
62625
62626


























































62627
62628
62629
62630
62631

62632
62633
62634


62635
62636

62637
62638

62639
62640
62641

62642
62643
62644
62645



62646
62647
62648
62649
62650
62651





62652
62653
62654
62655


62656
62657
62658
62659
62660
62661
62662
62663
62664
62665
62666
62667
62668











62669
62670
62671
62672
62673
62674





62675
62676
62677
62678
62679
62680
62681
62682
62683
62684
62685
62686
62687
62688
62689
62690
62691
62692
62693
62694



















62695
62696
62697
62698
62699
62700





62701
62702
62703


62704
62705
62706
62707


62708
62709
62710
62711
62712
62713
62714
62715
62716
62717
62718
62719
62720
62721
62722
62723
62724
62725
62726
62727
62728
62729
62730
62731
62732
62733
62734
62735
62736
62737
62738
62739
62740
62741
62742
62743
62744
62745
62746
62747
62748
62749
62750
62751
62752
62753
62754
62755
62756
62757
62758
62759
62760
62761
62762
62763























































62764
62765
62766

62767
62768
62769
62770
62771




62772
62773
62774
62775
62776
62777
62778
62779
62780
62781
62782
62783
62784
62785
62786
62787
62788
62789
62790
62791
62792
62793
62794
62795
62796
62797
62798
62799
62800
62801
62802
62803
62804
62805
62806






























62807
62808
62809

62810
62811
62812
62813
62814
62815
62816
62817
62818
62819
62820
62821
62822
62823
62824
62825
62826
62827
62828
62829
62830
62831
62832
62833
62834
62835
62836
62837
62838
62839





























62840
62841
62842
62843
62844
62845




62846
62847
62848
62849
62850
62851
62852
62853
62854




62855
62856
62857
62858
62859
62860
62861
62862
62863
62864
62865
62866
62867
62868
62869
62870
62871
62872
62873
62874
62875




















62876
62877

62878
62879
62880
62881
62882
62883
62884
62885
62886
62887








62888
62889
62890
62891
62892
62893
62894
62868
62869
62870
62871
62872
62873
62874

62875
62876






62877
62878
62879
62880
62881
62882
62883








62884
62885
62886
62887
62888
62889
62890
62891
62892


























































62893
62894
62895
62896
62897
62898
62899
62900
62901
62902
62903
62904
62905
62906
62907
62908
62909
62910
62911
62912
62913
62914
62915
62916
62917
62918
62919
62920
62921
62922
62923
62924
62925
62926
62927
62928
62929
62930
62931
62932
62933
62934
62935
62936
62937
62938
62939
62940
62941
62942
62943
62944
62945
62946
62947
62948
62949
62950
62951


























































62952
62953
62954
62955
62956
62957
62958
62959
62960
62961
62962
62963
62964
62965
62966
62967
62968
62969
62970
62971
62972
62973
62974
62975
62976
62977
62978
62979
62980
62981
62982
62983
62984
62985
62986
62987
62988
62989
62990
62991
62992
62993
62994
62995
62996
62997
62998
62999
63000
63001
63002
63003
63004
63005
63006
63007
63008
63009
63010
63011
63012
63013

63014
63015


63016
63017
63018

63019
63020

63021
63022
63023

63024
63025



63026
63027
63028
63029





63030
63031
63032
63033
63034
63035
63036


63037
63038
63039
63040











63041
63042
63043
63044
63045
63046
63047
63048
63049
63050
63051
63052





63053
63054
63055
63056
63057
63058



















63059
63060
63061
63062
63063
63064
63065
63066
63067
63068
63069
63070
63071
63072
63073
63074
63075
63076
63077
63078





63079
63080
63081
63082
63083
63084


63085
63086
63087
63088


63089
63090
63091























































63092
63093
63094
63095
63096
63097
63098
63099
63100
63101
63102
63103
63104
63105
63106
63107
63108
63109
63110
63111
63112
63113
63114
63115
63116
63117
63118
63119
63120
63121
63122
63123
63124
63125
63126
63127
63128
63129
63130
63131
63132
63133
63134
63135
63136
63137
63138
63139
63140
63141
63142
63143
63144
63145
63146
63147
63148

63149
63150




63151
63152
63153
63154
63155
63156
63157
63158
63159






























63160
63161
63162
63163
63164
63165
63166
63167
63168
63169
63170
63171
63172
63173
63174
63175
63176
63177
63178
63179
63180
63181
63182
63183
63184
63185
63186
63187
63188
63189
63190
63191

63192
63193





























63194
63195
63196
63197
63198
63199
63200
63201
63202
63203
63204
63205
63206
63207
63208
63209
63210
63211
63212
63213
63214
63215
63216
63217
63218
63219
63220
63221
63222
63223
63224




63225
63226
63227
63228
63229
63230
63231
63232
63233




63234
63235
63236
63237
63238




















63239
63240
63241
63242
63243
63244
63245
63246
63247
63248
63249
63250
63251
63252
63253
63254
63255
63256
63257
63258
63259

63260
63261
63262








63263
63264
63265
63266
63267
63268
63269
63270
63271
63272
63273
63274
63275
63276
63277







-
+

-
-
-
-
-
-
+
+
+
+
+
+

-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+




-
+

-
-
+
+

-
+

-
+


-
+

-
-
-
+
+
+

-
-
-
-
-
+
+
+
+
+


-
-
+
+


-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
-
-
-
-
+
+
+
+
+

-
-
+
+


-
-
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+

-
-
-
-
+
+
+
+





-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+


-
-
-
-
+
+
+
+





-
-
-
-
+
+
+
+

-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+

-
+


-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+







**  yy_shift_ofst[]    For each state, the offset into yy_action for
**                     shifting terminals.
**  yy_reduce_ofst[]   For each state, the offset into yy_action for
**                     shifting non-terminals after a reduce.
**  yy_default[]       Default action for each state.
*/
static const YYACTIONTYPE yy_action[] = {
 /*     0 */   289,  898,  121,  585,  405,  169,    2,  435,   61,   61,
 /*     0 */   290,  898,  122,  585,  407,  170,    2,  437,   61,   61,
 /*    10 */    61,   61,  517,   63,   63,   63,   63,   64,   64,   65,
 /*    20 */    65,   65,   66,  230,  387,  384,  420,  426,   68,   63,
 /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  230,
 /*    40 */   443,  208,  392,  447,   60,   59,  294,  430,  431,  427,
 /*    50 */   427,   62,   62,   61,   61,   61,   61,  205,   63,   63,
 /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  230,  289,
 /*    70 */   368,  316,  435,  487,  205,   80,   67,  415,   69,  151,
 /*    20 */    65,   65,   66,  231,  445,  209,  422,  428,   68,   63,
 /*    30 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  231,
 /*    40 */   389,  386,  394,  449,   60,   59,  295,  432,  433,  429,
 /*    50 */   429,   62,   62,   61,   61,   61,   61,  261,   63,   63,
 /*    60 */    63,   63,   64,   64,   65,   65,   65,   66,  231,  290,
 /*    70 */   491,  492,  437,  487,  206,   81,   67,  417,   69,  152,
 /*    80 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
 /*    90 */   230,  515,  162,  410,   35,  420,  426,  443,  571,   58,
 /*   100 */    64,   64,   65,   65,   65,   66,  230,  393,  394,  417,
 /*   110 */   417,  417,  289,   60,   59,  294,  430,  431,  427,  427,
 /*   120 */    62,   62,   61,   61,   61,   61,  302,   63,   63,   63,
 /*   130 */    63,   64,   64,   65,   65,   65,   66,  230,  420,  426,
 /*   140 */    92,   65,   65,   65,   66,  230,  392,  456,  472,   67,
 /*   150 */    56,   69,  151,  169,  406,  435,   60,   59,  294,  430,
 /*   160 */   431,  427,  427,   62,   62,   61,   61,   61,   61,  247,
 /*    90 */   231,   67,  460,   69,  152,  422,  428,  571,  262,   58,
 /*   100 */    64,   64,   65,   65,   65,   66,  231,  395,  396,  419,
 /*   110 */   419,  419,  290,   60,   59,  295,  432,  433,  429,  429,
 /*   120 */    62,   62,   61,   61,   61,   61,  315,   63,   63,   63,
 /*   130 */    63,   64,   64,   65,   65,   65,   66,  231,  422,  428,
 /*   140 */    93,   65,   65,   65,   66,  231,  394,  231,  412,   34,
 /*   150 */    56,  296,  440,  441,  408,  486,   60,   59,  295,  432,
 /*   160 */   433,  429,  429,   62,   62,   61,   61,   61,   61,  488,
 /*   170 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
 /*   180 */   230,  289,  569,  522,  292,  620,  111,  478,  515,  447,
 /*   190 */   230,  316,  403,   21,   67,  460,   69,  151,   66,  230,
 /*   200 */   568,  443,  208,   67,  224,   69,  151,  420,  426,  146,
 /*   210 */   147,  393,  394,  410,   41,  386,  148,  531,    2,  487,
 /*   220 */   435,  566,  232,  415,  289,   60,   59,  294,  430,  431,
 /*   230 */   427,  427,   62,   62,   61,   61,   61,   61,  316,   63,
 /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  230,
 /*   250 */   420,  426,  486,  330,  211,  417,  417,  417,  359,  270,
 /*   260 */   410,   41,  378,  207,  362,  542,  245,  289,   60,   59,
 /*   270 */   294,  430,  431,  427,  427,   62,   62,   61,   61,   61,
 /*   280 */    61,  392,   63,   63,   63,   63,   64,   64,   65,   65,
 /*   290 */    65,   66,  230,  420,  426,  260,  299,  273,  522,  271,
 /*   300 */   522,  210,  370,  319,  223,  433,  433,  532,   21,  576,
 /*   310 */    21,   60,   59,  294,  430,  431,  427,  427,   62,   62,
 /*   320 */    61,   61,   61,   61,  191,   63,   63,   63,   63,   64,
 /*   330 */    64,   65,   65,   65,   66,  230,  261,  316,  239,   76,
 /*   340 */   289,  544,  299,  149,  482,  150,  393,  394,  178,  240,
 /*   350 */   569,  341,  344,  345,  404,  520,  445,  322,  165,  410,
 /*   360 */    28,  540,  346,  517,  248,  539,  420,  426,  568,  567,
 /*   370 */   161,  115,  238,  339,  243,  340,  173,  358,  272,  411,
 /*   380 */   821,  488,   79,  249,   60,   59,  294,  430,  431,  427,
 /*   390 */   427,   62,   62,   61,   61,   61,   61,  530,   63,   63,
 /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  230,  289,
 /*   410 */   248,  178,  465,  485,  341,  344,  345,  115,  238,  339,
 /*   420 */   243,  340,  173,   82,  316,  346,  316,  491,  492,  249,
 /*   430 */   565,  207,  152,  523,  489,  420,  426,  178,  529,  503,
 /*   440 */   341,  344,  345,  407,  472,  528,  410,   35,  410,   35,
 /*   450 */   171,  346,  198,   60,   59,  294,  430,  431,  427,  427,
 /*   460 */    62,   62,   61,   61,   61,   61,  411,   63,   63,   63,
 /*   470 */    63,   64,   64,   65,   65,   65,   66,  230,  289,  548,
 /*   480 */   579,  288,  502,  234,  411,  316,  411,  316,  296,  283,
 /*   490 */   298,  316,  445,  521,  165,  476,  172,  157,  421,  422,
 /*   500 */   457,  335,  457,  144,  420,  426,  366,  410,   35,  410,
 /*   510 */    36,  435,    1,  410,   49,  327,  392,  547,  193,  424,
 /*   520 */   425,  156,   60,   59,  294,  430,  431,  427,  427,   62,
 /*   530 */    62,   61,   61,   61,   61,  333,   63,   63,   63,   63,
 /*   540 */    64,   64,   65,   65,   65,   66,  230,  289,  423,  332,
 /*   550 */   452,  252,  411,  295,  438,  439,  297,  316,  349,  307,
 /*   560 */   231,  457,  453,  321,  438,  439,  392,  369,  266,  265,
 /*   570 */   189,  217,  392,  420,  426,  454,  435,  493,  205,  410,
 /*   580 */    49,  393,  394,  583,  889,  174,  889,  494,  545,  492,
 /*   590 */   392,   60,   59,  294,  430,  431,  427,  427,   62,   62,
 /*   600 */    61,   61,   61,   61,  411,   63,   63,   63,   63,   64,
 /*   610 */    64,   65,   65,   65,   66,  230,  289,  207,  586,  387,
 /*   620 */   384,   91,   10,  580,  336,  308,  392,  207,  367,  480,
 /*   630 */   316,  393,  394,  583,  888,  219,  888,  393,  394,  476,
 /*   640 */   291,  233,  420,  426,  481,  249,  410,    3,  434,  260,
 /*   650 */   317,  363,  410,   29,  448,  393,  394,  468,  260,  289,
 /*   660 */    60,   59,  294,  430,  431,  427,  427,   62,   62,   61,
 /*   670 */    61,   61,   61,  580,   63,   63,   63,   63,   64,   64,
 /*   680 */    65,   65,   65,   66,  230,  420,  426,  391,  312,  388,
 /*   690 */   555,  393,  394,   75,  204,   77,  395,  396,  397,  557,
 /*   700 */   357,  197,  289,   60,   59,  294,  430,  431,  427,  427,
 /*   710 */    62,   62,   61,   61,   61,   61,  316,   63,   63,   63,
 /*   720 */    63,   64,   64,   65,   65,   65,   66,  230,  420,  426,
 /*   730 */   319,  116,  433,  433,  319,  411,  433,  433,  410,   24,
 /*   740 */   319,  515,  433,  433,  515,  289,   60,   70,  294,  430,
 /*   750 */   431,  427,  427,   62,   62,   61,   61,   61,   61,  375,
 /*   180 */   231,  290,  255,  522,  293,  569,  112,  406,  520,  449,
 /*   190 */   329,  315,  405,   20,  437,  338,  517,  394,  530,  529,
 /*   200 */   503,  445,  209,  568,  567,  206,  528,  422,  428,  147,
 /*   210 */   148,  395,  396,  412,   41,  208,  149,  531,  370,  487,
 /*   220 */   259,  566,  257,  417,  290,   60,   59,  295,  432,  433,
 /*   230 */   429,  429,   62,   62,   61,   61,   61,   61,  315,   63,
 /*   240 */    63,   63,   63,   64,   64,   65,   65,   65,   66,  231,
 /*   250 */   422,  428,  445,  331,  212,  419,  419,  419,  361,  437,
 /*   260 */   412,   41,  395,  396,  364,  565,  208,  290,   60,   59,
 /*   270 */   295,  432,  433,  429,  429,   62,   62,   61,   61,   61,
 /*   280 */    61,  394,   63,   63,   63,   63,   64,   64,   65,   65,
 /*   290 */    65,   66,  231,  422,  428,  489,  298,  522,  472,   66,
 /*   300 */   231,  211,  472,  224,  409,  284,  532,   20,  447,  521,
 /*   310 */   166,   60,   59,  295,  432,  433,  429,  429,   62,   62,
 /*   320 */    61,   61,   61,   61,  472,   63,   63,   63,   63,   64,
 /*   330 */    64,   65,   65,   65,   66,  231,  207,  478,  315,   76,
 /*   340 */   290,  235,  298,   55,  482,  225,  395,  396,  179,  545,
 /*   350 */   492,  343,  346,  347,   67,  150,   69,  152,  337,  522,
 /*   360 */   412,   35,  348,  237,  249,  368,  422,  428,  576,   20,
 /*   370 */   162,  116,  239,  341,  244,  342,  174,  320,  440,  441,
 /*   380 */   412,    3,   79,  250,   60,   59,  295,  432,  433,  429,
 /*   390 */   429,   62,   62,   61,   61,   61,   61,  172,   63,   63,
 /*   400 */    63,   63,   64,   64,   65,   65,   65,   66,  231,  290,
 /*   410 */   249,  548,  232,  485,  508,  351,  315,  116,  239,  341,
 /*   420 */   244,  342,  174,  179,  315,  523,  343,  346,  347,  250,
 /*   430 */   218,  413,  153,  462,  509,  422,  428,  348,  412,   34,
 /*   440 */   463,  208,  175,  173,  158,  233,  412,   34,  336,  547,
 /*   450 */   447,  321,  166,   60,   59,  295,  432,  433,  429,  429,
 /*   460 */    62,   62,   61,   61,   61,   61,  413,   63,   63,   63,
 /*   470 */    63,   64,   64,   65,   65,   65,   66,  231,  290,  540,
 /*   480 */   333,  515,  502,  539,  454,  569,  300,   19,  329,  142,
 /*   490 */   315,  388,  315,  328,    2,  360,  455,  292,  481,  371,
 /*   500 */   267,  266,  250,  568,  422,  428,  586,  389,  386,  456,
 /*   510 */   206,  493,  412,   49,  412,   49,  301,  583,  889,  157,
 /*   520 */   889,  494,   60,   59,  295,  432,  433,  429,  429,   62,
 /*   530 */    62,   61,   61,   61,   61,  199,   63,   63,   63,   63,
 /*   540 */    64,   64,   65,   65,   65,   66,  231,  290,  315,  179,
 /*   550 */   436,  253,  343,  346,  347,  368,  151,  580,  306,  248,
 /*   560 */   307,  450,   75,  348,   77,  380,  208,  423,  424,  413,
 /*   570 */   412,   27,  317,  422,  428,  438,    1,   22,  583,  888,
 /*   580 */   394,  888,  542,  476,  318,  261,  435,  435,  426,  427,
 /*   590 */   413,   60,   59,  295,  432,  433,  429,  429,   62,   62,
 /*   600 */    61,   61,   61,   61,  326,   63,   63,   63,   63,   64,
 /*   610 */    64,   65,   65,   65,   66,  231,  290,  425,  580,  372,
 /*   620 */   219,   92,  515,    9,  334,  394,  555,  394,  454,   67,
 /*   630 */   394,   69,  152,  397,  398,  399,  318,  234,  435,  435,
 /*   640 */   455,  316,  422,  428,  297,  395,  396,  318,  430,  435,
 /*   650 */   435,  579,  289,  456,  220,  325,    5,  217,  544,  290,
 /*   660 */    60,   59,  295,  432,  433,  429,  429,   62,   62,   61,
 /*   670 */    61,   61,   61,  393,   63,   63,   63,   63,   64,   64,
 /*   680 */    65,   65,   65,   66,  231,  422,  428,  480,  311,  390,
 /*   690 */   395,  396,  395,  396,  205,  395,  396,  821,  271,  515,
 /*   700 */   248,  198,  290,   60,   59,  295,  432,  433,  429,  429,
 /*   710 */    62,   62,   61,   61,   61,   61,  468,   63,   63,   63,
 /*   720 */    63,   64,   64,   65,   65,   65,   66,  231,  422,  428,
 /*   730 */   169,  158,  261,  261,  302,  413,  274,  117,  272,  261,
 /*   740 */   515,  515,  261,  515,  190,  290,   60,   70,  295,  432,
 /*   750 */   433,  429,  429,   62,   62,   61,   61,   61,   61,  377,
 /*   760 */    63,   63,   63,   63,   64,   64,   65,   65,   65,   66,
 /*   770 */   230,  420,  426,  538,  356,  538,  216,  260,  472,  303,
 /*   780 */   175,  176,  177,  254,  476,  515,  260,  383,  289,    5,
 /*   790 */    59,  294,  430,  431,  427,  427,   62,   62,   61,   61,
 /*   800 */    61,   61,  316,   63,   63,   63,   63,   64,   64,   65,
 /*   810 */    65,   65,   66,  230,  420,  426,  392,  236,  380,  247,
 /*   820 */   304,  258,  247,  256,  410,   33,  260,  558,  125,  467,
 /*   830 */   515,  416,  168,  157,  294,  430,  431,  427,  427,   62,
 /*   840 */    62,   61,   61,   61,   61,  306,   63,   63,   63,   63,
 /*   850 */    64,   64,   65,   65,   65,   66,  230,   72,  323,  452,
 /*   860 */     4,  153,   22,  247,  293,  305,  435,  559,  316,  382,
 /*   870 */   316,  453,  320,   72,  323,  316,    4,  366,  316,  180,
 /*   880 */   293,  393,  394,   20,  454,  141,  326,  316,  320,  325,
 /*   890 */   410,   53,  410,   52,  316,  411,  155,  410,   96,  447,
 /*   900 */   410,   94,  316,  500,  316,  325,  328,  469,  247,  410,
 /*   910 */    99,  444,  260,  411,  318,  447,  410,  100,  316,   74,
 /*   920 */    73,  467,  183,  260,  410,  110,  410,  112,   72,  314,
 /*   930 */   315,  435,  337,  415,  458,   74,   73,  479,  316,  377,
 /*   940 */   410,   17,  218,   19,   72,  314,  315,   72,  323,  415,
 /*   950 */     4,  205,  316,  274,  293,  316,  411,  466,  205,  409,
 /*   960 */   410,   97,  320,  408,  374,  417,  417,  417,  418,  419,
 /*   970 */    12,  376,  316,  206,  410,   34,  174,  410,   95,  325,
 /*   980 */    55,  417,  417,  417,  418,  419,   12,  310,  120,  447,
 /*   990 */   428,  159,    9,  260,  410,   25,  220,  221,  222,  102,
 /*  1000 */   441,  441,  316,  471,  409,  316,  475,  316,  408,   74,
 /*  1010 */    73,  436,  202,   23,  278,  455,  244,   13,   72,  314,
 /*  1020 */   315,  279,  316,  415,  410,   54,  316,  410,  113,  410,
 /*  1030 */   114,  291,  581,  200,  276,  547,  462,  497,  498,  199,
 /*  1040 */   316,  504,  201,  463,  410,   26,  316,  524,  410,   37,
 /*  1050 */   316,  474,  316,  170,  253,  417,  417,  417,  418,  419,
 /*  1060 */    12,  505,  410,   38,  510,  483,  316,   13,  410,   27,
 /*  1070 */   508,  582,  410,   39,  410,   40,  316,  255,  507,  506,
 /*  1080 */   512,  316,  125,  316,  511,  373,  275,  265,  410,   42,
 /*  1090 */   509,  290,  316,  251,  316,  125,  205,  257,  410,   43,
 /*  1100 */   316,  259,  316,  410,   44,  410,   30,  348,  316,  125,
 /*  1110 */   316,  353,  186,  316,  410,   31,  410,   45,  316,  543,
 /*  1120 */   379,  125,  410,   46,  410,   47,  316,  551,  264,  170,
 /*  1130 */   410,   48,  410,   32,  401,  410,   11,  552,  440,   89,
 /*  1140 */   410,   50,  301,  562,  578,   89,  287,  361,  410,   51,
 /*  1150 */   364,  365,  267,  268,  269,  554,  143,  564,  277,  324,
 /*  1160 */   280,  281,  575,  225,  442,  461,  464,  503,  241,  513,
 /*  1170 */   516,  550,  343,  160,  561,  390,    8,  313,  398,  399,
 /*  1180 */   400,  412,   82,  226,  331,  329,   81,  406,   57,   78,
 /*  1190 */   209,  167,   83,  459,  122,  414,  227,  334,  228,  338,
 /*  1200 */   300,  500,  103,  496,  246,  519,  514,  490,  495,  242,
 /*  1210 */   214,  518,  499,  229,  501,  413,  350,  533,  284,  525,
 /*  1220 */   526,  527,  235,  181,  473,  237,  285,  477,  182,  354,
 /*  1230 */   352,  184,   86,  185,  118,  535,  187,  546,  360,  190,
 /*  1240 */   129,  553,  139,  371,  372,  130,  215,  309,  560,  131,
 /*  1250 */   132,  133,  572,  577,  135,  573,   98,  574,  389,  262,
 /*  1260 */   402,  621,  536,  213,  101,  622,  432,  163,  164,  429,
 /*  1270 */   138,   71,  449,  437,  446,  140,  470,  154,    6,  450,
 /*  1280 */     7,  158,  166,  451,   14,  123,   13,  124,  484,  212,
 /*  1290 */    84,  342,  104,  105,   90,  250,   85,  117,  106,  347,
 /*  1300 */   179,  240,  351,  142,  534,  126,   18,  170,   93,  263,
 /*  1310 */   188,  107,  355,  286,  109,  127,  549,  541,  128,  119,
 /*  1320 */   537,  192,   15,  194,  195,  136,  196,  134,  556,  563,
 /*  1330 */   311,  137,   16,  108,  570,  203,  145,  385,  381,  282,
 /*  1340 */   584,  899,  899,  899,  899,  899,   87,  899,   88,
 /*   770 */   231,  422,  428,  382,  557,  303,  304,  248,  413,  318,
 /*   780 */   558,  435,  435,  559,  538,  358,  538,  385,  290,  194,
 /*   790 */    59,  295,  432,  433,  429,  429,   62,   62,   61,   61,
 /*   800 */    61,   61,  369,   63,   63,   63,   63,   64,   64,   65,
 /*   810 */    65,   65,   66,  231,  422,  428,  394,  273,  248,  248,
 /*   820 */   170,  246,  437,  413,  384,  365,  176,  177,  178,  467,
 /*   830 */   309,  121,  154,  126,  295,  432,  433,  429,  429,   62,
 /*   840 */    62,   61,   61,   61,   61,  315,   63,   63,   63,   63,
 /*   850 */    64,   64,   65,   65,   65,   66,  231,   72,  322,  175,
 /*   860 */     4,  315,  261,  315,  294,  261,  413,  412,   28,  315,
 /*   870 */   261,  315,  319,   72,  322,  315,    4,  418,  443,  443,
 /*   880 */   294,  395,  396,  412,   23,  412,   32,  437,  319,  324,
 /*   890 */   327,  412,   53,  412,   52,  315,  156,  412,   97,  449,
 /*   900 */   315,  192,  315,  275,  315,  324,  376,  469,  500,  315,
 /*   910 */   476,  277,  476,  163,  292,  449,  315,  412,   95,   74,
 /*   920 */    73,  467,  412,  100,  412,  101,  412,  111,   72,  313,
 /*   930 */   314,  412,  113,  417,  446,   74,   73,  479,  412,   16,
 /*   940 */   379,  315,  181,  465,   72,  313,  314,   72,  322,  417,
 /*   950 */     4,  206,  315,  184,  294,  315,  497,  498,  474,  206,
 /*   960 */   171,  339,  319,  412,   98,  419,  419,  419,  420,  421,
 /*   970 */    11,  359,  378,  305,  412,   33,  413,  412,   96,  324,
 /*   980 */   458,  419,  419,  419,  420,  421,   11,  413,  411,  449,
 /*   990 */   411,  160,  410,  315,  410,  466,  221,  222,  223,  103,
 /*  1000 */    83,  471,  315,  507,  506,  315,  620,  475,  315,   74,
 /*  1010 */    73,  245,  203,   21,  279,  412,   24,  437,   72,  313,
 /*  1020 */   314,  280,  315,  417,  412,   54,  505,  412,  114,  315,
 /*  1030 */   412,  115,  504,  201,  145,  547,  240,  510,  524,  200,
 /*  1040 */   315,  511,  202,  315,  412,   25,  315,  241,  315,   18,
 /*  1050 */   315,  412,   36,  315,  254,  419,  419,  419,  420,  421,
 /*  1060 */    11,  256,  412,   37,  258,  412,   26,  315,  412,   38,
 /*  1070 */   412,   39,  412,   40,  260,  412,   42,  315,  512,  315,
 /*  1080 */   126,  315,  437,  315,  187,  375,  276,  266,  265,  412,
 /*  1090 */    43,  291,  315,  252,  315,  126,  206,  581,    8,  412,
 /*  1100 */    44,  412,   29,  412,   30,  412,   45,  350,  363,  126,
 /*  1110 */   315,  543,  315,  126,  412,   46,  412,   47,  315,  355,
 /*  1120 */   381,  551,  315,  171,  552,  315,   90,  562,  578,   90,
 /*  1130 */   288,  366,  412,   48,  412,   31,  582,  367,  268,  269,
 /*  1140 */   412,   10,  270,  554,  412,   50,  564,  412,   51,  278,
 /*  1150 */   281,  282,  575,  144,  442,  403,  323,  226,  444,  461,
 /*  1160 */   464,  242,  503,  550,  561,  513,  161,  392,  400,  516,
 /*  1170 */   401,  345,  402,    7,  312,   83,  227,  332,  228,   82,
 /*  1180 */   330,   57,  408,  416,  168,   78,  459,  123,  210,  414,
 /*  1190 */    84,  335,  340,  299,  496,  500,  490,  229,  495,  243,
 /*  1200 */   104,  247,  499,  501,  230,  285,  415,  215,  514,  518,
 /*  1210 */   525,  526,  519,  236,  527,  473,  238,  352,  477,  286,
 /*  1220 */   182,  356,  533,  354,  119,  183,  185,   87,  546,  130,
 /*  1230 */   186,  535,  188,  140,  362,  191,  553,  216,  373,  374,
 /*  1240 */   131,  560,  308,  132,  133,  572,  577,  136,  263,  134,
 /*  1250 */   139,  536,  573,  391,   91,   94,  404,  574,   99,  214,
 /*  1260 */   102,  621,  622,  431,  164,  434,  165,   71,  141,   17,
 /*  1270 */   439,  448,  451,  155,    6,  452,  470,  110,  167,  453,
 /*  1280 */   457,  124,   13,  213,  120,   80,   12,  125,  159,  483,
 /*  1290 */   484,   85,  310,  105,  180,  251,  106,  118,   86,  107,
 /*  1300 */   241,  344,  349,  353,  143,  534,  127,  357,  171,  189,
 /*  1310 */   264,  108,  287,  128,  549,  129,  193,  537,  541,   14,
 /*  1320 */   195,   88,  196,  556,  197,  137,  138,  135,   15,  563,
 /*  1330 */   570,  109,  283,  146,  204,  383,  387,  899,  584,  899,
 /*  1340 */   899,  899,  899,  899,   89,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */    16,  139,  140,  141,  168,   21,  144,   23,   69,   70,
 /*    10 */    71,   72,  176,   74,   75,   76,   77,   78,   79,   80,
 /*    20 */    81,   82,   83,   84,    1,    2,   42,   43,   73,   74,
 /*    20 */    81,   82,   83,   84,   78,   79,   42,   43,   73,   74,
 /*    30 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
 /*    40 */    78,   79,   23,   58,   60,   61,   62,   63,   64,   65,
 /*    50 */    66,   67,   68,   69,   70,   71,   72,  110,   74,   75,
 /*    40 */     1,    2,   23,   58,   60,   61,   62,   63,   64,   65,
 /*    50 */    66,   67,   68,   69,   70,   71,   72,  147,   74,   75,
 /*    60 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
 /*    70 */   123,  147,   88,   88,  110,   22,  216,   92,  218,  219,
 /*    70 */   185,  186,   88,   88,  110,   22,  217,   92,  219,  220,
 /*    80 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
 /*    90 */    84,  147,   19,  169,  170,   42,   43,   78,  238,   46,
 /*    90 */    84,  217,  218,  219,  220,   42,   43,  238,  188,   46,
 /*   100 */    78,   79,   80,   81,   82,   83,   84,   88,   89,  124,
 /*   110 */   125,  126,   16,   60,   61,   62,   63,   64,   65,   66,
 /*   120 */    67,   68,   69,   70,   71,   72,  182,   74,   75,   76,
 /*   120 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
 /*   130 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
 /*   140 */    44,   80,   81,   82,   83,   84,   23,  223,  161,  216,
 /*   150 */    19,  218,  219,   21,   23,   23,   60,   61,   62,   63,
 /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  225,
 /*   140 */    44,   80,   81,   82,   83,   84,   23,   84,  169,  170,
 /*   150 */    19,  164,  165,  166,   23,  169,   60,   61,   62,   63,
 /*   160 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  169,
 /*   170 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
 /*   180 */    84,   16,  147,  147,  150,  112,   21,  200,  147,   58,
 /*   190 */    84,  147,  156,  157,  216,  217,  218,  219,   83,   84,
 /*   200 */   165,   78,   79,  216,  190,  218,  219,   42,   43,   78,
 /*   210 */    79,   88,   89,  169,  170,  141,  180,  181,  144,   88,
 /*   220 */    88,   98,  147,   92,   16,   60,   61,   62,   63,   64,
 /*   180 */    84,   16,   14,  147,  150,  147,   21,  167,  168,   58,
 /*   190 */   211,  147,  156,  157,   23,  216,  176,   23,  181,  176,
 /*   200 */   177,   78,   79,  165,  166,  110,  183,   42,   43,   78,
 /*   210 */    79,   88,   89,  169,  170,  228,  180,  181,  123,   88,
 /*   220 */    52,   98,   54,   92,   16,   60,   61,   62,   63,   64,
 /*   230 */    65,   66,   67,   68,   69,   70,   71,   72,  147,   74,
 /*   240 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   84,
 /*   250 */    42,   43,  169,  209,  210,  124,  125,  126,  224,   14,
 /*   260 */   169,  170,  227,  228,  230,   18,  225,   16,   60,   61,
 /*   250 */    42,   43,   78,  209,  210,  124,  125,  126,  224,   88,
 /*   260 */   169,  170,   88,   89,  230,  227,  228,   16,   60,   61,
 /*   270 */    62,   63,   64,   65,   66,   67,   68,   69,   70,   71,
 /*   280 */    72,   23,   74,   75,   76,   77,   78,   79,   80,   81,
 /*   290 */    82,   83,   84,   42,   43,  147,   16,   52,  147,   54,
 /*   300 */   147,  210,   55,  106,  153,  108,  109,  156,  157,  156,
 /*   310 */   157,   60,   61,   62,   63,   64,   65,   66,   67,   68,
 /*   320 */    69,   70,   71,   72,   22,   74,   75,   76,   77,   78,
 /*   330 */    79,   80,   81,   82,   83,   84,  188,  147,   92,  131,
 /*   340 */    16,   94,   16,   22,   20,  155,   88,   89,   90,  103,
 /*   350 */   147,   93,   94,   95,  167,  168,  161,  162,  163,  169,
 /*   360 */   170,   25,  104,  176,   84,   29,   42,   43,  165,  166,
 /*   370 */    90,   91,   92,   93,   94,   95,   96,   41,  133,  189,
 /*   380 */   133,  169,  131,  103,   60,   61,   62,   63,   64,   65,
 /*   390 */    66,   67,   68,   69,   70,   71,   72,  181,   74,   75,
 /*   290 */    82,   83,   84,   42,   43,  160,   16,  147,  161,   83,
 /*   300 */    84,  210,  161,  153,  169,  158,  156,  157,  161,  162,
 /*   310 */   163,   60,   61,   62,   63,   64,   65,   66,   67,   68,
 /*   320 */    69,   70,   71,   72,  161,   74,   75,   76,   77,   78,
 /*   330 */    79,   80,   81,   82,   83,   84,  192,  200,  147,  131,
 /*   340 */    16,  200,   16,  199,   20,  190,   88,   89,   90,  185,
 /*   350 */   186,   93,   94,   95,  217,   22,  219,  220,  147,  147,
 /*   360 */   169,  170,  104,  200,   84,  147,   42,   43,  156,  157,
 /*   370 */    90,   91,   92,   93,   94,   95,   96,  164,  165,  166,
 /*   380 */   169,  170,  131,  103,   60,   61,   62,   63,   64,   65,
 /*   390 */    66,   67,   68,   69,   70,   71,   72,  155,   74,   75,
 /*   400 */    76,   77,   78,   79,   80,   81,   82,   83,   84,   16,
 /*   410 */    84,   90,   22,   20,   93,   94,   95,   91,   92,   93,
 /*   420 */    94,   95,   96,  121,  147,  104,  147,  185,  186,  103,
 /*   430 */   227,  228,  155,  181,  160,   42,   43,   90,  176,  177,
 /*   440 */    93,   94,   95,  169,  161,  183,  169,  170,  169,  170,
 /*   450 */   155,  104,  155,   60,   61,   62,   63,   64,   65,   66,
 /*   410 */    84,   11,  221,   20,   30,   16,  147,   91,   92,   93,
 /*   420 */    94,   95,   96,   90,  147,  181,   93,   94,   95,  103,
 /*   430 */   212,  189,  155,   27,   50,   42,   43,  104,  169,  170,
 /*   440 */    34,  228,   43,  201,  202,  147,  169,  170,  206,   49,
 /*   450 */   161,  162,  163,   60,   61,   62,   63,   64,   65,   66,
 /*   460 */    67,   68,   69,   70,   71,   72,  189,   74,   75,   76,
 /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   11,
 /*   480 */   244,  245,   20,  200,  189,  147,  189,  147,  211,  158,
 /*   490 */   211,  147,  161,  162,  163,  147,  201,  202,   42,   43,
 /*   500 */   223,  206,  223,  113,   42,   43,  147,  169,  170,  169,
 /*   510 */   170,   23,   19,  169,  170,  186,   23,   49,  155,   63,
 /*   520 */    64,  147,   60,   61,   62,   63,   64,   65,   66,   67,
 /*   530 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
 /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,   92,  211,
 /*   550 */    12,   20,  189,  164,  165,  166,  208,  147,   16,  215,
 /*   560 */   220,  223,   24,  164,  165,  166,   23,   99,  100,  101,
 /*   570 */   155,  212,   23,   42,   43,   37,   88,   39,  110,  169,
 /*   580 */   170,   88,   89,   19,   20,   43,   22,   49,  185,  186,
 /*   590 */    23,   60,   61,   62,   63,   64,   65,   66,   67,   68,
 /*   600 */    69,   70,   71,   72,  189,   74,   75,   76,   77,   78,
 /*   610 */    79,   80,   81,   82,   83,   84,   16,  228,    0,    1,
 /*   620 */     2,   21,   19,   59,  147,  215,   23,  228,  213,   80,
 /*   630 */   147,   88,   89,   19,   20,  145,   22,   88,   89,  147,
 /*   640 */    98,  147,   42,   43,   20,  103,  169,  170,   20,  147,
 /*   650 */   147,  236,  169,  170,   20,   88,   89,  114,  147,   16,
 /*   470 */    77,   78,   79,   80,   81,   82,   83,   84,   16,   25,
 /*   480 */   211,  147,   20,   29,   12,  147,  102,   19,  211,   21,
 /*   490 */   147,  141,  147,  216,  144,   41,   24,   98,   20,   99,
 /*   500 */   100,  101,  103,  165,   42,   43,    0,    1,    2,   37,
 /*   510 */   110,   39,  169,  170,  169,  170,  182,   19,   20,  147,
 /*   520 */    22,   49,   60,   61,   62,   63,   64,   65,   66,   67,
 /*   530 */    68,   69,   70,   71,   72,  155,   74,   75,   76,   77,
 /*   540 */    78,   79,   80,   81,   82,   83,   84,   16,  147,   90,
 /*   550 */    20,   20,   93,   94,   95,  147,  155,   59,  215,  225,
 /*   560 */   215,   20,  130,  104,  132,  227,  228,   42,   43,  189,
 /*   570 */   169,  170,   16,   42,   43,   20,   19,   22,   19,   20,
 /*   580 */    23,   22,   18,  147,  106,  147,  108,  109,   63,   64,
 /*   590 */   189,   60,   61,   62,   63,   64,   65,   66,   67,   68,
 /*   600 */    69,   70,   71,   72,  186,   74,   75,   76,   77,   78,
 /*   610 */    79,   80,   81,   82,   83,   84,   16,   92,   59,   55,
 /*   620 */   212,   21,  147,   19,  147,   23,  188,   23,   12,  217,
 /*   630 */    23,  219,  220,    7,    8,    9,  106,  147,  108,  109,
 /*   640 */    24,  147,   42,   43,  208,   88,   89,  106,   92,  108,
 /*   650 */   109,  244,  245,   37,  145,   39,  191,  182,   94,   16,
 /*   660 */    60,   61,   62,   63,   64,   65,   66,   67,   68,   69,
 /*   670 */    70,   71,   72,   59,   74,   75,   76,   77,   78,   79,
 /*   680 */    80,   81,   82,   83,   84,   42,   43,  147,  142,  143,
 /*   690 */   188,   88,   89,  130,  148,  132,    7,    8,    9,  188,
 /*   700 */   208,  155,   16,   60,   61,   62,   63,   64,   65,   66,
 /*   710 */    67,   68,   69,   70,   71,   72,  147,   74,   75,   76,
 /*   670 */    70,   71,   72,  147,   74,   75,   76,   77,   78,   79,
 /*   680 */    80,   81,   82,   83,   84,   42,   43,   80,  142,  143,
 /*   690 */    88,   89,   88,   89,  148,   88,   89,  133,   14,  147,
 /*   700 */   225,  155,   16,   60,   61,   62,   63,   64,   65,   66,
 /*   710 */    67,   68,   69,   70,   71,   72,  114,   74,   75,   76,
 /*   720 */    77,   78,   79,   80,   81,   82,   83,   84,   42,   43,
 /*   730 */   106,  147,  108,  109,  106,  189,  108,  109,  169,  170,
 /*   740 */   106,  147,  108,  109,  147,   16,   60,   61,   62,   63,
 /*   730 */   201,  202,  147,  147,  182,  189,   52,  147,   54,  147,
 /*   740 */   147,  147,  147,  147,  155,   16,   60,   61,   62,   63,
 /*   750 */    64,   65,   66,   67,   68,   69,   70,   71,   72,  213,
 /*   760 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
 /*   770 */    84,   42,   43,   99,  100,  101,  182,  147,  161,  182,
 /*   780 */    99,  100,  101,   14,  147,  147,  147,  241,   16,  191,
 /*   770 */    84,   42,   43,  188,  188,  182,  182,  225,  189,  106,
 /*   780 */   188,  108,  109,  188,   99,  100,  101,  241,   16,  155,
 /*   790 */    61,   62,   63,   64,   65,   66,   67,   68,   69,   70,
 /*   800 */    71,   72,  147,   74,   75,   76,   77,   78,   79,   80,
 /*   810 */    81,   82,   83,   84,   42,   43,   23,  200,  188,  225,
 /*   820 */   182,   52,  225,   54,  169,  170,  147,  188,   22,   22,
 /*   830 */   147,  147,  201,  202,   62,   63,   64,   65,   66,   67,
 /*   840 */    68,   69,   70,   71,   72,  208,   74,   75,   76,   77,
 /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,   12,
 /*   860 */    19,  155,   19,  225,   23,  182,   23,  188,  147,  239,
 /*   870 */   147,   24,   31,   16,   17,  147,   19,  147,  147,  155,
 /*   880 */    23,   88,   89,   19,   37,   21,   39,  147,   31,   48,
 /*   890 */   169,  170,  169,  170,  147,  189,   89,  169,  170,   58,
 /*   900 */   169,  170,  147,   97,  147,   48,  147,  114,  225,  169,
 /*   910 */   170,  161,  147,  189,   16,   58,  169,  170,  147,   78,
 /*   920 */    79,  114,  155,  147,  169,  170,  169,  170,   87,   88,
 /*   930 */    89,   88,   80,   92,  147,   78,   79,   80,  147,   91,
 /*   940 */   169,  170,  212,   19,   87,   88,   89,   16,   17,   92,
 /*   950 */    19,  110,  147,  188,   23,  147,  189,  203,  110,  107,
 /*   960 */   169,  170,   31,  111,  188,  124,  125,  126,  127,  128,
 /*   970 */   129,  123,  147,  192,  169,  170,   43,  169,  170,   48,
 /*   980 */   199,  124,  125,  126,  127,  128,  129,  242,  243,   58,
 /*   990 */    92,    5,   68,  147,  169,  170,   10,   11,   12,   13,
 /*  1000 */   124,  125,  147,  147,  107,  147,  147,  147,  111,   78,
 /*  1010 */    79,   20,   26,   22,   28,   20,  147,   22,   87,   88,
 /*  1020 */    89,   35,  147,   92,  169,  170,  147,  169,  170,  169,
 /*  1030 */   170,   98,   20,   47,  188,   49,   27,    7,    8,   53,
 /*  1040 */   147,  147,   56,   34,  169,  170,  147,  147,  169,  170,
 /*  1050 */   147,   20,  147,   22,  147,  124,  125,  126,  127,  128,
 /*  1060 */   129,  178,  169,  170,  178,   20,  147,   22,  169,  170,
 /*  1070 */    30,   59,  169,  170,  169,  170,  147,  147,   91,   92,
 /*  1080 */    20,  147,   22,  147,  178,   99,  100,  101,  169,  170,
 /*  1090 */    50,  105,  147,   20,  147,   22,  110,  147,  169,  170,
 /*  1100 */   147,  147,  147,  169,  170,  169,  170,   20,  147,   22,
 /*  1110 */   147,  233,  232,  147,  169,  170,  169,  170,  147,   20,
 /*  1120 */   134,   22,  169,  170,  169,  170,  147,   20,  147,   22,
 /*  1130 */   169,  170,  169,  170,  149,  169,  170,   20,  229,   22,
 /*  1140 */   169,  170,  102,   20,   20,   22,   22,  147,  169,  170,
 /*  1150 */   147,  147,  147,  147,  147,  147,  191,  147,  147,  222,
 /*  1160 */   147,  147,  147,  193,  229,  172,  172,  177,  172,  172,
 /*  1170 */   172,  194,  173,    6,  194,  146,   22,  154,  146,  146,
 /*  1180 */   146,  189,  121,  194,  118,  116,  119,   23,  120,  130,
 /*  1190 */   221,  112,   98,  152,  152,  160,  195,  115,  196,   98,
 /*  1200 */    40,   97,   19,  179,   84,  179,  160,  171,  171,  171,
 /*  1210 */   226,  160,  173,  197,  171,  198,   15,  152,  174,  171,
 /*  1220 */   171,  171,  204,  151,  205,  204,  174,  205,  151,   38,
 /*  1230 */   152,  151,  130,  152,   60,  152,  151,  184,  152,  184,
 /*  1240 */    19,  194,  214,  152,   15,  187,  226,  152,  194,  187,
 /*  1250 */   187,  187,   33,  137,  184,  152,  159,  152,    1,  234,
 /*  1260 */    20,  112,  235,  175,  175,  112,  107,  112,  112,   92,
 /*  1270 */   214,   19,   11,   20,   20,   19,  114,   19,  117,   20,
 /*  1280 */   117,  112,   22,   20,   22,   19,   22,   20,   20,   44,
 /*  1290 */    19,   44,   19,   19,  237,   20,   19,   32,   19,   44,
 /*  1300 */    96,  103,   16,   21,   17,   98,  231,   22,  237,  133,
 /*  1310 */    98,   19,   36,    5,  240,   45,    1,   45,  102,  243,
 /*  1320 */    51,  122,   19,  113,   14,  102,  115,  113,   17,  123,
 /*  1330 */   246,  122,   19,   14,   20,  135,   19,    3,   57,  136,
 /*  1340 */     4,  247,  247,  247,  247,  247,   68,  247,   68,
 /*   800 */    71,   72,  213,   74,   75,   76,   77,   78,   79,   80,
 /*   810 */    81,   82,   83,   84,   42,   43,   23,  133,  225,  225,
 /*   820 */    21,  225,   23,  189,  239,  236,   99,  100,  101,   22,
 /*   830 */   242,  243,  155,   22,   62,   63,   64,   65,   66,   67,
 /*   840 */    68,   69,   70,   71,   72,  147,   74,   75,   76,   77,
 /*   850 */    78,   79,   80,   81,   82,   83,   84,   16,   17,   43,
 /*   860 */    19,  147,  147,  147,   23,  147,  189,  169,  170,  147,
 /*   870 */   147,  147,   31,   16,   17,  147,   19,  147,  124,  125,
 /*   880 */    23,   88,   89,  169,  170,  169,  170,   88,   31,   48,
 /*   890 */   147,  169,  170,  169,  170,  147,   89,  169,  170,   58,
 /*   900 */   147,   22,  147,  188,  147,   48,  188,  114,   97,  147,
 /*   910 */   147,  188,  147,   19,   98,   58,  147,  169,  170,   78,
 /*   920 */    79,  114,  169,  170,  169,  170,  169,  170,   87,   88,
 /*   930 */    89,  169,  170,   92,  161,   78,   79,   80,  169,  170,
 /*   940 */    91,  147,  155,   22,   87,   88,   89,   16,   17,   92,
 /*   950 */    19,  110,  147,  155,   23,  147,    7,    8,   20,  110,
 /*   960 */    22,   80,   31,  169,  170,  124,  125,  126,  127,  128,
 /*   970 */   129,  208,  123,  208,  169,  170,  189,  169,  170,   48,
 /*   980 */   147,  124,  125,  126,  127,  128,  129,  189,  107,   58,
 /*   990 */   107,    5,  111,  147,  111,  203,   10,   11,   12,   13,
 /*  1000 */   121,  147,  147,   91,   92,  147,  112,  147,  147,   78,
 /*  1010 */    79,  147,   26,   19,   28,  169,  170,   23,   87,   88,
 /*  1020 */    89,   35,  147,   92,  169,  170,  178,  169,  170,  147,
 /*  1030 */   169,  170,  147,   47,  113,   49,   92,  178,  147,   53,
 /*  1040 */   147,  178,   56,  147,  169,  170,  147,  103,  147,   19,
 /*  1050 */   147,  169,  170,  147,  147,  124,  125,  126,  127,  128,
 /*  1060 */   129,  147,  169,  170,  147,  169,  170,  147,  169,  170,
 /*  1070 */   169,  170,  169,  170,  147,  169,  170,  147,   20,  147,
 /*  1080 */    22,  147,   88,  147,  232,   99,  100,  101,  147,  169,
 /*  1090 */   170,  105,  147,   20,  147,   22,  110,   20,   68,  169,
 /*  1100 */   170,  169,  170,  169,  170,  169,  170,   20,  147,   22,
 /*  1110 */   147,   20,  147,   22,  169,  170,  169,  170,  147,  233,
 /*  1120 */   134,   20,  147,   22,   20,  147,   22,   20,   20,   22,
 /*  1130 */    22,  147,  169,  170,  169,  170,   59,  147,  147,  147,
 /*  1140 */   169,  170,  147,  147,  169,  170,  147,  169,  170,  147,
 /*  1150 */   147,  147,  147,  191,  229,  149,  223,  193,  229,  172,
 /*  1160 */   172,  172,  177,  194,  194,  172,    6,  146,  146,  172,
 /*  1170 */   146,  173,  146,   22,  154,  121,  194,  118,  195,  119,
 /*  1180 */   116,  120,   23,  160,  112,  130,  152,  152,  222,  189,
 /*  1190 */    98,  115,   98,   40,  179,   97,  171,  196,  171,  171,
 /*  1200 */    19,   84,  173,  171,  197,  174,  198,  226,  160,  160,
 /*  1210 */   171,  171,  179,  204,  171,  205,  204,   15,  205,  174,
 /*  1220 */   151,   38,  152,  152,   60,  151,  151,  130,  184,   19,
 /*  1230 */   152,  152,  151,  214,  152,  184,  194,  226,  152,   15,
 /*  1240 */   187,  194,  152,  187,  187,   33,  137,  184,  234,  187,
 /*  1250 */   214,  235,  152,    1,  237,  237,   20,  152,  159,  175,
 /*  1260 */   175,  112,  112,   92,  112,  107,  112,   19,   19,  231,
 /*  1270 */    20,   20,   11,   19,  117,   20,  114,  240,   22,   20,
 /*  1280 */    20,   19,  117,   44,  243,   22,   22,   20,  112,   20,
 /*  1290 */    20,   19,  246,   19,   96,   20,   19,   32,   19,   19,
 /*  1300 */   103,   44,   44,   16,   21,   17,   98,   36,   22,   98,
 /*  1310 */   133,   19,    5,   45,    1,  102,  122,   51,   45,   19,
 /*  1320 */   113,   68,   14,   17,  115,  102,  122,  113,   19,  123,
 /*  1330 */    20,   14,  136,   19,  135,   57,    3,  247,    4,  247,
 /*  1340 */   247,  247,  247,  247,   68,
};
#define YY_SHIFT_USE_DFLT (-62)
#define YY_SHIFT_MAX 385
#define YY_SHIFT_MAX 387
static const short yy_shift_ofst[] = {
 /*     0 */    23,  841,  986,  -16,  841,  931,  931,  931,  258,  123,
 /*    10 */   -36,   96,  931,  931,  931,  931,  931,  -45,  468,   19,
 /*    20 */   567,  488,  -38,  -38,   53,  165,  208,  251,  324,  393,
 /*    30 */   462,  531,  600,  643,  686,  643,  643,  643,  643,  643,
 /*     0 */    39,  841,  986,  -16,  841,  931,  931,  258,  123,  -36,
 /*    10 */    96,  931,  931,  931,  931,  931,  -45,  400,  174,   19,
 /*    20 */   171,  -54,  -54,   53,  165,  208,  251,  324,  393,  462,
 /*    30 */   531,  600,  643,  686,  643,  643,  643,  643,  643,  643,
 /*    40 */   643,  643,  643,  643,  643,  643,  643,  643,  643,  643,
 /*    50 */   643,  643,  729,  772,  772,  857,  931,  931,  931,  931,
 /*    60 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
 /*    70 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
 /*    80 */   931,  931,  931,  931,  931,  931,  931,  931,  931,  931,
 /*    90 */   931,  931,  931,  931,  -61,  -61,    6,    6,  280,   22,
 /*   100 */    61,  542,  247,  567,  567,  567,  567,  567,  567,  567,
 /*   110 */   115,  488,  106,  -62,  -62,  131,  326,  538,  538,  564,
 /*   120 */   614,  618,  132,  567,  132,  567,  567,  567,  567,  567,
 /*   130 */   567,  567,  567,  567,  567,  567,  567,  567,  848,  -53,
 /*   140 */   -36,  -36,  -36,  -62,  -62,  -62,  -15,  -15,  321,  347,
 /*   150 */   624,  493,  628,  634,  847,  543,  793,  603,  549,  689,
 /*   160 */   567,  567,  852,  567,  567,  843,  567,  567,  807,  567,
 /*   170 */   567,  197,  807,  567,  567, 1040, 1040, 1040,  567,  567,
 /*   180 */   197,  567,  567,  197,  567,  336,  674,  567,  567,  197,
 /*   190 */   567,  567,  567,  197,  567,  567,  567,  197,  197,  567,
 /*   200 */   567,  567,  567,  567,  864,  897,  390,  876,  876,  563,
 /*   210 */  1009, 1009, 1009,  933, 1009, 1009,  806,  302,  302, 1167,
 /*   220 */  1167, 1167, 1167, 1154,  -36, 1061, 1066, 1067, 1069, 1068,
 /*   230 */  1164, 1059, 1079, 1079, 1094, 1082, 1094, 1082, 1101, 1101,
 /*   240 */  1160, 1101, 1104, 1101, 1183, 1120, 1164, 1120, 1164, 1160,
 /*   250 */  1101, 1101, 1101, 1183, 1201, 1079, 1201, 1079, 1201, 1079,
 /*   260 */  1079, 1191, 1102, 1201, 1079, 1174, 1174, 1221, 1061, 1079,
 /*   270 */  1229, 1229, 1229, 1229, 1061, 1174, 1221, 1079, 1219, 1219,
 /*   280 */  1079, 1079, 1116,  -62,  -62,  -62,  -62,  -62,  -62,  456,
 /*   290 */   245,  681,  769,   73,  898,  991,  995, 1031, 1045,  246,
 /*   300 */  1030,  987, 1060, 1073, 1087, 1099, 1107, 1117, 1123,  924,
 /*   310 */  1124, 1012, 1257, 1240, 1149, 1153, 1155, 1156, 1177, 1159,
 /*   320 */  1252, 1253, 1254, 1256, 1261, 1258, 1259, 1260, 1263, 1161,
 /*   330 */  1262, 1163, 1264, 1162, 1266, 1267, 1169, 1268, 1265, 1245,
 /*   340 */  1271, 1247, 1273, 1275, 1274, 1277, 1255, 1279, 1204, 1198,
 /*   350 */  1286, 1287, 1282, 1207, 1276, 1269, 1270, 1285, 1272, 1176,
 /*   360 */  1212, 1292, 1308, 1315, 1216, 1278, 1280, 1199, 1303, 1210,
 /*   370 */  1310, 1211, 1311, 1214, 1223, 1209, 1313, 1206, 1314, 1319,
 /*   380 */  1281, 1200, 1203, 1317, 1334, 1336,
 /*    90 */   931,  931,  931,  931,  931,  -61,  -61,    6,    6,  280,
 /*   100 */    22,   61,  399,  564,   19,   19,   19,   19,   19,   19,
 /*   110 */    19,  216,  171,   63,  -62,  -62,  131,  326,  472,  472,
 /*   120 */   498,  559,  506,  799,   19,  799,   19,   19,   19,   19,
 /*   130 */    19,   19,   19,   19,   19,   19,   19,   19,   19,  849,
 /*   140 */    95,  -36,  -36,  -36,  -62,  -62,  -62,  -15,  -15,  333,
 /*   150 */   459,  478,  557,  530,  541,  616,  602,  793,  604,  607,
 /*   160 */   626,   19,   19,  881,   19,   19,  994,   19,   19,  807,
 /*   170 */    19,   19,  673,  807,   19,   19,  384,  384,  384,   19,
 /*   180 */    19,  673,   19,   19,  673,   19,  454,  685,   19,   19,
 /*   190 */   673,   19,   19,   19,  673,   19,   19,   19,  673,  673,
 /*   200 */    19,   19,   19,   19,   19,  468,  883,  921,  754,  754,
 /*   210 */   432,  406,  406,  406,  816,  406,  406,  811,  879,  879,
 /*   220 */  1160, 1160, 1160, 1160, 1151,  -36, 1054, 1059, 1060, 1064,
 /*   230 */  1061, 1159, 1055, 1072, 1072, 1092, 1076, 1092, 1076, 1094,
 /*   240 */  1094, 1153, 1094, 1098, 1094, 1181, 1117, 1159, 1117, 1159,
 /*   250 */  1153, 1094, 1094, 1094, 1181, 1202, 1072, 1202, 1072, 1202,
 /*   260 */  1072, 1072, 1183, 1097, 1202, 1072, 1164, 1164, 1210, 1054,
 /*   270 */  1072, 1224, 1224, 1224, 1224, 1054, 1164, 1210, 1072, 1212,
 /*   280 */  1212, 1072, 1072, 1109,  -62,  -62,  -62,  -62,  -62,  -62,
 /*   290 */   525,  684,  727,  168,  894,  556,  555,  938,  944,  949,
 /*   300 */   912, 1058, 1073, 1087, 1091, 1101, 1104, 1107, 1030, 1108,
 /*   310 */  1077, 1252, 1236, 1149, 1150, 1152, 1154, 1171, 1158, 1248,
 /*   320 */  1250, 1251, 1249, 1261, 1254, 1255, 1256, 1259, 1260, 1263,
 /*   330 */  1157, 1264, 1165, 1263, 1162, 1262, 1267, 1176, 1269, 1270,
 /*   340 */  1265, 1239, 1272, 1257, 1274, 1275, 1277, 1279, 1258, 1280,
 /*   350 */  1198, 1197, 1287, 1288, 1283, 1208, 1271, 1266, 1268, 1286,
 /*   360 */  1273, 1177, 1211, 1292, 1307, 1313, 1213, 1253, 1276, 1194,
 /*   370 */  1300, 1207, 1308, 1209, 1306, 1214, 1223, 1204, 1309, 1206,
 /*   380 */  1310, 1317, 1278, 1199, 1196, 1314, 1333, 1334,
};
#define YY_REDUCE_USE_DFLT (-165)
#define YY_REDUCE_MAX 288
#define YY_REDUCE_MAX 289
static const short yy_reduce_ofst[] = {
 /*     0 */  -138,  277,  546,  -13,  190,  279,   44,  338,   36,  203,
 /*    10 */   295, -140,  340,  -76,   91,  344,  410,  -22,  415,   35,
 /*    20 */   151,  331,  389,  399,  -67,  -67,  -67,  -67,  -67,  -67,
 /*    30 */   -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,
 /*    40 */   -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,  -67,
 /*    50 */   -67,  -67,  -67,  -67,  -67,  477,  483,  569,  655,  721,
 /*    60 */   723,  728,  731,  740,  747,  755,  757,  771,  791,  805,
 /*    70 */   808,  825,  855,  858,  860,  875,  879,  893,  899,  903,
 /*    80 */   905,  919,  929,  934,  936,  945,  947,  953,  955,  961,
 /*    90 */   963,  966,  971,  979,  -67,  -67,  -67,  -67,  187,  -67,
 /*   100 */   -67,  262,   34,  -56,  594,  597,  638,  683,  630,  153,
 /*   110 */   -67,  195,  -67,  -67,  -67,  274, -164,  242,  403,  236,
 /*   120 */   236,   74,  283,  348,  617,   41,  148,  492,  359,  637,
 /*   130 */   502,  511,  639,  679,  765,  776,  730,  846,  297,  363,
 /*   140 */   706,  724,  767,  781,  631,  745,   83,  212,  216,  252,
 /*   150 */    14,   75,   14,   14,  329,  374,  388,  494,  503,  490,
 /*   160 */   540,  584,  598,  503,  684,  750,  759,  787,  754,  856,
 /*   170 */   859,   14,  754,  869,  894,  883,  886,  906,  900,  907,
 /*   180 */    14,  930,  950,   14,  954,  880,  878,  981, 1000,   14,
 /*   190 */  1003, 1004, 1005,   14, 1006, 1007, 1008,   14,   14, 1010,
 /*   200 */  1011, 1013, 1014, 1015,  985,  965,  970,  909,  935,  937,
 /*   210 */   993,  994,  996,  990,  997,  998,  999,  977,  980, 1029,
 /*   220 */  1032, 1033, 1034, 1023,  992,  989, 1001, 1002, 1016, 1017,
 /*   230 */  1035,  969, 1041, 1042, 1018, 1019, 1021, 1022, 1036, 1037,
 /*   240 */  1024, 1038, 1039, 1043, 1044,  984, 1046, 1020, 1051, 1026,
 /*   250 */  1048, 1049, 1050, 1052, 1072, 1065, 1077, 1078, 1080, 1081,
 /*   260 */  1083, 1025, 1027, 1085, 1086, 1053, 1055, 1028, 1047, 1091,
 /*   270 */  1058, 1062, 1063, 1064, 1054, 1070, 1056, 1095, 1057, 1071,
 /*   280 */  1103, 1105, 1074, 1097, 1088, 1089, 1075, 1076, 1084,
 /*     0 */  -138,  277,  546,  137,  401,  -21,   44,   36,   38,  242,
 /*    10 */  -141,  191,   91,  269,  343,  345, -126,  589,  338,  150,
 /*    20 */   147,  -13,  213,  412,  412,  412,  412,  412,  412,  412,
 /*    30 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
 /*    40 */   412,  412,  412,  412,  412,  412,  412,  412,  412,  412,
 /*    50 */   412,  412,  412,  412,  412,  211,  698,  714,  716,  722,
 /*    60 */   724,  728,  748,  753,  755,  757,  762,  769,  794,  805,
 /*    70 */   808,  846,  855,  858,  861,  875,  882,  893,  896,  899,
 /*    80 */   901,  903,  906,  920,  930,  932,  934,  936,  945,  947,
 /*    90 */   963,  965,  971,  975,  978,  412,  412,  412,  412,   20,
 /*   100 */   412,  412,   23,   34,  334,  475,  552,  593,  594,  585,
 /*   110 */   212,  412,  289,  412,  412,  412,  135, -164, -115,  164,
 /*   120 */   407,  407,  350,  141,  436,  163,  596,  -90,  763,  218,
 /*   130 */   765,  438,  586,  592,  595,  715,  718,  408,  723,  380,
 /*   140 */   634,  677,  787,  798,  144,  529,  588,  -14,    0,   17,
 /*   150 */   244,  155,  298,  155,  155,  418,  372,  477,  490,  494,
 /*   160 */   509,  526,  590,  465,  494,  730,  773,  743,  833,  792,
 /*   170 */   854,  860,  155,  792,  864,  885,  848,  859,  863,  891,
 /*   180 */   907,  155,  914,  917,  155,  927,  852,  886,  941,  961,
 /*   190 */   155,  984,  990,  991,  155,  992,  995,  996,  155,  155,
 /*   200 */   999, 1002, 1003, 1004, 1005, 1006,  962,  964,  925,  929,
 /*   210 */   933,  987,  988,  989,  985,  993,  997,  998,  969,  970,
 /*   220 */  1021, 1022, 1024, 1026, 1020, 1000,  982,  983, 1001, 1007,
 /*   230 */  1008, 1023,  966, 1034, 1035, 1009, 1010, 1012, 1013, 1025,
 /*   240 */  1027, 1015, 1028, 1029, 1032, 1031,  981, 1048, 1011, 1049,
 /*   250 */  1033, 1039, 1040, 1043, 1045, 1069, 1070, 1074, 1071, 1075,
 /*   260 */  1078, 1079, 1014, 1016, 1081, 1082, 1044, 1051, 1019, 1042,
 /*   270 */  1086, 1053, 1056, 1057, 1062, 1047, 1063, 1036, 1090, 1017,
 /*   280 */  1018, 1100, 1105, 1037, 1099, 1084, 1085, 1038, 1041, 1046,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */   592,  818,  897,  707,  897,  818,  897,  818,  897,  843,
 /*    10 */   711,  872,  814,  818,  897,  897,  897,  789,  897,  843,
 /*    20 */   897,  623,  843,  843,  740,  897,  897,  897,  897,  897,
 /*    30 */   897,  897,  897,  741,  897,  817,  813,  809,  811,  810,
 /*     0 */   592,  816,  897,  707,  897,  816,  897,  897,  843,  711,
 /*    10 */   872,  814,  897,  897,  897,  897,  789,  897,  843,  897,
 /*    20 */   623,  843,  843,  740,  897,  897,  897,  897,  897,  897,
 /*    30 */   897,  897,  741,  897,  818,  813,  809,  811,  810,  817,
 /*    40 */   742,  731,  738,  745,  723,  856,  747,  748,  754,  755,
 /*    50 */   873,  871,  777,  776,  795,  897,  897,  897,  897,  897,
 /*    60 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*    70 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*    80 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*    90 */   897,  897,  897,  897,  779,  800,  778,  788,  616,  780,
 /*   100 */   781,  676,  611,  897,  897,  897,  897,  897,  897,  897,
 /*   110 */   782,  897,  783,  796,  797,  897,  897,  897,  897,  897,
 /*   120 */   897,  592,  707,  897,  707,  897,  897,  897,  897,  897,
 /*    90 */   897,  897,  897,  897,  897,  779,  800,  778,  788,  616,
 /*   100 */   780,  781,  676,  611,  897,  897,  897,  897,  897,  897,
 /*   110 */   897,  782,  897,  783,  796,  797,  897,  897,  897,  897,
 /*   120 */   897,  897,  592,  707,  897,  707,  897,  897,  897,  897,
 /*   130 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   140 */   897,  897,  897,  701,  711,  890,  897,  897,  667,  897,
 /*   150 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  599,
 /*   160 */   597,  897,  699,  897,  897,  625,  897,  897,  709,  897,
 /*   170 */   897,  714,  715,  897,  897,  897,  897,  897,  897,  897,
 /*   180 */   613,  897,  897,  688,  897,  849,  897,  897,  897,  863,
 /*   190 */   897,  897,  897,  861,  897,  897,  897,  690,  750,  830,
 /*   200 */   897,  876,  878,  897,  897,  699,  708,  897,  897,  812,
 /*   210 */   734,  734,  734,  646,  734,  734,  649,  744,  744,  596,
 /*   220 */   596,  596,  596,  666,  897,  744,  735,  737,  727,  739,
 /*   230 */   897,  897,  716,  716,  724,  726,  724,  726,  678,  678,
 /*   240 */   663,  678,  649,  678,  822,  827,  897,  827,  897,  663,
 /*   250 */   678,  678,  678,  822,  608,  716,  608,  716,  608,  716,
 /*   260 */   716,  853,  855,  608,  716,  680,  680,  756,  744,  716,
 /*   270 */   687,  687,  687,  687,  744,  680,  756,  716,  875,  875,
 /*   280 */   716,  716,  883,  633,  651,  651,  858,  890,  895,  897,
 /*   290 */   897,  897,  897,  763,  897,  897,  897,  897,  897,  897,
 /*   300 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  836,
 /*   310 */   897,  897,  897,  897,  768,  764,  897,  765,  897,  693,
 /*   320 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   330 */   728,  897,  736,  897,  897,  897,  897,  897,  897,  897,
 /*   140 */   897,  897,  897,  897,  701,  711,  890,  897,  897,  667,
 /*   150 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   160 */   599,  597,  897,  699,  897,  897,  625,  897,  897,  709,
 /*   170 */   897,  897,  714,  715,  897,  897,  897,  897,  897,  897,
 /*   180 */   897,  613,  897,  897,  688,  897,  849,  897,  897,  897,
 /*   190 */   863,  897,  897,  897,  861,  897,  897,  897,  690,  750,
 /*   200 */   830,  897,  876,  878,  897,  897,  699,  708,  897,  897,
 /*   210 */   812,  734,  734,  734,  646,  734,  734,  649,  744,  744,
 /*   220 */   596,  596,  596,  596,  666,  897,  744,  735,  737,  727,
 /*   230 */   739,  897,  897,  716,  716,  724,  726,  724,  726,  678,
 /*   240 */   678,  663,  678,  649,  678,  822,  827,  897,  827,  897,
 /*   250 */   663,  678,  678,  678,  822,  608,  716,  608,  716,  608,
 /*   260 */   716,  716,  853,  855,  608,  716,  680,  680,  756,  744,
 /*   270 */   716,  687,  687,  687,  687,  744,  680,  756,  716,  875,
 /*   280 */   875,  716,  716,  883,  633,  651,  651,  858,  890,  895,
 /*   290 */   897,  897,  897,  897,  763,  897,  897,  897,  897,  897,
 /*   300 */   897,  897,  897,  897,  897,  897,  897,  897,  836,  897,
 /*   310 */   897,  897,  897,  768,  764,  897,  765,  897,  693,  897,
 /*   320 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  815,
 /*   330 */   897,  728,  897,  736,  897,  897,  897,  897,  897,  897,
 /*   340 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   350 */   897,  897,  897,  897,  897,  897,  851,  852,  897,  897,
 /*   350 */   897,  897,  897,  897,  897,  897,  897,  897,  851,  852,
 /*   360 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   370 */   897,  897,  897,  897,  897,  897,  897,  897,  897,  897,
 /*   380 */   882,  897,  897,  885,  593,  897,  587,  590,  589,  591,
 /*   390 */   595,  598,  620,  621,  622,  600,  601,  602,  603,  604,
 /*   400 */   605,  606,  612,  614,  632,  634,  618,  636,  697,  698,
 /*   410 */   760,  691,  692,  696,  771,  762,  766,  767,  769,  770,
 /*   420 */   784,  785,  787,  793,  799,  802,  786,  791,  792,  794,
 /*   430 */   798,  801,  694,  695,  805,  619,  626,  627,  630,  631,
 /*   440 */   839,  841,  840,  842,  629,  628,  772,  775,  807,  808,
 /*   450 */   864,  865,  866,  867,  868,  803,  815,  816,  717,  806,
 /*   380 */   897,  897,  882,  897,  897,  885,  593,  897,  587,  590,
 /*   390 */   589,  591,  595,  598,  620,  621,  622,  600,  601,  602,
 /*   400 */   603,  604,  605,  606,  612,  614,  632,  634,  618,  636,
 /*   410 */   697,  698,  760,  691,  692,  696,  771,  762,  766,  767,
 /*   420 */   769,  770,  784,  785,  787,  793,  799,  802,  786,  791,
 /*   430 */   792,  794,  798,  801,  694,  695,  805,  619,  626,  627,
 /*   440 */   630,  631,  839,  841,  840,  842,  629,  628,  772,  775,
 /*   450 */   807,  808,  864,  865,  866,  867,  868,  803,  717,  806,
 /*   460 */   790,  729,  732,  733,  730,  700,  710,  719,  720,  721,
 /*   470 */   722,  705,  706,  712,  725,  758,  759,  713,  702,  703,
 /*   480 */   704,  804,  761,  773,  774,  637,  638,  768,  639,  640,
 /*   490 */   641,  679,  682,  683,  684,  642,  661,  664,  665,  643,
 /*   500 */   650,  644,  645,  652,  653,  654,  657,  658,  659,  660,
 /*   510 */   655,  656,  823,  824,  828,  826,  825,  647,  648,  662,
 /*   520 */   635,  624,  617,  668,  671,  672,  673,  674,  675,  677,
63109
63110
63111
63112
63113
63114
63115
63116

63117
63118
63119
63120
63121
63122
63123
63492
63493
63494
63495
63496
63497
63498

63499
63500
63501
63502
63503
63504
63505
63506







-
+







**      line of trace output.  If NULL, then tracing is
**      turned off.
** </ul>
**
** Outputs:
** None.
*/
static void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  yyTraceFILE = TraceFILE;
  yyTracePrompt = zTracePrompt;
  if( yyTraceFILE==0 ) yyTracePrompt = 0;
  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
}
#endif /* NDEBUG */

63173
63174
63175
63176
63177
63178
63179
63180

63181
63182
63183


63184
63185
63186
63187
63188
63189
63190
63556
63557
63558
63559
63560
63561
63562

63563
63564


63565
63566
63567
63568
63569
63570
63571
63572
63573







-
+

-
-
+
+







  "conslist",      "tcons",         "idxlist",       "defer_subclause_opt",
  "orconf",        "resolvetype",   "raisetype",     "ifexists",    
  "fullname",      "oneselect",     "multiselect_op",  "distinct",    
  "selcollist",    "from",          "where_opt",     "groupby_opt", 
  "having_opt",    "orderby_opt",   "limit_opt",     "sclp",        
  "as",            "seltablist",    "stl_prefix",    "joinop",      
  "on_opt",        "using_opt",     "seltablist_paren",  "joinop2",     
  "inscollist",    "sortlist",      "sortitem",      "exprlist",    
  "inscollist",    "sortlist",      "sortitem",      "nexprlist",   
  "setlist",       "insert_cmd",    "inscollist_opt",  "itemlist",    
  "likeop",        "escape",        "between_op",    "in_op",       
  "case_operand",  "case_exprlist",  "case_else",     "expritem",    
  "exprlist",      "likeop",        "escape",        "between_op",  
  "in_op",         "case_operand",  "case_exprlist",  "case_else",   
  "uniqueflag",    "idxitem",       "collate",       "nmnum",       
  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
  "trigger_cmd",   "database_kw_opt",  "key_opt",       "add_column_fullname",
  "kwcolumn_opt",  "create_vtab",   "vtabarglist",   "vtabarg",     
  "vtabargtoken",  "lp",            "anylist",     
};
63340
63341
63342
63343
63344
63345
63346
63347

63348
63349
63350
63351
63352
63353
63354
63723
63724
63725
63726
63727
63728
63729

63730
63731
63732
63733
63734
63735
63736
63737







-
+







 /* 143 */ "sortlist ::= sortlist COMMA sortitem sortorder",
 /* 144 */ "sortlist ::= sortitem sortorder",
 /* 145 */ "sortitem ::= expr",
 /* 146 */ "sortorder ::= ASC",
 /* 147 */ "sortorder ::= DESC",
 /* 148 */ "sortorder ::=",
 /* 149 */ "groupby_opt ::=",
 /* 150 */ "groupby_opt ::= GROUP BY exprlist",
 /* 150 */ "groupby_opt ::= GROUP BY nexprlist",
 /* 151 */ "having_opt ::=",
 /* 152 */ "having_opt ::= HAVING expr",
 /* 153 */ "limit_opt ::=",
 /* 154 */ "limit_opt ::= LIMIT expr",
 /* 155 */ "limit_opt ::= LIMIT expr OFFSET expr",
 /* 156 */ "limit_opt ::= LIMIT expr COMMA expr",
 /* 157 */ "cmd ::= DELETE FROM fullname where_opt",
63419
63420
63421
63422
63423
63424
63425
63426
63427
63428
63429




63430
63431
63432
63433
63434
63435
63436
63802
63803
63804
63805
63806
63807
63808




63809
63810
63811
63812
63813
63814
63815
63816
63817
63818
63819







-
-
-
-
+
+
+
+







 /* 222 */ "expr ::= CASE case_operand case_exprlist case_else END",
 /* 223 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
 /* 224 */ "case_exprlist ::= WHEN expr THEN expr",
 /* 225 */ "case_else ::= ELSE expr",
 /* 226 */ "case_else ::=",
 /* 227 */ "case_operand ::= expr",
 /* 228 */ "case_operand ::=",
 /* 229 */ "exprlist ::= exprlist COMMA expritem",
 /* 230 */ "exprlist ::= expritem",
 /* 231 */ "expritem ::= expr",
 /* 232 */ "expritem ::=",
 /* 229 */ "exprlist ::= nexprlist",
 /* 230 */ "exprlist ::=",
 /* 231 */ "nexprlist ::= nexprlist COMMA expr",
 /* 232 */ "nexprlist ::= expr",
 /* 233 */ "cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
 /* 234 */ "uniqueflag ::= UNIQUE",
 /* 235 */ "uniqueflag ::=",
 /* 236 */ "idxlist_opt ::=",
 /* 237 */ "idxlist_opt ::= LP idxlist RP",
 /* 238 */ "idxlist ::= idxlist COMMA idxitem collate sortorder",
 /* 239 */ "idxlist ::= idxitem collate sortorder",
63540
63541
63542
63543
63544
63545
63546
63547

63548
63549
63550
63551
63552
63553
63554
63923
63924
63925
63926
63927
63928
63929

63930
63931
63932
63933
63934
63935
63936
63937







-
+







** Inputs:
** A pointer to the function used to allocate memory.
**
** Outputs:
** A pointer to a parser.  This pointer is used in subsequent calls
** to sqlite3Parser and sqlite3ParserFree.
*/
static void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  yyParser *pParser;
  pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  if( pParser ){
    pParser->yyidx = -1;
#if YYSTACKDEPTH<=0
    yyGrowStack(pParser);
#endif
63580
63581
63582
63583
63584
63585
63586
63587
63588


63589
63590
63591
63592
63593
63594
63595
63596
63597
63598
63599
63600
63601
63602
63603
63604


63605
63606
63607
63608
63609
63610
63611
63963
63964
63965
63966
63967
63968
63969


63970
63971

63972
63973
63974
63975
63976
63977
63978
63979
63980
63981
63982
63983
63984
63985

63986
63987
63988
63989
63990
63991
63992
63993
63994







-
-
+
+
-














-
+
+







      break;
    case 169:
    case 170:
    case 194:
    case 196:
    case 204:
    case 210:
    case 217:
    case 220:
    case 218:
    case 221:
    case 222:
    case 223:
    case 235:
{sqlite3ExprDelete((yypminor->yy172));}
      break;
    case 174:
    case 182:
    case 192:
    case 195:
    case 197:
    case 199:
    case 209:
    case 211:
    case 212:
    case 215:
    case 221:
    case 216:
    case 222:
{sqlite3ExprListDelete((yypminor->yy174));}
      break;
    case 188:
    case 193:
    case 201:
    case 202:
{sqlite3SrcListDelete((yypminor->yy373));}
63663
63664
63665
63666
63667
63668
63669
63670

63671
63672
63673
63674
63675
63676
63677
64046
64047
64048
64049
64050
64051
64052

64053
64054
64055
64056
64057
64058
64059
64060







-
+







** <ul>
** <li>  A pointer to the parser.  This should be a pointer
**       obtained from sqlite3ParserAlloc.
** <li>  A pointer to a function used to reclaim memory obtained
**       from malloc.
** </ul>
*/
static void sqlite3ParserFree(
SQLITE_PRIVATE void sqlite3ParserFree(
  void *p,                    /* The parser to be deleted */
  void (*freeProc)(void*)     /* Function used to reclaim memory */
){
  yyParser *pParser = (yyParser*)p;
  if( pParser==0 ) return;
  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
#if YYSTACKDEPTH<=0
64030
64031
64032
64033
64034
64035
64036
64037
64038
64039
64040
64041
64042






64043
64044
64045
64046
64047
64048
64049
64050
64051
64052


64053
64054
64055


64056
64057
64058
64059
64060
64061
64062
64063
64064
64065
64066
64067








64068
64069
64070
64071
64072
64073
64074
64075
64076
64077
64078
64413
64414
64415
64416
64417
64418
64419






64420
64421
64422
64423
64424
64425
64426
64427
64428
64429
64430
64431
64432
64433


64434
64435
64436


64437
64438
64439
64440
64441
64442
64443
64444






64445
64446
64447
64448
64449
64450
64451
64452
64453
64454


64455
64456
64457
64458
64459
64460
64461







-
-
-
-
-
-
+
+
+
+
+
+








-
-
+
+

-
-
+
+






-
-
-
-
-
-
+
+
+
+
+
+
+
+


-
-







  { 170, 3 },
  { 170, 3 },
  { 170, 3 },
  { 170, 3 },
  { 170, 3 },
  { 170, 3 },
  { 170, 3 },
  { 216, 1 },
  { 216, 2 },
  { 216, 1 },
  { 216, 2 },
  { 217, 2 },
  { 217, 0 },
  { 217, 1 },
  { 217, 2 },
  { 217, 1 },
  { 217, 2 },
  { 218, 2 },
  { 218, 0 },
  { 170, 4 },
  { 170, 2 },
  { 170, 3 },
  { 170, 3 },
  { 170, 4 },
  { 170, 2 },
  { 170, 2 },
  { 170, 2 },
  { 218, 1 },
  { 218, 2 },
  { 219, 1 },
  { 219, 2 },
  { 170, 5 },
  { 219, 1 },
  { 219, 2 },
  { 220, 1 },
  { 220, 2 },
  { 170, 5 },
  { 170, 3 },
  { 170, 5 },
  { 170, 4 },
  { 170, 4 },
  { 170, 5 },
  { 221, 5 },
  { 221, 4 },
  { 222, 2 },
  { 222, 0 },
  { 220, 1 },
  { 220, 0 },
  { 222, 5 },
  { 222, 4 },
  { 223, 2 },
  { 223, 0 },
  { 221, 1 },
  { 221, 0 },
  { 216, 1 },
  { 216, 0 },
  { 211, 3 },
  { 211, 1 },
  { 223, 1 },
  { 223, 0 },
  { 143, 11 },
  { 224, 1 },
  { 224, 0 },
  { 174, 0 },
  { 174, 3 },
  { 182, 5 },
  { 182, 3 },
64518
64519
64520
64521
64522
64523
64524

64525
64526
64527
64528
64529
64530
64531
64901
64902
64903
64904
64905
64906
64907
64908
64909
64910
64911
64912
64913
64914
64915







+







      case 114:
      case 237:
{yygotominor.yy174 = yymsp[-1].minor.yy174;}
        break;
      case 115:
      case 141:
      case 149:
      case 230:
      case 236:
{yygotominor.yy174 = 0;}
        break;
      case 116:
{
   yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[-1].minor.yy172,yymsp[0].minor.yy410.n?&yymsp[0].minor.yy410:0);
}
64601
64602
64603
64604
64605
64606
64607
64608
64609
64610
64611
64612
64613
64614
64615
64616
64617
64618
64619
64620
64621
64622
64623
64624
64625
64626
64627
64628
64629

64630
64631
64632
64633
64634
64635
64636
64985
64986
64987
64988
64989
64990
64991

64992
64993
64994
64995
64996
64997
64998
64999

65000
65001
65002
65003
65004
65005
65006
65007
65008
65009
65010
65011
65012
65013
65014
65015
65016
65017
65018
65019







-








-












+







      case 145:
      case 152:
      case 159:
      case 174:
      case 202:
      case 225:
      case 227:
      case 231:
{yygotominor.yy172 = yymsp[0].minor.yy172;}
        break;
      case 138:
      case 151:
      case 158:
      case 203:
      case 226:
      case 228:
      case 232:
{yygotominor.yy172 = 0;}
        break;
      case 139:
      case 171:
{yygotominor.yy432 = yymsp[-1].minor.yy432;}
        break;
      case 140:
      case 170:
{yygotominor.yy432 = 0;}
        break;
      case 142:
      case 150:
      case 229:
{yygotominor.yy174 = yymsp[0].minor.yy174;}
        break;
      case 143:
{
  yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-3].minor.yy174,yymsp[-1].minor.yy172,0);
  if( yygotominor.yy174 ) yygotominor.yy174->a[yygotominor.yy174->nExpr-1].sortOrder = yymsp[0].minor.yy46;
}
64681
64682
64683
64684
64685
64686
64687
64688

64689
64690
64691
64692

64693
64694
64695
64696
64697
64698
64699
65064
65065
65066
65067
65068
65069
65070

65071
65072
65073
65074

65075
65076
65077
65078
65079
65080
65081
65082







-
+



-
+







      case 164:
{sqlite3Insert(pParse, yymsp[-2].minor.yy373, 0, yymsp[0].minor.yy219, yymsp[-1].minor.yy432, yymsp[-4].minor.yy46);}
        break;
      case 165:
{sqlite3Insert(pParse, yymsp[-3].minor.yy373, 0, 0, yymsp[-2].minor.yy432, yymsp[-5].minor.yy46);}
        break;
      case 168:
      case 229:
      case 231:
{yygotominor.yy174 = sqlite3ExprListAppend(yymsp[-2].minor.yy174,yymsp[0].minor.yy172,0);}
        break;
      case 169:
      case 230:
      case 232:
{yygotominor.yy174 = sqlite3ExprListAppend(0,yymsp[0].minor.yy172,0);}
        break;
      case 172:
{yygotominor.yy432 = sqlite3IdListAppend(yymsp[-2].minor.yy432,&yymsp[0].minor.yy410);}
        break;
      case 173:
{yygotominor.yy432 = sqlite3IdListAppend(0,&yymsp[0].minor.yy410);}
65274
65275
65276
65277
65278
65279
65280
65281

65282
65283
65284
65285
65286
65287
65288
65657
65658
65659
65660
65661
65662
65663

65664
65665
65666
65667
65668
65669
65670
65671







-
+







** <li> The minor token number.
** <li> An option argument of a grammar-specified type.
** </ul>
**
** Outputs:
** None.
*/
static void sqlite3Parser(
SQLITE_PRIVATE void sqlite3Parser(
  void *yyp,                   /* The parser */
  int yymajor,                 /* The major token code number */
  sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
  sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
){
  YYMINORTYPE yyminorunion;
  int yyact;            /* The parser action. */
65432
65433
65434
65435
65436
65437
65438
65439

65440
65441
65442
65443
65444
65445
65446
65815
65816
65817
65818
65819
65820
65821

65822
65823
65824
65825
65826
65827
65828
65829







-
+







*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The charMap() macro maps alphabetic characters into their
** lower-case ASCII equivalent.  On ASCII machines, this is just
** an upper-to-lower case map.  On EBCDIC machines we also need
** to adjust the encoding.  Only alphabetic characters and underscores
65485
65486
65487
65488
65489
65490
65491
65492

65493
65494
65495
65496
65497
65498
65499
65868
65869
65870
65871
65872
65873
65874

65875
65876
65877
65878
65879
65880
65881
65882







-
+







*/
/************** Include keywordhash.h in the middle of tokenize.c ************/
/************** Begin file keywordhash.h *************************************/
/***** This file contains automatically generated code ******
**
** The code in this file has been automatically generated by
**
**     $Header: /cvsroot/sqlite-dotnet2/SQLite.NET/SQLite.Interop/src/sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
**     $Header: /cvsroot/sqlite-dotnet2/SQLite.NET/SQLite.Interop/src/sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
**
** The code in this file implements a function that determines whether
** or not a given identifier is really an SQL keyword.  The same thing
** might be implemented more directly using a hand-written hash table.
** But by using this automatically generated code, the size of the code
** is substantially reduced.  This is important for embedded applications
** on platforms with limited memory.
65590
65591
65592
65593
65594
65595
65596
65597

65598
65599
65600
65601
65602
65603
65604
65973
65974
65975
65976
65977
65978
65979

65980
65981
65982
65983
65984
65985
65986
65987







-
+







  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
    if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
      return aCode[i];
    }
  }
  return TK_ID;
}
static int sqlite3KeywordCode(const unsigned char *z, int n){
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  return keywordCode((char*)z, n);
}

/************** End of keywordhash.h *****************************************/
/************** Continuing where we left off in tokenize.c *******************/


65905
65906
65907
65908
65909
65910
65911
65912

65913
65914
65915







65916
65917
65918
65919
65920
65921
65922
65923

65924
65925
65926
65927
65928
65929
65930
65931
65932
65933
65934
65935
65936
65937
65938
65939
66288
66289
66290
66291
66292
66293
66294

66295
66296
66297
66298
66299
66300
66301
66302
66303
66304
66305
66306
66307
66308
66309
66310
66311
66312

66313
66314
66315
66316
66317
66318
66319



66320
66321
66322
66323
66324
66325
66326







-
+



+
+
+
+
+
+
+







-
+






-
-
-







      *tokenType = keywordCode((char*)z, i);
      return i;
    }
  }
  *tokenType = TK_ILLEGAL;
  return 1;
}
static int sqlite3GetToken(const unsigned char *z, int *tokenType){
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  return getToken(z, tokenType);
}

/*
** The interface to the LEMON-generated parser
*/
SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);

/*
** Run the parser on the given SQL string.  The parser structure is
** passed in.  An SQLITE_ status code is returned.  If an error occurs
** and pzErrMsg!=NULL then an error message might be written into 
** memory obtained from malloc() and *pzErrMsg made to point to that
** error message.  Or maybe not.
*/
static int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  int nErr = 0;
  int i;
  void *pEngine;
  int tokenType;
  int lastTokenParsed = -1;
  sqlite3 *db = pParse->db;
  extern void *sqlite3ParserAlloc(void*(*)(size_t));
  extern void sqlite3ParserFree(void*, void(*)(void*));
  extern void sqlite3Parser(void*, int, Token, Parse*);

  if( db->activeVdbeCnt==0 ){
    db->u1.isInterrupted = 0;
  }
  pParse->rc = SQLITE_OK;
  i = 0;
  pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3MallocX);
66057
66058
66059
66060
66061
66062
66063
66064

66065
66066
66067
66068
66069
66070
66071

66072
66073
66074
66075
66076
66077
66078
66444
66445
66446
66447
66448
66449
66450

66451
66452
66453
66454
66455
66456
66457

66458
66459
66460
66461
66462
66463
66464
66465







-
+






-
+







**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: sqlite3.c,v 1.3 2007/06/19 22:43:23 rmsimpson Exp $
** $Id: sqlite3.c,v 1.4 2007/07/21 08:51:43 rmsimpson Exp $
*/

/*
** The version of the library
*/
const char sqlite3_version[] = SQLITE_VERSION;
const char *sqlite3_libversion(void){ return sqlite3_version; }
SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }

/*
** If the following function pointer is not NULL and if
** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
** I/O active are written using this function.  These messages
** are intended for debugging activity only.
66135
66136
66137
66138
66139
66140
66141
66142

66143
66144
66145
66146
66147
66148
66149
66150
66151
66152
66153
66154
66155
66156

66157
66158
66159
66160
66161
66162
66163
66522
66523
66524
66525
66526
66527
66528

66529
66530
66531
66532
66533
66534
66535
66536
66537
66538
66539
66540
66541
66542

66543
66544
66545
66546
66547
66548
66549
66550







-
+













-
+







sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  return db->lastRowid;
}

/*
** Return the number of changes in the most recent call to sqlite3_exec().
*/
int sqlite3_changes(sqlite3 *db){
SQLITE_API int sqlite3_changes(sqlite3 *db){
  return db->nChange;
}

/*
** Return the number of changes since the database handle was opened.
*/
int sqlite3_total_changes(sqlite3 *db){
  return db->nTotalChange;
}

/*
** Close an existing SQLite database
*/
int sqlite3_close(sqlite3 *db){
SQLITE_API int sqlite3_close(sqlite3 *db){
  HashElem *i;
  int j;

  if( !db ){
    return SQLITE_OK;
  }
  if( sqlite3SafetyCheck(db) ){
66234
66235
66236
66237
66238
66239
66240



66241
66242
66243
66244
66245
66246
66247
66621
66622
66623
66624
66625
66626
66627
66628
66629
66630
66631
66632
66633
66634
66635
66636
66637







+
+
+







    }
    sqliteFree(pColl);
  }
  sqlite3HashClear(&db->aCollSeq);
#ifndef SQLITE_OMIT_VIRTUALTABLE
  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
    Module *pMod = (Module *)sqliteHashData(i);
    if( pMod->xDestroy ){
      pMod->xDestroy(pMod->pAux);
    }
    sqliteFree(pMod);
  }
  sqlite3HashClear(&db->aModule);
#endif

  sqlite3HashClear(&db->aFunc);
  sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
66263
66264
66265
66266
66267
66268
66269
66270

66271
66272
66273
66274
66275
66276
66277
66653
66654
66655
66656
66657
66658
66659

66660
66661
66662
66663
66664
66665
66666
66667







-
+







  sqlite3ReleaseThreadData();
  return SQLITE_OK;
}

/*
** Rollback all database files.
*/
static void sqlite3RollbackAll(sqlite3 *db){
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
  int i;
  int inTrans = 0;
  for(i=0; i<db->nDb; i++){
    if( db->aDb[i].pBt ){
      if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
        inTrans = 1;
      }
66290
66291
66292
66293
66294
66295
66296
66297

66298
66299
66300
66301
66302
66303
66304
66680
66681
66682
66683
66684
66685
66686

66687
66688
66689
66690
66691
66692
66693
66694







-
+







  }
}

/*
** Return a static string that describes the kind of error specified in the
** argument.
*/
static const char *sqlite3ErrStr(int rc){
SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  const char *z;
  switch( rc & 0xff ){
    case SQLITE_ROW:
    case SQLITE_DONE:
    case SQLITE_OK:         z = "not an error";                          break;
    case SQLITE_ERROR:      z = "SQL logic error or missing database";   break;
    case SQLITE_PERM:       z = "access permission denied";              break;
66374
66375
66376
66377
66378
66379
66380
66381

66382
66383
66384
66385
66386
66387
66388
66764
66765
66766
66767
66768
66769
66770

66771
66772
66773
66774
66775
66776
66777
66778







-
+







/*
** Invoke the given busy handler.
**
** This routine is called when an operation failed with a lock.
** If this routine returns non-zero, the lock is retried.  If it
** returns 0, the operation aborts with an SQLITE_BUSY error.
*/
static int sqlite3InvokeBusyHandler(BusyHandler *p){
SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  int rc;
  if( p==0 || p->xFunc==0 || p->nBusy<0 ) return 0;
  rc = p->xFunc(p->pArg, p->nBusy);
  if( rc==0 ){
    p->nBusy = -1;
  }else{
    p->nBusy++;
66451
66452
66453
66454
66455
66456
66457
66458

66459
66460
66461
66462
66463
66464
66465
66466
66467
66468
66469
66470
66471
66472
66473
66474
66475
66476



66477
66478
66479
66480
66481
66482
66483
66484
66485
66486
66487
66488
66489
66490
66491
66492
66493
66494
66495

66496
66497
66498
66499
66500
66501
66502
66841
66842
66843
66844
66845
66846
66847

66848
66849
66850
66851
66852
66853
66854
66855
66856
66857
66858
66859
66860
66861
66862
66863



66864
66865
66866
66867
66868
66869
66870
66871
66872
66873
66874
66875
66876
66877
66878
66879
66880
66881
66882
66883
66884

66885
66886
66887
66888
66889
66890
66891
66892







-
+















-
-
-
+
+
+


















-
+







  }
  return SQLITE_OK;
}

/*
** Cause any pending operation to stop at its earliest opportunity.
*/
void sqlite3_interrupt(sqlite3 *db){
SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  if( db && (db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_BUSY) ){
    db->u1.isInterrupted = 1;
  }
}

/*
** Memory allocation routines that use SQLites internal memory
** memory allocator.  Depending on how SQLite is compiled, the
** internal memory allocator might be just an alias for the
** system default malloc/realloc/free.  Or the built-in allocator
** might do extra stuff like put sentinals around buffers to 
** check for overruns or look for memory leaks.
**
** Use sqlite3_free() to free memory returned by sqlite3_mprintf().
*/
void sqlite3_free(void *p){ if( p ) sqlite3OsFree(p); }
void *sqlite3_malloc(int nByte){ return nByte>0 ? sqlite3OsMalloc(nByte) : 0; }
void *sqlite3_realloc(void *pOld, int nByte){ 
SQLITE_API void sqlite3_free(void *p){ if( p ) sqlite3OsFree(p); }
SQLITE_API void *sqlite3_malloc(int nByte){ return nByte>0 ? sqlite3OsMalloc(nByte) : 0; }
SQLITE_API void *sqlite3_realloc(void *pOld, int nByte){ 
  if( pOld ){
    if( nByte>0 ){
      return sqlite3OsRealloc(pOld, nByte);
    }else{
      sqlite3OsFree(pOld);
      return 0;
    }
  }else{
    return sqlite3_malloc(nByte);
  }
}

/*
** This function is exactly the same as sqlite3_create_function(), except
** that it is designed to be called by internal code. The difference is
** that if a malloc() fails in sqlite3_create_function(), an error code
** is returned and the mallocFailed flag cleared. 
*/
static int sqlite3CreateFunc(
SQLITE_PRIVATE int sqlite3CreateFunc(
  sqlite3 *db,
  const char *zFunctionName,
  int nArg,
  int enc,
  void *pUserData,
  void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
66645
66646
66647
66648
66649
66650
66651
66652

66653
66654
66655
66656
66657
66658
66659
66660
66661
66662
66663
66664
66665
66666

66667
66668
66669
66670
66671
66672
66673
67035
67036
67037
67038
67039
67040
67041

67042
67043
67044
67045
67046
67047
67048
67049
67050
67051
67052
67053
67054
67055

67056
67057
67058
67059
67060
67061
67062
67063







-
+













-
+







** Register a trace function.  The pArg from the previously registered trace
** is returned.  
**
** A NULL trace function means that no tracing is executes.  A non-NULL
** trace is a pointer to a function that is invoked at the start of each
** SQL statement.
*/
void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  void *pOld = db->pTraceArg;
  db->xTrace = xTrace;
  db->pTraceArg = pArg;
  return pOld;
}
/*
** Register a profile function.  The pArg from the previously registered 
** profile function is returned.  
**
** A NULL profile function means that no profiling is executes.  A non-NULL
** profile is a pointer to a function that is invoked at the conclusion of
** each SQL statement that is run.
*/
void *sqlite3_profile(
SQLITE_API void *sqlite3_profile(
  sqlite3 *db,
  void (*xProfile)(void*,const char*,sqlite_uint64),
  void *pArg
){
  void *pOld = db->pProfileArg;
  db->xProfile = xProfile;
  db->pProfileArg = pArg;
66743
66744
66745
66746
66747
66748
66749
66750

66751
66752
66753
66754
66755
66756
66757
67133
67134
67135
67136
67137
67138
67139

67140
67141
67142
67143
67144
67145
67146
67147







-
+







**           1                2              memory
**           1                0              file
**           2                1              file
**           2                2              memory
**           2                0              memory
**           3               any             memory
*/
static int sqlite3BtreeFactory(
SQLITE_PRIVATE int sqlite3BtreeFactory(
  const sqlite3 *db,        /* Main database when opening aux otherwise 0 */
  const char *zFilename,    /* Name of the file containing the BTree database */
  int omitJournal,          /* if TRUE then do not journal this file */
  int nCache,               /* How many pages in the page cache */
  Btree **ppBtree           /* Pointer to new Btree object written here */
){
  int btree_flags = 0;
66789
66790
66791
66792
66793
66794
66795
66796

66797
66798
66799
66800
66801
66802
66803
66804
66805
66806
66807
66808
66809
66810
66811
66812
66813
66814
66815
66816
66817

66818
66819
66820
66821
66822
66823
66824
67179
67180
67181
67182
67183
67184
67185

67186
67187
67188
67189
67190
67191
67192
67193
67194
67195
67196
67197
67198
67199
67200
67201
67202
67203
67204
67205
67206

67207
67208
67209
67210
67211
67212
67213
67214







-
+




















-
+







  return rc;
}

/*
** Return UTF-8 encoded English language explanation of the most recent
** error.
*/
const char *sqlite3_errmsg(sqlite3 *db){
SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  const char *z;
  assert( !sqlite3MallocFailed() );
  if( !db ){
    return sqlite3ErrStr(SQLITE_NOMEM);
  }
  if( sqlite3SafetyCheck(db) || db->errCode==SQLITE_MISUSE ){
    return sqlite3ErrStr(SQLITE_MISUSE);
  }
  z = (char*)sqlite3_value_text(db->pErr);
  if( z==0 ){
    z = sqlite3ErrStr(db->errCode);
  }
  return z;
}

#ifndef SQLITE_OMIT_UTF16
/*
** Return UTF-16 encoded English language explanation of the most recent
** error.
*/
const void *sqlite3_errmsg16(sqlite3 *db){
SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  /* Because all the characters in the string are in the unicode
  ** range 0x00-0xFF, if we pad the big-endian string with a 
  ** zero byte, we can obtain the little-endian string with
  ** &big_endian[1].
  */
  static const char outOfMemBe[] = {
    0, 'o', 0, 'u', 0, 't', 0, ' ', 
66853
66854
66855
66856
66857
66858
66859
66860

66861
66862
66863
66864
66865
66866
66867
67243
67244
67245
67246
67247
67248
67249

67250
67251
67252
67253
67254
67255
67256
67257







-
+







}
#endif /* SQLITE_OMIT_UTF16 */

/*
** Return the most recent error code generated by an SQLite routine. If NULL is
** passed to this function, we assume a malloc() failed during sqlite3_open().
*/
int sqlite3_errcode(sqlite3 *db){
SQLITE_API int sqlite3_errcode(sqlite3 *db){
  if( !db || sqlite3MallocFailed() ){
    return SQLITE_NOMEM;
  }
  if( sqlite3SafetyCheck(db) ){
    return SQLITE_MISUSE;
  }
  return db->errCode & db->errMask;
67025
67026
67027
67028
67029
67030
67031





67032
67033
67034
67035
67036
67037
67038
67039
67040
67041
67042
67043
67044
67045
67046


67047

67048
67049



67050
67051

67052
67053
67054
67055
67056

67057
67058

67059
67060
67061
67062
67063

67064
67065

67066
67067

67068
67069
67070
67071
67072
67073
67074
67415
67416
67417
67418
67419
67420
67421
67422
67423
67424
67425
67426
67427
67428
67429
67430
67431

67432
67433


67434
67435
67436
67437
67438
67439
67440

67441


67442
67443
67444
67445

67446
67447
67448
67449
67450

67451
67452

67453
67454
67455
67456
67457

67458
67459

67460
67461
67462
67463
67464
67465
67466
67467
67468
67469
67470







+
+
+
+
+





-


-
-





+
+
-
+
-
-
+
+
+

-
+




-
+

-
+




-
+

-
+


+







  */
  db->aDb[0].zName = "main";
  db->aDb[0].safety_level = 3;
#ifndef SQLITE_OMIT_TEMPDB
  db->aDb[1].zName = "temp";
  db->aDb[1].safety_level = 1;
#endif

  db->magic = SQLITE_MAGIC_OPEN;
  if( sqlite3MallocFailed() ){
    goto opendb_out;
  }

  /* Register all built-in functions, but do not attempt to read the
  ** database schema yet. This is delayed until the first time the database
  ** is accessed.
  */
  if( !sqlite3MallocFailed() ){
    sqlite3Error(db, SQLITE_OK, 0);
    sqlite3RegisterBuiltinFunctions(db);
  }
  db->magic = SQLITE_MAGIC_OPEN;

  /* Load automatic extensions - extensions that have been registered
  ** using the sqlite3_automatic_extension() API.
  */
  (void)sqlite3AutoLoadExtensions(db);
  if( sqlite3_errcode(db)!=SQLITE_OK ){
    goto opendb_out;

  }
#ifdef SQLITE_ENABLE_FTS1
  {

#ifdef SQLITE_ENABLE_FTS1
  if( !sqlite3MallocFailed() ){
    extern int sqlite3Fts1Init(sqlite3*);
    sqlite3Fts1Init(db);
    rc = sqlite3Fts1Init(db);
  }
#endif

#ifdef SQLITE_ENABLE_FTS2
  {
  if( !sqlite3MallocFailed() && rc==SQLITE_OK ){
    extern int sqlite3Fts2Init(sqlite3*);
    sqlite3Fts2Init(db);
    rc = sqlite3Fts2Init(db);
  }
#endif

#ifdef SQLITE_ENABLE_ICU
  if( !sqlite3MallocFailed() ){
  if( !sqlite3MallocFailed() && rc==SQLITE_OK ){
    extern int sqlite3IcuInit(sqlite3*);
    sqlite3IcuInit(db);
    rc = sqlite3IcuInit(db);
  }
#endif
  sqlite3Error(db, rc, 0);

  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  ** mode.  Doing nothing at all also makes NORMAL the default.
  */
#ifdef SQLITE_DEFAULT_LOCKING_MODE
  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
67084
67085
67086
67087
67088
67089
67090
67091

67092
67093
67094
67095
67096
67097
67098
67099
67100
67101
67102

67103
67104
67105
67106
67107
67108
67109
67480
67481
67482
67483
67484
67485
67486

67487
67488
67489
67490
67491
67492
67493
67494
67495
67496
67497

67498
67499
67500
67501
67502
67503
67504
67505







-
+










-
+







  *ppDb = db;
  return sqlite3ApiExit(0, rc);
}

/*
** Open a new database handle.
*/
int sqlite3_open(
SQLITE_API int sqlite3_open(
  const char *zFilename, 
  sqlite3 **ppDb 
){
  return openDatabase(zFilename, ppDb);
}

#ifndef SQLITE_OMIT_UTF16
/*
** Open a new database handle.
*/
int sqlite3_open16(
SQLITE_API int sqlite3_open16(
  const void *zFilename, 
  sqlite3 **ppDb
){
  char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
  int rc = SQLITE_OK;
  sqlite3_value *pVal;

67134
67135
67136
67137
67138
67139
67140
67141

67142
67143
67144
67145
67146
67147
67148
67149
67150
67151
67152
67153
67154
67155
67156
67157
67158
67159

67160
67161
67162
67163
67164
67165
67166
67530
67531
67532
67533
67534
67535
67536

67537
67538
67539
67540
67541
67542
67543
67544
67545
67546
67547
67548
67549
67550
67551
67552
67553
67554

67555
67556
67557
67558
67559
67560
67561
67562







-
+

















-
+







** the sqlite3_compile() routine. The integer returned is an SQLITE_
** success/failure code that describes the result of executing the virtual
** machine.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_finalize(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  int rc;
  if( pStmt==0 ){
    rc = SQLITE_OK;
  }else{
    rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  }
  return rc;
}

/*
** Terminate the current execution of an SQL statement and reset it
** back to its starting state so that it can be reused. A success code from
** the prior execution is returned.
**
** This routine sets the error code and string returned by
** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
*/
int sqlite3_reset(sqlite3_stmt *pStmt){
SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  int rc;
  if( pStmt==0 ){
    rc = SQLITE_OK;
  }else{
    rc = sqlite3VdbeReset((Vdbe*)pStmt);
    sqlite3VdbeMakeReady((Vdbe*)pStmt, -1, 0, 0, 0);
    assert( (rc & (sqlite3_db_handle(pStmt)->errMask))==rc );
67286
67287
67288
67289
67290
67291
67292
67293

67294
67295
67296
67297
67298
67299
67300
67682
67683
67684
67685
67686
67687
67688

67689
67690
67691
67692
67693
67694
67695
67696







-
+








#ifdef SQLITE_DEBUG
/*
** The following routine is subtituted for constant SQLITE_CORRUPT in
** debugging builds.  This provides a way to set a breakpoint for when
** corruption is first detected.
*/
static int sqlite3Corrupt(void){
SQLITE_PRIVATE int sqlite3Corrupt(void){
  return SQLITE_CORRUPT;
}
#endif


#ifndef SQLITE_OMIT_SHARED_CACHE
/*
67460
67461
67462
67463
67464
67465
67466
67467

67468
67469
67470
67471
67472
67473
67474
67475
67476
67477
67478
67479
67856
67857
67858
67859
67860
67861
67862

67863
67864
67865
67866
67867
67868
67869
67870
67871
67872
67873
67874
67875







-
+












  }
  return rc;
}

/*
** Sleep for a little while.  Return the amount of time slept.
*/
int sqlite3_sleep(int ms){
SQLITE_API int sqlite3_sleep(int ms){
  return sqlite3OsSleep(ms);
}

/*
** Enable or disable the extended result codes.
*/
int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  db->errMask = onoff ? 0xffffffff : 0xff;
  return SQLITE_OK;
}

/************** End of main.c ************************************************/
Changes to SQLite.Interop/src/sqlite3.h.
26
27
28
29
30
31
32
33

34
35
36
37
38
39
40
26
27
28
29
30
31
32

33
34
35
36
37
38
39
40







-
+







** on how SQLite interfaces are suppose to operate.
**
** The name of this file under configuration management is "sqlite.h.in".
** The makefile makes some minor changes to this file (such as inserting
** the version number) and changes its name to "sqlite3.h" as
** part of the build process.
**
** @(#) $Id: sqlite3.h,v 1.30 2007/06/19 22:43:24 rmsimpson Exp $
** @(#) $Id: sqlite3.h,v 1.31 2007/07/21 08:51:43 rmsimpson Exp $
*/
#ifndef _SQLITE3_H_
#define _SQLITE3_H_
#include <stdarg.h>     /* Needed for the definition of va_list */

/*
** Make sure we can call this stuff from C++.
77
78
79
80
81
82
83
84
85


86
87
88
89
90
91
92
77
78
79
80
81
82
83


84
85
86
87
88
89
90
91
92







-
-
+
+







** (X*1000000 + Y*1000 + Z). For example, for version "3.1.1beta", 
** SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using 
** version 3.1.1 or greater at compile time, programs may use the test 
** (SQLITE_VERSION_NUMBER>=3001001).
**
** See also: [sqlite3_libversion()] and [sqlite3_libversion_number()].
*/
#define SQLITE_VERSION         "3.4.0"
#define SQLITE_VERSION_NUMBER 3004000
#define SQLITE_VERSION         "3.4.1"
#define SQLITE_VERSION_NUMBER 3004001

/*
** CAPI3REF: Run-Time Library Version Numbers
**
** These routines return values equivalent to the header constants
** [SQLITE_VERSION] and [SQLITE_VERSION_NUMBER].  The values returned
** by this routines should only be different from the header values
365
366
367
368
369
370
371
372

373
374
375
376
377
378
379
365
366
367
368
369
370
371

372
373
374
375
376
377
378
379







-
+







**
** If a callback invokes [sqlite3_exec()] or [sqlite3_step()] recursively,
** then the changes in the inner, recursive call are counted together
** with the changes in the outer call.
**
** SQLite implements the command "DELETE FROM table" without a WHERE clause
** by dropping and recreating the table.  (This is much faster than going
** through and deleting individual elements form the table.)  Because of
** through and deleting individual elements from the table.)  Because of
** this optimization, the change count for "DELETE FROM table" will be
** zero regardless of the number of elements that were originally in the
** table. To get an accurate count of the number of rows deleted, use
** "DELETE FROM table WHERE 1" instead.
*/
int sqlite3_changes(sqlite3*);

959
960
961
962
963
964
965
966



967
968
969




970
971
972
973
974
975
976
959
960
961
962
963
964
965

966
967
968
969


970
971
972
973
974
975
976
977
978
979
980







-
+
+
+

-
-
+
+
+
+







** program using one of these routines. 
**
** The first argument "db" is an [sqlite3 | SQLite database handle] 
** obtained from a prior call to [sqlite3_open()] or [sqlite3_open16()].
** The second argument "zSql" is the statement to be compiled, encoded
** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
** interfaces uses UTF-8 and sqlite3_prepare16() and sqlite3_prepare16_v2()
** use UTF-16. If the next argument, "nBytes", is less
** use UTF-16.
**
** If the nByte argument is less
** than zero, then zSql is read up to the first zero terminator.  If
** "nBytes" is not less than zero, then it is the length of the string zSql
** in bytes (not characters).
** nByte is non-negative, then it is the maximum number of 
** bytes read from zSql.  When nByte is non-negative, the
** zSql string ends at either the first '\000' character or 
** until the nByte-th byte, whichever comes first.
**
** *pzTail is made to point to the first byte past the end of the first
** SQL statement in zSql.  This routine only compiles the first statement
** in zSql, so *pzTail is left pointing to what remains uncompiled.
**
** *ppStmt is left pointing to a compiled 
** [sqlite3_stmt | SQL statement structure] that can be
1015
1016
1017
1018
1019
1020
1021
1022

1023
1024
1025
1026
1027
1028
1029

1030
1031
1032
1033
1034
1035
1036

1037
1038
1039
1040
1041
1042
1043

1044
1045
1046
1047
1048
1049
1050
1019
1020
1021
1022
1023
1024
1025

1026
1027
1028
1029
1030
1031
1032

1033
1034
1035
1036
1037
1038
1039

1040
1041
1042
1043
1044
1045
1046

1047
1048
1049
1050
1051
1052
1053
1054







-
+






-
+






-
+






-
+







** returned immediately.
** </li>
** </ol>
*/
int sqlite3_prepare(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare_v2(
  sqlite3 *db,            /* Database handle */
  const char *zSql,       /* SQL statement, UTF-8 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const char **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);
int sqlite3_prepare16_v2(
  sqlite3 *db,            /* Database handle */
  const void *zSql,       /* SQL statement, UTF-16 encoded */
  int nBytes,             /* Length of zSql in bytes. */
  int nByte,              /* Maximum length of zSql in bytes. */
  sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
  const void **pzTail     /* OUT: Pointer to unused portion of zSql */
);

/*
** CAPI3REF:  Dynamically Typed Value Object
**
1233
1234
1235
1236
1237
1238
1239
1240




1241
1242
1243




1244
1245
1246
1247
1248
1249
1250
1237
1238
1239
1240
1241
1242
1243

1244
1245
1246
1247
1248
1249

1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260







-
+
+
+
+


-
+
+
+
+








/*
** CAPI3REF: Source Of Data In A Query Result
**
** These routines provide a means to determine what column of what
** table in which database a result of a SELECT statement comes from.
** The name of the database or table or column can be returned as
** either a UTF8 or UTF16 string.  The returned string is valid until
** either a UTF8 or UTF16 string.  The _database_ routines return
** the database name, the _table_ routines return the table name, and
** the origin_ routines return the column name.
** The returned string is valid until
** the [sqlite3_stmt | prepared statement] is destroyed using
** [sqlite3_finalize()] or until the same information is requested
** again about the same column.
** again in a different encoding.
**
** The names returned are the original un-aliased names of the
** database, table, and column.
**
** The first argument to the following calls is a 
** [sqlite3_stmt | compiled SQL statement].
** These functions return information about the Nth column returned by 
** the statement, where N is the second function argument.
**
** If the Nth column returned by the statement is an expression
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1446
1447
1448
1449
1450
1451
1452


1453
1454
1455
1456
1457
1458
1459







-
-







** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
** returned by sqlite3_column_type() is only meaningful if no type
** conversions have occurred as described below.  After a type conversion,
** the value returned by sqlite3_column_type() is undefined.  Future
** versions of SQLite may change the behavior of sqlite3_column_type()
** following a type conversion.
**
*** The sqlite3_column_nm
**
** If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes() 
** routine returns the number of bytes in that BLOB or string.
** If the result is a UTF-16 string, then sqlite3_column_bytes() converts
** the string to UTF-8 and then returns the number of bytes.
** If the result is a numeric value then sqlite3_column_bytes() uses
** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
** the number of bytes in that string.
1984
1985
1986
1987
1988
1989
1990
1991

1992
1993
1994
1995
1996
1997
1998
1992
1993
1994
1995
1996
1997
1998

1999
2000
2001
2002
2003
2004
2005
2006







-
+







  sqlite3 *db,                   /* Database to be rekeyed */
  const void *pKey, int nKey     /* The new key */
);

/*
** CAPI3REF:  Suspend Execution For A Short Time
**
** This function causes the current thread to suspect execution
** This function causes the current thread to suspend execution
** a number of milliseconds specified in its parameter.
**
** If the operating system does not support sleep requests with 
** millisecond time resolution, then the time will be rounded up to 
** the nearest second. The number of milliseconds of sleep actually 
** requested from the operating system is returned.
*/
2395
2396
2397
2398
2399
2400
2401


2402
2403
2404
2405
2406
2407
2408
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418







+
+







  int (*xBegin)(sqlite3_vtab *pVTab);
  int (*xSync)(sqlite3_vtab *pVTab);
  int (*xCommit)(sqlite3_vtab *pVTab);
  int (*xRollback)(sqlite3_vtab *pVTab);
  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
                       void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
                       void **ppArg);

  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
};

/*
** The sqlite3_index_info structure and its substructures is used to
** pass information into and receive the reply from the xBestIndex
** method of an sqlite3_module.  The fields under **Inputs** are the
** inputs to xBestIndex and are read-only.  xBestIndex inserts its
2488
2489
2490
2491
2492
2493
2494













2495
2496
2497
2498
2499
2500
2501
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524







+
+
+
+
+
+
+
+
+
+
+
+
+







*/
int sqlite3_create_module(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *,    /* Methods for the module */
  void *                     /* Client data for xCreate/xConnect */
);

/*
** This routine is identical to the sqlite3_create_module() method above,
** except that it allows a destructor function to be specified. It is
** even more experimental than the rest of the virtual tables API.
*/
int sqlite3_create_module_v2(
  sqlite3 *db,               /* SQLite connection to register module with */
  const char *zName,         /* Name of the module */
  const sqlite3_module *,    /* Methods for the module */
  void *,                    /* Client data for xCreate/xConnect */
  void(*xDestroy)(void*)     /* Module destructor function */
);

/*
** Every module implementation uses a subclass of the following structure
** to describe a particular instance of the module.  Each subclass will
** be taylored to the specific needs of the module implementation.   The
** purpose of this superclass is to define certain fields that are common
** to all module implementations.
Changes to SQLite.Interop/src/sqlite3ext.h.
11
12
13
14
15
16
17

18




19
20
21
22
23
24
25
26
27
28






29
30
31
32
33
34
35
11
12
13
14
15
16
17
18

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45







+
-
+
+
+
+










+
+
+
+
+
+







*************************************************************************
** This header file defines the SQLite interface for use by
** shared libraries that want to be imported as extensions into
** an SQLite instance.  Shared libraries that intend to be loaded
** as extensions by SQLite should #include this file instead of 
** sqlite3.h.
**
<<<<<<< sqlite3ext.h
** @(#) $Id: sqlite3ext.h,v 1.7 2007/06/19 22:43:24 rmsimpson Exp $
** @(#) $Id: sqlite3ext.h,v 1.9 2007/07/21 08:54:21 rmsimpson Exp $
=======
** @(#) $Id: sqlite3ext.h,v 1.9 2007/07/21 08:54:21 rmsimpson Exp $
>>>>>>> 1.8
*/
#ifndef _SQLITE3EXT_H_
#define _SQLITE3EXT_H_
#include "sqlite3.h"

typedef struct sqlite3_api_routines sqlite3_api_routines;

/*
** The following structure hold pointers to all of the SQLite API
** routines.
**
** WARNING:  In order to maintain backwards compatibility, add new
** interfaces to the end of this structure only.  If you insert new
** interfaces in the middle of this structure, then older different
** versions of SQLite will not be able to load each others shared
** libraries!
*/
struct sqlite3_api_routines {
  void * (*aggregate_context)(sqlite3_context*,int nBytes);
  int  (*aggregate_count)(sqlite3_context*);
  int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  int  (*bind_double)(sqlite3_stmt*,int,double);
  int  (*bind_int)(sqlite3_stmt*,int,int);
143
144
145
146
147
148
149

150
151
152
153
154
155
156
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167







+







  const void * (*value_text16le)(sqlite3_value*);
  int  (*value_type)(sqlite3_value*);
  char *(*vmprintf)(const char*,va_list);
  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  int (*clear_bindings)(sqlite3_stmt*);
  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
};

/*
** The following macros redefine the API routines so that they are
** redirected throught the global sqlite3_api structure.
**
** This header file is also used by the loadext.c source file
205
206
207
208
209
210
211

212
213
214
215
216
217
218
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230







+







#define sqlite3_complete               sqlite3_api->complete
#define sqlite3_complete16             sqlite3_api->complete16
#define sqlite3_create_collation       sqlite3_api->create_collation
#define sqlite3_create_collation16     sqlite3_api->create_collation16
#define sqlite3_create_function        sqlite3_api->create_function
#define sqlite3_create_function16      sqlite3_api->create_function16
#define sqlite3_create_module          sqlite3_api->create_module
#define sqlite3_create_module_v2       sqlite3_api->create_module_v2
#define sqlite3_data_count             sqlite3_api->data_count
#define sqlite3_db_handle              sqlite3_api->db_handle
#define sqlite3_declare_vtab           sqlite3_api->declare_vtab
#define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
#define sqlite3_errcode                sqlite3_api->errcode
#define sqlite3_errmsg                 sqlite3_api->errmsg
#define sqlite3_errmsg16               sqlite3_api->errmsg16
Changes to System.Data.SQLite/AssemblyInfo.cs.
44
45
46
47
48
49
50
51

52
53

54
44
45
46
47
48
49
50

51
52

53
54







-
+

-
+

//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.42.0")]
[assembly: AssemblyVersion("1.0.44.0")]
#if !PLATFORM_COMPACTFRAMEWORK
[assembly: AssemblyFileVersion("1.0.42.0")]
[assembly: AssemblyFileVersion("1.0.44.0")]
#endif
Changes to System.Data.SQLite/SQLite3.cs.
69
70
71
72
73
74
75
76

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114

115
116
117

118
119
120
121

122
123

124
125
126
127
128
129
130
69
70
71
72
73
74
75

76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113

114
115
116

117


118

119
120

121
122
123
124
125
126
127
128







-
+















-

+




















-
+


-
+
-
-

-
+

-
+








    internal override void Open(string strFilename)
    {
      if (_sql != null) return;
      IntPtr db;

      int n = UnsafeNativeMethods.sqlite3_open_interop(ToUTF8(strFilename), out db);
      if (n > 0) throw new SQLiteException(n, SQLiteLastError());
      if (n > 0) throw new SQLiteException(n, null);

      _sql = db;

      _functionsArray = SQLiteFunction.BindFunctions(this);
    }

    internal override void SetTimeout(int nTimeoutMS)
    {
      int n = UnsafeNativeMethods.sqlite3_busy_timeout_interop(_sql, nTimeoutMS);
      if (n > 0) throw new SQLiteException(n, SQLiteLastError());
    }

    internal override bool Step(SQLiteStatement stmt)
    {
      int n;
      long timeout = 0;
      Random rnd = null;
      uint timeout = (uint)(Environment.TickCount + (stmt._command._commandTimeout * 1000));

      while (true)
      {
        n = UnsafeNativeMethods.sqlite3_step_interop(stmt._sqlite_stmt);

        if (n == 100) return true;
        if (n == 101) return false;

        if (n > 0)
        {
          int r;

          // An error occurred, attempt to reset the statement.  If the reset worked because the
          // schema has changed, re-try the step again.  If it errored our because the database
          // is locked, then keep retrying until the command timeout occurs.
          r = Reset(stmt);

          if (r == 0)
            throw new SQLiteException(n, SQLiteLastError());

          else if (r == 6 && stmt._command != null) // SQLITE_LOCKED
          else if ((r == 6 || r == 5) && stmt._command != null) // SQLITE_LOCKED || SQLITE_BUSY
          {
            // Keep trying
            if (timeout == 0) // First time we've encountered the lock
            if (rnd == null) // First time we've encountered the lock
            {
              timeout = Environment.TickCount + (stmt._command._commandTimeout * 1000);
              rnd = new Random();
            }

            // If we've exceeded the command's timeout, give up and throw an error
            if (Environment.TickCount - timeout > 0)
            if ((uint)Environment.TickCount - timeout > 0)
            {
              throw new SQLiteException(r, SQLiteLastError());
            }
            else
            {
              // Otherwise sleep for a random amount of time up to 250ms
              UnsafeNativeMethods.sqlite3_sleep_interop((uint)rnd.Next(1, 250));
316
317
318
319
320
321
322
323

324
325
326
327
328
329
330
314
315
316
317
318
319
320

321
322
323
324
325
326
327
328







-
+








      if (p != IntPtr.Zero) return base.ToString(p, len);
      else
      {
        string[] ar = stmt.TypeDefinitions;
        if (ar != null)
        {
          if (index < ar.Length)
          if (index < ar.Length && ar[index] != null)
            return ar[index];
        }

        switch (nAffinity)
        {
          case TypeAffinity.Int64:
            return "BIGINT";
Changes to System.Data.SQLite/SQLite3_UTF16.cs.
43
44
45
46
47
48
49
50

51
52
53
54
55
56
57
43
44
45
46
47
48
49

50
51
52
53
54
55
56
57







-
+








    internal override void Open(string strFilename)
    {
      if (_sql != null) return;
      IntPtr db;

      int n = UnsafeNativeMethods.sqlite3_open16_interop(strFilename, out db);
      if (n > 0) throw new SQLiteException(n, SQLiteLastError());
      if (n > 0) throw new SQLiteException(n, null);

      _sql = db;
      _functionsArray = SQLiteFunction.BindFunctions(this);
    }

    internal override void Bind_DateTime(SQLiteStatement stmt, int index, DateTime dt)
    {
Changes to System.Data.SQLite/SQLiteDataAdapter.cs.
68
69
70
71
72
73
74

75
76
77
78
79
80
81
82
83

84
85
86
87
88

89
90
91
92
93
94
95
96
97
98
99
100
101
102
103

104
105
106
107
108
109
110
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114







+









+





+















+







    /// <summary>
    /// Row updating event handler
    /// </summary>
    public event EventHandler<RowUpdatingEventArgs> RowUpdating
    {
      add
      {
#if !PLATFORM_COMPACTFRAMEWORK
        EventHandler<RowUpdatingEventArgs> previous = (EventHandler<RowUpdatingEventArgs>)base.Events[_updatingEventPH];
        if ((previous != null) && (value.Target is DbCommandBuilder))
        {
          EventHandler<RowUpdatingEventArgs> handler = (EventHandler<RowUpdatingEventArgs>)FindBuilder(previous);
          if (handler != null)
          {
            base.Events.RemoveHandler(_updatingEventPH, handler);
          }
        }
#endif
        base.Events.AddHandler(_updatingEventPH, value); 
      }
      remove { base.Events.RemoveHandler(_updatingEventPH, value); }
    }

#if !PLATFORM_COMPACTFRAMEWORK
    internal static Delegate FindBuilder(MulticastDelegate mcd)
    {
      if (mcd != null)
      {
        Delegate[] invocationList = mcd.GetInvocationList();
        for (int i = 0; i < invocationList.Length; i++)
        {
          if (invocationList[i].Target is DbCommandBuilder)
          {
            return invocationList[i];
          }
        }
      }
      return null;
    }
#endif

    /// <summary>
    /// Row updated event handler
    /// </summary>
    public event EventHandler<RowUpdatedEventArgs> RowUpdated
    {
      add { base.Events.AddHandler(_updatedEventPH, value); }
Changes to System.Data.SQLite/SQLiteDataReader.cs.
751
752
753
754
755
756
757
758
759








760
761
762
763
764


765
766
767
768
769
770
771
751
752
753
754
755
756
757


758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779







-
-
+
+
+
+
+
+
+
+





+
+







    {
      CheckClosed();

      if (i >= VisibleFieldCount && _keyInfo != null)
        return _keyInfo.GetValue(i - VisibleFieldCount);

      SQLiteType typ = GetSQLiteType(i);
      TypeAffinity aff = _activeStatement._sql.ColumnAffinity(_activeStatement, i);


      // Because SQLite is inherently type-less, check this column and row's type
      // against the cache.  If they're different, then the db owner put varying datatypes in 
      // this column.  If that's the case, then stick with using SQLite's base datatypes rather
      // than the richer declared type in the table schema.
      if (typ.Type != DbType.Object)
      {
        TypeAffinity aff = _activeStatement._sql.ColumnAffinity(_activeStatement, i);
      if (aff != typ.Affinity)
      {
        typ.Type = DbType.Object;
        typ.Affinity = aff;
      }
      }

      return _activeStatement._sql.GetValue(_activeStatement, i, ref typ);
    }

    /// <summary>
    /// Retreives the values of multiple columns, up to the size of the supplied array
    /// </summary>
    /// <param name="values">The array to fill with values from the columns in the current resultset</param>
910
911
912
913
914
915
916
917

918
919
920
921
922
923
924
918
919
920
921
922
923
924

925
926
927
928
929
930
931
932







-
+







    /// </summary>
    /// <param name="i">The index of the column to retrieve</param>
    /// <returns>A SQLiteType structure</returns>
    private SQLiteType GetSQLiteType(int i)
    {
      if (_fieldTypeArray == null) _fieldTypeArray = new SQLiteType[VisibleFieldCount];

      if (_fieldTypeArray[i].Affinity == TypeAffinity.Uninitialized || _fieldTypeArray[i].Affinity == TypeAffinity.Null)
      if (_fieldTypeArray[i].Affinity == TypeAffinity.Uninitialized)
        _fieldTypeArray[i].Type = SQLiteConvert.TypeNameToDbType(_activeStatement._sql.ColumnType(_activeStatement, i, out _fieldTypeArray[i].Affinity));
      return _fieldTypeArray[i];
    }

    /// <summary>
    /// Reads the next row from the resultset
    /// </summary>
Changes to System.Data.SQLite/SQLiteStatement.cs.
221
222
223
224
225
226
227
228

229
230
231
232
233
234
235


236
237
238

239
240
241
242
243
244
245
246
247
248
221
222
223
224
225
226
227

228
229

230
231
232


233
234
235


236







237
238
239







-
+

-



-
-
+
+

-
-
+
-
-
-
-
-
-
-



    }

    internal void SetTypes(string typedefs)
    {
      int pos = typedefs.IndexOf("TYPES", 0, StringComparison.OrdinalIgnoreCase);
      if (pos == -1) throw new ArgumentOutOfRangeException();

      string[] types = typedefs.Substring(pos + 6).Replace(" ", "").Replace(";", "").Replace("\"", "").Replace("[", "").Replace("]", "").Split(',', '\r', '\n', '\t');
      string[] types = typedefs.Substring(pos + 6).Replace(" ", "").Replace(";", "").Replace("\"", "").Replace("[", "").Replace("]", "").Replace("`","").Split(',', '\r', '\n', '\t');

      int cols = 0;
      int n;
      for (n = 0; n < types.Length; n++)
      {
        if (String.IsNullOrEmpty(types[n]) == false)
          cols++;
        if (String.IsNullOrEmpty(types[n]) == true)
          types[n] = null;
      }

      _types = new string[cols];
      _types = types;

      cols = 0;
      for (n = 0; n < types.Length; n++)
      {
        if (String.IsNullOrEmpty(types[n]) == false)
          _types[cols++] = types[n];
      }
    }
  }
}