sqllogictest

Check-in [e2565741f0]
Login

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

Overview
Comment:Update the SQLite amalgamation to the latest from CVS.
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e2565741f0eb5e4aac860df637cc84ec53532428
User & Date: drh 2009-02-03 16:35:33.000
Context
2009-02-03
18:18
Add the "run-all.sh" script. Add the SQLITE_NO_SYNC option to the Makefile. Add the no-ODBC makefile. check-in: ec2223d775 user: drh tags: trunk
16:35
Update the SQLite amalgamation to the latest from CVS. check-in: e2565741f0 user: drh tags: trunk
2009-01-23
23:53
Added more 'commute' test cases. Added simple tests for DELETE. check-in: 6b97c59722 user: shaneh tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
Changes to src/sqlite3.c.
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
** the "sqlite3.h" header file at hand, you will find a copy in the first
** 6736 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 2009-01-16 15:02:40 UTC.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
#ifndef SQLITE_API







|







13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
** the "sqlite3.h" header file at hand, you will find a copy in the first
** 6736 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 2009-02-03 16:30:31 UTC.
*/
#define SQLITE_CORE 1
#define SQLITE_AMALGAMATION 1
#ifndef SQLITE_PRIVATE
# define SQLITE_PRIVATE static
#endif
#ifndef SQLITE_API
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
**    May you 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: sqliteInt.h,v 1.825 2009/01/15 17:40:43 drh Exp $
*/
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

/*
** Include the configuration header output by 'configure' if we're using the
** autoconf-based build







|







37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
**    May you 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: sqliteInt.h,v 1.830 2009/01/24 11:30:43 drh Exp $
*/
#ifndef _SQLITEINT_H_
#define _SQLITEINT_H_

/*
** Include the configuration header output by 'configure' if we're using the
** autoconf-based build
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
** 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: sqlite.h.in,v 1.421 2008/12/30 06:24:58 danielk1977 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++.







|







528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
** 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: sqlite.h.in,v 1.422 2009/01/23 16:45:01 danielk1977 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++.
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
**                SQLite is holding pinned pages that can be unpinned
**                by writing their contents to the database file (a
**                relatively expensive operation). In this situation the
**                cache implementation has two choices: it can return NULL,
**                in which case SQLite will attempt to unpin one or more 
**                pages before re-requesting the same page, or it can
**                allocate a new page and return a pointer to it. If a new
**                page is allocated, then it must be completely zeroed before 
**                it is returned.
**   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
**                pinned pages associated with the specific cache passed
**                as the first argument to xFetch() that can be unpinned. The
**                cache implementation should attempt to allocate a new
**                cache entry and return a pointer to it. Again, the new
**                page should be zeroed before it is returned. If the xFetch()
**                method returns NULL when createFlag==2, SQLite assumes that
**                a memory allocation failed and returns SQLITE_NOMEM to the
**                user.
** </table>
**
** xUnpin() is called by SQLite with a pointer to a currently pinned page
** as its second argument. If the third parameter, discard, is non-zero,
** then the page should be evicted from the cache. In this case SQLite 
** assumes that the next time the page is retrieved from the cache using
** the xFetch() method, it will be zeroed. If the discard parameter is







|
|




|
|
|
|
|







7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
**                SQLite is holding pinned pages that can be unpinned
**                by writing their contents to the database file (a
**                relatively expensive operation). In this situation the
**                cache implementation has two choices: it can return NULL,
**                in which case SQLite will attempt to unpin one or more 
**                pages before re-requesting the same page, or it can
**                allocate a new page and return a pointer to it. If a new
**                page is allocated, then the first sizeof(void*) bytes of
**                it (at least) must be zeroed before it is returned.
**   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
**                pinned pages associated with the specific cache passed
**                as the first argument to xFetch() that can be unpinned. The
**                cache implementation should attempt to allocate a new
**                cache entry and return a pointer to it. Again, the first
**                sizeof(void*) bytes of the page should be zeroed before 
**                it is returned. If the xFetch() method returns NULL when 
**                createFlag==2, SQLite assumes that a memory allocation 
**                failed and returns SQLITE_NOMEM to the user.
** </table>
**
** xUnpin() is called by SQLite with a pointer to a currently pinned page
** as its second argument. If the third parameter, discard, is non-zero,
** then the page should be evicted from the cache. In this case SQLite 
** assumes that the next time the page is retrieved from the cache using
** the xFetch() method, it will be zeroed. If the discard parameter is
7361
7362
7363
7364
7365
7366
7367

7368
7369

7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
#define TK_ID                             26
#define TK_ABORT                          27
#define TK_AFTER                          28
#define TK_ANALYZE                        29
#define TK_ASC                            30
#define TK_ATTACH                         31
#define TK_BEFORE                         32

#define TK_CASCADE                        33
#define TK_CAST                           34

#define TK_CONFLICT                       35
#define TK_DATABASE                       36
#define TK_DESC                           37
#define TK_DETACH                         38
#define TK_EACH                           39
#define TK_FAIL                           40
#define TK_FOR                            41
#define TK_IGNORE                         42
#define TK_INITIALLY                      43
#define TK_INSTEAD                        44
#define TK_LIKE_KW                        45
#define TK_MATCH                          46
#define TK_KEY                            47
#define TK_OF                             48
#define TK_OFFSET                         49
#define TK_PRAGMA                         50
#define TK_RAISE                          51
#define TK_REPLACE                        52
#define TK_RESTRICT                       53
#define TK_ROW                            54
#define TK_TRIGGER                        55
#define TK_VACUUM                         56
#define TK_VIEW                           57
#define TK_VIRTUAL                        58
#define TK_REINDEX                        59
#define TK_RENAME                         60
#define TK_CTIME_KW                       61
#define TK_ANY                            62
#define TK_OR                             63
#define TK_AND                            64
#define TK_IS                             65
#define TK_BETWEEN                        66
#define TK_IN                             67
#define TK_ISNULL                         68
#define TK_NOTNULL                        69
#define TK_NE                             70
#define TK_EQ                             71
#define TK_GT                             72
#define TK_LE                             73
#define TK_LT                             74
#define TK_GE                             75
#define TK_ESCAPE                         76
#define TK_BITAND                         77
#define TK_BITOR                          78
#define TK_LSHIFT                         79
#define TK_RSHIFT                         80
#define TK_PLUS                           81
#define TK_MINUS                          82
#define TK_STAR                           83
#define TK_SLASH                          84
#define TK_REM                            85
#define TK_CONCAT                         86
#define TK_COLLATE                        87
#define TK_UMINUS                         88
#define TK_UPLUS                          89
#define TK_BITNOT                         90
#define TK_STRING                         91
#define TK_JOIN_KW                        92
#define TK_CONSTRAINT                     93
#define TK_DEFAULT                        94
#define TK_NULL                           95
#define TK_PRIMARY                        96
#define TK_UNIQUE                         97
#define TK_CHECK                          98
#define TK_REFERENCES                     99
#define TK_AUTOINCR                       100
#define TK_ON                             101
#define TK_DELETE                         102
#define TK_UPDATE                         103
#define TK_INSERT                         104
#define TK_SET                            105
#define TK_DEFERRABLE                     106
#define TK_FOREIGN                        107
#define TK_DROP                           108
#define TK_UNION                          109
#define TK_ALL                            110
#define TK_EXCEPT                         111
#define TK_INTERSECT                      112
#define TK_SELECT                         113
#define TK_DISTINCT                       114
#define TK_DOT                            115
#define TK_FROM                           116
#define TK_JOIN                           117
#define TK_INDEXED                        118
#define TK_BY                             119
#define TK_USING                          120
#define TK_ORDER                          121
#define TK_GROUP                          122
#define TK_HAVING                         123
#define TK_LIMIT                          124
#define TK_WHERE                          125
#define TK_INTO                           126
#define TK_VALUES                         127
#define TK_INTEGER                        128
#define TK_FLOAT                          129
#define TK_BLOB                           130
#define TK_REGISTER                       131
#define TK_VARIABLE                       132
#define TK_CASE                           133
#define TK_WHEN                           134
#define TK_THEN                           135
#define TK_ELSE                           136
#define TK_INDEX                          137
#define TK_TO_TEXT                        138
#define TK_TO_BLOB                        139
#define TK_TO_NUMERIC                     140
#define TK_TO_INT                         141
#define TK_TO_REAL                        142
#define TK_END_OF_FILE                    143
#define TK_ILLEGAL                        144
#define TK_SPACE                          145
#define TK_UNCLOSED_STRING                146
#define TK_FUNCTION                       147
#define TK_COLUMN                         148
#define TK_AGG_FUNCTION                   149
#define TK_AGG_COLUMN                     150
#define TK_CONST_FUNC                     151

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







>
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455

7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
#define TK_ID                             26
#define TK_ABORT                          27
#define TK_AFTER                          28
#define TK_ANALYZE                        29
#define TK_ASC                            30
#define TK_ATTACH                         31
#define TK_BEFORE                         32
#define TK_BY                             33
#define TK_CASCADE                        34
#define TK_CAST                           35
#define TK_COLUMNKW                       36
#define TK_CONFLICT                       37
#define TK_DATABASE                       38
#define TK_DESC                           39
#define TK_DETACH                         40
#define TK_EACH                           41
#define TK_FAIL                           42
#define TK_FOR                            43
#define TK_IGNORE                         44
#define TK_INITIALLY                      45
#define TK_INSTEAD                        46
#define TK_LIKE_KW                        47
#define TK_MATCH                          48
#define TK_KEY                            49
#define TK_OF                             50
#define TK_OFFSET                         51
#define TK_PRAGMA                         52
#define TK_RAISE                          53
#define TK_REPLACE                        54
#define TK_RESTRICT                       55
#define TK_ROW                            56
#define TK_TRIGGER                        57
#define TK_VACUUM                         58
#define TK_VIEW                           59
#define TK_VIRTUAL                        60
#define TK_REINDEX                        61
#define TK_RENAME                         62
#define TK_CTIME_KW                       63
#define TK_ANY                            64
#define TK_OR                             65
#define TK_AND                            66
#define TK_IS                             67
#define TK_BETWEEN                        68
#define TK_IN                             69
#define TK_ISNULL                         70
#define TK_NOTNULL                        71
#define TK_NE                             72
#define TK_EQ                             73
#define TK_GT                             74
#define TK_LE                             75
#define TK_LT                             76
#define TK_GE                             77
#define TK_ESCAPE                         78
#define TK_BITAND                         79
#define TK_BITOR                          80
#define TK_LSHIFT                         81
#define TK_RSHIFT                         82
#define TK_PLUS                           83
#define TK_MINUS                          84
#define TK_STAR                           85
#define TK_SLASH                          86
#define TK_REM                            87
#define TK_CONCAT                         88
#define TK_COLLATE                        89
#define TK_UMINUS                         90
#define TK_UPLUS                          91
#define TK_BITNOT                         92
#define TK_STRING                         93
#define TK_JOIN_KW                        94
#define TK_CONSTRAINT                     95
#define TK_DEFAULT                        96
#define TK_NULL                           97
#define TK_PRIMARY                        98
#define TK_UNIQUE                         99
#define TK_CHECK                          100
#define TK_REFERENCES                     101
#define TK_AUTOINCR                       102
#define TK_ON                             103
#define TK_DELETE                         104
#define TK_UPDATE                         105
#define TK_INSERT                         106
#define TK_SET                            107
#define TK_DEFERRABLE                     108
#define TK_FOREIGN                        109
#define TK_DROP                           110
#define TK_UNION                          111
#define TK_ALL                            112
#define TK_EXCEPT                         113
#define TK_INTERSECT                      114
#define TK_SELECT                         115
#define TK_DISTINCT                       116
#define TK_DOT                            117
#define TK_FROM                           118
#define TK_JOIN                           119
#define TK_INDEXED                        120

#define TK_USING                          121
#define TK_ORDER                          122
#define TK_GROUP                          123
#define TK_HAVING                         124
#define TK_LIMIT                          125
#define TK_WHERE                          126
#define TK_INTO                           127
#define TK_VALUES                         128
#define TK_INTEGER                        129
#define TK_FLOAT                          130
#define TK_BLOB                           131
#define TK_REGISTER                       132
#define TK_VARIABLE                       133
#define TK_CASE                           134
#define TK_WHEN                           135
#define TK_THEN                           136
#define TK_ELSE                           137
#define TK_INDEX                          138
#define TK_TO_TEXT                        139
#define TK_TO_BLOB                        140
#define TK_TO_NUMERIC                     141
#define TK_TO_INT                         142
#define TK_TO_REAL                        143
#define TK_END_OF_FILE                    144
#define TK_ILLEGAL                        145
#define TK_SPACE                          146
#define TK_UNCLOSED_STRING                147
#define TK_FUNCTION                       148
#define TK_COLUMN                         149
#define TK_AGG_FUNCTION                   150
#define TK_AGG_COLUMN                     151
#define TK_CONST_FUNC                     152

/************** End of parse.h ***********************************************/
/************** Continuing where we left off in sqliteInt.h ******************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite B-Tree file
** subsystem.  See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: btree.h,v 1.106 2008/12/17 17:30:26 danielk1977 Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_

/* TODO: This definition is just included so other modules compile. It
** needs to be revisited.
*/







|







7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite B-Tree file
** subsystem.  See comments in the source code for a detailed description
** of what each interface routine does.
**
** @(#) $Id: btree.h,v 1.107 2009/01/24 11:30:43 drh Exp $
*/
#ifndef _BTREE_H_
#define _BTREE_H_

/* TODO: This definition is just included so other modules compile. It
** needs to be revisited.
*/
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
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);
SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);

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

SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);

/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
** of the following flags:







<







7896
7897
7898
7899
7900
7901
7902

7903
7904
7905
7906
7907
7908
7909
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);
SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);

SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);

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

SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);

/* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
** of the following flags:
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318

8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349

8350
8351
8352
8353
8354
8355
8356
/* Automatically generated.  Do not edit */
/* See the mkopcodeh.awk script for details */
#define OP_VNext                                1
#define OP_Affinity                             2
#define OP_Column                               3
#define OP_SetCookie                            4
#define OP_Seek                                 5
#define OP_Real                               129   /* same as TK_FLOAT    */
#define OP_Sequence                             6
#define OP_Savepoint                            7
#define OP_Ge                                  75   /* same as TK_GE       */
#define OP_RowKey                               8
#define OP_SCopy                                9
#define OP_Eq                                  71   /* same as TK_EQ       */
#define OP_OpenWrite                           10
#define OP_NotNull                             69   /* same as TK_NOTNULL  */
#define OP_If                                  11
#define OP_ToInt                              141   /* same as TK_TO_INT   */
#define OP_String8                             91   /* same as TK_STRING   */
#define OP_VRowid                              12
#define OP_CollSeq                             13
#define OP_OpenRead                            14
#define OP_Expire                              15
#define OP_AutoCommit                          16
#define OP_Gt                                  72   /* same as TK_GT       */
#define OP_Pagecount                           17
#define OP_IntegrityCk                         18
#define OP_Sort                                20
#define OP_Copy                                21
#define OP_Trace                               22
#define OP_Function                            23
#define OP_IfNeg                               24
#define OP_And                                 64   /* same as TK_AND      */
#define OP_Subtract                            82   /* same as TK_MINUS    */
#define OP_Noop                                25
#define OP_Return                              26
#define OP_Remainder                           85   /* same as TK_REM      */
#define OP_NewRowid                            27
#define OP_Multiply                            83   /* same as TK_STAR     */
#define OP_Variable                            28
#define OP_String                              29
#define OP_RealAffinity                        30
#define OP_VRename                             31
#define OP_ParseSchema                         32
#define OP_VOpen                               33
#define OP_Close                               34
#define OP_CreateIndex                         35
#define OP_IsUnique                            36
#define OP_NotFound                            37
#define OP_Int64                               38
#define OP_MustBeInt                           39
#define OP_Halt                                40
#define OP_Rowid                               41
#define OP_IdxLT                               42
#define OP_AddImm                              43
#define OP_Statement                           44
#define OP_RowData                             45
#define OP_MemMax                              46
#define OP_Or                                  63   /* same as TK_OR       */
#define OP_NotExists                           47
#define OP_Gosub                               48
#define OP_Divide                              84   /* same as TK_SLASH    */
#define OP_Integer                             49
#define OP_ToNumeric                          140   /* same as TK_TO_NUMERIC*/
#define OP_Prev                                50
#define OP_RowSetRead                          51
#define OP_Concat                              86   /* same as TK_CONCAT   */
#define OP_RowSetAdd                           52
#define OP_BitAnd                              77   /* same as TK_BITAND   */
#define OP_VColumn                             53
#define OP_CreateTable                         54
#define OP_Last                                55
#define OP_SeekLe                              56
#define OP_IsNull                              68   /* same as TK_ISNULL   */
#define OP_IncrVacuum                          57
#define OP_IdxRowid                            58
#define OP_ShiftRight                          80   /* same as TK_RSHIFT   */
#define OP_ResetCount                          59
#define OP_ContextPush                         60
#define OP_Yield                               61
#define OP_DropTrigger                         62
#define OP_DropIndex                           65
#define OP_IdxGE                               66
#define OP_IdxDelete                           67
#define OP_Vacuum                              76
#define OP_IfNot                               87
#define OP_DropTable                           88
#define OP_SeekLt                              89
#define OP_MakeRecord                          92
#define OP_ToBlob                             139   /* same as TK_TO_BLOB  */
#define OP_ResultRow                           93
#define OP_Delete                              94
#define OP_AggFinal                            95
#define OP_Compare                             96
#define OP_ShiftLeft                           79   /* same as TK_LSHIFT   */
#define OP_Goto                                97
#define OP_TableLock                           98
#define OP_Clear                               99
#define OP_Le                                  73   /* same as TK_LE       */
#define OP_VerifyCookie                       100
#define OP_AggStep                            101
#define OP_ToText                             138   /* same as TK_TO_TEXT  */
#define OP_Not                                 19   /* same as TK_NOT      */
#define OP_ToReal                             142   /* same as TK_TO_REAL  */
#define OP_SetNumColumns                      102
#define OP_Transaction                        103
#define OP_VFilter                            104
#define OP_Ne                                  70   /* same as TK_NE       */
#define OP_VDestroy                           105
#define OP_ContextPop                         106
#define OP_BitOr                               78   /* same as TK_BITOR    */
#define OP_Next                               107
#define OP_IdxInsert                          108
#define OP_Lt                                  74   /* same as TK_LT       */
#define OP_SeekGe                             109
#define OP_Insert                             110
#define OP_Destroy                            111
#define OP_ReadCookie                         112
#define OP_LoadAnalysis                       113
#define OP_Explain                            114
#define OP_OpenPseudo                         115
#define OP_OpenEphemeral                      116
#define OP_Null                               117
#define OP_Move                               118
#define OP_Blob                               119
#define OP_Add                                 81   /* same as TK_PLUS     */
#define OP_Rewind                             120
#define OP_SeekGt                             121
#define OP_VBegin                             122
#define OP_VUpdate                            123
#define OP_IfZero                             124
#define OP_BitNot                              90   /* same as TK_BITNOT   */
#define OP_VCreate                            125
#define OP_Found                              126
#define OP_IfPos                              127
#define OP_NullRow                            128
#define OP_Jump                               130
#define OP_Permutation                        131

/* The following opcode values are never used */
#define OP_NotUsed_132                        132
#define OP_NotUsed_133                        133
#define OP_NotUsed_134                        134
#define OP_NotUsed_135                        135
#define OP_NotUsed_136                        136
#define OP_NotUsed_137                        137



/* Properties such as "out2" or "jump" that are specified in
** comments following the "case" for each opcode in the vdbe.c
** are encoded into bitvectors as follows:
*/
#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
#define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
#define OPFLG_INITIALIZER {\
/*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
/*   8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
/*  16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
/*  24 */ 0x05, 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00,\
/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
/*  40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
/*  48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
/*  56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x2c,\
/*  64 */ 0x2c, 0x00, 0x11, 0x00, 0x05, 0x05, 0x15, 0x15,\
/*  72 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x2c, 0x2c, 0x2c,\
/*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x05,\
/*  88 */ 0x00, 0x11, 0x04, 0x02, 0x00, 0x00, 0x00, 0x00,\
/*  96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 104 */ 0x01, 0x00, 0x00, 0x01, 0x08, 0x11, 0x00, 0x02,\
/* 112 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02,\
/* 120 */ 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x05,\
/* 128 */ 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 136 */ 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,}


/************** 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.







|


|


|

|

|
|





|







|
|


|

|



















|


|

|


|

|




|


|




|
|

|
|
|

|
|
|



|



|


|

|



|


|


|











|





|




|









>




















|
|
|
|
|




|
|
>







8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
/* Automatically generated.  Do not edit */
/* See the mkopcodeh.awk script for details */
#define OP_VNext                                1
#define OP_Affinity                             2
#define OP_Column                               3
#define OP_SetCookie                            4
#define OP_Seek                                 5
#define OP_Real                               130   /* same as TK_FLOAT    */
#define OP_Sequence                             6
#define OP_Savepoint                            7
#define OP_Ge                                  77   /* same as TK_GE       */
#define OP_RowKey                               8
#define OP_SCopy                                9
#define OP_Eq                                  73   /* same as TK_EQ       */
#define OP_OpenWrite                           10
#define OP_NotNull                             71   /* same as TK_NOTNULL  */
#define OP_If                                  11
#define OP_ToInt                              142   /* same as TK_TO_INT   */
#define OP_String8                             93   /* same as TK_STRING   */
#define OP_VRowid                              12
#define OP_CollSeq                             13
#define OP_OpenRead                            14
#define OP_Expire                              15
#define OP_AutoCommit                          16
#define OP_Gt                                  74   /* same as TK_GT       */
#define OP_Pagecount                           17
#define OP_IntegrityCk                         18
#define OP_Sort                                20
#define OP_Copy                                21
#define OP_Trace                               22
#define OP_Function                            23
#define OP_IfNeg                               24
#define OP_And                                 66   /* same as TK_AND      */
#define OP_Subtract                            84   /* same as TK_MINUS    */
#define OP_Noop                                25
#define OP_Return                              26
#define OP_Remainder                           87   /* same as TK_REM      */
#define OP_NewRowid                            27
#define OP_Multiply                            85   /* same as TK_STAR     */
#define OP_Variable                            28
#define OP_String                              29
#define OP_RealAffinity                        30
#define OP_VRename                             31
#define OP_ParseSchema                         32
#define OP_VOpen                               33
#define OP_Close                               34
#define OP_CreateIndex                         35
#define OP_IsUnique                            36
#define OP_NotFound                            37
#define OP_Int64                               38
#define OP_MustBeInt                           39
#define OP_Halt                                40
#define OP_Rowid                               41
#define OP_IdxLT                               42
#define OP_AddImm                              43
#define OP_Statement                           44
#define OP_RowData                             45
#define OP_MemMax                              46
#define OP_Or                                  65   /* same as TK_OR       */
#define OP_NotExists                           47
#define OP_Gosub                               48
#define OP_Divide                              86   /* same as TK_SLASH    */
#define OP_Integer                             49
#define OP_ToNumeric                          141   /* same as TK_TO_NUMERIC*/
#define OP_Prev                                50
#define OP_RowSetRead                          51
#define OP_Concat                              88   /* same as TK_CONCAT   */
#define OP_RowSetAdd                           52
#define OP_BitAnd                              79   /* same as TK_BITAND   */
#define OP_VColumn                             53
#define OP_CreateTable                         54
#define OP_Last                                55
#define OP_SeekLe                              56
#define OP_IsNull                              70   /* same as TK_ISNULL   */
#define OP_IncrVacuum                          57
#define OP_IdxRowid                            58
#define OP_ShiftRight                          82   /* same as TK_RSHIFT   */
#define OP_ResetCount                          59
#define OP_ContextPush                         60
#define OP_Yield                               61
#define OP_DropTrigger                         62
#define OP_DropIndex                           63
#define OP_IdxGE                               64
#define OP_IdxDelete                           67
#define OP_Vacuum                              68
#define OP_IfNot                               69
#define OP_DropTable                           78
#define OP_SeekLt                              89
#define OP_MakeRecord                          90
#define OP_ToBlob                             140   /* same as TK_TO_BLOB  */
#define OP_ResultRow                           91
#define OP_Delete                              94
#define OP_AggFinal                            95
#define OP_Compare                             96
#define OP_ShiftLeft                           81   /* same as TK_LSHIFT   */
#define OP_Goto                                97
#define OP_TableLock                           98
#define OP_Clear                               99
#define OP_Le                                  75   /* same as TK_LE       */
#define OP_VerifyCookie                       100
#define OP_AggStep                            101
#define OP_ToText                             139   /* same as TK_TO_TEXT  */
#define OP_Not                                 19   /* same as TK_NOT      */
#define OP_ToReal                             143   /* same as TK_TO_REAL  */
#define OP_SetNumColumns                      102
#define OP_Transaction                        103
#define OP_VFilter                            104
#define OP_Ne                                  72   /* same as TK_NE       */
#define OP_VDestroy                           105
#define OP_ContextPop                         106
#define OP_BitOr                               80   /* same as TK_BITOR    */
#define OP_Next                               107
#define OP_IdxInsert                          108
#define OP_Lt                                  76   /* same as TK_LT       */
#define OP_SeekGe                             109
#define OP_Insert                             110
#define OP_Destroy                            111
#define OP_ReadCookie                         112
#define OP_LoadAnalysis                       113
#define OP_Explain                            114
#define OP_OpenPseudo                         115
#define OP_OpenEphemeral                      116
#define OP_Null                               117
#define OP_Move                               118
#define OP_Blob                               119
#define OP_Add                                 83   /* same as TK_PLUS     */
#define OP_Rewind                             120
#define OP_SeekGt                             121
#define OP_VBegin                             122
#define OP_VUpdate                            123
#define OP_IfZero                             124
#define OP_BitNot                              92   /* same as TK_BITNOT   */
#define OP_VCreate                            125
#define OP_Found                              126
#define OP_IfPos                              127
#define OP_NullRow                            128
#define OP_Jump                               129
#define OP_Permutation                        131

/* The following opcode values are never used */
#define OP_NotUsed_132                        132
#define OP_NotUsed_133                        133
#define OP_NotUsed_134                        134
#define OP_NotUsed_135                        135
#define OP_NotUsed_136                        136
#define OP_NotUsed_137                        137
#define OP_NotUsed_138                        138


/* Properties such as "out2" or "jump" that are specified in
** comments following the "case" for each opcode in the vdbe.c
** are encoded into bitvectors as follows:
*/
#define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
#define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
#define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
#define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
#define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
#define OPFLG_OUT3            0x0020  /* out3:  P3 is an output */
#define OPFLG_INITIALIZER {\
/*   0 */ 0x00, 0x01, 0x00, 0x00, 0x10, 0x08, 0x02, 0x00,\
/*   8 */ 0x00, 0x04, 0x00, 0x05, 0x02, 0x00, 0x00, 0x00,\
/*  16 */ 0x00, 0x02, 0x00, 0x04, 0x01, 0x04, 0x00, 0x00,\
/*  24 */ 0x05, 0x00, 0x04, 0x02, 0x02, 0x02, 0x04, 0x00,\
/*  32 */ 0x00, 0x00, 0x00, 0x02, 0x11, 0x11, 0x02, 0x05,\
/*  40 */ 0x00, 0x02, 0x11, 0x04, 0x00, 0x00, 0x0c, 0x11,\
/*  48 */ 0x01, 0x02, 0x01, 0x21, 0x08, 0x00, 0x02, 0x01,\
/*  56 */ 0x11, 0x01, 0x02, 0x00, 0x00, 0x04, 0x00, 0x00,\
/*  64 */ 0x11, 0x2c, 0x2c, 0x00, 0x00, 0x05, 0x05, 0x05,\
/*  72 */ 0x15, 0x15, 0x15, 0x15, 0x15, 0x15, 0x00, 0x2c,\
/*  80 */ 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c, 0x2c,\
/*  88 */ 0x2c, 0x11, 0x00, 0x00, 0x04, 0x02, 0x00, 0x00,\
/*  96 */ 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 104 */ 0x01, 0x00, 0x00, 0x01, 0x08, 0x11, 0x00, 0x02,\
/* 112 */ 0x02, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02,\
/* 120 */ 0x01, 0x11, 0x00, 0x00, 0x05, 0x00, 0x11, 0x05,\
/* 128 */ 0x00, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,\
/* 136 */ 0x00, 0x00, 0x00, 0x04, 0x04, 0x04, 0x04, 0x04,\
}

/************** 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.
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439

8440
8441
8442
8443
8444
8445
8446
8447
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem.  The page cache subsystem reads and writes a file a page
** at a time and provides a journal for rollback.
**
** @(#) $Id: pager.h,v 1.93 2009/01/07 15:18:21 danielk1977 Exp $
*/

#ifndef _PAGER_H_
#define _PAGER_H_

/*
** If defined as non-zero, auto-vacuum is enabled by default. Otherwise

** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
*/
#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
#endif

/*
** The type used to represent a page number.  The first page in a file







|






|
>
|







8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem.  The page cache subsystem reads and writes a file a page
** at a time and provides a journal for rollback.
**
** @(#) $Id: pager.h,v 1.99 2009/01/31 14:54:07 danielk1977 Exp $
*/

#ifndef _PAGER_H_
#define _PAGER_H_

/*
** Default maximum size for persistent journal files. A negative 
** value means no limit. This value may be overridden using the 
** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
*/
#ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
#endif

/*
** The type used to represent a page number.  The first page in a file
8455
8456
8457
8458
8459
8460
8461










8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
typedef struct Pager Pager;

/*
** Handle type for pages.
*/
typedef struct PgHdr DbPage;











/*
** Allowed values for the flags parameter to sqlite3PagerOpen().
**
** NOTE: This values must match the corresponding BTREE_ values in btree.h.
*/
#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */

/*
** Valid values for the second argument to sqlite3PagerLockingMode().
*/







>
>
>
>
>
>
>
>
>
>



|







8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
typedef struct Pager Pager;

/*
** Handle type for pages.
*/
typedef struct PgHdr DbPage;

/*
** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
** reserved for working around a windows/posix incompatibility). It is
** used in the journal to signify that the remainder of the journal file 
** is devoted to storing a master journal name - there are no more pages to
** roll back. See comments for function writeMasterJournal() in pager.c 
** for details.
*/
#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))

/*
** Allowed values for the flags parameter to sqlite3PagerOpen().
**
** NOTE: These values must match the corresponding BTREE_ values in btree.h.
*/
#define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
#define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */

/*
** Valid values for the second argument to sqlite3PagerLockingMode().
*/
8481
8482
8483
8484
8485
8486
8487

8488
8489
8490


8491




8492
8493
8494
8495
8496
8497
8498




8499
8500
8501


8502

8503

8504
8505




8506
8507
8508

8509
8510




8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538

8539
8540
8541
8542

8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */

/*

** See source code comments for a detailed description of the following
** routines:
*/


SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);




SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
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)
SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);


SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);

SQLITE_PRIVATE int sqlite3PagerRef(DbPage*);

SQLITE_PRIVATE int sqlite3PagerUnref(DbPage*);
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);




SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
SQLITE_PRIVATE int sqlite3PagerBegin(DbPage*, int exFlag);
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);

SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);




SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage*);
SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage*);
SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(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,int);
SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);

SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);

#ifndef SQLITE_OMIT_AUTOVACUUM
SQLITE_PRIVATE   void sqlite3PagerTruncateImage(Pager*,Pgno);
SQLITE_PRIVATE   Pgno sqlite3PagerImageSize(Pager *);
#endif


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


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

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

#ifdef SQLITE_TEST
void disable_simulated_io_errors(void);
void enable_simulated_io_errors(void);
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

#endif /* _PAGER_H_ */








>
|
|

>
>

>
>
>
>




|
|
|
>
>
>
>



>
>
|
>
|
>
|
|
>
>
>
>

|

>


>
>
>
>

<
<

<



<


<
<
<
<
<
<

<

<
<
|
<
|
<
<

>




>




<




<
<
<
|
|







8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548


8549

8550
8551
8552

8553
8554






8555

8556


8557

8558


8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569

8570
8571
8572
8573



8574
8575
8576
8577
8578
8579
8580
8581
8582
#define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
#define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
#define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
#define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
#define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */

/*
** The remainder of this file contains the declarations of the functions
** that make up the Pager sub-system API. See source code comments for 
** a detailed description of each routine.
*/

/* Open and close a Pager connection. */ 
SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char*, int,int,int);
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);

/* Functions used to configure a Pager object. */
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager*, void(*)(DbPage*));
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*);
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);

/* Functions used to obtain and release page references. */ 
SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
#define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);

/* Operations on page references. */
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 

/* Functions used to manage pager transactions and savepoints. */
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag);
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);

/* Functions used to query pager state and configuration. */
SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);


SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);

SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);

SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);






SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);




/* Functions used to truncate the database file. */

SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);



/* Used by encryption extensions. */
#ifdef SQLITE_HAS_CODEC
SQLITE_PRIVATE   void sqlite3PagerSetCodec(Pager*,void*(*)(void*,void*,Pgno,int),void*);
#endif

/* Functions to support testing and debugging. */
#if !defined(NDEBUG) || defined(SQLITE_TEST)
SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
#endif

#ifdef SQLITE_TEST
SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
SQLITE_PRIVATE   int sqlite3PagerIsMemdb(Pager*);



  void disable_simulated_io_errors(void);
  void enable_simulated_io_errors(void);
#else
# define disable_simulated_io_errors()
# define enable_simulated_io_errors()
#endif

#endif /* _PAGER_H_ */

8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem. 
**
** @(#) $Id: pcache.h,v 1.16 2008/11/19 16:52:44 danielk1977 Exp $
*/

#ifndef _PCACHE_H_

typedef struct PgHdr PgHdr;
typedef struct PCache PCache;








|







8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This header file defines the interface that the sqlite page cache
** subsystem. 
**
** @(#) $Id: pcache.h,v 1.19 2009/01/20 17:06:27 danielk1977 Exp $
*/

#ifndef _PCACHE_H_

typedef struct PgHdr PgHdr;
typedef struct PCache PCache;

8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
/* Reset and close the cache object */
SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);

/* Clear flags from pages of the page cache */
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
SQLITE_PRIVATE int sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);








|







8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
/* Reset and close the cache object */
SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);

/* Clear flags from pages of the page cache */
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);

/* Discard the contents of the cache */
SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);

/* Return the total number of outstanding page references */
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);

/* Increment the reference count of an existing page */
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);

8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);

/*







|







9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
#ifndef SQLITE_OMIT_LOAD_EXTENSION
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);

/*
10640
10641
10642
10643
10644
10645
10646
























10647
10648
10649
10650
10651
10652
10653
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE   int sqlite3Corrupt(void);
# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
#else
# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
#endif

























/*
** Internal function prototypes
*/
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);
SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE   int sqlite3Corrupt(void);
# define SQLITE_CORRUPT_BKPT sqlite3Corrupt()
#else
# define SQLITE_CORRUPT_BKPT SQLITE_CORRUPT
#endif

/*
** The following macros mimic the standard library functions toupper(),
** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
** sqlite versions only work for ASCII characters, regardless of locale.
*/
#ifdef SQLITE_ASCII
# define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
# define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
# define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
# define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
# define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
# define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
# define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
#else
# include <ctype.h>
# define sqlite3Toupper(x)   toupper((unsigned char)(x))
# define sqlite3Isspace(x)   isspace((unsigned char)(x))
# define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
# define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
# define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
# define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
# define sqlite3Tolower(x)   tolower((unsigned char)(x))
#endif

/*
** Internal function prototypes
*/
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);
SQLITE_PRIVATE int sqlite3Strlen(sqlite3*, const char*);
10748
10749
10750
10751
10752
10753
10754

10755
10756
10757
10758
10759
10760
10761
SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);

SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);

SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);

SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);








>







10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);

SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32);
SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);

SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);

10996
10997
10998
10999
11000
11001
11002

11003
11004
11005
11006
11007
11008
11009
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
#ifndef SQLITE_AMALGAMATION
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];

SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
#endif
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*);







>







11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int);
SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
#ifndef SQLITE_AMALGAMATION
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
#endif
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*);
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains definitions of global variables and contants.
**
** $Id: global.c,v 1.9 2008/12/08 18:19:18 drh Exp $
*/


/* An array to map all upper-case characters into their corresponding
** lower-case character. 
**
** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not







|







11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains definitions of global variables and contants.
**
** $Id: global.c,v 1.11 2009/01/24 11:30:43 drh Exp $
*/


/* An array to map all upper-case characters into their corresponding
** lower-case character. 
**
** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
11236
11237
11238
11239
11240
11241
11242


































































11243
11244
11245
11246
11247
11248
11249
    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
#endif
};



































































/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
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
    176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
    192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
    208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
    224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
    239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
#endif
};

/*
** The following 256 byte lookup table is used to support SQLites built-in
** equivalents to the following standard library functions:
**
**   isspace()                        0x01
**   isalpha()                        0x02
**   isdigit()                        0x04
**   isalnum()                        0x06
**   isxdigit()                       0x08
**   toupper()                        0x20
**
** Bit 0x20 is set if the mapped character requires translation to upper
** case. i.e. if the character is a lower-case ASCII character.
** If x is a lower-case ASCII character, then its upper-case equivalent
** is (x - 0x20). Therefore toupper() can be implemented as:
**
**   (x & ~(map[x]&0x20))
**
** Standard function tolower() is implemented using the sqlite3UpperToLower[]
** array. tolower() is used more often than toupper() by SQLite.
**
** SQLite's versions are identical to the standard versions assuming a
** locale of "C". They are implemented as macros in sqliteInt.h.
*/
#ifdef SQLITE_ASCII
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
  0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */

  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
  0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 58..5f    XYZ[\]^_ */
  0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */

  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 80..87    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 88..8f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 90..97    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 98..9f    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a0..a7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* a8..af    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b0..b7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* b8..bf    ........ */

  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c0..c7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* c8..cf    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d0..d7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* d8..df    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e0..e7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* e8..ef    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* f0..f7    ........ */
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00   /* f8..ff    ........ */
};
#endif



/*
** The following singleton contains the global configuration for
** the SQLite library.
*/
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
   SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: date.c,v 1.99 2008/12/20 13:18:50 drh Exp $
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system. 
**
** 1970-01-01 00:00:00 is JD 2440587.5







|







11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
** This file contains the C functions that implement date and time
** functions for SQLite.  
**
** There is only one exported symbol in this file - the function
** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
** All other code has file scope.
**
** $Id: date.c,v 1.102 2009/01/30 17:27:44 drh Exp $
**
** SQLite processes all times and dates as Julian Day numbers.  The
** dates and times are stored as the number of days since noon
** in Greenwich on November 24, 4714 B.C. according to the Gregorian
** calendar system. 
**
** 1970-01-01 00:00:00 is JD 2440587.5
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
**
**      Jean Meeus
**      Astronomical Algorithms, 2nd Edition, 1998
**      ISBM 0-943396-61-1
**      Willmann-Bell, Inc
**      Richmond, Virginia (USA)
*/
#include <ctype.h>
#include <time.h>

#ifndef SQLITE_OMIT_DATETIME_FUNCS

/*
** On recent Windows platforms, the localtime_s() function is available
** as part of the "Secure CRT". It is essentially equivalent to 







<







11562
11563
11564
11565
11566
11567
11568

11569
11570
11571
11572
11573
11574
11575
**
**      Jean Meeus
**      Astronomical Algorithms, 2nd Edition, 1998
**      ISBM 0-943396-61-1
**      Willmann-Bell, Inc
**      Richmond, Virginia (USA)
*/

#include <time.h>

#ifndef SQLITE_OMIT_DATETIME_FUNCS

/*
** On recent Windows platforms, the localtime_s() function is available
** as part of the "Secure CRT". It is essentially equivalent to 
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
    N = va_arg(ap, int);
    min = va_arg(ap, int);
    max = va_arg(ap, int);
    nextC = va_arg(ap, int);
    pVal = va_arg(ap, int*);
    val = 0;
    while( N-- ){
      if( !isdigit(*(u8*)zDate) ){
        goto end_getDigits;
      }
      val = val*10 + *zDate - '0';
      zDate++;
    }
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
      goto end_getDigits;







|







11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
    N = va_arg(ap, int);
    min = va_arg(ap, int);
    max = va_arg(ap, int);
    nextC = va_arg(ap, int);
    pVal = va_arg(ap, int*);
    val = 0;
    while( N-- ){
      if( !sqlite3Isdigit(*zDate) ){
        goto end_getDigits;
      }
      val = val*10 + *zDate - '0';
      zDate++;
    }
    if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
      goto end_getDigits;
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
**
** A missing specifier is not considered an error.
*/
static int parseTimezone(const char *zDate, DateTime *p){
  int sgn = 0;
  int nHr, nMn;
  int c;
  while( isspace(*(u8*)zDate) ){ zDate++; }
  p->tz = 0;
  c = *zDate;
  if( c=='-' ){
    sgn = -1;
  }else if( c=='+' ){
    sgn = +1;
  }else if( c=='Z' || c=='z' ){
    zDate++;
    goto zulu_time;
  }else{
    return c!=0;
  }
  zDate++;
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
    return 1;
  }
  zDate += 5;
  p->tz = sgn*(nMn + nHr*60);
zulu_time:
  while( isspace(*(u8*)zDate) ){ zDate++; }
  return *zDate!=0;
}

/*
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
** The HH, MM, and SS must each be exactly 2 digits.  The
** fractional seconds FFFF can be one or more digits.







|



















|







11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
**
** A missing specifier is not considered an error.
*/
static int parseTimezone(const char *zDate, DateTime *p){
  int sgn = 0;
  int nHr, nMn;
  int c;
  while( sqlite3Isspace(*zDate) ){ zDate++; }
  p->tz = 0;
  c = *zDate;
  if( c=='-' ){
    sgn = -1;
  }else if( c=='+' ){
    sgn = +1;
  }else if( c=='Z' || c=='z' ){
    zDate++;
    goto zulu_time;
  }else{
    return c!=0;
  }
  zDate++;
  if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
    return 1;
  }
  zDate += 5;
  p->tz = sgn*(nMn + nHr*60);
zulu_time:
  while( sqlite3Isspace(*zDate) ){ zDate++; }
  return *zDate!=0;
}

/*
** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
** The HH, MM, and SS must each be exactly 2 digits.  The
** fractional seconds FFFF can be one or more digits.
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
  zDate += 5;
  if( *zDate==':' ){
    zDate++;
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
      return 1;
    }
    zDate += 2;
    if( *zDate=='.' && isdigit((u8)zDate[1]) ){
      double rScale = 1.0;
      zDate++;
      while( isdigit(*(u8*)zDate) ){
        ms = ms*10.0 + *zDate - '0';
        rScale *= 10.0;
        zDate++;
      }
      ms /= rScale;
    }
  }else{







|


|







11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
  zDate += 5;
  if( *zDate==':' ){
    zDate++;
    if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
      return 1;
    }
    zDate += 2;
    if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
      double rScale = 1.0;
      zDate++;
      while( sqlite3Isdigit(*zDate) ){
        ms = ms*10.0 + *zDate - '0';
        rScale *= 10.0;
        zDate++;
      }
      ms /= rScale;
    }
  }else{
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
  }else{
    neg = 0;
  }
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
    return 1;
  }
  zDate += 10;
  while( isspace(*(u8*)zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  if( parseHhMmSs(zDate, p)==0 ){
    /* We got the time */
  }else if( *zDate==0 ){
    p->validHMS = 0;
  }else{
    return 1;
  }







|







11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
  }else{
    neg = 0;
  }
  if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
    return 1;
  }
  zDate += 10;
  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  if( parseHhMmSs(zDate, p)==0 ){
    /* We got the time */
  }else if( *zDate==0 ){
    p->validHMS = 0;
  }else{
    return 1;
  }
12033
12034
12035
12036
12037
12038
12039

12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071

12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093

12094
12095
12096
12097



12098
12099
12100
12101
12102
12103
12104
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': {

      n = getValue(z, &r);
      assert( n>=1 );
      if( z[n]==':' ){
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
        ** specified number of hours, minutes, seconds, and fractional seconds
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
        ** omitted.
        */
        const char *z2 = z;
        DateTime tx;
        sqlite3_int64 day;
        if( !isdigit(*(u8*)z2) ) z2++;
        memset(&tx, 0, sizeof(tx));
        if( parseHhMmSs(z2, &tx) ) break;
        computeJD(&tx);
        tx.iJD -= 43200000;
        day = tx.iJD/86400000;
        tx.iJD -= day*86400000;
        if( z[0]=='-' ) tx.iJD = -tx.iJD;
        computeJD(p);
        clearYMD_HMS_TZ(p);
        p->iJD += tx.iJD;
        rc = 0;
        break;
      }
      z += n;
      while( isspace(*(u8*)z) ) z++;
      n = sqlite3Strlen30(z);
      if( n>10 || n<3 ) break;
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
      computeJD(p);
      rc = 0;

      if( n==3 && strcmp(z,"day")==0 ){
        p->iJD += (sqlite3_int64)(r*86400000.0 + 0.5);
      }else if( n==4 && strcmp(z,"hour")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + 0.5);
      }else if( n==6 && strcmp(z,"minute")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + 0.5);
      }else if( n==6 && strcmp(z,"second")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + 0.5);
      }else if( n==5 && strcmp(z,"month")==0 ){
        int x, y;
        computeYMD_HMS(p);
        p->M += (int)r;
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
        p->Y += x;
        p->M -= x*12;
        p->validJD = 0;
        computeJD(p);
        y = (int)r;
        if( y!=r ){
          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + 0.5);
        }
      }else if( n==4 && strcmp(z,"year")==0 ){

        computeYMD_HMS(p);
        p->Y += (int)r;
        p->validJD = 0;
        computeJD(p);



      }else{
        rc = 1;
      }
      clearYMD_HMS_TZ(p);
      break;
    }
    default: {







>











|














|





>

|

|

|

|











|


>

|


>
>
>







12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
    case '3':
    case '4':
    case '5':
    case '6':
    case '7':
    case '8':
    case '9': {
      double rRounder;
      n = getValue(z, &r);
      assert( n>=1 );
      if( z[n]==':' ){
        /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
        ** specified number of hours, minutes, seconds, and fractional seconds
        ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
        ** omitted.
        */
        const char *z2 = z;
        DateTime tx;
        sqlite3_int64 day;
        if( !sqlite3Isdigit(*z2) ) z2++;
        memset(&tx, 0, sizeof(tx));
        if( parseHhMmSs(z2, &tx) ) break;
        computeJD(&tx);
        tx.iJD -= 43200000;
        day = tx.iJD/86400000;
        tx.iJD -= day*86400000;
        if( z[0]=='-' ) tx.iJD = -tx.iJD;
        computeJD(p);
        clearYMD_HMS_TZ(p);
        p->iJD += tx.iJD;
        rc = 0;
        break;
      }
      z += n;
      while( sqlite3Isspace(*z) ) z++;
      n = sqlite3Strlen30(z);
      if( n>10 || n<3 ) break;
      if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
      computeJD(p);
      rc = 0;
      rRounder = r<0 ? -0.5 : +0.5;
      if( n==3 && strcmp(z,"day")==0 ){
        p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
      }else if( n==4 && strcmp(z,"hour")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
      }else if( n==6 && strcmp(z,"minute")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
      }else if( n==6 && strcmp(z,"second")==0 ){
        p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
      }else if( n==5 && strcmp(z,"month")==0 ){
        int x, y;
        computeYMD_HMS(p);
        p->M += (int)r;
        x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
        p->Y += x;
        p->M -= x*12;
        p->validJD = 0;
        computeJD(p);
        y = (int)r;
        if( y!=r ){
          p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
        }
      }else if( n==4 && strcmp(z,"year")==0 ){
        int y = (int)r;
        computeYMD_HMS(p);
        p->Y += y;
        p->validJD = 0;
        computeJD(p);
        if( y!=r ){
          p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
        }
      }else{
        rc = 1;
      }
      clearYMD_HMS_TZ(p);
      break;
    }
    default: {
12290
12291
12292
12293
12294
12295
12296




12297
12298
12299
12300
12301
12302
12303
          break;
        default:
          return;  /* ERROR.  return a NULL */
      }
      i++;
    }
  }




  if( n<sizeof(zBuf) ){
    z = zBuf;
  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(context);
    return;
  }else{
    z = sqlite3DbMallocRaw(db, (int)n);







>
>
>
>







12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
          break;
        default:
          return;  /* ERROR.  return a NULL */
      }
      i++;
    }
  }
  testcase( n==sizeof(zBuf)-1 );
  testcase( n==sizeof(zBuf) );
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  if( n<sizeof(zBuf) ){
    z = zBuf;
  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
    sqlite3_result_error_toobig(context);
    return;
  }else{
    z = sqlite3DbMallocRaw(db, (int)n);
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
#ifndef SQLITE_OMIT_LOAD_EXTENSION
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return pVfs->xDlOpen(pVfs, zPath);
}
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  pVfs->xDlError(pVfs, nByte, zBufOut);
}
void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  return pVfs->xDlSym(pVfs, pHdle, zSym);
}
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  pVfs->xDlClose(pVfs, pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){







|







12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
#ifndef SQLITE_OMIT_LOAD_EXTENSION
SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  return pVfs->xDlOpen(pVfs, zPath);
}
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  pVfs->xDlError(pVfs, nByte, zBufOut);
}
SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  return pVfs->xDlSym(pVfs, pHdle, zSym);
}
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  pVfs->xDlClose(pVfs, pHandle);
}
#endif /* SQLITE_OMIT_LOAD_EXTENSION */
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for win32
**
** $Id: mutex_w32.c,v 1.13 2008/12/08 18:19:18 drh Exp $
*/

/*
** The code in this file is only used if we are compiling multithreaded
** on a win32 system.
*/
#ifdef SQLITE_MUTEX_W32







|







15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the C functions that implement mutexes for win32
**
** $Id: mutex_w32.c,v 1.15 2009/01/30 16:09:23 shane Exp $
*/

/*
** The code in this file is only used if we are compiling multithreaded
** on a win32 system.
*/
#ifdef SQLITE_MUTEX_W32
15852
15853
15854
15855
15856
15857
15858


15859
15860
15861
15862
15863
15864
15865
  */
#if 0
  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
    p->owner = GetCurrentThreadId();
    p->nRef++;
    rc = SQLITE_OK;
  }


#endif
  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior







>
>







15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
  */
#if 0
  if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
    p->owner = GetCurrentThreadId();
    p->nRef++;
    rc = SQLITE_OK;
  }
#else
  UNUSED_PARAMETER(p);
#endif
  return rc;
}

/*
** The sqlite3_mutex_leave() routine exits a mutex that was
** previously entered by the same thread.  The behavior
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
**
** $Id: malloc.c,v 1.53 2008/12/16 17:20:38 shane Exp $
*/

/*
** This routine runs when the memory allocator sees that the
** total memory allocation is about to exceed the soft heap
** limit.
*/







|







16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** Memory allocation functions used throughout sqlite.
**
** $Id: malloc.c,v 1.54 2009/01/20 16:53:41 danielk1977 Exp $
*/

/*
** This routine runs when the memory allocator sees that the
** total memory allocation is about to exceed the soft heap
** limit.
*/
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
*************************************************************************
** This is the header file for information that is private to the
** VDBE.  This information used to all be at the top of the single
** source code file "vdbe.c".  When that file became too big (over
** 6000 lines long) it was split up into several smaller files and
** this header information was factored out.
**
** $Id: vdbeInt.h,v 1.161 2009/01/05 18:02:27 drh Exp $
*/
#ifndef _VDBEINT_H_
#define _VDBEINT_H_

/*
** intToKey() and keyToInt() used to transform the rowid.  But with
** the latest versions of the design they are no-ops.







|







17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
*************************************************************************
** This is the header file for information that is private to the
** VDBE.  This information used to all be at the top of the single
** source code file "vdbe.c".  When that file became too big (over
** 6000 lines long) it was split up into several smaller files and
** this header information was factored out.
**
** $Id: vdbeInt.h,v 1.162 2009/02/03 15:39:01 drh Exp $
*/
#ifndef _VDBEINT_H_
#define _VDBEINT_H_

/*
** intToKey() and keyToInt() used to transform the rowid.  But with
** the latest versions of the design they are no-ops.
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
#endif

#ifndef NDEBUG
SQLITE_PRIVATE   void sqlite3VdbeMemSanity(Mem*);
#endif
SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
#endif
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);








<
<
<







18318
18319
18320
18321
18322
18323
18324



18325
18326
18327
18328
18329
18330
18331
SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
SQLITE_PRIVATE int sqlite3VdbeOpcodeHasProperty(int, int);
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
#ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
SQLITE_PRIVATE int sqlite3VdbeReleaseBuffers(Vdbe *p);
#endif




SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
#ifdef SQLITE_DEBUG
SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
#endif
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);

18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: util.c,v 1.246 2009/01/10 16:15:22 drh Exp $
*/


/*
** Routine needed to support the testcase() macro.
*/
#ifdef SQLITE_COVERAGE_TEST







|







18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
**
*************************************************************************
** Utility functions used throughout sqlite.
**
** This file contains functions for allocating memory, comparing
** strings, and stuff like that.
**
** $Id: util.c,v 1.247 2009/01/20 16:53:41 danielk1977 Exp $
*/


/*
** Routine needed to support the testcase() macro.
*/
#ifdef SQLITE_COVERAGE_TEST
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
**
** An empty string is considered non-numeric.
*/
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;
  if( realnum ) *realnum = 0;
  while( isdigit(*(u8*)z) ){ z += incr; }
  if( *z=='.' ){
    z += incr;
    if( !isdigit(*(u8*)z) ) return 0;
    while( isdigit(*(u8*)z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z += incr;
    if( *z=='+' || *z=='-' ) z += incr;
    if( !isdigit(*(u8*)z) ) return 0;
    while( isdigit(*(u8*)z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ascii representation of a real number.







|




|


|
|





|
|







19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
**
** An empty string is considered non-numeric.
*/
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( !sqlite3Isdigit(*z) ){
    return 0;
  }
  z += incr;
  if( realnum ) *realnum = 0;
  while( sqlite3Isdigit(*z) ){ z += incr; }
  if( *z=='.' ){
    z += incr;
    if( !sqlite3Isdigit(*z) ) return 0;
    while( sqlite3Isdigit(*z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  if( *z=='e' || *z=='E' ){
    z += incr;
    if( *z=='+' || *z=='-' ) z += incr;
    if( !sqlite3Isdigit(*z) ) return 0;
    while( sqlite3Isdigit(*z) ){ z += incr; }
    if( realnum ) *realnum = 1;
  }
  return *z==0;
}

/*
** The string z[] is an ascii representation of a real number.
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
*/
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;
  int nSignificant = 0;
  while( isspace(*(u8*)z) ) z++;
  if( *z=='-' ){
    sign = -1;
    z++;
  }else if( *z=='+' ){
    z++;
  }
  while( z[0]=='0' ){
    z++;
  }
  while( isdigit(*(u8*)z) ){
    v1 = v1*10.0 + (*z - '0');
    z++;
    nSignificant++;
  }
  if( *z=='.' ){
    LONGDOUBLE_TYPE divisor = 1.0;
    z++;
    if( nSignificant==0 ){
      while( z[0]=='0' ){
        divisor *= 10.0;
        z++;
      }
    }
    while( isdigit(*(u8*)z) ){
      if( nSignificant<18 ){
        v1 = v1*10.0 + (*z - '0');
        divisor *= 10.0;
        nSignificant++;
      }
      z++;
    }
    v1 /= divisor;
  }
  if( *z=='e' || *z=='E' ){
    int esign = 1;
    int eval = 0;
    LONGDOUBLE_TYPE scale = 1.0;
    z++;
    if( *z=='-' ){
      esign = -1;
      z++;
    }else if( *z=='+' ){
      z++;
    }
    while( isdigit(*(u8*)z) ){
      eval = eval*10 + *z - '0';
      z++;
    }
    while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
    while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
    while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
    while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }







|









|













|




















|







19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
*/
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;
  int nSignificant = 0;
  while( sqlite3Isspace(*z) ) z++;
  if( *z=='-' ){
    sign = -1;
    z++;
  }else if( *z=='+' ){
    z++;
  }
  while( z[0]=='0' ){
    z++;
  }
  while( sqlite3Isdigit(*z) ){
    v1 = v1*10.0 + (*z - '0');
    z++;
    nSignificant++;
  }
  if( *z=='.' ){
    LONGDOUBLE_TYPE divisor = 1.0;
    z++;
    if( nSignificant==0 ){
      while( z[0]=='0' ){
        divisor *= 10.0;
        z++;
      }
    }
    while( sqlite3Isdigit(*z) ){
      if( nSignificant<18 ){
        v1 = v1*10.0 + (*z - '0');
        divisor *= 10.0;
        nSignificant++;
      }
      z++;
    }
    v1 /= divisor;
  }
  if( *z=='e' || *z=='E' ){
    int esign = 1;
    int eval = 0;
    LONGDOUBLE_TYPE scale = 1.0;
    z++;
    if( *z=='-' ){
      esign = -1;
      z++;
    }else if( *z=='+' ){
      z++;
    }
    while( sqlite3Isdigit(*z) ){
      eval = eval*10 + *z - '0';
      z++;
    }
    while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
    while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
    while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
    while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
** atoi() library routine in RedHat 7.2.
*/
SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;
  const char *zStart;
  while( isspace(*(u8*)zNum) ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{







|







19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
** atoi() library routine in RedHat 7.2.
*/
SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
  i64 v = 0;
  int neg;
  int i, c;
  const char *zStart;
  while( sqlite3Isspace(*zNum) ) zNum++;
  if( *zNum=='-' ){
    neg = 1;
    zNum++;
  }else if( *zNum=='+' ){
    neg = 0;
    zNum++;
  }else{
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
     /*  56 */ "SeekLe",
     /*  57 */ "IncrVacuum",
     /*  58 */ "IdxRowid",
     /*  59 */ "ResetCount",
     /*  60 */ "ContextPush",
     /*  61 */ "Yield",
     /*  62 */ "DropTrigger",
     /*  63 */ "Or",
     /*  64 */ "And",
     /*  65 */ "DropIndex",
     /*  66 */ "IdxGE",
     /*  67 */ "IdxDelete",
     /*  68 */ "IsNull",
     /*  69 */ "NotNull",
     /*  70 */ "Ne",
     /*  71 */ "Eq",
     /*  72 */ "Gt",
     /*  73 */ "Le",
     /*  74 */ "Lt",
     /*  75 */ "Ge",
     /*  76 */ "Vacuum",
     /*  77 */ "BitAnd",
     /*  78 */ "BitOr",
     /*  79 */ "ShiftLeft",
     /*  80 */ "ShiftRight",
     /*  81 */ "Add",
     /*  82 */ "Subtract",
     /*  83 */ "Multiply",
     /*  84 */ "Divide",
     /*  85 */ "Remainder",
     /*  86 */ "Concat",
     /*  87 */ "IfNot",
     /*  88 */ "DropTable",
     /*  89 */ "SeekLt",
     /*  90 */ "BitNot",
     /*  91 */ "String8",
     /*  92 */ "MakeRecord",
     /*  93 */ "ResultRow",
     /*  94 */ "Delete",
     /*  95 */ "AggFinal",
     /*  96 */ "Compare",
     /*  97 */ "Goto",
     /*  98 */ "TableLock",
     /*  99 */ "Clear",
     /* 100 */ "VerifyCookie",







|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|







20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
     /*  56 */ "SeekLe",
     /*  57 */ "IncrVacuum",
     /*  58 */ "IdxRowid",
     /*  59 */ "ResetCount",
     /*  60 */ "ContextPush",
     /*  61 */ "Yield",
     /*  62 */ "DropTrigger",
     /*  63 */ "DropIndex",
     /*  64 */ "IdxGE",
     /*  65 */ "Or",
     /*  66 */ "And",
     /*  67 */ "IdxDelete",
     /*  68 */ "Vacuum",
     /*  69 */ "IfNot",
     /*  70 */ "IsNull",
     /*  71 */ "NotNull",
     /*  72 */ "Ne",
     /*  73 */ "Eq",
     /*  74 */ "Gt",
     /*  75 */ "Le",
     /*  76 */ "Lt",
     /*  77 */ "Ge",
     /*  78 */ "DropTable",
     /*  79 */ "BitAnd",
     /*  80 */ "BitOr",
     /*  81 */ "ShiftLeft",
     /*  82 */ "ShiftRight",
     /*  83 */ "Add",
     /*  84 */ "Subtract",
     /*  85 */ "Multiply",
     /*  86 */ "Divide",
     /*  87 */ "Remainder",
     /*  88 */ "Concat",
     /*  89 */ "SeekLt",
     /*  90 */ "MakeRecord",
     /*  91 */ "ResultRow",
     /*  92 */ "BitNot",
     /*  93 */ "String8",
     /*  94 */ "Delete",
     /*  95 */ "AggFinal",
     /*  96 */ "Compare",
     /*  97 */ "Goto",
     /*  98 */ "TableLock",
     /*  99 */ "Clear",
     /* 100 */ "VerifyCookie",
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165

20166
20167
20168
20169
20170
20171
20172
     /* 122 */ "VBegin",
     /* 123 */ "VUpdate",
     /* 124 */ "IfZero",
     /* 125 */ "VCreate",
     /* 126 */ "Found",
     /* 127 */ "IfPos",
     /* 128 */ "NullRow",
     /* 129 */ "Real",
     /* 130 */ "Jump",
     /* 131 */ "Permutation",
     /* 132 */ "NotUsed_132",
     /* 133 */ "NotUsed_133",
     /* 134 */ "NotUsed_134",
     /* 135 */ "NotUsed_135",
     /* 136 */ "NotUsed_136",
     /* 137 */ "NotUsed_137",
     /* 138 */ "ToText",
     /* 139 */ "ToBlob",
     /* 140 */ "ToNumeric",
     /* 141 */ "ToInt",
     /* 142 */ "ToReal",

  };
  return azName[i];
}
#endif

/************** End of opcodes.c *********************************************/
/************** Begin file os_os2.c ******************************************/







|
|







|
|
|
|
|
>







20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
     /* 122 */ "VBegin",
     /* 123 */ "VUpdate",
     /* 124 */ "IfZero",
     /* 125 */ "VCreate",
     /* 126 */ "Found",
     /* 127 */ "IfPos",
     /* 128 */ "NullRow",
     /* 129 */ "Jump",
     /* 130 */ "Real",
     /* 131 */ "Permutation",
     /* 132 */ "NotUsed_132",
     /* 133 */ "NotUsed_133",
     /* 134 */ "NotUsed_134",
     /* 135 */ "NotUsed_135",
     /* 136 */ "NotUsed_136",
     /* 137 */ "NotUsed_137",
     /* 138 */ "NotUsed_138",
     /* 139 */ "ToText",
     /* 140 */ "ToBlob",
     /* 141 */ "ToNumeric",
     /* 142 */ "ToInt",
     /* 143 */ "ToReal",
  };
  return azName[i];
}
#endif

/************** End of opcodes.c *********************************************/
/************** Begin file os_os2.c ******************************************/
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
**   *  Definitions of sqlite3_io_methods objects for all locking
**      methods plus "finder" functions for each locking method.
**   *  sqlite3_vfs method implementations.
**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
**   *  Definitions of sqlite3_vfs objects for all locking methods
**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
**
** $Id: os_unix.c,v 1.237 2009/01/15 04:30:03 drh Exp $
*/
#if SQLITE_OS_UNIX              /* This file is used on unix only */

/*
** There are various methods for file locking used for concurrency
** control:
**







|







21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
**   *  Definitions of sqlite3_io_methods objects for all locking
**      methods plus "finder" functions for each locking method.
**   *  sqlite3_vfs method implementations.
**   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
**   *  Definitions of sqlite3_vfs objects for all locking methods
**      plus implementations of sqlite3_os_init() and sqlite3_os_end().
**
** $Id: os_unix.c,v 1.239 2009/02/03 15:27:02 drh Exp $
*/
#if SQLITE_OS_UNIX              /* This file is used on unix only */

/*
** There are various methods for file locking used for concurrency
** control:
**
22678
22679
22680
22681
22682
22683
22684

22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696



22697
22698
22699
22700
22701
22702

22703
22704
22705
22706
22707
22708
22709
    pFile->lastErrno = errno;
#ifdef EOVERFLOW
    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
#endif
    return SQLITE_IOERR;
  }


  /* On OS X on an msdos filesystem, the inode number is reported
  ** incorrectly for zero-size files.  See ticket #3260.  To work
  ** around this problem (we consider it a bug in OS X, not SQLite)
  ** we always increase the file size to 1 by writing a single byte
  ** prior to accessing the inode number.  The one byte written is
  ** an ASCII 'S' character which also happens to be the first byte
  ** in the header of every SQLite database.  In this way, if there
  ** is a race condition such that another thread has already populated
  ** the first page of the database, no damage is done.
  */
  if( statbuf.st_size==0 ){
    write(fd, "S", 1);



    rc = fstat(fd, &statbuf);
    if( rc!=0 ){
      pFile->lastErrno = errno;
      return SQLITE_IOERR;
    }
  }


  memset(&lockKey, 0, sizeof(lockKey));
  lockKey.fid.dev = statbuf.st_dev;
#if OS_VXWORKS
  lockKey.fid.pId = pFile->pId;
#else
  lockKey.fid.ino = statbuf.st_ino;







>











|
>
>
>






>







22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
    pFile->lastErrno = errno;
#ifdef EOVERFLOW
    if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
#endif
    return SQLITE_IOERR;
  }

#ifdef __APPLE__
  /* On OS X on an msdos filesystem, the inode number is reported
  ** incorrectly for zero-size files.  See ticket #3260.  To work
  ** around this problem (we consider it a bug in OS X, not SQLite)
  ** we always increase the file size to 1 by writing a single byte
  ** prior to accessing the inode number.  The one byte written is
  ** an ASCII 'S' character which also happens to be the first byte
  ** in the header of every SQLite database.  In this way, if there
  ** is a race condition such that another thread has already populated
  ** the first page of the database, no damage is done.
  */
  if( statbuf.st_size==0 ){
    rc = write(fd, "S", 1);
    if( rc!=1 ){
      return SQLITE_IOERR;
    }
    rc = fstat(fd, &statbuf);
    if( rc!=0 ){
      pFile->lastErrno = errno;
      return SQLITE_IOERR;
    }
  }
#endif

  memset(&lockKey, 0, sizeof(lockKey));
  lockKey.fid.dev = statbuf.st_dev;
#if OS_VXWORKS
  lockKey.fid.pId = pFile->pId;
#else
  lockKey.fid.ino = statbuf.st_ino;
24516
24517
24518
24519
24520
24521
24522

24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
  ** has changed.  If the transaction counter is modified, record that
  ** fact too.
  */
  if( ((unixFile*)id)->inNormalWrite ){
    unixFile *pFile = (unixFile*)id;
    pFile->dbUpdate = 1;  /* The database has been modified */
    if( offset<=24 && offset+amt>=27 ){

      char oldCntr[4];
      SimulateIOErrorBenign(1);
      seekAndRead(pFile, 24, oldCntr, 4);
      SimulateIOErrorBenign(0);
      if( memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
        pFile->transCntrChng = 1;  /* The transaction counter has changed */
      }
    }
  }
#endif

  while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){







>


|

|







24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
  ** has changed.  If the transaction counter is modified, record that
  ** fact too.
  */
  if( ((unixFile*)id)->inNormalWrite ){
    unixFile *pFile = (unixFile*)id;
    pFile->dbUpdate = 1;  /* The database has been modified */
    if( offset<=24 && offset+amt>=27 ){
      int rc;
      char oldCntr[4];
      SimulateIOErrorBenign(1);
      rc = seekAndRead(pFile, 24, oldCntr, 4);
      SimulateIOErrorBenign(0);
      if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
        pFile->transCntrChng = 1;  /* The transaction counter has changed */
      }
    }
  }
#endif

  while( amt>0 && (wrote = seekAndWrite((unixFile*)id, offset, pBuf, amt))>0 ){
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to windows.
**
** $Id: os_win.c,v 1.145 2008/12/11 02:58:27 shane Exp $
*/
#if SQLITE_OS_WIN               /* This file is used for windows only */


/*
** A Note About Memory Allocation:
**







|







26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
******************************************************************************
**
** This file contains code that is specific to windows.
**
** $Id: os_win.c,v 1.146 2009/01/30 05:59:11 shane Exp $
*/
#if SQLITE_OS_WIN               /* This file is used for windows only */


/*
** A Note About Memory Allocation:
**
27147
27148
27149
27150
27151
27152
27153

27154
27155
27156
27157
27158
27159
27160
*/
typedef struct winFile winFile;
struct winFile {
  const sqlite3_io_methods *pMethod;/* Must be first */
  HANDLE h;               /* Handle for accessing the file */
  unsigned char locktype; /* Type of lock currently held on this file */
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */

#if SQLITE_OS_WINCE
  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
  HANDLE hShared;         /* Shared memory segment used for locking */
  winceLock local;        /* Locks obtained by this instance of winFile */
  winceLock *shared;      /* Global shared lock memory for the file  */
#endif







>







27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
*/
typedef struct winFile winFile;
struct winFile {
  const sqlite3_io_methods *pMethod;/* Must be first */
  HANDLE h;               /* Handle for accessing the file */
  unsigned char locktype; /* Type of lock currently held on this file */
  short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
  DWORD lastErrno;        /* The Windows errno from the last I/O error */
#if SQLITE_OS_WINCE
  WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
  HANDLE hMutex;          /* Mutex used to control access to shared lock */  
  HANDLE hShared;         /* Shared memory segment used for locking */
  winceLock local;        /* Locks obtained by this instance of winFile */
  winceLock *shared;      /* Global shared lock memory for the file  */
#endif
27404
27405
27406
27407
27408
27409
27410

27411
27412
27413
27414
27415
27416
27417
  for (;*zTok;zTok++){
    if (*zTok == '\\') *zTok = '_';
  }

  /* Create/open the named mutex */
  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  if (!pFile->hMutex){

    free(zName);
    return FALSE;
  }

  /* Acquire the mutex before continuing */
  winceMutexAcquire(pFile->hMutex);
  







>







27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
  for (;*zTok;zTok++){
    if (*zTok == '\\') *zTok = '_';
  }

  /* Create/open the named mutex */
  pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
  if (!pFile->hMutex){
    pFile->lastErrno = GetLastError();
    free(zName);
    return FALSE;
  }

  /* Acquire the mutex before continuing */
  winceMutexAcquire(pFile->hMutex);
  
27434
27435
27436
27437
27438
27439
27440

27441
27442
27443
27444
27445
27446
27447

  /* If we succeeded in making the shared memory handle, map it. */
  if (pFile->hShared){
    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
    /* If mapping failed, close the shared memory handle and erase it */
    if (!pFile->shared){

      CloseHandle(pFile->hShared);
      pFile->hShared = NULL;
    }
  }

  /* If shared memory could not be created, then close the mutex and fail */
  if (pFile->hShared == NULL){







>







27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576

  /* If we succeeded in making the shared memory handle, map it. */
  if (pFile->hShared){
    pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
             FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
    /* If mapping failed, close the shared memory handle and erase it */
    if (!pFile->shared){
      pFile->lastErrno = GetLastError();
      CloseHandle(pFile->hShared);
      pFile->hShared = NULL;
    }
  }

  /* If shared memory could not be created, then close the mutex and fail */
  if (pFile->hShared == NULL){
27699
27700
27701
27702
27703
27704
27705

27706
27707
27708
27709
27710

27711
27712
27713

27714
27715
27716
27717
27718
27719
27720
  sqlite3_int64 offset       /* Begin reading at this offset */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  DWORD got;
  winFile *pFile = (winFile*)id;

  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_READ);
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){

    return SQLITE_FULL;
  }
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){

    return SQLITE_IOERR_READ;
  }
  if( got==(DWORD)amt ){
    return SQLITE_OK;
  }else{
    /* Unread parts of the buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);







>




|
>



>







27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
  sqlite3_int64 offset       /* Begin reading at this offset */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  DWORD got;
  winFile *pFile = (winFile*)id;
  DWORD error;
  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_READ);
  OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
    pFile->lastErrno = error;
    return SQLITE_FULL;
  }
  if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
    pFile->lastErrno = GetLastError();
    return SQLITE_IOERR_READ;
  }
  if( got==(DWORD)amt ){
    return SQLITE_OK;
  }else{
    /* Unread parts of the buffer must be zero-filled */
    memset(&((char*)pBuf)[got], 0, amt-got);
27733
27734
27735
27736
27737
27738
27739

27740
27741
27742
27743
27744
27745

27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757

27758
27759
27760
27761
27762
27763
27764
  sqlite3_int64 offset      /* Offset into the file to begin writing at */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  DWORD wrote = 0;
  winFile *pFile = (winFile*)id;

  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_WRITE);
  SimulateDiskfullError(return SQLITE_FULL);
  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && GetLastError()!=NO_ERROR ){

    return SQLITE_FULL;
  }
  assert( amt>0 );
  while(
     amt>0
     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
     && wrote>0
  ){
    amt -= wrote;
    pBuf = &((char*)pBuf)[wrote];
  }
  if( !rc || amt>(int)wrote ){

    return SQLITE_FULL;
  }
  return SQLITE_OK;
}

/*
** Truncate an open file to a specified size







>





|
>












>







27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
  sqlite3_int64 offset      /* Offset into the file to begin writing at */
){
  LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
  LONG lowerBits = (LONG)(offset & 0xffffffff);
  DWORD rc;
  DWORD wrote = 0;
  winFile *pFile = (winFile*)id;
  DWORD error;
  assert( id!=0 );
  SimulateIOError(return SQLITE_IOERR_WRITE);
  SimulateDiskfullError(return SQLITE_FULL);
  OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
    pFile->lastErrno = error;
    return SQLITE_FULL;
  }
  assert( amt>0 );
  while(
     amt>0
     && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
     && wrote>0
  ){
    amt -= wrote;
    pBuf = &((char*)pBuf)[wrote];
  }
  if( !rc || amt>(int)wrote ){
    pFile->lastErrno = GetLastError();
    return SQLITE_FULL;
  }
  return SQLITE_OK;
}

/*
** Truncate an open file to a specified size
27773
27774
27775
27776
27777
27778
27779

27780
27781
27782
27783
27784
27785
27786
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( INVALID_SET_FILE_POINTER != rc ){
    /* SetEndOfFile will fail if nByte is negative */
    if( SetEndOfFile(pFile->h) ){
      return SQLITE_OK;
    }
  }

  return SQLITE_IOERR_TRUNCATE;
}

#ifdef SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occuring at the right times.







>







27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
  rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  if( INVALID_SET_FILE_POINTER != rc ){
    /* SetEndOfFile will fail if nByte is negative */
    if( SetEndOfFile(pFile->h) ){
      return SQLITE_OK;
    }
  }
  pFile->lastErrno = GetLastError();
  return SQLITE_IOERR_TRUNCATE;
}

#ifdef SQLITE_TEST
/*
** Count the number of fullsyncs and normal syncs.  This is used to test
** that syncs and fullsyncs are occuring at the right times.
27812
27813
27814
27815
27816
27817
27818

27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829

27830
27831






27832
27833
27834
27835
27836
27837
27838
  */
#ifdef SQLITE_NO_SYNC
    return SQLITE_OK;
#else
  if( FlushFileBuffers(pFile->h) ){
    return SQLITE_OK;
  }else{

    return SQLITE_IOERR;
  }
#endif
}

/*
** Determine the current size of a file in bytes
*/
static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  winFile *pFile = (winFile*)id;
  DWORD upperBits, lowerBits;

  SimulateIOError(return SQLITE_IOERR_FSTAT);
  lowerBits = GetFileSize(pFile->h, &upperBits);






  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  return SQLITE_OK;
}

/*
** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
*/







>











>


>
>
>
>
>
>







27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
  */
#ifdef SQLITE_NO_SYNC
    return SQLITE_OK;
#else
  if( FlushFileBuffers(pFile->h) ){
    return SQLITE_OK;
  }else{
    pFile->lastErrno = GetLastError();
    return SQLITE_IOERR;
  }
#endif
}

/*
** Determine the current size of a file in bytes
*/
static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  winFile *pFile = (winFile*)id;
  DWORD upperBits, lowerBits;
  DWORD error;
  SimulateIOError(return SQLITE_IOERR_FSTAT);
  lowerBits = GetFileSize(pFile->h, &upperBits);
  if(   (lowerBits == INVALID_FILE_SIZE)
     && ((error = GetLastError()) != NO_ERROR) )
  {
    pFile->lastErrno = error;
    return SQLITE_IOERR_FSTAT;
  }
  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  return SQLITE_OK;
}

/*
** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
*/
27860
27861
27862
27863
27864
27865
27866



27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883



27884
27885
27886
27887
27888
27889
27890
  }else{
    int lk;
    sqlite3_randomness(sizeof(lk), &lk);
    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
#endif
  }



  return res;
}

/*
** Undo a readlock
*/
static int unlockReadLock(winFile *pFile){
  int res;
  if( isNT() ){
    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
*/
#if SQLITE_OS_WINCE==0
  }else{
    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
#endif
  }



  return res;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**







>
>
>

















>
>
>







28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
  }else{
    int lk;
    sqlite3_randomness(sizeof(lk), &lk);
    pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
    res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
#endif
  }
  if( res == 0 ){
    pFile->lastErrno = GetLastError();
  }
  return res;
}

/*
** Undo a readlock
*/
static int unlockReadLock(winFile *pFile){
  int res;
  if( isNT() ){
    res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
/* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
*/
#if SQLITE_OS_WINCE==0
  }else{
    res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
#endif
  }
  if( res == 0 ){
    pFile->lastErrno = GetLastError();
  }
  return res;
}

/*
** Lock the file with the lock specified by parameter locktype - one
** of the following:
**
27912
27913
27914
27915
27916
27917
27918

27919
27920
27921
27922
27923
27924
27925
*/
static int winLock(sqlite3_file *id, int locktype){
  int rc = SQLITE_OK;    /* Return code from subroutines */
  int res = 1;           /* Result of a windows lock call */
  int newLocktype;       /* Set pFile->locktype to this value before exiting */
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  winFile *pFile = (winFile*)id;


  assert( pFile!=0 );
  OSTRACE5("LOCK %d %d was %d(%d)\n",
          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);

  /* If there is already a lock of this type or more restrictive on the
  ** OsFile, do nothing. Don't use the end_lock: exit path, as







>







28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
*/
static int winLock(sqlite3_file *id, int locktype){
  int rc = SQLITE_OK;    /* Return code from subroutines */
  int res = 1;           /* Result of a windows lock call */
  int newLocktype;       /* Set pFile->locktype to this value before exiting */
  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  winFile *pFile = (winFile*)id;
  DWORD error = NO_ERROR;

  assert( pFile!=0 );
  OSTRACE5("LOCK %d %d was %d(%d)\n",
          pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);

  /* If there is already a lock of this type or more restrictive on the
  ** OsFile, do nothing. Don't use the end_lock: exit path, as
27936
27937
27938
27939
27940
27941
27942
27943

27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954



27955
27956
27957
27958
27959
27960
27961
27962
27963


27964
27965
27966
27967
27968
27969
27970
27971
27972
27973


27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993

27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013

28014
28015
28016
28017
28018
28019
28020
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if( pFile->locktype==NO_LOCK

   || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
  ){
    int cnt = 3;
    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
      /* Try 3 times to get the pending lock.  The pending lock might be
      ** held by another reader process who will release it momentarily.
      */
      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
      Sleep(1);
    }
    gotPendingLock = res;



  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res ){
    assert( pFile->locktype==NO_LOCK );
    res = getReadLock(pFile);
    if( res ){
      newLocktype = SHARED_LOCK;


    }
  }

  /* Acquire a RESERVED lock
  */
  if( locktype==RESERVED_LOCK && res ){
    assert( pFile->locktype==SHARED_LOCK );
    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
    if( res ){
      newLocktype = RESERVED_LOCK;


    }
  }

  /* Acquire a PENDING lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    newLocktype = PENDING_LOCK;
    gotPendingLock = 0;
  }

  /* Acquire an EXCLUSIVE lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    assert( pFile->locktype>=SHARED_LOCK );
    res = unlockReadLock(pFile);
    OSTRACE2("unreadlock = %d\n", res);
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
    if( res ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{

      OSTRACE2("error-code = %d\n", GetLastError());
      getReadLock(pFile);
    }
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  }

  /* Update the state of the lock has held in the file descriptor then
  ** return the appropriate result code.
  */
  if( res ){
    rc = SQLITE_OK;
  }else{
    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
           locktype, newLocktype);

    rc = SQLITE_BUSY;
  }
  pFile->locktype = (u8)newLocktype;
  return rc;
}

/*







|
>
|










>
>
>









>
>










>
>




















>
|



















>







28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );

  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
  ** the PENDING_LOCK byte is temporary.
  */
  newLocktype = pFile->locktype;
  if(   (pFile->locktype==NO_LOCK)
     || (   (locktype==EXCLUSIVE_LOCK)
         && (pFile->locktype==RESERVED_LOCK))
  ){
    int cnt = 3;
    while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
      /* Try 3 times to get the pending lock.  The pending lock might be
      ** held by another reader process who will release it momentarily.
      */
      OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
      Sleep(1);
    }
    gotPendingLock = res;
    if( !res ){
      error = GetLastError();
    }
  }

  /* Acquire a shared lock
  */
  if( locktype==SHARED_LOCK && res ){
    assert( pFile->locktype==NO_LOCK );
    res = getReadLock(pFile);
    if( res ){
      newLocktype = SHARED_LOCK;
    }else{
      error = GetLastError();
    }
  }

  /* Acquire a RESERVED lock
  */
  if( locktype==RESERVED_LOCK && res ){
    assert( pFile->locktype==SHARED_LOCK );
    res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
    if( res ){
      newLocktype = RESERVED_LOCK;
    }else{
      error = GetLastError();
    }
  }

  /* Acquire a PENDING lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    newLocktype = PENDING_LOCK;
    gotPendingLock = 0;
  }

  /* Acquire an EXCLUSIVE lock
  */
  if( locktype==EXCLUSIVE_LOCK && res ){
    assert( pFile->locktype>=SHARED_LOCK );
    res = unlockReadLock(pFile);
    OSTRACE2("unreadlock = %d\n", res);
    res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
    if( res ){
      newLocktype = EXCLUSIVE_LOCK;
    }else{
      error = GetLastError();
      OSTRACE2("error-code = %d\n", error);
      getReadLock(pFile);
    }
  }

  /* If we are holding a PENDING lock that ought to be released, then
  ** release it now.
  */
  if( gotPendingLock && locktype==SHARED_LOCK ){
    UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
  }

  /* Update the state of the lock has held in the file descriptor then
  ** return the appropriate result code.
  */
  if( res ){
    rc = SQLITE_OK;
  }else{
    OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
           locktype, newLocktype);
    pFile->lastErrno = error;
    rc = SQLITE_BUSY;
  }
  pFile->locktype = (u8)newLocktype;
  return rc;
}

/*
28086
28087
28088
28089
28090
28091
28092




28093
28094
28095
28096
28097
28098
28099
** Control and query of the open file handle.
*/
static int winFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      *(int*)pArg = ((winFile*)id)->locktype;
      return SQLITE_OK;




    }
  }
  return SQLITE_ERROR;
}

/*
** Return the sector size in bytes of the underlying block device for







>
>
>
>







28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
** Control and query of the open file handle.
*/
static int winFileControl(sqlite3_file *id, int op, void *pArg){
  switch( op ){
    case SQLITE_FCNTL_LOCKSTATE: {
      *(int*)pArg = ((winFile*)id)->locktype;
      return SQLITE_OK;
    }
    case SQLITE_LAST_ERRNO: {
      *(int*)pArg = (int)((winFile*)id)->lastErrno;
      return SQLITE_OK;
    }
  }
  return SQLITE_ERROR;
}

/*
** Return the sector size in bytes of the underlying block device for
28366
28367
28368
28369
28370
28371
28372

28373
28374
28375
28376
28377
28378
28379
    }else{
      *pOutFlags = SQLITE_OPEN_READONLY;
    }
  }
  memset(pFile, 0, sizeof(*pFile));
  pFile->pMethod = &winIoMethod;
  pFile->h = h;

#if SQLITE_OS_WINCE
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
       && !winceCreateLock(zName, pFile)
  ){
    CloseHandle(h);
    free(zConverted);







>







28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
    }else{
      *pOutFlags = SQLITE_OPEN_READONLY;
    }
  }
  memset(pFile, 0, sizeof(*pFile));
  pFile->pMethod = &winIoMethod;
  pFile->h = h;
  pFile->lastErrno = NO_ERROR;
#if SQLITE_OS_WINCE
  if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
               (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
       && !winceCreateLock(zName, pFile)
  ){
    CloseHandle(h);
    free(zConverted);
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
** Clear operations are exceedingly rare.  There are usually between
** 5 and 500 set operations per Bitvec object, though the number of sets can
** sometimes grow into tens of thousands or larger.  The size of the
** Bitvec object is the number of pages in the database file at the
** start of a transaction, and is thus usually less than a few thousand,
** but can be as large as 2 billion for a really big database.
**
** @(#) $Id: bitvec.c,v 1.10 2009/01/02 21:39:39 drh Exp $
*/

/* Size of the Bitvec structure in bytes. */
#define BITVEC_SZ        512

/* Round the union size down to the nearest pointer boundary, since that's how 
** it will be aligned within the Bitvec struct. */







|







28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
** Clear operations are exceedingly rare.  There are usually between
** 5 and 500 set operations per Bitvec object, though the number of sets can
** sometimes grow into tens of thousands or larger.  The size of the
** Bitvec object is the number of pages in the database file at the
** start of a transaction, and is thus usually less than a few thousand,
** but can be as large as 2 billion for a really big database.
**
** @(#) $Id: bitvec.c,v 1.13 2009/01/20 17:06:27 danielk1977 Exp $
*/

/* Size of the Bitvec structure in bytes. */
#define BITVEC_SZ        512

/* Round the union size down to the nearest pointer boundary, since that's how 
** it will be aligned within the Bitvec struct. */
29046
29047
29048
29049
29050
29051
29052








29053
29054
29055
29056
29057
29058
29059
    unsigned int i;
    for(i=0; i<BITVEC_NPTR; i++){
      sqlite3BitvecDestroy(p->u.apSub[i]);
    }
  }
  sqlite3_free(p);
}









#ifndef SQLITE_OMIT_BUILTIN_TEST
/*
** Let V[] be an array of unsigned characters sufficient to hold
** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
** Then the following macros can be used to set, clear, or test
** individual bits within V.







>
>
>
>
>
>
>
>







29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
    unsigned int i;
    for(i=0; i<BITVEC_NPTR; i++){
      sqlite3BitvecDestroy(p->u.apSub[i]);
    }
  }
  sqlite3_free(p);
}

/*
** Return the value of the iSize parameter specified when Bitvec *p
** was created.
*/
SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  return p->iSize;
}

#ifndef SQLITE_OMIT_BUILTIN_TEST
/*
** Let V[] be an array of unsigned characters sufficient to hold
** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
** Then the following macros can be used to set, clear, or test
** individual bits within V.
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
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements that page cache.
**
** @(#) $Id: pcache.c,v 1.39 2008/12/04 20:40:10 drh Exp $
*/

/*
** A complete page cache is an instance of this structure.
*/
struct PCache {
  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
  PgHdr *pSynced;                     /* Last synced page in dirty page list */
  int nRef;                           /* Number of referenced pages */
  int nMax;                           /* Configured cache size */
  int nMin;                           /* Configured minimum cache size */
  int szPage;                         /* Size of every page in this cache */
  int szExtra;                        /* Size of extra space for each page */
  int bPurgeable;                     /* True if pages are on backing store */
  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
  void *pStress;                      /* Argument to xStress */
  sqlite3_pcache *pCache;             /* Pluggable cache module */
  PgHdr *pPage1;
};

/*
** Some of the assert() macros in this code are too expensive to run
** even during normal debugging.  Use them only rarely on long-running
** tests.  Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.







|










<






|







29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363

29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file implements that page cache.
**
** @(#) $Id: pcache.c,v 1.43 2009/01/23 16:45:01 danielk1977 Exp $
*/

/*
** A complete page cache is an instance of this structure.
*/
struct PCache {
  PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
  PgHdr *pSynced;                     /* Last synced page in dirty page list */
  int nRef;                           /* Number of referenced pages */
  int nMax;                           /* Configured cache size */

  int szPage;                         /* Size of every page in this cache */
  int szExtra;                        /* Size of extra space for each page */
  int bPurgeable;                     /* True if pages are on backing store */
  int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
  void *pStress;                      /* Argument to xStress */
  sqlite3_pcache *pCache;             /* Pluggable cache module */
  PgHdr *pPage1;                      /* Reference to page 1 */
};

/*
** Some of the assert() macros in this code are too expensive to run
** even during normal debugging.  Use them only rarely on long-running
** tests.  Enable the expensive asserts using the
** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
  memset(p, 0, sizeof(PCache));
  p->szPage = szPage;
  p->szExtra = szExtra;
  p->bPurgeable = bPurgeable;
  p->xStress = xStress;
  p->pStress = pStress;
  p->nMax = 100;
  p->nMin = 10;
}

/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){







<







29514
29515
29516
29517
29518
29519
29520

29521
29522
29523
29524
29525
29526
29527
  memset(p, 0, sizeof(PCache));
  p->szPage = szPage;
  p->szExtra = szExtra;
  p->bPurgeable = bPurgeable;
  p->xStress = xStress;
  p->pStress = pStress;
  p->nMax = 100;

}

/*
** Change the page size for PCache object. The caller must ensure that there
** are no outstanding page references when this function is called.
*/
SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
29423
29424
29425
29426
29427
29428
29429











29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
      }
    }

    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  }

  if( pPage ){











    if( 0==pPage->nRef ){
      pCache->nRef++;
    }
    pPage->nRef++;
    pPage->pData = (void*)&pPage[1];
    pPage->pExtra = (void*)&((char*)pPage->pData)[pCache->szPage];
    pPage->pCache = pCache;
    pPage->pgno = pgno;
    if( pgno==1 ){
      pCache->pPage1 = pPage;
    }
  }
  *ppPage = pPage;
  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
}







>
>
>
>
>
>
>
>
>
>
>




<
<
<
<







29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616




29617
29618
29619
29620
29621
29622
29623
      }
    }

    pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
  }

  if( pPage ){
    if( !pPage->pData ){
      memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
      pPage->pExtra = (void*)&pPage[1];
      pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
      pPage->pCache = pCache;
      pPage->pgno = pgno;
    }
    assert( pPage->pCache==pCache );
    assert( pPage->pgno==pgno );
    assert( pPage->pExtra==(void *)&pPage[1] );

    if( 0==pPage->nRef ){
      pCache->nRef++;
    }
    pPage->nRef++;




    if( pgno==1 ){
      pCache->pPage1 = pPage;
    }
  }
  *ppPage = pPage;
  return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
}
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  }
}

/* 
** Discard the contents of the cache.
*/
SQLITE_PRIVATE int sqlite3PcacheClear(PCache *pCache){
  sqlite3PcacheTruncate(pCache, 0);
  return SQLITE_OK;
}

/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){







|

<







29770
29771
29772
29773
29774
29775
29776
29777
29778

29779
29780
29781
29782
29783
29784
29785
    sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
  }
}

/* 
** Discard the contents of the cache.
*/
SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  sqlite3PcacheTruncate(pCache, 0);

}

/*
** Merge two lists of pages connected by pDirty and in pgno order.
** Do not both fixing the pDirtyPrev pointers.
*/
static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
**
** This file implements the default page cache implementation (the
** sqlite3_pcache interface). It also contains part of the implementation
** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
** If the default page cache implementation is overriden, then neither of
** these two features are available.
**
** @(#) $Id: pcache1.c,v 1.7 2009/01/07 15:18:21 danielk1977 Exp $
*/


typedef struct PCache1 PCache1;
typedef struct PgHdr1 PgHdr1;
typedef struct PgFreeslot PgFreeslot;








|







29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
**
** This file implements the default page cache implementation (the
** sqlite3_pcache interface). It also contains part of the implementation
** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
** If the default page cache implementation is overriden, then neither of
** these two features are available.
**
** @(#) $Id: pcache1.c,v 1.8 2009/01/23 16:45:01 danielk1977 Exp $
*/


typedef struct PCache1 PCache1;
typedef struct PgHdr1 PgHdr1;
typedef struct PgFreeslot PgFreeslot;

29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
/*
** Allocate a new page object initially associated with cache pCache.
*/
static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  int nByte = sizeof(PgHdr1) + pCache->szPage;
  PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
  if( p ){
    memset(p, 0, nByte);
    if( pCache->bPurgeable ){
      pcache1.nCurrentPage++;
    }
  }
  return p;
}








<







30121
30122
30123
30124
30125
30126
30127

30128
30129
30130
30131
30132
30133
30134
/*
** Allocate a new page object initially associated with cache pCache.
*/
static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  int nByte = sizeof(PgHdr1) + pCache->szPage;
  PgHdr1 *p = (PgHdr1 *)pcache1Alloc(nByte);
  if( p ){

    if( pCache->bPurgeable ){
      pcache1.nCurrentPage++;
    }
  }
  return p;
}

30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303


30304
30305
30306
30307
30308
30309
30310
  */
  if( !pPage ){
    pPage = pcache1AllocPage(pCache);
  }

  if( pPage ){
    unsigned int h = iKey % pCache->nHash;
    memset(pPage, 0, pCache->szPage + sizeof(PgHdr1));
    pCache->nPage++;
    pPage->iKey = iKey;
    pPage->pNext = pCache->apHash[h];
    pPage->pCache = pCache;


    pCache->apHash[h] = pPage;
  }

fetch_out:
  if( pPage && iKey>pCache->iMaxKey ){
    pCache->iMaxKey = iKey;
  }







|




>
>







30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
  */
  if( !pPage ){
    pPage = pcache1AllocPage(pCache);
  }

  if( pPage ){
    unsigned int h = iKey % pCache->nHash;
    *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
    pCache->nPage++;
    pPage->iKey = iKey;
    pPage->pNext = pCache->apHash[h];
    pPage->pCache = pCache;
    pPage->pLruPrev = 0;
    pPage->pLruNext = 0;
    pCache->apHash[h] = pPage;
  }

fetch_out:
  if( pPage && iKey>pCache->iMaxKey ){
    pCache->iMaxKey = iKey;
  }
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
**
** @(#) $Id: pager.c,v 1.551 2009/01/14 23:03:41 drh Exp $
*/
#ifndef SQLITE_OMIT_DISKIO

/*
** Macros for troubleshooting.  Normally turned off
*/
#if 0







|







30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
** The pager is used to access a database disk file.  It implements
** atomic commit and rollback through the use of a journal file that
** is separate from the database file.  The pager also implements file
** locking to prevent two processes from writing the same database
** file simultaneously, or one process from reading the database while
** another is writing.
**
** @(#) $Id: pager.c,v 1.561 2009/01/31 14:54:07 danielk1977 Exp $
*/
#ifndef SQLITE_OMIT_DISKIO

/*
** Macros for troubleshooting.  Normally turned off
*/
#if 0
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898










30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909































































30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926



30927
30928






30929
30930


30931


30932
30933
30934
30935
30936
30937
30938
30939











30940
30941

30942
30943
30944
30945
30946
30947
30948
30949
30950
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
30979
  Pgno nOrig;                  /* Original number of pages in file */
  Pgno iSubRec;                /* Index of first record in sub-journal */
};

/*
** A open page cache is an instance of the following structure.
**
** Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
** or SQLITE_FULL. Once one of the first three errors occurs, it persists
** and is returned as the result of every major pager API call.  The
** SQLITE_FULL return code is slightly different. It persists only until the
** next successful rollback is performed on the pager cache. Also,
** SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
** APIs, they may still be used successfully.
**










** Managing the size of the database file in pages is a little complicated.
** The variable Pager.dbSize contains the number of pages that the database
** image currently contains. As the database image grows or shrinks this
** variable is updated. The variable Pager.dbFileSize contains the number
** of pages in the database file. This may be different from Pager.dbSize
** if some pages have been appended to the database image but not yet written
** out from the cache to the actual file on disk. Or if the image has been
** truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
** contains the number of pages in the database image when the current
** transaction was opened. The contents of all three of these variables is
** only guaranteed to be correct if the boolean Pager.dbSizeValid is true.































































*/
struct Pager {
  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
  u8 journalOpen;             /* True if journal file descriptors is valid */
  u8 journalStarted;          /* True if header of journal is synced */
  u8 useJournal;              /* Use a rollback journal on this file */
  u8 noReadlock;              /* Do not bother to obtain readlocks */
  u8 noSync;                  /* Do not sync the journal if true */
  u8 fullSync;                /* Do extra syncs of the journal for robustness */
  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
  u8 tempFile;                /* zFilename is a temporary file */
  u8 readOnly;                /* True for a read-only database */
  u8 needSync;                /* True if an fsync() is needed on the journal */
  u8 dirtyCache;              /* True if cached pages have changed */
  u8 memDb;                   /* True to inhibit all file I/O */
  u8 setMaster;               /* True if a m-j name has been written to jrnl */



  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */






  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
  u8 dbModified;              /* True if there are any changes to the Db */


  u8 changeCountDone;         /* Set after incrementing the change-counter */


  u8 dbSizeValid;             /* Set when dbSize is correct */
  Pgno dbSize;                /* Number of pages in the database */
  Pgno dbOrigSize;            /* dbSize before the current transaction */
  Pgno dbFileSize;            /* Number of pages in the database file */
  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
  int errCode;                /* One of several kinds of errors */
  int nRec;                   /* Number of pages written to the journal */
  u32 cksumInit;              /* Quasi-random value added to every checksum */











  int stmtNRec;               /* Number of records in stmt subjournal */
  int nExtra;                 /* Add this many bytes to each in-memory page */

  int pageSize;               /* Number of bytes in a page */
  int nPage;                  /* Total number of in-memory pages */
  int mxPage;                 /* Maximum number of pages to hold in cache */
  Pgno mxPgno;                /* Maximum allowed size of the database */
  Bitvec *pInJournal;         /* One bit for each page in the database file */
  Bitvec *pAlwaysRollback;    /* One bit for each page marked always-rollback */
  char *zFilename;            /* Name of the database file */
  char *zJournal;             /* Name of the journal file */
  char *zDirectory;           /* Directory hold database and journal files */
  sqlite3_file *fd, *jfd;     /* File descriptors for database and journal */
  sqlite3_file *sjfd;         /* File descriptor for the sub-journal*/
  int (*xBusyHandler)(void*); /* Function to call when busy */
  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
  i64 journalOff;             /* Current byte offset in the journal file */
  i64 journalHdr;             /* Byte offset to previous journal header */
  u32 sectorSize;             /* Assumed sector size during rollback */
#ifdef SQLITE_TEST
  int nHit, nMiss;            /* Cache hits and missing */
  int nRead, nWrite;          /* Database pages read/written */
#endif
  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
#ifdef SQLITE_HAS_CODEC
  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  void *pCodecArg;            /* First argument to xCodec() */
#endif
  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
  char dbFileVers[16];        /* Changes whenever database file changes */
  i64 journalSizeLimit;       /* Size limit for persistent journal files */
  PCache *pPCache;            /* Pointer to page cache object */
  PagerSavepoint *aSavepoint; /* Array of active savepoints */
  int nSavepoint;             /* Number of elements in aSavepoint[] */
};

/*
** The following global variables hold counters used for
** testing purposes only.  These variables do not exist in
** a non-testing build.  These variables are not thread-safe.
*/







|
<
<
<
<
<
<

>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>



|
|





<


<
<

|
>
>
>
|
|
>
>
>
>
>
>
|

>
>

>
>




<

|

>
>
>
>
>
>
>
>
>
>
>
|

>

<
<

<
<


<
<
<


<
<
<










<


<
<







31063
31064
31065
31066
31067
31068
31069
31070






31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
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
31188
31189
31190
31191

31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209


31210


31211
31212



31213
31214



31215
31216
31217
31218
31219
31220
31221
31222
31223
31224

31225
31226


31227
31228
31229
31230
31231
31232
31233
  Pgno nOrig;                  /* Original number of pages in file */
  Pgno iSubRec;                /* Index of first record in sub-journal */
};

/*
** A open page cache is an instance of the following structure.
**
** errCode






**
**   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
**   or SQLITE_FULL. Once one of the first three errors occurs, it persists
**   and is returned as the result of every major pager API call.  The
**   SQLITE_FULL return code is slightly different. It persists only until the
**   next successful rollback is performed on the pager cache. Also,
**   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
**   APIs, they may still be used successfully.
**
** dbSizeValid, dbSize, dbOrigSize, dbFileSize
**
**   Managing the size of the database file in pages is a little complicated.
**   The variable Pager.dbSize contains the number of pages that the database
**   image currently contains. As the database image grows or shrinks this
**   variable is updated. The variable Pager.dbFileSize contains the number
**   of pages in the database file. This may be different from Pager.dbSize
**   if some pages have been appended to the database image but not yet written
**   out from the cache to the actual file on disk. Or if the image has been
**   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
**   contains the number of pages in the database image when the current
**   transaction was opened. The contents of all three of these variables is
**   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
**
**   TODO: Under what conditions is dbSizeValid set? Cleared?
**
** changeCountDone
**
**   This boolean variable is used to make sure that the change-counter 
**   (the 4-byte header field at byte offset 24 of the database file) is 
**   not updated more often than necessary. 
**
**   It is set to true when the change-counter field is updated, which 
**   can only happen if an exclusive lock is held on the database file.
**   It is cleared (set to false) whenever an exclusive lock is 
**   relinquished on the database file. Each time a transaction is committed,
**   The changeCountDone flag is inspected. If it is true, the work of
**   updating the change-counter is omitted for the current transaction.
**
**   This mechanism means that when running in exclusive mode, a connection 
**   need only update the change-counter once, for the first transaction
**   committed.
**
** dbModified
**
**   The dbModified flag is set whenever a database page is dirtied.
**   It is cleared at the end of each transaction.
**
**   It is used when committing or otherwise ending a transaction. If
**   the dbModified flag is clear then less work has to be done.
**
** journalStarted
**
**   This flag is set whenever the the main journal is synced. 
**
**   The point of this flag is that it must be set after the 
**   first journal header in a journal file has been synced to disk.
**   After this has happened, new pages appended to the database 
**   do not need the PGHDR_NEED_SYNC flag set, as they do not need
**   to wait for a journal sync before they can be written out to
**   the database file (see function pager_write()).
**   
** setMaster
**
**   This variable is used to ensure that the master journal file name
**   (if any) is only written into the journal file once.
**
**   When committing a transaction, the master journal file name (if any)
**   may be written into the journal file while the pager is still in
**   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
**   then attempts to upgrade to an exclusive lock. If this attempt
**   fails, then SQLITE_BUSY may be returned to the user and the user
**   may attempt to commit the transaction again later (calling
**   CommitPhaseOne() again). This flag is used to ensure that the 
**   master journal name is only written to the journal file the first
**   time CommitPhaseOne() is called.
**
** doNotSync
**
**   This variable is set and cleared by sqlite3PagerWrite().
**
** needSync
**
**   TODO: It might be easier to set this variable in writeJournalHdr()
**   and writeMasterJournal() only. Change its meaning to "unsynced data
**   has been written to the journal".
*/
struct Pager {
  sqlite3_vfs *pVfs;          /* OS functions to use for IO */
  u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
  u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
  u8 useJournal;              /* Use a rollback journal on this file */
  u8 noReadlock;              /* Do not bother to obtain readlocks */
  u8 noSync;                  /* Do not sync the journal if true */
  u8 fullSync;                /* Do extra syncs of the journal for robustness */
  u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */

  u8 tempFile;                /* zFilename is a temporary file */
  u8 readOnly;                /* True for a read-only database */


  u8 memDb;                   /* True to inhibit all file I/O */

  /* The following block contains those class members that are dynamically
  ** modified during normal operations. The other variables in this structure
  ** are either constant throughout the lifetime of the pager, or else
  ** used to store configuration parameters that affect the way the pager 
  ** operates.
  **
  ** The 'state' variable is described in more detail along with the
  ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
  ** other variables in this block are described in the comment directly 
  ** above this class definition.
  */
  u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
  u8 dbModified;              /* True if there are any changes to the Db */
  u8 needSync;                /* True if an fsync() is needed on the journal */
  u8 journalStarted;          /* True if header of journal is synced */
  u8 changeCountDone;         /* Set after incrementing the change-counter */
  u8 setMaster;               /* True if a m-j name has been written to jrnl */
  u8 doNotSync;               /* Boolean. While true, do not spill the cache */
  u8 dbSizeValid;             /* Set when dbSize is correct */
  Pgno dbSize;                /* Number of pages in the database */
  Pgno dbOrigSize;            /* dbSize before the current transaction */
  Pgno dbFileSize;            /* Number of pages in the database file */

  int errCode;                /* One of several kinds of errors */
  int nRec;                   /* Pages journalled since last j-header written */
  u32 cksumInit;              /* Quasi-random value added to every checksum */
  u32 nSubRec;                /* Number of records written to sub-journal */
  Bitvec *pInJournal;         /* One bit for each page in the database file */
  sqlite3_file *fd;           /* File descriptor for database */
  sqlite3_file *jfd;          /* File descriptor for main journal */
  sqlite3_file *sjfd;         /* File descriptor for sub-journal */
  i64 journalOff;             /* Current write offset in the journal file */
  i64 journalHdr;             /* Byte offset to previous journal header */
  PagerSavepoint *aSavepoint; /* Array of active savepoints */
  int nSavepoint;             /* Number of elements in aSavepoint[] */
  char dbFileVers[16];        /* Changes whenever database file changes */
  u32 sectorSize;             /* Assumed sector size during rollback */

  int nExtra;                 /* Add this many bytes to each in-memory page */
  u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
  int pageSize;               /* Number of bytes in a page */


  Pgno mxPgno;                /* Maximum allowed size of the database */


  char *zFilename;            /* Name of the database file */
  char *zJournal;             /* Name of the journal file */



  int (*xBusyHandler)(void*); /* Function to call when busy */
  void *pBusyHandlerArg;      /* Context argument for xBusyHandler */



#ifdef SQLITE_TEST
  int nHit, nMiss;            /* Cache hits and missing */
  int nRead, nWrite;          /* Database pages read/written */
#endif
  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
#ifdef SQLITE_HAS_CODEC
  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  void *pCodecArg;            /* First argument to xCodec() */
#endif
  char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */

  i64 journalSizeLimit;       /* Size limit for persistent journal files */
  PCache *pPCache;            /* Pointer to page cache object */


};

/*
** The following global variables hold counters used for
** testing purposes only.  These variables do not exist in
** a non-testing build.  These variables are not thread-safe.
*/
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
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
** is different for every journal, we minimize that risk.
*/
static const unsigned char aJournalMagic[] = {
  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
};

/*
** The size of the header and of each page in the journal is determined
** by the following macros.
*/
#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)

/*
** The journal header size for this pager. In the future, this could be
** set to some value read from the disk controller. The important
** characteristic is that it is the same size as a disk sector.
*/
#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)

/*
** The macro MEMDB is true if we are dealing with an in-memory database.
** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
** the value of MEMDB will be a constant and the compiler will optimize
** out code that would never execute.
*/
#ifdef SQLITE_OMIT_MEMORYDB
# define MEMDB 0
#else
# define MEMDB pPager->memDb
#endif

/*
** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
** reserved for working around a windows/posix incompatibility). It is
** used in the journal to signify that the remainder of the journal file 
** is devoted to storing a master journal name - there are no more pages to
** roll back. See comments for function writeMasterJournal() for details.
*/
/* #define PAGER_MJ_PGNO(x) (PENDING_BYTE/((x)->pageSize)) */
#define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))

/*
** The maximum legal page number is (2^31 - 1).
*/
#define PAGER_MAX_PGNO 2147483647



















/*
** Return true if it is necessary to write page *pPg into the sub-journal.
** A page needs to be written into the sub-journal if there exists one
** or more open savepoints for which:
**
**   * The page-number is less than or equal to PagerSavepoint.nOrig, and







|
|




|
<
|















<
<
<
<
<
<
<
<
<
<




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279

31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
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
31321
31322
31323
31324
** is different for every journal, we minimize that risk.
*/
static const unsigned char aJournalMagic[] = {
  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
};

/*
** The size of the of each page record in the journal is given by
** the following macro.
*/
#define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)

/*
** The journal header size for this pager. This is usually the same 

** size as a single disk sector. See also setSectorSize().
*/
#define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)

/*
** The macro MEMDB is true if we are dealing with an in-memory database.
** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
** the value of MEMDB will be a constant and the compiler will optimize
** out code that would never execute.
*/
#ifdef SQLITE_OMIT_MEMORYDB
# define MEMDB 0
#else
# define MEMDB pPager->memDb
#endif











/*
** The maximum legal page number is (2^31 - 1).
*/
#define PAGER_MAX_PGNO 2147483647

#ifndef NDEBUG 
/*
** Usage:
**
**   assert( assert_pager_state(pPager) );
*/
static int assert_pager_state(Pager *pPager){

  /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
  assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );

  /* The changeCountDone flag is always set for temp-files */
  assert( pPager->tempFile==0 || pPager->changeCountDone );

  return 1;
}
#endif

/*
** Return true if it is necessary to write page *pPg into the sub-journal.
** A page needs to be written into the sub-journal if there exists one
** or more open savepoints for which:
**
**   * The page-number is less than or equal to PagerSavepoint.nOrig, and
31111
31112
31113
31114
31115
31116
31117














31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135




31136
31137
31138
31139
31140
31141
31142


31143
31144
31145
31146
31147
31148

31149
31150
31151
31152
31153
31154
31155
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
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207

31208
31209
31210
31211
31212
31213
31214
*/
static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  char ac[4];
  put32bits(ac, val);
  return sqlite3OsWrite(fd, ac, 4, offset);
}















/*
** If file pFd is open, call sqlite3OsUnlock() on it.
*/
static int osUnlock(sqlite3_file *pFd, int eLock){
  if( !pFd->pMethods ){
    return SQLITE_OK;
  }
  return sqlite3OsUnlock(pFd, eLock);
}

/*
** This function determines whether or not the atomic-write optimization
** can be used with this pager. The optimization can be used if:
**
**  (a) the value returned by OsDeviceCharacteristics() indicates that
**      a database page may be written atomically, and
**  (b) the value returned by OsSectorSize() is less than or equal
**      to the page size.




**
** If the optimization cannot be used, 0 is returned. If it can be used,
** then the value returned is the size of the journal file when it
** contains rollback data for exactly one page.
*/
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
static int jrnlBufferSize(Pager *pPager){


  int dc;           /* Device characteristics */
  int nSector;      /* Sector size */
  int szPage;        /* Page size */
  sqlite3_file *fd = pPager->fd;

  if( fd->pMethods ){

    dc = sqlite3OsDeviceCharacteristics(fd);
    nSector = pPager->sectorSize;
    szPage = pPager->pageSize;
  }

  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));

  if( !fd->pMethods || 
       (dc & (SQLITE_IOCAP_ATOMIC|(szPage>>8)) && nSector<=szPage) ){
    return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  }
  return 0;
}
#endif

/*
** 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. 
**
** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
** the error becomes persistent. Until the persisten error is cleared,
** subsequent API calls on this Pager will immediately return the same 
** error code.
**
** A persistent error indicates that the contents of the pager-cache 
** cannot be trusted. This state can be cleared by completely discarding 
** the contents of the pager-cache. If a transaction was active when
** the persistent error occured, then the rollback journal may need
** to be replayed.
*/
static void pager_unlock(Pager *pPager);
static int pager_error(Pager *pPager, int rc){
  int rc2 = rc & 0xff;
  assert(
       pPager->errCode==SQLITE_FULL ||
       pPager->errCode==SQLITE_OK ||
       (pPager->errCode & 0xff)==SQLITE_IOERR
  );
  if(
    rc2==SQLITE_FULL ||
    rc2==SQLITE_IOERR ||
    rc2==SQLITE_CORRUPT
  ){
    pPager->errCode = rc;
    if( pPager->state==PAGER_UNLOCK 
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
    ){
      /* If the pager is already unlocked, call pager_unlock() now to
      ** clear the error state and ensure that the pager-cache is 
      ** completely empty.
      */
      pager_unlock(pPager);
    }
  }
  return rc;
}


/*
** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
** on the cache using a hash function.  This is used for testing
** and debugging only.
*/
#ifdef SQLITE_CHECK_PAGES







>
>
>
>
>
>
>
>
>
>
>
>
>
>




|













>
>
>
>







>
>
|
|
|
<

<
>
|


|
<
|
|
<
<
|
<
<
|
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
|

>







31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426

31427

31428
31429
31430
31431
31432

31433
31434


31435


31436
31437

31438







































31439

31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
*/
static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  char ac[4];
  put32bits(ac, val);
  return sqlite3OsWrite(fd, ac, 4, offset);
}

/*
** The argument to this macro is a file descriptor (type sqlite3_file*).
** Return 0 if it is not open, or non-zero (but not 1) if it is.
**
** This is so that expressions can be written as:
**
**   if( isOpen(pPager->jfd) ){ ...
**
** instead of
**
**   if( pPager->jfd->pMethods ){ ...
*/
#define isOpen(pFd) ((pFd)->pMethods)

/*
** If file pFd is open, call sqlite3OsUnlock() on it.
*/
static int osUnlock(sqlite3_file *pFd, int eLock){
  if( !isOpen(pFd) ){
    return SQLITE_OK;
  }
  return sqlite3OsUnlock(pFd, eLock);
}

/*
** This function determines whether or not the atomic-write optimization
** can be used with this pager. The optimization can be used if:
**
**  (a) the value returned by OsDeviceCharacteristics() indicates that
**      a database page may be written atomically, and
**  (b) the value returned by OsSectorSize() is less than or equal
**      to the page size.
**
** The optimization is also always enabled for temporary files. It is
** an error to call this function if pPager is opened on an in-memory
** database.
**
** If the optimization cannot be used, 0 is returned. If it can be used,
** then the value returned is the size of the journal file when it
** contains rollback data for exactly one page.
*/
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
static int jrnlBufferSize(Pager *pPager){
  assert( !MEMDB );
  if( !pPager->tempFile ){
    int dc;                           /* Device characteristics */
    int nSector;                      /* Sector size */
    int szPage;                       /* Page size */



    assert( isOpen(pPager->fd) );
    dc = sqlite3OsDeviceCharacteristics(pPager->fd);
    nSector = pPager->sectorSize;
    szPage = pPager->pageSize;


    assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
    assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));


    if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){


      return 0;
    }

  }









































  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
}
#endif

/*
** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
** on the cache using a hash function.  This is used for testing
** and debugging only.
*/
#ifdef SQLITE_CHECK_PAGES
31246
31247
31248
31249
31250
31251
31252

31253
31254

31255
31256
31257
31258
31259
31260
31261
31262





31263
31264



31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
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
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344







31345






31346

31347


31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359

31360
31361
31362
31363
31364
31365
31366
#define pager_datahash(X,Y)  0
#define pager_pagehash(X)  0
#define CHECK_PAGE(x)
#endif  /* SQLITE_CHECK_PAGES */

/*
** When this is called the journal file for pager pPager must be open.

** The master journal file name is read from the end of the file and 
** written into memory supplied by the caller. 

**
** zMaster must point to a buffer of at least nMaster bytes allocated by
** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
** enough space to write the master journal name). If the master journal
** name in the journal is longer than nMaster bytes (including a
** nul-terminator), then this is handled as if no master journal name
** were present in the journal.
**





** If no master journal file name is present zMaster[0] is set to 0 and
** SQLITE_OK returned.



*/
static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  int rc;
  u32 len;
  i64 szJ;
  u32 cksum;
  u32 u;                   /* Unsigned loop counter */
  unsigned char aMagic[8]; /* A buffer to hold the magic header */

  zMaster[0] = '\0';

  rc = sqlite3OsFileSize(pJrnl, &szJ);
  if( rc!=SQLITE_OK || szJ<16 ) return rc;

  rc = read32bits(pJrnl, szJ-16, &len);
  if( rc!=SQLITE_OK ) return rc;

  if( len>=nMaster ){
    return SQLITE_OK;
  }

  rc = read32bits(pJrnl, szJ-12, &cksum);
  if( rc!=SQLITE_OK ) return rc;

  rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8);
  if( rc!=SQLITE_OK || memcmp(aMagic, aJournalMagic, 8) ) return rc;

  rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  zMaster[len] = '\0';

  /* See if the checksum matches the master journal name */
  for(u=0; u<len; u++){
    cksum -= zMaster[u];
   }
  if( cksum ){
    /* If the checksum doesn't add up, then one or more of the disk sectors
    ** containing the master journal filename is corrupted. This means
    ** definitely roll back, so just return SQLITE_OK and report a (nul)
    ** master-journal filename.
    */
    zMaster[0] = '\0';
  }

   
  return SQLITE_OK;
}

/*
** Seek the journal file descriptor to the next sector boundary where a
** journal header may be read or written. Pager.journalOff is updated with
** the new seek offset.
**
** i.e for a sector size of 512:
**
** Input Offset              Output Offset
** ---------------------------------------
** 0                         0
** 512                       512
** 100                       512
** 2000                      2048
** 
*/
static i64 journalHdrOffset(Pager *pPager){
  i64 offset = 0;
  i64 c = pPager->journalOff;
  if( c ){
    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  }
  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  assert( offset>=c );
  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  return offset;
}
static void seekJournalHdr(Pager *pPager){
  pPager->journalOff = journalHdrOffset(pPager);
}

/*







** Write zeros over the header of the journal file.  This has the






** effect of invalidating the journal file and committing the

** transaction.


*/
static int zeroJournalHdr(Pager *pPager, int doTruncate){
  int rc = SQLITE_OK;
  static const char zeroHdr[28] = {0};

  if( pPager->journalOff ){
    i64 iLimit = pPager->journalSizeLimit;

    IOTRACE(("JZEROHDR %p\n", pPager))
    if( doTruncate || iLimit==0 ){
      rc = sqlite3OsTruncate(pPager->jfd, 0);
    }else{

      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
    }
    if( rc==SQLITE_OK && !pPager->noSync ){
      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
    }

    /* At this point the transaction is committed but the write lock 







>
|
|
>








>
>
>
>
>
|
|
>
>
>


|
|
|
|
|
|
<


|
|
<
|
<
<
|
<
<
<
|
<
<
|
|
<
|
|


<




|






|

>





|
|
|



|
|
|
|
|
|













<
<
|
<

>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
>
|
>
>


|
<
|

|





>







31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517

31518
31519
31520
31521

31522


31523



31524


31525
31526

31527
31528
31529
31530

31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574


31575

31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598

31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
#define pager_datahash(X,Y)  0
#define pager_pagehash(X)  0
#define CHECK_PAGE(x)
#endif  /* SQLITE_CHECK_PAGES */

/*
** When this is called the journal file for pager pPager must be open.
** This function attempts to read a master journal file name from the 
** end of the file and, if successful, copies it into memory supplied 
** by the caller. See comments above writeMasterJournal() for the format
** used to store a master journal file name at the end of a journal file.
**
** zMaster must point to a buffer of at least nMaster bytes allocated by
** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
** enough space to write the master journal name). If the master journal
** name in the journal is longer than nMaster bytes (including a
** nul-terminator), then this is handled as if no master journal name
** were present in the journal.
**
** If a master journal file name is present at the end of the journal
** file, then it is copied into the buffer pointed to by zMaster. A
** nul-terminator byte is appended to the buffer following the master
** journal file name.
**
** If it is determined that no master journal file name is present 
** zMaster[0] is set to 0 and SQLITE_OK returned.
**
** If an error occurs while reading from the journal file, an SQLite
** error code is returned.
*/
static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  int rc;                    /* Return code */
  u32 len;                   /* Length in bytes of master journal name */
  i64 szJ;                   /* Total size in bytes of journal file pJrnl */
  u32 cksum;                 /* MJ checksum value read from journal */
  u32 u;                     /* Unsigned loop counter */
  unsigned char aMagic[8];   /* A buffer to hold the magic header */

  zMaster[0] = '\0';

  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
   || szJ<16

   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))


   || len>=nMaster 



   || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))


   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
   || memcmp(aMagic, aJournalMagic, 8)

   || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  ){
    return rc;
  }


  /* See if the checksum matches the master journal name */
  for(u=0; u<len; u++){
    cksum -= zMaster[u];
  }
  if( cksum ){
    /* If the checksum doesn't add up, then one or more of the disk sectors
    ** containing the master journal filename is corrupted. This means
    ** definitely roll back, so just return SQLITE_OK and report a (nul)
    ** master-journal filename.
    */
    len = 0;
  }
  zMaster[len] = '\0';
   
  return SQLITE_OK;
}

/*
** Return the offset of the sector boundary at or immediately 
** following the value in pPager->journalOff, assuming a sector 
** size of pPager->sectorSize bytes.
**
** i.e for a sector size of 512:
**
**   Pager.journalOff          Return value
**   ---------------------------------------
**   0                         0
**   512                       512
**   100                       512
**   2000                      2048
** 
*/
static i64 journalHdrOffset(Pager *pPager){
  i64 offset = 0;
  i64 c = pPager->journalOff;
  if( c ){
    offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  }
  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  assert( offset>=c );
  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  return offset;
}




/*
** The journal file must be open when this function is called.
**
** This function is a no-op if the journal file has not been written to
** within the current transaction (i.e. if Pager.journalOff==0).
**
** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
** zero the 28-byte header at the start of the journal file. In either case, 
** if the pager is not in no-sync mode, sync the journal file immediately 
** after writing or truncating it.
**
** If Pager.journalSizeLimit is set to a positive, non-zero value, and
** following the truncation or zeroing described above the size of the 
** journal file in bytes is larger than this value, then truncate the
** journal file to Pager.journalSizeLimit bytes. The journal file does
** not need to be synced following this operation.
**
** If an IO error occurs, abandon processing and return the IO error code.
** Otherwise, return SQLITE_OK.
*/
static int zeroJournalHdr(Pager *pPager, int doTruncate){
  int rc = SQLITE_OK;                               /* Return code */

  assert( isOpen(pPager->jfd) );
  if( pPager->journalOff ){
    const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */

    IOTRACE(("JZEROHDR %p\n", pPager))
    if( doTruncate || iLimit==0 ){
      rc = sqlite3OsTruncate(pPager->jfd, 0);
    }else{
      static const char zeroHdr[28] = {0};
      rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
    }
    if( rc==SQLITE_OK && !pPager->noSync ){
      rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
    }

    /* At this point the transaction is committed but the write lock 
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403


31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
** - 4 bytes: Initial database page count.
** - 4 bytes: Sector size used by the process that wrote this journal.
** - 4 bytes: Database page size.
** 
** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
*/
static int writeJournalHdr(Pager *pPager){
  int rc = SQLITE_OK;
  char *zHeader = pPager->pTmpSpace;
  u32 nHeader = pPager->pageSize;
  u32 nWrite;
  int ii;



  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
    nHeader = JOURNAL_HDR_SZ(pPager);
  }

  /* If there are active savepoints and any of them were created since the
  ** most recent journal header was written, update the PagerSavepoint.iHdrOff
  ** fields now.
  */
  for(ii=0; ii<pPager->nSavepoint; ii++){
    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
    }
  }

  seekJournalHdr(pPager);
  pPager->journalHdr = pPager->journalOff;

  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));

  /* 
  ** Write the nRec Field - the number of page records that follow this
  ** journal header. Normally, zero is written to this value at this time.
  ** After the records are added to the journal (and the journal synced, 
  ** if in full-sync mode), the zero is overwritten with the true number







|
|
|
|
|
>
>





|
|
|







<
|
<







31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668

31669

31670
31671
31672
31673
31674
31675
31676
** - 4 bytes: Initial database page count.
** - 4 bytes: Sector size used by the process that wrote this journal.
** - 4 bytes: Database page size.
** 
** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
*/
static int writeJournalHdr(Pager *pPager){
  int rc = SQLITE_OK;                 /* Return code */
  char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
  u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
  u32 nWrite;                         /* Bytes of header sector written */
  int ii;                             /* Loop counter */

  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */

  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
    nHeader = JOURNAL_HDR_SZ(pPager);
  }

  /* If there are active savepoints and any of them were created 
  ** since the most recent journal header was written, update the 
  ** PagerSavepoint.iHdrOffset fields now.
  */
  for(ii=0; ii<pPager->nSavepoint; ii++){
    if( pPager->aSavepoint[ii].iHdrOffset==0 ){
      pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
    }
  }


  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);

  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));

  /* 
  ** Write the nRec Field - the number of page records that follow this
  ** journal header. Normally, zero is written to this value at this time.
  ** After the records are added to the journal (and the journal synced, 
  ** if in full-sync mode), the zero is overwritten with the true number
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460



31461
31462
31463
31464
31465
31466
31467
31468


31469










31470
31471
31472
31473


31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511




31512
31513
31514
31515
31516
31517





31518
31519
31520
31521
31522
31523
31524
31525




31526
31527
31528
31529

31530
31531
31532
31533
31534
31535






31536

31537
31538






31539
31540
31541
31542
31543
31544
31545

31546
31547

31548




31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606




31607

31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623





31624
31625
31626
31627
31628

31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660

31661
31662
31663




31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676

31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700

31701
31702
31703
31704
31705
31706
31707
31708
31709

31710
31711
31712
31713
31714
31715
31716
31717

31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740






31741
31742
31743
31744

31745
31746
31747
31748
31749
31750
31751
31752


31753

31754
31755
31756
31757
31758
31759

































31760






31761
31762
31763

31764

31765
31766


31767
31768










31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
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
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836

31837

31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853

31854



31855
31856
31857
31858
31859
31860
31861
31862
31863
31864

31865

31866
31867
31868
31869

31870
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
  **
  **   * When the pager is in no-sync mode. Corruption can follow a
  **     power failure in this case anyway.
  **
  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  **     that garbage data is never appended to the journal file.
  */
  assert(pPager->fd->pMethods||pPager->noSync);
  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
  ){
    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  }else{
    put32bits(&zHeader[sizeof(aJournalMagic)], 0);
  }

  /* The random check-hash initialiser */ 
  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  /* The initial database size */
  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  /* The assumed sector size for this process */
  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);




  /* Initializing the tail of the buffer is not necessary.  Everything
  ** works find if the following memset() is omitted.  But initializing
  ** the memory prevents valgrind from complaining, so we are willing to
  ** take the performance hit.
  */
  memset(&zHeader[sizeof(aJournalMagic)+16], 0,
         nHeader-(sizeof(aJournalMagic)+16));



  if( pPager->journalHdr==0 ){










    /* The page size */
    put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  }



  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
    pPager->journalOff += nHeader;
  }

  return rc;
}

/*
** The journal file must be open when this is called. A journal header file
** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
** file. The current location in the journal file is given by
** pPager->journalOff.  See comments above function writeJournalHdr() for
** a description of the journal header format.
**
** If the header is read successfully, *nRec is set to the number of
** page records following this header and *dbSize is set to the size of the
** database before the transaction began, in pages. Also, pPager->cksumInit
** is set to the value read from the journal header. SQLITE_OK is returned
** in this case.
**
** If the journal header file appears to be corrupted, SQLITE_DONE is
** returned and *nRec and *dbSize are undefined.  If JOURNAL_HDR_SZ bytes
** cannot be read from the journal file an error code is returned.
*/
static int readJournalHdr(
  Pager *pPager, 
  i64 journalSize,
  u32 *pNRec, 
  u32 *pDbSize
){
  int rc;
  unsigned char aMagic[8]; /* A buffer to hold the magic header */
  i64 jrnlOff;
  u32 iPageSize;
  u32 iSectorSize;





  seekJournalHdr(pPager);
  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
    return SQLITE_DONE;
  }
  jrnlOff = pPager->journalOff;






  rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), jrnlOff);
  if( rc ) return rc;
  jrnlOff += sizeof(aMagic);

  if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
    return SQLITE_DONE;
  }





  rc = read32bits(pPager->jfd, jrnlOff, pNRec);
  if( rc ) return rc;

  rc = read32bits(pPager->jfd, jrnlOff+4, &pPager->cksumInit);

  if( rc ) return rc;

  rc = read32bits(pPager->jfd, jrnlOff+8, pDbSize);
  if( rc ) return rc;

  if( pPager->journalOff==0 ){






    rc = read32bits(pPager->jfd, jrnlOff+16, &iPageSize);

    if( rc ) return rc;







    if( iPageSize<512 
     || iPageSize>SQLITE_MAX_PAGE_SIZE 
     || ((iPageSize-1)&iPageSize)!=0 
    ){
      /* If the page-size in the journal-header is invalid, then the process
      ** that wrote the journal-header must have crashed before the header
      ** was synced. In this case stop reading the journal file here.

      */
      rc = SQLITE_DONE;

    }else{




      u16 pagesize = (u16)iPageSize;
      rc = sqlite3PagerSetPagesize(pPager, &pagesize);
      assert( rc!=SQLITE_OK || pagesize==(u16)iPageSize );
    }
    if( rc ) return rc;
  
    /* Update the assumed sector-size to match the value used by 
    ** the process that created this journal. If this journal was
    ** created by a process other than this one, then this routine
    ** is being called from within pager_playback(). The local value
    ** of Pager.sectorSize is restored at the end of that routine.
    */
    rc = read32bits(pPager->jfd, jrnlOff+12, &iSectorSize);
    if( rc ) return rc;
    if( (iSectorSize&(iSectorSize-1))
      || iSectorSize<512
      || iSectorSize>MAX_SECTOR_SIZE
    ){
      return SQLITE_DONE;
    }
    pPager->sectorSize = iSectorSize;
  }

  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  return SQLITE_OK;
}


/*
** Write the supplied master journal name into the journal file for pager
** pPager at the current location. The master journal name must be the last
** thing written to a journal file. If the pager is in full-sync mode, the
** journal file descriptor is advanced to the next sector boundary before
** anything is written. The format is:
**
** + 4 bytes: PAGER_MJ_PGNO.
** + N bytes: length of master journal name.
** + 4 bytes: N
** + 4 bytes: Master journal name checksum.
** + 8 bytes: aJournalMagic[].
**
** The master journal page checksum is the sum of the bytes in the master
** journal name.
**
** If zMaster is a NULL pointer (occurs for a single database transaction), 
** this call is a no-op.
*/
static int writeMasterJournal(Pager *pPager, const char *zMaster){
  int rc;
  int len; 
  int i; 
  i64 jrnlOff;
  i64 jrnlSize;
  u32 cksum = 0;
  char zBuf[sizeof(aJournalMagic)+2*4];

  if( !zMaster || pPager->setMaster ) return SQLITE_OK;
  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ) return SQLITE_OK;




  pPager->setMaster = 1;


  len = sqlite3Strlen30(zMaster);
  for(i=0; i<len; i++){
    cksum += zMaster[i];
  }

  /* If in full-sync mode, advance to the next disk sector before writing
  ** the master journal name. This is in case the previous page written to
  ** the journal has already been synced.
  */
  if( pPager->fullSync ){
    seekJournalHdr(pPager);
  }
  jrnlOff = pPager->journalOff;
  pPager->journalOff += (len+20);






  rc = write32bits(pPager->jfd, jrnlOff, PAGER_MJ_PGNO(pPager));
  if( rc!=SQLITE_OK ) return rc;
  jrnlOff += 4;

  rc = sqlite3OsWrite(pPager->jfd, zMaster, len, jrnlOff);

  if( rc!=SQLITE_OK ) return rc;
  jrnlOff += len;

  put32bits(zBuf, len);
  put32bits(&zBuf[4], cksum);
  memcpy(&zBuf[8], aJournalMagic, sizeof(aJournalMagic));
  rc = sqlite3OsWrite(pPager->jfd, zBuf, 8+sizeof(aJournalMagic), jrnlOff);
  jrnlOff += 8+sizeof(aJournalMagic);
  pPager->needSync = !pPager->noSync;

  /* If the pager is in peristent-journal mode, then the physical 
  ** journal-file may extend past the end of the master-journal name
  ** and 8 bytes of magic data just written to the file. This is 
  ** dangerous because the code to rollback a hot-journal file
  ** will not be able to find the master-journal name to determine 
  ** whether or not the journal is hot. 
  **
  ** Easiest thing to do in this scenario is to truncate the journal 
  ** file to the required size.
  */ 
  if( (rc==SQLITE_OK)
   && (rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))==SQLITE_OK
   && jrnlSize>jrnlOff
  ){
    rc = sqlite3OsTruncate(pPager->jfd, jrnlOff);
  }
  return rc;
}

/*
** Find a page in the hash table given its page number.  Return
** a pointer to the page or NULL if not found.

*/
static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  PgHdr *p;




  sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  return p;
}

/*
** Clear the in-memory cache.  This routine
** sets the state of the pager back to what it was when it was first
** opened.  Any outstanding pages are invalidated and subsequent attempts
** to access those pages will likely result in a coredump.
*/
static void pager_reset(Pager *pPager){
  if( pPager->errCode ) return;
  sqlite3PcacheClear(pPager->pPCache);

}

/*
** Free all structures in the Pager.aSavepoint[] array and set both
** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
** if it is open and the pager is not in exclusive mode.
*/
static void releaseAllSavepoint(Pager *pPager){
  int ii;
  for(ii=0; ii<pPager->nSavepoint; ii++){
    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  }
  if( !pPager->exclusiveMode ){
    sqlite3OsClose(pPager->sjfd);
  }
  sqlite3_free(pPager->aSavepoint);
  pPager->aSavepoint = 0;
  pPager->nSavepoint = 0;
  pPager->stmtNRec = 0;
}

/*
** Set the bit number pgno in the PagerSavepoint.pInSavepoint bitvecs of
** all open savepoints.

*/
static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  int ii;                   /* Loop counter */
  int rc = SQLITE_OK;       /* Result code */

  for(ii=0; ii<pPager->nSavepoint; ii++){
    PagerSavepoint *p = &pPager->aSavepoint[ii];
    if( pgno<=p->nOrig ){
      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);

      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
    }
  }
  return rc;
}

/*
** Unlock the database file. 

**
** If the pager is currently in error state, discard the contents of 
** the cache and reset the Pager structure internal state. If there is
** an open journal-file, then the next time a shared-lock is obtained
** on the pager file (by this or any other process), it will be
** treated as a hot-journal and rolled back.
*/
static void pager_unlock(Pager *pPager){
  if( !pPager->exclusiveMode ){
    int rc;

    /* Always close the journal file when dropping the database lock.
    ** Otherwise, another connection with journal_mode=delete might
    ** delete the file out from under us.
    */
    if( pPager->journalOpen ){
      sqlite3OsClose(pPager->jfd);
      pPager->journalOpen = 0;
      sqlite3BitvecDestroy(pPager->pInJournal);
      pPager->pInJournal = 0;
      sqlite3BitvecDestroy(pPager->pAlwaysRollback);
      pPager->pAlwaysRollback = 0;
    }







    rc = osUnlock(pPager->fd, NO_LOCK);
    if( rc ) pPager->errCode = rc;
    pPager->dbSizeValid = 0;

    IOTRACE(("UNLOCK %p\n", pPager))

    /* If Pager.errCode is set, the contents of the pager cache cannot be
    ** trusted. Now that the pager file is unlocked, the contents of the
    ** cache can be discarded and the error code safely cleared.
    */
    if( pPager->errCode ){
      if( rc==SQLITE_OK ) pPager->errCode = SQLITE_OK;


      pager_reset(pPager);

      releaseAllSavepoint(pPager);
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
      pPager->dbOrigSize = 0;
    }


































    pPager->state = PAGER_UNLOCK;






    pPager->changeCountDone = 0;
  }
}



/*
** Execute a rollback if a transaction is active and unlock the 


** database file. If the pager has already entered the error state, 
** do not attempt the rollback.










*/
static void pagerUnlockAndRollback(Pager *p){
  if( p->errCode==SQLITE_OK && p->state>=PAGER_RESERVED ){
    sqlite3BeginBenignMalloc();
    sqlite3PagerRollback(p);
    sqlite3EndBenignMalloc();
  }
  pager_unlock(p);
}

/*
** This routine ends a transaction.  A transaction is ended by either
** a COMMIT or a ROLLBACK.



**

** When this routine is called, the pager has the journal file open and
** a RESERVED or EXCLUSIVE lock on the database.  This routine will release






** the database lock and acquires a SHARED lock in its place if that is
** the appropriate thing to do.  Release locks usually is appropriate,
** unless we are in exclusive access mode or unless this is a 
** COMMIT AND BEGIN or ROLLBACK AND BEGIN operation.

**













** The journal file is either deleted or truncated.
**

** TODO: Consider keeping the journal file open for temporary databases.
** This might give a performance improvement on windows where opening














** a file is an expensive operation.




*/
static int pager_end_transaction(Pager *pPager, int hasMaster){
  int rc = SQLITE_OK;
  int rc2 = SQLITE_OK;

  if( pPager->state<PAGER_RESERVED ){
    return SQLITE_OK;
  }
  releaseAllSavepoint(pPager);
  if( pPager->journalOpen ){












    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
      sqlite3OsClose(pPager->jfd);
      pPager->journalOpen = 0;
      if( !isMemoryJournal ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
      }
    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
         && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else if( pPager->exclusiveMode 
     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
    ){
      rc = zeroJournalHdr(pPager, hasMaster);
      pager_error(pPager, rc);
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else{
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
      sqlite3OsClose(pPager->jfd);
      pPager->journalOpen = 0;
      if( rc==SQLITE_OK && !pPager->tempFile ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
      }
    }
    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
    sqlite3BitvecDestroy(pPager->pAlwaysRollback);
    pPager->pAlwaysRollback = 0;
#ifdef SQLITE_CHECK_PAGES
    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
#endif

    sqlite3PcacheCleanAll(pPager->pPCache);

    pPager->dirtyCache = 0;
    pPager->nRec = 0;
  }else{
    assert( pPager->pInJournal==0 );
  }

  if( !pPager->exclusiveMode ){
    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
    pPager->state = PAGER_SHARED;
    pPager->changeCountDone = 0;
  }else if( pPager->state==PAGER_SYNCED ){
    pPager->state = PAGER_EXCLUSIVE;
  }
  pPager->dbOrigSize = 0;
  pPager->setMaster = 0;
  pPager->needSync = 0;

  /* lruListSetFirstSynced(pPager); */



  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  if( !MEMDB ){
    pPager->dbSizeValid = 0;
  }
  pPager->dbModified = 0;

  return (rc==SQLITE_OK?rc2:rc);
}

/*

** Compute and return a checksum for the page of data.

**
** This is not a real checksum.  It is really just the sum of the 
** random initial value and the page number.  We experimented with
** a checksum of the entire data, but that was found to be too slow.

**
** Note that the page number is stored at the beginning of data and

** the checksum is stored at the end.  This is important.  If journal

** corruption occurs due to a power failure, the most likely scenario
** is that one end or the other of the record will be changed.  It is
** much less likely that the two ends of the journal record will be
** correct and the middle be corrupt.  Thus, this "checksum" scheme,
** though fast and simple, catches the mostly likely kind of corruption.
**
** FIX ME:  Consider adding every 200th (or so) byte of the data to the
** checksum.  That way if a single page spans 3 or more disk sectors and
** only the middle sector is corrupt, we will still have a reasonable
** chance of failing the checksum and thus detecting the problem.
*/
static u32 pager_cksum(Pager *pPager, const u8 *aData){
  u32 cksum = pPager->cksumInit;
  int i = pPager->pageSize-200;
  while( i>0 ){
    cksum += aData[i];
    i -= 200;
  }
  return cksum;
}

/*
** Read a single page from either the journal file (if isMainJrnl==1) or
** from the sub-journal (if isMainJrnl==0) and playback that page.
** The page begins at offset *pOffset into the file.  The  *pOffset
** value is increased to the start of the next page in the journal.
**
** The isMainJrnl flag is true if this is the main rollback journal and
** false for the statement journal.  The main rollback journal uses
** checksums - the statement journal does not.




**
** If pDone is not NULL, then it is a record of pages that have already
** been played back.  If the page at *pOffset has already been played back
** (if the corresponding pDone bit is set) then skip the playback.
** Make sure the pDone bit corresponding to the *pOffset page is set
** prior to returning.


















*/
static int pager_playback_one_page(
  Pager *pPager,                /* The pager being played back */
  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
  i64 *pOffset,                 /* Offset of record to playback */
  int isSavepnt,                /* True for a savepoint rollback */
  Bitvec *pDone                 /* Bitvec of pages already played back */







|
















>
>
>





|
|

>
>
|
>
>
>
>
>
>
>
>
>
>
|
<
<
|
>
>













|


|
|





|



|
|
|
|

|
|
|
|
|

>
>
>
>
|



|

>
>
>
>
>
|
|
|
|




>
>
>
>
|
<
|
|
>
|
|
<
<


>
>
>
>
>
>
|
>
|
|
>
>
>
>
>
>
|
|
|

|
|
|
>

|
>
|
>
>
>
>
|
|
|
<
|
|






<
<
<
<
<
<
<
<




|










|
|
|
|
|


|





|
<
|
|
|
|
<

|
|
>
>
>
>

>

|
|
|







|

|
<

>
>
>
>
>
|
<
<
|
|
>
|
<
|
<
<
<
<
|












<
|
|

|





|
|
>


|
>
>
>
>
|




|
|
<
<


|
|
>







|
|









|



|
|
>









>







|
>









|





<
|
<
|
|
<
|
|
>
>
>
>
>
>


|
|
>







|
>
>

>
|
|
<
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
|
|
>
|
>


>
>
|
|
>
>
>
>
>
>
>
>
>
>

|
|

|


|



|
|
>
>
>
|
>
|
<
>
>
>
>
>
>
|
<
|
<
>

>
>
>
>
>
>
>
>
>
>
>
>
>
|

>
|
<
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>


|
|
>



|
|
>
>
>
>
>
>
>
>
>
>
>
>



<

















<




|
<
<
<



>

>
|

<
<









<


>
|
>
>
>




<





>
|
>

|
|
|
>

<
>
|
>
|
|
|


<
<
<
<
<


|
|










|





>
>
>
>






>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733


31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
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
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844

31845
31846
31847
31848
31849
31850
31851
31852








31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
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

31920




31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933

31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959


31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
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
32046
32047
32048
32049
32050
32051
32052
32053

32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137

32138
32139
32140
32141
32142
32143
32144

32145

32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164

32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208

32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225

32226
32227
32228
32229
32230



32231
32232
32233
32234
32235
32236
32237
32238


32239
32240
32241
32242
32243
32244
32245
32246
32247

32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258

32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272

32273
32274
32275
32276
32277
32278
32279
32280





32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
  **
  **   * When the pager is in no-sync mode. Corruption can follow a
  **     power failure in this case anyway.
  **
  **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  **     that garbage data is never appended to the journal file.
  */
  assert( isOpen(pPager->fd) || pPager->noSync );
  if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
   || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
  ){
    put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  }else{
    put32bits(&zHeader[sizeof(aJournalMagic)], 0);
  }

  /* The random check-hash initialiser */ 
  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  /* The initial database size */
  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  /* The assumed sector size for this process */
  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);

  /* The page size */
  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);

  /* Initializing the tail of the buffer is not necessary.  Everything
  ** works find if the following memset() is omitted.  But initializing
  ** the memory prevents valgrind from complaining, so we are willing to
  ** take the performance hit.
  */
  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
         nHeader-(sizeof(aJournalMagic)+20));

  /* In theory, it is only necessary to write the 28 bytes that the 
  ** journal header consumes to the journal file here. Then increment the 
  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
  ** record is written to the following sector (leaving a gap in the file
  ** that will be implicitly filled in by the OS).
  **
  ** However it has been discovered that on some systems this pattern can 
  ** be significantly slower than contiguously writing data to the file,
  ** even if that means explicitly writing data to the block of 
  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  ** is done. 
  **
  ** The loop is required here in case the sector-size is larger than the 
  ** database page size. Since the zHeader buffer is only Pager.pageSize


  ** bytes in size, more than one call to sqlite3OsWrite() may be required
  ** to populate the entire journal header sector.
  */ 
  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
    IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
    rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
    pPager->journalOff += nHeader;
  }

  return rc;
}

/*
** The journal file must be open when this is called. A journal header file
** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
** file. The current location in the journal file is given by
** pPager->journalOff. See comments above function writeJournalHdr() for
** a description of the journal header format.
**
** If the header is read successfully, *pNRec is set to the number of
** page records following this header and *pDbSize is set to the size of the
** database before the transaction began, in pages. Also, pPager->cksumInit
** is set to the value read from the journal header. SQLITE_OK is returned
** in this case.
**
** If the journal header file appears to be corrupted, SQLITE_DONE is
** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
** cannot be read from the journal file an error code is returned.
*/
static int readJournalHdr(
  Pager *pPager,               /* Pager object */
  i64 journalSize,             /* Size of the open journal file in bytes */
  u32 *pNRec,                  /* OUT: Value read from the nRec field */
  u32 *pDbSize                 /* OUT: Value of original database size field */
){
  int rc;                      /* Return code */
  unsigned char aMagic[8];     /* A buffer to hold the magic header */
  i64 iHdrOff;                 /* Offset of journal header being read */

  assert( isOpen(pPager->jfd) );      /* Journal file must be open. */

  /* Advance Pager.journalOff to the start of the next sector. If the
  ** journal file is too small for there to be a header stored at this
  ** point, return SQLITE_DONE.
  */
  pPager->journalOff = journalHdrOffset(pPager);
  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
    return SQLITE_DONE;
  }
  iHdrOff = pPager->journalOff;

  /* Read in the first 8 bytes of the journal header. If they do not match
  ** the  magic string found at the start of each journal header, return
  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  ** proceed.
  */
  rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  if( rc ){
    return rc;
  }
  if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
    return SQLITE_DONE;
  }

  /* Read the first three 32-bit fields of the journal header: The nRec
  ** field, the checksum-initializer and the database size at the start
  ** of the transaction. Return an error code if anything goes wrong.
  */
  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))

   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
   || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  ){
    return rc;
  }



  if( pPager->journalOff==0 ){
    u32 iPageSize;               /* Page-size field of journal header */
    u32 iSectorSize;             /* Sector-size field of journal header */
    u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */

    /* Read the page-size and sector-size journal header fields. */
    if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
     || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
    ){
      return rc;
    }

    /* Check that the values read from the page-size and sector-size fields
    ** are within range. To be 'in range', both values need to be a power
    ** of two greater than or equal to 512, and not greater than their 
    ** respective compile time maximum limits.
    */
    if( iPageSize<512                  || iSectorSize<512
     || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
     || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
    ){
      /* If the either the page-size or sector-size in the journal-header is 
      ** invalid, then the process that wrote the journal-header must have 
      ** crashed before the header was synced. In this case stop reading 
      ** the journal file here.
      */
      return SQLITE_DONE;
    }

    /* Update the page-size to match the value read from the journal. 
    ** Use a testcase() macro to make sure that malloc failure within 
    ** PagerSetPagesize() is tested.
    */
    iPageSize16 = (u16)iPageSize;
    rc = sqlite3PagerSetPagesize(pPager, &iPageSize16);
    testcase( rc!=SQLITE_OK );

    assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );

    /* Update the assumed sector-size to match the value used by 
    ** the process that created this journal. If this journal was
    ** created by a process other than this one, then this routine
    ** is being called from within pager_playback(). The local value
    ** of Pager.sectorSize is restored at the end of that routine.
    */








    pPager->sectorSize = iSectorSize;
  }

  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  return rc;
}


/*
** Write the supplied master journal name into the journal file for pager
** pPager at the current location. The master journal name must be the last
** thing written to a journal file. If the pager is in full-sync mode, the
** journal file descriptor is advanced to the next sector boundary before
** anything is written. The format is:
**
**   + 4 bytes: PAGER_MJ_PGNO.
**   + N bytes: Master journal filename in utf-8.
**   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
**   + 4 bytes: Master journal name checksum.
**   + 8 bytes: aJournalMagic[].
**
** The master journal page checksum is the sum of the bytes in the master
** journal name, where each byte is interpreted as a signed 8-bit integer.
**
** If zMaster is a NULL pointer (occurs for a single database transaction), 
** this call is a no-op.
*/
static int writeMasterJournal(Pager *pPager, const char *zMaster){
  int rc;                          /* Return code */

  int nMaster;                     /* Length of string zMaster */
  i64 iHdrOff;                     /* Offset of header in journal file */
  i64 jrnlSize;                    /* Size of journal file on disk */
  u32 cksum = 0;                   /* Checksum of string zMaster */


  if( !zMaster || pPager->setMaster
   || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
   || pPager->journalMode==PAGER_JOURNALMODE_OFF 
  ){
    return SQLITE_OK;
  }
  pPager->setMaster = 1;
  assert( isOpen(pPager->jfd) );

  /* Calculate the length in bytes and the checksum of zMaster */
  for(nMaster=0; zMaster[nMaster]; nMaster++){
    cksum += zMaster[nMaster];
  }

  /* If in full-sync mode, advance to the next disk sector before writing
  ** the master journal name. This is in case the previous page written to
  ** the journal has already been synced.
  */
  if( pPager->fullSync ){
    pPager->journalOff = journalHdrOffset(pPager);
  }
  iHdrOff = pPager->journalOff;


  /* Write the master journal data to the end of the journal file. If
  ** an error occurs, return the error code to the caller.
  */
  if( (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager)))
   || (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4))
   || (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster))


   || (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum))
   || (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8))
  ){
    return rc;

  }




  pPager->journalOff += (nMaster+20);
  pPager->needSync = !pPager->noSync;

  /* If the pager is in peristent-journal mode, then the physical 
  ** journal-file may extend past the end of the master-journal name
  ** and 8 bytes of magic data just written to the file. This is 
  ** dangerous because the code to rollback a hot-journal file
  ** will not be able to find the master-journal name to determine 
  ** whether or not the journal is hot. 
  **
  ** Easiest thing to do in this scenario is to truncate the journal 
  ** file to the required size.
  */ 

  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
   && jrnlSize>pPager->journalOff
  ){
    rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  }
  return rc;
}

/*
** Find a page in the hash table given its page number. Return
** a pointer to the page or NULL if the requested page is not 
** already in memory.
*/
static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  PgHdr *p;                         /* Return value */

  /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  ** fail, since no attempt to allocate dynamic memory will be made.
  */
  (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  return p;
}

/*
** Unless the pager is in error-state, discard all in-memory pages. If
** the pager is in error-state, then this call is a no-op.


*/
static void pager_reset(Pager *pPager){
  if( SQLITE_OK==pPager->errCode ){
    sqlite3PcacheClear(pPager->pPCache);
  }
}

/*
** Free all structures in the Pager.aSavepoint[] array and set both
** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
** if it is open and the pager is not in exclusive mode.
*/
static void releaseAllSavepoints(Pager *pPager){
  int ii;               /* Iterator for looping through Pager.aSavepoint */
  for(ii=0; ii<pPager->nSavepoint; ii++){
    sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  }
  if( !pPager->exclusiveMode ){
    sqlite3OsClose(pPager->sjfd);
  }
  sqlite3_free(pPager->aSavepoint);
  pPager->aSavepoint = 0;
  pPager->nSavepoint = 0;
  pPager->nSubRec = 0;
}

/*
** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
** bitvecs of all open savepoints. Return SQLITE_OK if successful
** or SQLITE_NOMEM if a malloc failure occurs.
*/
static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  int ii;                   /* Loop counter */
  int rc = SQLITE_OK;       /* Result code */

  for(ii=0; ii<pPager->nSavepoint; ii++){
    PagerSavepoint *p = &pPager->aSavepoint[ii];
    if( pgno<=p->nOrig ){
      rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
      testcase( rc==SQLITE_NOMEM );
      assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
    }
  }
  return rc;
}

/*
** Unlock the database file. This function is a no-op if the pager
** is in exclusive mode.
**
** If the pager is currently in error state, discard the contents of 
** the cache and reset the Pager structure internal state. If there is
** an open journal-file, then the next time a shared-lock is obtained
** on the pager file (by this or any other process), it will be
** treated as a hot-journal and rolled back.
*/
static void pager_unlock(Pager *pPager){
  if( !pPager->exclusiveMode ){
    int rc;                      /* Return code */

    /* Always close the journal file when dropping the database lock.
    ** Otherwise, another connection with journal_mode=delete might
    ** delete the file out from under us.
    */

    sqlite3OsClose(pPager->jfd);

    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;

    releaseAllSavepoints(pPager);

    /* If the file is unlocked, somebody else might change it. The
    ** values stored in Pager.dbSize etc. might become invalid if
    ** this happens. TODO: Really, this doesn't need to be cleared
    ** until the change-counter check fails in pagerSharedLock().
    */
    pPager->dbSizeValid = 0;

    rc = osUnlock(pPager->fd, NO_LOCK);
    if( rc ){
      pPager->errCode = rc;
    }
    IOTRACE(("UNLOCK %p\n", pPager))

    /* If Pager.errCode is set, the contents of the pager cache cannot be
    ** trusted. Now that the pager file is unlocked, the contents of the
    ** cache can be discarded and the error code safely cleared.
    */
    if( pPager->errCode ){
      if( rc==SQLITE_OK ){
        pPager->errCode = SQLITE_OK;
      }
      pager_reset(pPager);
    }

    pPager->changeCountDone = 0;

    pPager->state = PAGER_UNLOCK;
  }
}

/*
** This function should be called when an IOERR, CORRUPT or FULL error
** may have occured. The first argument is a pointer to the pager 
** structure, the second the error-code about to be returned by a pager 
** API function. The value returned is a copy of the second argument 
** to this function. 
**
** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
** the error becomes persistent. Until the persisten error is cleared,
** subsequent API calls on this Pager will immediately return the same 
** error code.
**
** A persistent error indicates that the contents of the pager-cache 
** cannot be trusted. This state can be cleared by completely discarding 
** the contents of the pager-cache. If a transaction was active when
** the persistent error occured, then the rollback journal may need
** to be replayed to restore the contents of the database file (as if
** it were a hot-journal).
*/
static int pager_error(Pager *pPager, int rc){
  int rc2 = rc & 0xff;
  assert(
       pPager->errCode==SQLITE_FULL ||
       pPager->errCode==SQLITE_OK ||
       (pPager->errCode & 0xff)==SQLITE_IOERR
  );
  if(
    rc2==SQLITE_FULL ||
    rc2==SQLITE_IOERR ||
    rc2==SQLITE_CORRUPT
  ){
    pPager->errCode = rc;
    if( pPager->state==PAGER_UNLOCK 
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
    ){
      /* If the pager is already unlocked, call pager_unlock() now to
      ** clear the error state and ensure that the pager-cache is 
      ** completely empty.
      */
      pager_unlock(pPager);
    }
  }
  return rc;
}

/*
** Execute a rollback if a transaction is active and unlock the 
** database file. 
**
** If the pager has already entered the error state, do not attempt 
** the rollback at this time. Instead, pager_unlock() is called. The
** call to pager_unlock() will discard all in-memory pages, unlock
** the database file and clear the error state. If this means that
** there is a hot-journal left in the file-system, the next connection
** to obtain a shared lock on the pager (which may be this one) will
** roll it back.
**
** If the pager has not already entered the error state, but an IO or
** malloc error occurs during a rollback, then this will itself cause 
** the pager to enter the error state. Which will be cleared by the
** call to pager_unlock(), as described above.
*/
static void pagerUnlockAndRollback(Pager *pPager){
  if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
    sqlite3BeginBenignMalloc();
    sqlite3PagerRollback(pPager);
    sqlite3EndBenignMalloc();
  }
  pager_unlock(pPager);
}

/*
** This routine ends a transaction. A transaction is usually ended by 
** either a COMMIT or a ROLLBACK operation. This routine may be called 
** after rollback of a hot-journal, or if an error occurs while opening
** the journal file or writing the very first journal-header of a
** database transaction.
** 
** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
** routine is called, it is a no-op (returns SQLITE_OK).

**
** Otherwise, any active savepoints are released.
**
** If the journal file is open, then it is "finalized". Once a journal 
** file has been finalized it is not possible to use it to roll back a 
** transaction. Nor will it be considered to be a hot-journal by this
** or any other database connection. Exactly how a journal is finalized

** depends on whether or not the pager is running in exclusive mode and

** the current journal-mode (Pager.journalMode value), as follows:
**
**   journalMode==MEMORY
**     Journal file descriptor is simply closed. This destroys an 
**     in-memory journal.
**
**   journalMode==TRUNCATE
**     Journal file is truncated to zero bytes in size.
**
**   journalMode==PERSIST
**     The first 28 bytes of the journal file are zeroed. This invalidates
**     the first journal header in the file, and hence the entire journal
**     file. An invalid journal file cannot be rolled back.
**
**   journalMode==DELETE
**     The journal file is closed and deleted using sqlite3OsDelete().
**
**     If the pager is running in exclusive mode, this method of finalizing
**     the journal file is never used. Instead, if the journalMode is

**     DELETE and the pager is in exclusive mode, the method described under
**     journalMode==PERSIST is used instead.
**
** After the journal is finalized, if running in non-exclusive mode, the
** pager moves to PAGER_SHARED state (and downgrades the lock on the
** database file accordingly).
**
** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
** exclusive mode.
**
** SQLITE_OK is returned if no error occurs. If an error occurs during
** any of the IO operations to finalize the journal file or unlock the
** database then the IO error code is returned to the user. If the 
** operation to finalize the journal file fails, then the code still
** tries to unlock the database file if not in exclusive mode. If the
** unlock operation fails as well, then the first error code related
** to the first error encountered (the journal finalization one) is
** returned.
*/
static int pager_end_transaction(Pager *pPager, int hasMaster){
  int rc = SQLITE_OK;      /* Error code from journal finalization operation */
  int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */

  if( pPager->state<PAGER_RESERVED ){
    return SQLITE_OK;
  }
  releaseAllSavepoints(pPager);

  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  if( isOpen(pPager->jfd) ){

    /* TODO: There's a problem here if a journal-file was opened in MEMORY
    ** mode and then the journal-mode is changed to TRUNCATE or PERSIST
    ** during the transaction. This code should be changed to assume
    ** that the journal mode has not changed since the transaction was
    ** started. And the sqlite3PagerJournalMode() function should be
    ** changed to make sure that this is the case too.
    */

    /* Finalize the journal file. */
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      int isMemoryJournal = sqlite3IsMemJournal(pPager->jfd);
      sqlite3OsClose(pPager->jfd);

      if( !isMemoryJournal ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
      }
    }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE
         && (rc = sqlite3OsTruncate(pPager->jfd, 0))==SQLITE_OK ){
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else if( pPager->exclusiveMode 
     || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
    ){
      rc = zeroJournalHdr(pPager, hasMaster);
      pager_error(pPager, rc);
      pPager->journalOff = 0;
      pPager->journalStarted = 0;
    }else{
      assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE || rc );
      sqlite3OsClose(pPager->jfd);

      if( rc==SQLITE_OK && !pPager->tempFile ){
        rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
      }
    }




#ifdef SQLITE_CHECK_PAGES
    sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
#endif

    sqlite3PcacheCleanAll(pPager->pPCache);
    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
    pPager->nRec = 0;


  }

  if( !pPager->exclusiveMode ){
    rc2 = osUnlock(pPager->fd, SHARED_LOCK);
    pPager->state = PAGER_SHARED;
    pPager->changeCountDone = 0;
  }else if( pPager->state==PAGER_SYNCED ){
    pPager->state = PAGER_EXCLUSIVE;
  }

  pPager->setMaster = 0;
  pPager->needSync = 0;
  pPager->dbModified = 0;

  /* TODO: Is this optimal? Why is the db size invalidated here 
  ** when the database file is not unlocked? */
  pPager->dbOrigSize = 0;
  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  if( !MEMDB ){
    pPager->dbSizeValid = 0;
  }


  return (rc==SQLITE_OK?rc2:rc);
}

/*
** Parameter aData must point to a buffer of pPager->pageSize bytes
** of data. Compute and return a checksum based ont the contents of the 
** page of data and the current value of pPager->cksumInit.
**
** This is not a real checksum. It is really just the sum of the 
** random initial value (pPager->cksumInit) and every 200th byte
** of the page data, starting with byte offset (pPager->pageSize%200).
** Each byte is interpreted as an 8-bit unsigned integer.
**

** Changing the formula used to compute this checksum results in an
** incompatible journal file format.
**
** If journal corruption occurs due to a power failure, the most likely 
** scenario is that one end or the other of the record will be changed. 
** It is much less likely that the two ends of the journal record will be
** correct and the middle be corrupt.  Thus, this "checksum" scheme,
** though fast and simple, catches the mostly likely kind of corruption.





*/
static u32 pager_cksum(Pager *pPager, const u8 *aData){
  u32 cksum = pPager->cksumInit;         /* Checksum value to return */
  int i = pPager->pageSize-200;          /* Loop counter */
  while( i>0 ){
    cksum += aData[i];
    i -= 200;
  }
  return cksum;
}

/*
** Read a single page from either the journal file (if isMainJrnl==1) or
** from the sub-journal (if isMainJrnl==0) and playback that page.
** The page begins at offset *pOffset into the file. The *pOffset
** value is increased to the start of the next page in the journal.
**
** The isMainJrnl flag is true if this is the main rollback journal and
** false for the statement journal.  The main rollback journal uses
** checksums - the statement journal does not.
**
** If the page number of the page record read from the (sub-)journal file
** is greater than the current value of Pager.dbSize, then playback is
** skipped and SQLITE_OK is returned.
**
** If pDone is not NULL, then it is a record of pages that have already
** been played back.  If the page at *pOffset has already been played back
** (if the corresponding pDone bit is set) then skip the playback.
** Make sure the pDone bit corresponding to the *pOffset page is set
** prior to returning.
**
** If the page record is successfully read from the (sub-)journal file
** and played back, then SQLITE_OK is returned. If an IO error occurs
** while reading the record from the (sub-)journal file or while writing
** to the database file, then the IO error code is returned. If data
** is successfully read from the (sub-)journal file but appears to be
** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
** two circumstances:
** 
**   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
**   * If the record is being rolled back from the main journal file
**     and the checksum field does not match the record content.
**
** Neither of these two scenarios are possible during a savepoint rollback.
**
** If this is a savepoint rollback, then memory may have to be dynamically
** allocated by this function. If this is the case and an allocation fails,
** SQLITE_NOMEM is returned.
*/
static int pager_playback_one_page(
  Pager *pPager,                /* The pager being played back */
  int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
  i64 *pOffset,                 /* Offset of record to playback */
  int isSavepnt,                /* True for a savepoint rollback */
  Bitvec *pDone                 /* Bitvec of pages already played back */
31925
31926
31927
31928
31929
31930
31931



31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945

31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957

31958
31959
31960
31961
31962
31963
31964
31965
  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */

  aData = (u8*)pPager->pTmpSpace;
  assert( aData );         /* Temp storage must have already been allocated */




  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;

  rc = read32bits(jfd, *pOffset, &pgno);
  if( rc!=SQLITE_OK ) return rc;
  rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
  if( rc!=SQLITE_OK ) return rc;
  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;

  /* Sanity checking on the page.  This is more important that I originally
  ** thought.  If a power failure occurs while the journal is being written,
  ** it could cause invalid data to be written into the journal.  We need to
  ** detect this invalid data (with high probability) and ignore it.
  */
  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){

    return SQLITE_DONE;
  }
  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
    return SQLITE_OK;
  }
  if( isMainJrnl ){
    rc = read32bits(jfd, (*pOffset)-4, &cksum);
    if( rc ) return rc;
    if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
      return SQLITE_DONE;
    }
  }

  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno)) ){
    return rc;
  }

  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );

  /* If the pager is in RESERVED state, then there must be a copy of this
  ** page in the pager cache. In this case just update the pager cache,







>
>
>

<












>












>
|







32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355

32356
32357
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
32388
32389
  assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
  assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
  assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */

  aData = (u8*)pPager->pTmpSpace;
  assert( aData );         /* Temp storage must have already been allocated */

  /* Read the page number and page data from the journal or sub-journal
  ** file. Return an error code to the caller if an IO error occurs.
  */
  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;

  rc = read32bits(jfd, *pOffset, &pgno);
  if( rc!=SQLITE_OK ) return rc;
  rc = sqlite3OsRead(jfd, aData, pPager->pageSize, (*pOffset)+4);
  if( rc!=SQLITE_OK ) return rc;
  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;

  /* Sanity checking on the page.  This is more important that I originally
  ** thought.  If a power failure occurs while the journal is being written,
  ** it could cause invalid data to be written into the journal.  We need to
  ** detect this invalid data (with high probability) and ignore it.
  */
  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
    assert( !isSavepnt );
    return SQLITE_DONE;
  }
  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
    return SQLITE_OK;
  }
  if( isMainJrnl ){
    rc = read32bits(jfd, (*pOffset)-4, &cksum);
    if( rc ) return rc;
    if( !isSavepnt && pager_cksum(pPager, aData)!=cksum ){
      return SQLITE_DONE;
    }
  }

  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
    return rc;
  }

  assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );

  /* If the pager is in RESERVED state, then there must be a copy of this
  ** page in the pager cache. In this case just update the pager cache,
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
  pPg = pager_lookup(pPager, pgno);
  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
               PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
               (isMainJrnl?"main-journal":"sub-journal")
  ));
  if( (pPager->state>=PAGER_EXCLUSIVE)
   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
   && (pPager->fd->pMethods)
  ){
    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
    rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
    if( pgno>pPager->dbFileSize ){
      pPager->dbFileSize = pgno;
    }
  }else if( !isMainJrnl && pPg==0 ){







|







32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
  pPg = pager_lookup(pPager, pgno);
  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
               PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, aData),
               (isMainJrnl?"main-journal":"sub-journal")
  ));
  if( (pPager->state>=PAGER_EXCLUSIVE)
   && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
   && isOpen(pPager->fd)
  ){
    i64 ofst = (pgno-1)*(i64)pPager->pageSize;
    rc = sqlite3OsWrite(pPager->fd, aData, pPager->pageSize, ofst);
    if( pgno>pPager->dbFileSize ){
      pPager->dbFileSize = pgno;
    }
  }else if( !isMainJrnl && pPg==0 ){
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
32046
32047
32048
32049
32050
32051
32052
32053
32054
    **
    ** The solution is to add an in-memory page to the cache containing
    ** the data just read from the sub-journal. Mark the page as dirty 
    ** and if the pager requires a journal-sync, then mark the page as 
    ** requiring a journal-sync before it is written.
    */
    assert( isSavepnt );
    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1)) ){
      return rc;
    }
    pPg->flags &= ~PGHDR_NEED_READ;
    sqlite3PcacheMakeDirty(pPg);
  }
  if( pPg ){
    /* No page should ever be explicitly rolled back that is in use, except
    ** for page 1 which is held in use in order to keep the lock on the
    ** database active. However such a page may be rolled back as a result
    ** of an internal error resulting in an automatic call to
    ** sqlite3PagerRollback().
    */
    void *pData;
    pData = pPg->pData;
    memcpy(pData, aData, pPager->pageSize);
    if( pPager->xReiniter ){
      pPager->xReiniter(pPg);
    }
    if( isMainJrnl && (!isSavepnt || pPager->journalOff<=pPager->journalHdr) ){
      /* If the contents of this page were just restored from the main 
      ** journal file, then its content must be as they were when the 
      ** transaction was first opened. In this case we can mark the page
      ** as clean, since there will be no need to write it out to the.
      **
      ** There is one exception to this rule. If the page is being rolled
      ** back as part of a savepoint (or statement) rollback from an 







|


















|







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
    **
    ** The solution is to add an in-memory page to the cache containing
    ** the data just read from the sub-journal. Mark the page as dirty 
    ** and if the pager requires a journal-sync, then mark the page as 
    ** requiring a journal-sync before it is written.
    */
    assert( isSavepnt );
    if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
      return rc;
    }
    pPg->flags &= ~PGHDR_NEED_READ;
    sqlite3PcacheMakeDirty(pPg);
  }
  if( pPg ){
    /* No page should ever be explicitly rolled back that is in use, except
    ** for page 1 which is held in use in order to keep the lock on the
    ** database active. However such a page may be rolled back as a result
    ** of an internal error resulting in an automatic call to
    ** sqlite3PagerRollback().
    */
    void *pData;
    pData = pPg->pData;
    memcpy(pData, aData, pPager->pageSize);
    if( pPager->xReiniter ){
      pPager->xReiniter(pPg);
    }
    if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
      /* If the contents of this page were just restored from the main 
      ** journal file, then its content must be as they were when the 
      ** transaction was first opened. In this case we can mark the page
      ** as clean, since there will be no need to write it out to the.
      **
      ** There is one exception to this rule. If the page is being rolled
      ** back as part of a savepoint (or statement) rollback from an 
32126
32127
32128
32129
32130
32131
32132





32133


32134










32135
32136










32137


32138
32139
32140
32141
32142
32143
32144
32145
32146
32147

32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
** file that referred to the master journal file has just been rolled back.
** This routine checks if it is possible to delete the master journal file,
** and does so if it is.
**
** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
** available for use within this function.
**





**


** The master journal file contains the names of all child journals.










** To tell if a master journal can be deleted, check to each of the
** children.  If all children are either missing or do not refer to










** a different master journal, then this master journal can be deleted.


*/
static int pager_delmaster(Pager *pPager, const char *zMaster){
  sqlite3_vfs *pVfs = pPager->pVfs;
  int rc;
  int master_open = 0;
  sqlite3_file *pMaster;
  sqlite3_file *pJournal;
  char *zMasterJournal = 0; /* Contents of master journal file */
  i64 nMasterJournal;       /* Size of master journal file */


  /* Open the master journal file exclusively in case some other process
  ** is running this routine also. Not that it makes too much difference.
  */
  pMaster = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile * 2);
  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  if( !pMaster ){
    rc = SQLITE_NOMEM;
  }else{
    int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  }
  if( rc!=SQLITE_OK ) goto delmaster_out;
  master_open = 1;

  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  if( rc!=SQLITE_OK ) goto delmaster_out;

  if( nMasterJournal>0 ){
    char *zJournal;
    char *zMasterPtr = 0;
    int nMasterPtr = pPager->pVfs->mxPathname+1;

    /* Load the entire master journal file into space obtained from
    ** sqlite3_malloc() and pointed to by zMasterJournal. 
    */
    zMasterJournal = (char *)sqlite3Malloc((int)nMasterJournal + nMasterPtr);
    if( !zMasterJournal ){
      rc = SQLITE_NOMEM;







>
>
>
>
>

>
>
|
>
>
>
>
>
>
>
>
>
>
|
<
>
>
>
>
>
>
>
>
>
>
|
>
>



|
<
|
|



>
|
<

|




|



<







|







32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
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
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
** file that referred to the master journal file has just been rolled back.
** This routine checks if it is possible to delete the master journal file,
** and does so if it is.
**
** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
** available for use within this function.
**
** When a master journal file is created, it is populated with the names 
** of all of its child journals, one after another, formatted as utf-8 
** encoded text. The end of each child journal file is marked with a 
** nul-terminator byte (0x00). i.e. the entire contents of a master journal
** file for a transaction involving two databases might be:
**
**   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
**
** A master journal file may only be deleted once all of its child 
** journals have been rolled back.
**
** This function reads the contents of the master-journal file into 
** memory and loops through each of the child journal names. For
** each child journal, it checks if:
**
**   * if the child journal exists, and if so
**   * if the child journal contains a reference to master journal 
**     file zMaster
**
** If a child journal can be found that matches both of the criteria

** above, this function returns without doing anything. Otherwise, if
** no such child journal can be found, file zMaster is deleted from
** the file-system using sqlite3OsDelete().
**
** If an IO error within this function, an error code is returned. This
** function allocates memory by calling sqlite3Malloc(). If an allocation
** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
** occur, SQLITE_OK is returned.
**
** TODO: This function allocates a single block of memory to load
** the entire contents of the master journal file. This could be
** a couple of kilobytes or so - potentially larger than the page 
** size.
*/
static int pager_delmaster(Pager *pPager, const char *zMaster){
  sqlite3_vfs *pVfs = pPager->pVfs;
  int rc;                   /* Return code */

  sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
  sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
  char *zMasterJournal = 0; /* Contents of master journal file */
  i64 nMasterJournal;       /* Size of master journal file */

  /* Allocate space for both the pJournal and pMaster file descriptors.
  ** If successful, open the master journal file for reading.

  */
  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  if( !pMaster ){
    rc = SQLITE_NOMEM;
  }else{
    const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
    rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  }
  if( rc!=SQLITE_OK ) goto delmaster_out;


  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  if( rc!=SQLITE_OK ) goto delmaster_out;

  if( nMasterJournal>0 ){
    char *zJournal;
    char *zMasterPtr = 0;
    int nMasterPtr = pVfs->mxPathname+1;

    /* Load the entire master journal file into space obtained from
    ** sqlite3_malloc() and pointed to by zMasterJournal. 
    */
    zMasterJournal = (char *)sqlite3Malloc((int)nMasterJournal + nMasterPtr);
    if( !zMasterJournal ){
      rc = SQLITE_NOMEM;
32216
32217
32218
32219
32220
32221
32222
32223
32224

32225
32226
32227
32228
32229
32230
32231




32232



32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243



32244
32245
32246
32247
32248

32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266




32267
32268


32269


32270
32271

32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283

32284
32285
32286
32287
32288
32289
32290
  
  rc = sqlite3OsDelete(pVfs, zMaster, 0);

delmaster_out:
  if( zMasterJournal ){
    sqlite3_free(zMasterJournal);
  }  
  if( master_open ){
    sqlite3OsClose(pMaster);

  }
  sqlite3_free(pMaster);
  return rc;
}


/*




** If the main database file is open and an exclusive lock is held, 



** truncate the main file of the given pager to the specified number 
** of pages.
**
** It might might be the case that the file on disk is smaller than nPage.
** This can happen, for example, if we are in the middle of a transaction
** which has extended the file size and the new pages are still all held
** in cache, then an INSERT or UPDATE does a statement rollback.  Some
** operating system implementations can get confused if you try to
** truncate a file to some size that is larger than it currently is,
** so detect this case and write a single zero byte to the end of the new
** file instead.



*/
static int pager_truncate(Pager *pPager, Pgno nPage){
  int rc = SQLITE_OK;
  if( pPager->state>=PAGER_EXCLUSIVE && pPager->fd->pMethods ){
    i64 currentSize, newSize;

    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
    newSize = pPager->pageSize*(i64)nPage;
    if( rc==SQLITE_OK && currentSize!=newSize ){
      if( currentSize>newSize ){
        rc = sqlite3OsTruncate(pPager->fd, newSize);
      }else{
        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
      }
      if( rc==SQLITE_OK ){
        pPager->dbFileSize = nPage;
      }
    }
  }
  return rc;
}

/*
** Set the sectorSize for the given pager.




**
** The sector size is at least as big as the sector size reported


** by sqlite3OsSectorSize(). The minimum sector size is 512.


*/
static void setSectorSize(Pager *pPager){

  assert(pPager->fd->pMethods||pPager->tempFile);
  if( !pPager->tempFile ){
    /* Sector size doesn't matter for temporary files. Also, the file
    ** may not have been opened yet, in whcih case the OsSectorSize()
    ** call will segfault.
    */
    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  }
  if( pPager->sectorSize<512 ){
    pPager->sectorSize = 512;
  }
  if( pPager->sectorSize>MAX_SECTOR_SIZE ){

    pPager->sectorSize = MAX_SECTOR_SIZE;
  }
}

/*
** Playback the journal and thus restore the database file to
** the state it was in before we started making changes.  







|

>







>
>
>
>
|
>
>
>
|
<

|
<
<
<
|
|
|
|
>
>
>



|

>

















|
>
>
>
>

|
>
>
|
>
>


>
|


|








>







32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691

32692
32693



32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
  
  rc = sqlite3OsDelete(pVfs, zMaster, 0);

delmaster_out:
  if( zMasterJournal ){
    sqlite3_free(zMasterJournal);
  }  
  if( pMaster ){
    sqlite3OsClose(pMaster);
    assert( !isOpen(pJournal) );
  }
  sqlite3_free(pMaster);
  return rc;
}


/*
** This function is used to change the actual size of the database 
** file in the file-system. This only happens when committing a transaction,
** or rolling back a transaction (including rolling back a hot-journal).
**
** If the main database file is not open, or an exclusive lock is not
** held, this function is a no-op. Otherwise, the size of the file is
** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
** on disk is currently larger than nPage pages, then use the VFS
** xTruncate() method to truncate it.

**
** Or, it might might be the case that the file on disk is smaller than 



** nPage pages. Some operating system implementations can get confused if 
** you try to truncate a file to some size that is larger than it 
** currently is, so detect this case and write a single zero byte to 
** the end of the new file instead.
**
** If successful, return SQLITE_OK. If an IO error occurs while modifying
** the database file, return the error code to the caller.
*/
static int pager_truncate(Pager *pPager, Pgno nPage){
  int rc = SQLITE_OK;
  if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
    i64 currentSize, newSize;
    /* TODO: Is it safe to use Pager.dbFileSize here? */
    rc = sqlite3OsFileSize(pPager->fd, &currentSize);
    newSize = pPager->pageSize*(i64)nPage;
    if( rc==SQLITE_OK && currentSize!=newSize ){
      if( currentSize>newSize ){
        rc = sqlite3OsTruncate(pPager->fd, newSize);
      }else{
        rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
      }
      if( rc==SQLITE_OK ){
        pPager->dbFileSize = nPage;
      }
    }
  }
  return rc;
}

/*
** Set the value of the Pager.sectorSize variable for the given
** pager based on the value returned by the xSectorSize method
** of the open database file. The sector size will be used used 
** to determine the size and alignment of journal header and 
** master journal pointers within created journal files.
**
** For temporary files the effective sector size is always 512 bytes.
**
** Otherwise, for non-temporary files, the effective sector size is
** the value returned by the xSectorSize() method rounded up to 512 if
** it is less than 512, or rounded down to MAX_SECTOR_SIZE if it
** is greater than MAX_SECTOR_SIZE.
*/
static void setSectorSize(Pager *pPager){
  assert( isOpen(pPager->fd) || pPager->tempFile );

  if( !pPager->tempFile ){
    /* Sector size doesn't matter for temporary files. Also, the file
    ** may not have been opened yet, in which case the OsSectorSize()
    ** call will segfault.
    */
    pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
  }
  if( pPager->sectorSize<512 ){
    pPager->sectorSize = 512;
  }
  if( pPager->sectorSize>MAX_SECTOR_SIZE ){
    assert( MAX_SECTOR_SIZE>=512 );
    pPager->sectorSize = MAX_SECTOR_SIZE;
  }
}

/*
** Playback the journal and thus restore the database file to
** the state it was in before we started making changes.  
32350
32351
32352
32353
32354
32355
32356
32357
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
  int rc;                  /* Result code of a subroutine */
  int res = 1;             /* Value returned by sqlite3OsAccess() */
  char *zMaster = 0;       /* Name of master journal file if any */

  /* Figure out how many records are in the journal.  Abort early if
  ** the journal is empty.
  */
  assert( pPager->journalOpen );
  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  if( rc!=SQLITE_OK || szJ==0 ){
    goto end_playback;
  }

  /* Read the master journal name from the journal, if it is present.
  ** If a master journal file name is specified, but the file is not
  ** present on disk, then the journal is not hot and does not need to be
  ** played back.






  */
  zMaster = pPager->pTmpSpace;
  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  if( rc==SQLITE_OK && zMaster[0] ){
    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  }
  zMaster = 0;
  if( rc!=SQLITE_OK || !res ){
    goto end_playback;
  }
  pPager->journalOff = 0;

  /* This loop terminates either when the readJournalHdr() call returns
  ** SQLITE_DONE or an IO error occurs. */


  while( 1 ){

    /* Read the next journal header from the journal file.  If there are
    ** not enough bytes left in the journal file for a complete header, or
    ** it is corrupted, then a process must of failed while writing it.
    ** This indicates nothing more needs to be rolled back.
    */







|









>
>
>
>
>
>












|
|
>
>







32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
  int rc;                  /* Result code of a subroutine */
  int res = 1;             /* Value returned by sqlite3OsAccess() */
  char *zMaster = 0;       /* Name of master journal file if any */

  /* Figure out how many records are in the journal.  Abort early if
  ** the journal is empty.
  */
  assert( isOpen(pPager->jfd) );
  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  if( rc!=SQLITE_OK || szJ==0 ){
    goto end_playback;
  }

  /* Read the master journal name from the journal, if it is present.
  ** If a master journal file name is specified, but the file is not
  ** present on disk, then the journal is not hot and does not need to be
  ** played back.
  **
  ** TODO: Technically the following is an error because it assumes that
  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  **  mxPathname is 512, which is the same as the minimum allowable value
  ** for pageSize.
  */
  zMaster = pPager->pTmpSpace;
  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  if( rc==SQLITE_OK && zMaster[0] ){
    rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  }
  zMaster = 0;
  if( rc!=SQLITE_OK || !res ){
    goto end_playback;
  }
  pPager->journalOff = 0;

  /* This loop terminates either when a readJournalHdr() or 
  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
  ** occurs. 
  */
  while( 1 ){

    /* Read the next journal header from the journal file.  If there are
    ** not enough bytes left in the journal file for a complete header, or
    ** it is corrupted, then a process must of failed while writing it.
    ** This indicates nothing more needs to be rolled back.
    */
32434
32435
32436
32437
32438
32439
32440
32441

32442
32443
32444
32445
32446
32447
32448
      rc = pager_truncate(pPager, mxPg);
      if( rc!=SQLITE_OK ){
        goto end_playback;
      }
      pPager->dbSize = mxPg;
    }

    /* Copy original pages out of the journal and back into the database file.

    */
    for(u=0; u<nRec; u++){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 0, 0);
      if( rc!=SQLITE_OK ){
        if( rc==SQLITE_DONE ){
          rc = SQLITE_OK;
          pPager->journalOff = szJ;







|
>







32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
      rc = pager_truncate(pPager, mxPg);
      if( rc!=SQLITE_OK ){
        goto end_playback;
      }
      pPager->dbSize = mxPg;
    }

    /* Copy original pages out of the journal and back into the 
    ** database file and/or page cache.
    */
    for(u=0; u<nRec; u++){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 0, 0);
      if( rc!=SQLITE_OK ){
        if( rc==SQLITE_DONE ){
          rc = SQLITE_OK;
          pPager->journalOff = szJ;
32468
32469
32470
32471
32472
32473
32474











32475
32476
32477

32478
32479
32480

32481
32482
32483
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
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545

32546
32547
32548
32549
32550
32551
32552
32553
32554
32555

32556
32557
32558
32559
32560
32561
32562
32563
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
  ** assertion that the transaction counter was modified.
  */
  assert(
    pPager->fd->pMethods==0 ||
    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  );












  if( rc==SQLITE_OK ){
    zMaster = pPager->pTmpSpace;
    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);

  }
  if( rc==SQLITE_OK ){
    rc = pager_end_transaction(pPager, zMaster[0]!='\0');

  }
  if( rc==SQLITE_OK && zMaster[0] && res ){
    /* If there was a master journal and this routine will return success,
    ** see if it is possible to delete the master journal.
    */
    rc = pager_delmaster(pPager, zMaster);

  }

  /* The Pager.sectorSize variable may have been updated while rolling
  ** back a journal created by a process with a different sector size
  ** value. Reset it to the correct value for this process.
  */
  setSectorSize(pPager);
  return rc;
}

/*
** Playback savepoint pSavepoint.  Or, if pSavepoint==NULL, then playback
** the entire master journal file.


**







** The case pSavepoint==NULL occurs when a ROLLBACK TO command is invoked



















** on a SAVEPOINT that is a transaction savepoint.

*/
static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  i64 szJ;                 /* Effective size of the main journal */
  i64 iHdrOff;             /* End of first segment of main-journal records */
  Pgno ii;                 /* Loop counter */
  int rc = SQLITE_OK;      /* Return code */
  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */



  /* Allocate a bitvec to use to store the set of pages rolled back */
  if( pSavepoint ){
    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
    if( !pDone ){
      return SQLITE_NOMEM;
    }
  }

  /* Truncate the database back to the size it was before the 
  ** savepoint being reverted was opened.
  */
  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  assert( pPager->state>=PAGER_SHARED );

  /* Use pPager->journalOff as the effective size of the main rollback
  ** journal.  The actual file might be larger than this in
  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
  ** past pPager->journalOff is off-limits to us.
  */
  szJ = pPager->journalOff;

  /* Begin by rolling back records from the main journal starting at
  ** PagerSavepoint.iOffset and continuing to the next journal header.
  ** There might be records in the main journal that have a page number
  ** greater than the current database size (pPager->dbSize) but those
  ** will be skipped automatically.  Pages are added to pDone as they
  ** are played back.
  */
  if( pSavepoint ){
    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
    pPager->journalOff = pSavepoint->iOffset;
    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);
      assert( rc!=SQLITE_DONE );
    }

  }else{
    pPager->journalOff = 0;
  }

  /* Continue rolling back records out of the main journal starting at
  ** the first journal header seen and continuing until the effective end
  ** of the main journal file.  Continue to skip out-of-range pages and
  ** continue adding pages rolled back to pDone.
  */
  while( rc==SQLITE_OK && pPager->journalOff<szJ ){

    u32 nJRec = 0;     /* Number of Journal Records */
    u32 dummy;
    rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
    assert( rc!=SQLITE_DONE );

    /*
    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
    ** test is related to ticket #2565.  See the discussion in the
    ** pager_playback() function for additional information.
    */
    assert( !(nJRec==0
         && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
         && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
         && pagerNextJournalPageIsValid(pPager))
    );
    if( nJRec==0 
     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
    ){
      nJRec = (szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager);
    }
    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);
      assert( rc!=SQLITE_DONE );
    }

  }
  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );

  /* Finally,  rollback pages from the sub-journal.  Page that were
  ** previously rolled back out of the main journal (and are hence in pDone)
  ** will be skipped.  Out-of-range pages are also skipped.
  */
  if( pSavepoint ){

    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK&&ii<(u32)pPager->stmtNRec; ii++){
      assert( offset == ii*(4+pPager->pageSize) );
      rc = pager_playback_one_page(pPager, 0, &offset, 1, pDone);
      assert( rc!=SQLITE_DONE );
    }

  }

  sqlite3BitvecDestroy(pDone);
  if( rc==SQLITE_OK ){
    pPager->journalOff = szJ;
  }
  return rc;







>
>
>
>
>
>
>
>
>
>
>



>



>






>











|
|
>
>

>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>




<


>
>









|
|


<




















<

>










>


















|



<

>








>

|
|

<

>







32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026

33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043

33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063

33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098

33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113

33114
33115
33116
33117
33118
33119
33120
33121
33122
  ** assertion that the transaction counter was modified.
  */
  assert(
    pPager->fd->pMethods==0 ||
    sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
  );

  /* If this playback is happening automatically as a result of an IO or 
  ** malloc error that occured after the change-counter was updated but 
  ** before the transaction was committed, then the change-counter 
  ** modification may just have been reverted. If this happens in exclusive 
  ** mode, then subsequent transactions performed by the connection will not
  ** update the change-counter at all. This may lead to cache inconsistency
  ** problems for other processes at some point in the future. So, just
  ** in case this has happened, clear the changeCountDone flag now.
  */
  pPager->changeCountDone = pPager->tempFile;

  if( rc==SQLITE_OK ){
    zMaster = pPager->pTmpSpace;
    rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
    testcase( rc!=SQLITE_OK );
  }
  if( rc==SQLITE_OK ){
    rc = pager_end_transaction(pPager, zMaster[0]!='\0');
    testcase( rc!=SQLITE_OK );
  }
  if( rc==SQLITE_OK && zMaster[0] && res ){
    /* If there was a master journal and this routine will return success,
    ** see if it is possible to delete the master journal.
    */
    rc = pager_delmaster(pPager, zMaster);
    testcase( rc!=SQLITE_OK );
  }

  /* The Pager.sectorSize variable may have been updated while rolling
  ** back a journal created by a process with a different sector size
  ** value. Reset it to the correct value for this process.
  */
  setSectorSize(pPager);
  return rc;
}

/*
** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
** the entire master journal file. The case pSavepoint==NULL occurs when 
** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
** savepoint.
**
** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
** being rolled back), then the rollback consists of up to three stages,
** performed in the order specified:
**
**   * Pages are played back from the main journal starting at byte
**     offset PagerSavepoint.iOffset and continuing to 
**     PagerSavepoint.iHdrOffset, or to the end of the main journal
**     file if PagerSavepoint.iHdrOffset is zero.
**
**   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
**     back starting from the journal header immediately following 
**     PagerSavepoint.iHdrOffset to the end of the main journal file.
**
**   * Pages are then played back from the sub-journal file, starting
**     with the PagerSavepoint.iSubRec and continuing to the end of
**     the journal file.
**
** Throughout the rollback process, each time a page is rolled back, the
** corresponding bit is set in a bitvec structure (variable pDone in the
** implementation below). This is used to ensure that a page is only
** rolled back the first time it is encountered in either journal.
**
** If pSavepoint is NULL, then pages are only played back from the main
** journal file. There is no need for a bitvec in this case.
**
** In either case, before playback commences the Pager.dbSize variable
** is reset to the value that it held at the start of the savepoint 
** (or transaction). No page with a page-number greater than this value
** is played back. If one is encountered it is simply skipped.
*/
static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  i64 szJ;                 /* Effective size of the main journal */
  i64 iHdrOff;             /* End of first segment of main-journal records */

  int rc = SQLITE_OK;      /* Return code */
  Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */

  assert( pPager->state>=PAGER_SHARED );

  /* Allocate a bitvec to use to store the set of pages rolled back */
  if( pSavepoint ){
    pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
    if( !pDone ){
      return SQLITE_NOMEM;
    }
  }

  /* Set the database size back to the value it was before the savepoint 
  ** being reverted was opened.
  */
  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;


  /* Use pPager->journalOff as the effective size of the main rollback
  ** journal.  The actual file might be larger than this in
  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
  ** past pPager->journalOff is off-limits to us.
  */
  szJ = pPager->journalOff;

  /* Begin by rolling back records from the main journal starting at
  ** PagerSavepoint.iOffset and continuing to the next journal header.
  ** There might be records in the main journal that have a page number
  ** greater than the current database size (pPager->dbSize) but those
  ** will be skipped automatically.  Pages are added to pDone as they
  ** are played back.
  */
  if( pSavepoint ){
    iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
    pPager->journalOff = pSavepoint->iOffset;
    while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);

    }
    assert( rc!=SQLITE_DONE );
  }else{
    pPager->journalOff = 0;
  }

  /* Continue rolling back records out of the main journal starting at
  ** the first journal header seen and continuing until the effective end
  ** of the main journal file.  Continue to skip out-of-range pages and
  ** continue adding pages rolled back to pDone.
  */
  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
    u32 ii;            /* Loop counter */
    u32 nJRec = 0;     /* Number of Journal Records */
    u32 dummy;
    rc = readJournalHdr(pPager, szJ, &nJRec, &dummy);
    assert( rc!=SQLITE_DONE );

    /*
    ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
    ** test is related to ticket #2565.  See the discussion in the
    ** pager_playback() function for additional information.
    */
    assert( !(nJRec==0
         && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)!=pPager->journalOff
         && ((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager))>0
         && pagerNextJournalPageIsValid(pPager))
    );
    if( nJRec==0 
     && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
    ){
      nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
    }
    for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
      rc = pager_playback_one_page(pPager, 1, &pPager->journalOff, 1, pDone);

    }
    assert( rc!=SQLITE_DONE );
  }
  assert( rc!=SQLITE_OK || pPager->journalOff==szJ );

  /* Finally,  rollback pages from the sub-journal.  Page that were
  ** previously rolled back out of the main journal (and are hence in pDone)
  ** will be skipped.  Out-of-range pages are also skipped.
  */
  if( pSavepoint ){
    u32 ii;            /* Loop counter */
    i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
    for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
      assert( offset==ii*(4+pPager->pageSize) );
      rc = pager_playback_one_page(pPager, 0, &offset, 1, pDone);

    }
    assert( rc!=SQLITE_DONE );
  }

  sqlite3BitvecDestroy(pDone);
  if( rc==SQLITE_OK ){
    pPager->journalOff = szJ;
  }
  return rc;
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659








32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
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
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
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
32911
32912
32913
32914
32915


















32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937









32938







32939









32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
** testing and analysis only.  
*/
#ifdef SQLITE_TEST
SQLITE_API int sqlite3_opentemp_count = 0;
#endif

/*
** Open a temporary file. 
**
** Write the file descriptor into *fd.  Return SQLITE_OK on success or some
** other error code if we fail. The OS will automatically delete the temporary
** file when it is closed.








*/
static int sqlite3PagerOpentemp(
  Pager *pPager,        /* The pager object */
  sqlite3_file *pFile,  /* Write the file descriptor here */
  int vfsFlags          /* Flags passed through to the VFS */
){
  int rc;

#ifdef SQLITE_TEST
  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
#endif

  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  assert( rc!=SQLITE_OK || pFile->pMethods );
  return rc;
}

static int pagerStress(void *,PgHdr *);

/*
** Create a new page cache and put a pointer to the page cache in *ppPager.
** The file to be cached need not exist.  The file is not locked until
** the first call to sqlite3PagerGet() and is only held open until the
** last page is released using sqlite3PagerUnref().
**
** If zFilename is NULL then a randomly-named temporary file is created
** 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.
*/
SQLITE_PRIVATE int sqlite3PagerOpen(
  sqlite3_vfs *pVfs,       /* The virtual file system to use */
  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 */
  int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
){
  u8 *pPtr;
  Pager *pPager = 0;
  int rc = SQLITE_OK;
  int i;
  int tempFile = 0;
  int memDb = 0;
  int readOnly = 0;
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0;
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;
  int journalFileSize;
  int pcacheSize = sqlite3PcacheSize();
  int szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;
  char *zPathname = 0;
  int nPathname = 0;

  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
    journalFileSize = sqlite3JournalSize(pVfs);
  }else{
    journalFileSize = sqlite3MemJournalSize();
  }

  /* The default return is a NULL pointer */
  *ppPager = 0;

  /* Compute and store the full pathname in an allocated buffer pointed
  ** to by zPathname, length nPathname. Or, if this is a temporary file,
  ** leave both nPathname and zPathname set to 0.
  */
  if( zFilename && zFilename[0] ){
    nPathname = pVfs->mxPathname+1;
    zPathname = sqlite3Malloc(nPathname*2);
    if( zPathname==0 ){
      return SQLITE_NOMEM;
    }
#ifndef SQLITE_OMIT_MEMORYDB
    if( strcmp(zFilename,":memory:")==0 ){
      memDb = 1;
      zPathname[0] = 0;
    }else
#endif
    {
      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
    }
    if( rc!=SQLITE_OK ){
      sqlite3_free(zPathname);
      return rc;
    }
    nPathname = sqlite3Strlen30(zPathname);
  }

  /* Allocate memory for the pager structure */
  pPager = sqlite3MallocZero(
    sizeof(*pPager) +           /* Pager structure */
    pcacheSize      +           /* PCache object */
    journalFileSize +           /* The journal file structure */ 
    pVfs->szOsFile  +           /* The main db file */
    journalFileSize * 2 +       /* The two journal files */ 
    3*nPathname + 40            /* zFilename, zDirectory, zJournal */
  );
  if( !pPager ){
    sqlite3_free(zPathname);
    return SQLITE_NOMEM;
  }
  pPager->pPCache = (PCache *)&pPager[1];
  pPtr = ((u8 *)&pPager[1]) + pcacheSize;
  pPager->vfsFlags = vfsFlags;
  pPager->fd = (sqlite3_file*)&pPtr[pVfs->szOsFile*0];
  pPager->sjfd = (sqlite3_file*)&pPtr[pVfs->szOsFile];
  pPager->jfd = (sqlite3_file*)&pPtr[pVfs->szOsFile+journalFileSize];
  pPager->zFilename = (char*)&pPtr[pVfs->szOsFile+2*journalFileSize];
  pPager->zDirectory = &pPager->zFilename[nPathname+1];
  pPager->zJournal = &pPager->zDirectory[nPathname+1];
  pPager->pVfs = pVfs;
  if( zPathname ){
    memcpy(pPager->zFilename, zPathname, nPathname+1);
    sqlite3_free(zPathname);
  }

  /* Open the pager file.
  */
  if( zFilename && zFilename[0] && !memDb ){
    if( nPathname>(pVfs->mxPathname - (int)sizeof("-journal")) ){
      rc = SQLITE_CANTOPEN;
    }else{
      int fout = 0;
      rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd,
                         pPager->vfsFlags, &fout);
      readOnly = (fout&SQLITE_OPEN_READONLY);

      /* If the file was successfully opened for read/write access,
      ** choose a default page size in case we have to create the
      ** database file. The default page size is the maximum of:
      **
      **    + SQLITE_DEFAULT_PAGE_SIZE,
      **    + The value returned by sqlite3OsSectorSize()
      **    + The largest page size that can be written atomically.
      */
      if( rc==SQLITE_OK && !readOnly ){
        setSectorSize(pPager);
        if( szPageDflt<pPager->sectorSize ){
          szPageDflt = pPager->sectorSize;
        }
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
        {
          int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
          int ii;
          assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
          assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
          assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
          for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
            if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ) szPageDflt = ii;
          }
        }
#endif
        if( szPageDflt>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
        }
      }
    }
  }else{
    /* If a temporary file is requested, it is not opened immediately.
    ** In this case we accept the default page size and delay actually
    ** opening the file until the first call to OsWrite().
    **
    ** This branch is also run for an in-memory database. An in-memory
    ** database is the same as a temp-file that is never written out to
    ** disk and uses an in-memory rollback journal.
    */ 
    tempFile = 1;
    pPager->state = PAGER_EXCLUSIVE;
  }

  if( pPager && rc==SQLITE_OK ){
    pPager->pTmpSpace = sqlite3PageMalloc(szPageDflt);
  }

  /* If an error occured in either of the blocks above.
  ** Free the Pager structure and close the file.
  ** Since the pager is not allocated there is no need to set 
  ** any Pager.errMask variables.
  */
  if( !pPager || !pPager->pTmpSpace ){
    sqlite3OsClose(pPager->fd);
    sqlite3_free(pPager);
    return ((rc==SQLITE_OK)?SQLITE_NOMEM:rc);
  }
  nExtra = FORCE_ALIGNMENT(nExtra);
  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);

  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))

  /* Fill in Pager.zDirectory[] */
  memcpy(pPager->zDirectory, pPager->zFilename, nPathname+1);
  for(i=sqlite3Strlen30(pPager->zDirectory); 
      i>0 && pPager->zDirectory[i-1]!='/'; i--){}
  if( i>0 ) pPager->zDirectory[i-1] = 0;

  /* Fill in Pager.zJournal[] */
  if( zPathname ){
    memcpy(pPager->zJournal, pPager->zFilename, nPathname);
    memcpy(&pPager->zJournal[nPathname], "-journal", 9);
  }else{
    pPager->zJournal = 0;
  }

  /* pPager->journalOpen = 0; */
  pPager->useJournal = (u8)useJournal;
  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  /* pPager->stmtOpen = 0; */
  /* pPager->stmtInUse = 0; */
  /* pPager->nRef = 0; */
  pPager->dbSizeValid = (u8)memDb;
  pPager->pageSize = szPageDflt;
  /* pPager->stmtSize = 0; */
  /* pPager->stmtJSize = 0; */
  /* pPager->nPage = 0; */
  pPager->mxPage = 100;
  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  /* pPager->state = PAGER_UNLOCK; */
  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  /* pPager->errMask = 0; */
  pPager->tempFile = (u8)tempFile;
  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  pPager->exclusiveMode = (u8)tempFile; 
  pPager->memDb = (u8)memDb;
  pPager->readOnly = (u8)readOnly;
  /* pPager->needSync = 0; */
  pPager->noSync = (pPager->tempFile || !useJournal) ?1:0;
  pPager->fullSync = pPager->noSync ?0:1;
  pPager->sync_flags = SQLITE_SYNC_NORMAL;
  /* pPager->pFirst = 0; */
  /* pPager->pFirstSynced = 0; */
  /* pPager->pLast = 0; */
  pPager->nExtra = nExtra;
  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  assert(pPager->fd->pMethods||tempFile);
  setSectorSize(pPager);
  if( memDb ){
    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  }
  /* pPager->xBusyHandler = 0; */
  /* pPager->pBusyHandlerArg = 0; */
  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  *ppPager = pPager;
  return SQLITE_OK;
}

/*
** Set the busy handler function.


















*/
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  Pager *pPager, 
  int (*xBusyHandler)(void *),
  void *pBusyHandlerArg
){  
  pPager->xBusyHandler = xBusyHandler;
  pPager->pBusyHandlerArg = pBusyHandlerArg;
}

/*
** 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.
*/
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
  pPager->xReiniter = xReinit;
}

/*









** Set the page size to *pPageSize. If the suggest new page size is







** inappropriate, then an alternative page size is set to that









** value before returning.
*/
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
  int rc = pPager->errCode;
  if( rc==SQLITE_OK ){
    u16 pageSize = *pPageSize;
    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
    if( pageSize && pageSize!=pPager->pageSize 
     && (pPager->memDb==0 || pPager->dbSize==0)
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
    ){
      char *pNew = (char *)sqlite3PageMalloc(pageSize);
      if( !pNew ){
        rc = SQLITE_NOMEM;
      }else{
        pager_reset(pPager);
        pPager->pageSize = pageSize;
        if( !pPager->memDb ) setSectorSize(pPager);
        sqlite3PageFree(pPager->pTmpSpace);
        pPager->pTmpSpace = pNew;
        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
      }
    }
    *pPageSize = (u16)pPager->pageSize;
  }







|

|
|
|
>
>
>
>
>
>
>
>

|




|








|

<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


|
|
|






|
|
|
|
|






>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
|
















<







33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206











































































































































































































































33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294

33295
33296
33297
33298
33299
33300
33301
** testing and analysis only.  
*/
#ifdef SQLITE_TEST
SQLITE_API int sqlite3_opentemp_count = 0;
#endif

/*
** Open a temporary file.
**
** Write the file descriptor into *pFile. Return SQLITE_OK on success 
** or some other error code if we fail. The OS will automatically 
** delete the temporary file when it is closed.
**
** The flags passed to the VFS layer xOpen() call are those specified
** by parameter vfsFlags ORed with the following:
**
**     SQLITE_OPEN_READWRITE
**     SQLITE_OPEN_CREATE
**     SQLITE_OPEN_EXCLUSIVE
**     SQLITE_OPEN_DELETEONCLOSE
*/
static int pagerOpentemp(
  Pager *pPager,        /* The pager object */
  sqlite3_file *pFile,  /* Write the file descriptor here */
  int vfsFlags          /* Flags passed through to the VFS */
){
  int rc;               /* Return code */

#ifdef SQLITE_TEST
  sqlite3_opentemp_count++;  /* Used for testing and analysis only */
#endif

  vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
            SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  assert( rc!=SQLITE_OK || isOpen(pFile) );
  return rc;











































































































































































































































}

/*
** Set the busy handler function.
**
** The pager invokes the busy-handler if sqlite3OsLock() returns 
** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
** lock. It does *not* invoke the busy handler when upgrading from
** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
** (which occurs during hot-journal rollback). Summary:
**
**   Transition                        | Invokes xBusyHandler
**   --------------------------------------------------------
**   NO_LOCK       -> SHARED_LOCK      | Yes
**   SHARED_LOCK   -> RESERVED_LOCK    | No
**   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
**   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
**
** If the busy-handler callback returns non-zero, the lock is 
** retried. If it returns zero, then the SQLITE_BUSY error is
** returned to the caller of the pager API function.
*/
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  Pager *pPager,                       /* Pager object */
  int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
  void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
){  
  pPager->xBusyHandler = xBusyHandler;
  pPager->pBusyHandlerArg = pBusyHandlerArg;
}

/*
** Set the reinitializer for this pager. If not NULL, the reinitializer
** is called when the content of a page in cache is modified (restored)
** as part of a transaction or savepoint rollback. The callback gives 
** higher-level code an opportunity to restore the EXTRA section to 
** agree with the restored page data.
*/
SQLITE_PRIVATE void sqlite3PagerSetReiniter(Pager *pPager, void (*xReinit)(DbPage*)){
  pPager->xReiniter = xReinit;
}

/*
** Change the page size used by the Pager object. The new page size 
** is passed in *pPageSize.
**
** If the pager is in the error state when this function is called, it
** is a no-op. The value returned is the error state error code (i.e. 
** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
**
** Otherwise, if all of the following are true:
**
**   * the new page size (value of *pPageSize) is valid (a power 
**     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
**
**   * there are no outstanding page references, and
**
**   * the database is either not an in-memory database or it is
**     an in-memory database that currently consists of zero pages.
**
** then the pager object page size is set to *pPageSize.
**
** If the page size is changed, then this function uses sqlite3PagerMalloc() 
** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
** In all other cases, SQLITE_OK is returned.
**
** If the page size is not changed, either because one of the enumerated
** conditions above is not true, the pager was in error state when this
** function was called, or because the memory allocation attempt failed, 
** then *pPageSize is set to the old, retained page size before returning.
*/
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize){
  int rc = pPager->errCode;
  if( rc==SQLITE_OK ){
    u16 pageSize = *pPageSize;
    assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
    if( pageSize && pageSize!=pPager->pageSize 
     && (pPager->memDb==0 || pPager->dbSize==0)
     && sqlite3PcacheRefCount(pPager->pPCache)==0 
    ){
      char *pNew = (char *)sqlite3PageMalloc(pageSize);
      if( !pNew ){
        rc = SQLITE_NOMEM;
      }else{
        pager_reset(pPager);
        pPager->pageSize = pageSize;

        sqlite3PageFree(pPager->pTmpSpace);
        pPager->pTmpSpace = pNew;
        sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
      }
    }
    *pPageSize = (u16)pPager->pageSize;
  }
33016
33017
33018
33019
33020
33021
33022


33023
33024
33025
33026
33027




33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045


33046
33047

33048
33049
33050




33051
33052

33053
33054
33055

33056
33057
33058
33059


33060
33061
33062


33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082




33083
33084
33085


33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097





33098
33099
33100
33101
33102
33103

33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114










33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139

33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180


33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191

33192
33193
33194
33195


33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233


33234
33235


33236
33237
33238

33239

33240

33241


33242
33243
33244
33245
33246

33247
33248
33249


33250

33251

33252
33253

33254



33255
33256
33257
33258
33259
33260
33261
33262
33263
33264

33265
33266
33267
33268



33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287





33288


33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332

33333
33334


33335
33336
33337
33338
33339
33340
33341

33342







33343






33344
33345







33346




33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370

33371
33372
33373
33374
33375

33376
33377
33378
33379
33380
33381
33382
33383



33384
33385
33386
33387
33388



33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399



33400
33401
33402
33403
33404
33405
33406
33407





33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422

33423
33424




33425



33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444

33445
33446
33447
33448
33449
33450
33451
33452

33453
33454

33455










33456
33457
33458
33459
33460
33461
33462
33463
33464
33465














33466




33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477









33478

















33479
33480
33481


33482

33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494

33495
33496
33497
33498
33499
















































































































































































































































































33500
33501






33502
33503
33504
33505

33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516






33517
33518
33519
33520
33521
33522

33523
33524

33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538

33539
33540
33541
33542
33543
33544
33545
33546








33547
33548


33549

33550
33551
33552
33553

33554
33555
33556
33557






33558
33559
33560
33561
33562
33563
33564
33565
33566
33567

33568
33569
33570
33571
33572
33573

33574
33575
33576


33577
33578









33579









33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
# define enable_simulated_io_errors()
#endif

/*
** Read the first N bytes from the beginning of the file into memory
** that pDest points to. 
**


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




*/
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  int rc = SQLITE_OK;
  memset(pDest, 0, N);
  assert(pPager->fd->pMethods||pPager->tempFile);
  if( pPager->fd->pMethods ){
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
    if( rc==SQLITE_IOERR_SHORT_READ ){
      rc = SQLITE_OK;
    }
  }
  return rc;
}

/*
** Return the total number of pages in the disk file associated with
** 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.




*/
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){

  i64 n = 0;
  int rc;
  assert( pPager!=0 );

  if( pPager->errCode ){
    rc = pPager->errCode;
    return rc;
  }


  if( pPager->dbSizeValid ){
    n = pPager->dbSize;
  } else {


    assert(pPager->fd->pMethods||pPager->tempFile);
    if( (pPager->fd->pMethods)
     && (rc = sqlite3OsFileSize(pPager->fd, &n))!=SQLITE_OK ){
      pager_error(pPager, rc);
      return rc;
    }
    if( n>0 && n<pPager->pageSize ){
      n = 1;
    }else{
      n /= pPager->pageSize;
    }
    if( pPager->state!=PAGER_UNLOCK ){
      pPager->dbSize = (Pgno)n;
      pPager->dbFileSize = (Pgno)n;
      pPager->dbSizeValid = 1;
    }
  }
  if( n==(PENDING_BYTE/pPager->pageSize) ){
    n++;
  }




  if( n>pPager->mxPgno ){
    pPager->mxPgno = (Pgno)n;
  }


  if( pnPage ){
    *pnPage = (int)n;
  }
  return SQLITE_OK;
}

/*
** Forward declaration
*/
static int syncJournal(Pager*);

/*





** Try to obtain a lock on a file.  Invoke the busy callback if the lock
** is currently not available.  Repeat until the busy callback returns
** false or until the lock succeeds.
**
** Return SQLITE_OK on success and an error code if we cannot obtain
** the lock.

*/
static int pager_wait_on_lock(Pager *pPager, int locktype){
  int rc;

  /* The OS lock values must be the same as the Pager lock values */
  assert( PAGER_SHARED==SHARED_LOCK );
  assert( PAGER_RESERVED==RESERVED_LOCK );
  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );

  /* If the file is currently unlocked then the size must be unknown */
  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );











  if( pPager->state>=locktype ){
    rc = SQLITE_OK;
  }else{
    do {
      rc = sqlite3OsLock(pPager->fd, locktype);
    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
    if( rc==SQLITE_OK ){
      pPager->state = (u8)locktype;
      IOTRACE(("LOCK %p %d\n", pPager, locktype))
    }
  }
  return rc;
}

#ifndef SQLITE_OMIT_AUTOVACUUM
/*
** Truncate the in-memory database file image to nPage pages. This 
** function does not actually modify the database file on disk. It 
** just sets the internal state of the pager object so that the 
** truncation will be done when the current transaction is committed.
*/
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  assert( pPager->dbSizeValid );
  assert( pPager->dbSize>=nPage );

  pPager->dbSize = nPage;
}

/*
** Return the current size of the database file image in pages. This
** function differs from sqlite3PagerPagecount() in two ways:
**
**  a) It may only be called when at least one reference to a database
**     page is held. This guarantees that the database size is already
**     known and a call to sqlite3OsFileSize() is not required.
**
**  b) The return value is not adjusted for the locking page.
*/
SQLITE_PRIVATE Pgno sqlite3PagerImageSize(Pager *pPager){
  assert( pPager->dbSizeValid );
  return pPager->dbSize;
}
#endif  /* ifndef SQLITE_OMIT_AUTOVACUUM */

/*
** Shutdown the page cache.  Free all memory and close all files.
**
** If a transaction was in progress when this routine is called, that
** transaction is rolled back.  All outstanding pages are invalidated
** and their memory is freed.  Any attempt to use a page associated
** with this page cache after this function returns will likely
** result in a coredump.
**
** This function always succeeds. If a transaction is active an attempt
** is made to roll it back. If an error occurs during the rollback 
** a hot journal may be left in the filesystem but no error is returned
** to the caller.
*/
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){

  disable_simulated_io_errors();
  sqlite3BeginBenignMalloc();
  pPager->errCode = 0;
  pPager->exclusiveMode = 0;
  pager_reset(pPager);
  if( !MEMDB ){


    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
    ** call which may be made from within pagerUnlockAndRollback(). If it
    ** is not -1, then the unsynced portion of an open journal file may
    ** be played back into the database. If a power failure occurs while
    ** this is happening, the database may become corrupt.
    */
    pPager->journalHdr = -1;
    pagerUnlockAndRollback(pPager);
  }
  enable_simulated_io_errors();
  sqlite3EndBenignMalloc();

  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  IOTRACE(("CLOSE %p\n", pPager))
  if( pPager->journalOpen ){
    sqlite3OsClose(pPager->jfd);


  }
  sqlite3BitvecDestroy(pPager->pInJournal);
  sqlite3BitvecDestroy(pPager->pAlwaysRollback);
  releaseAllSavepoint(pPager);
  sqlite3OsClose(pPager->fd);
  /* Temp files are automatically deleted by the OS
  ** if( pPager->tempFile ){
  **   sqlite3OsDelete(pPager->zFilename);
  ** }
  */

  sqlite3PageFree(pPager->pTmpSpace);
  sqlite3PcacheClose(pPager->pPCache);
  sqlite3_free(pPager);
  return SQLITE_OK;
}

#if !defined(NDEBUG) || defined(SQLITE_TEST)
/*
** Return the page number for the given page data.
*/
SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *p){
  return p->pgno;
}
#endif

/*
** Increment the reference count for a page.  The input pointer is
** a reference to the page data.
*/
SQLITE_PRIVATE int sqlite3PagerRef(DbPage *pPg){
  sqlite3PcacheRef(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


** disk.  It is not safe to modify the original database file until after
** the journal has been synced.  If the original database is modified before


** the journal is synced and a power failure occurs, the unsynced journal
** data would be lost and we would be unable to completely rollback the
** database changes.  Database corruption would occur.

** 

** This routine also updates the nRec field in the header of the journal.

** (See comments on the pager_playback() routine for additional information.)


** If the sync mode is FULL, two syncs will occur.  First the whole journal
** is synced, then the nRec field is updated, then a second sync occurs.
**
** For temporary databases, we do not care if we are able to rollback
** after a power failure, so no sync occurs.

**
** If the IOCAP_SEQUENTIAL flag is set for the persistent media on which
** the database is stored, then OsSync() is never called on the journal


** file. In this case all that is required is to update the nRec field in

** the journal header.

**
** This routine clears the needSync field of every page current held in

** memory.



*/
static int syncJournal(Pager *pPager){
  int rc = SQLITE_OK;

  /* Sync the journal before modifying the main database
  ** (assuming there is a journal and it needs to be synced.)
  */
  if( pPager->needSync ){
    assert( !pPager->tempFile );
    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){

      int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
      assert( pPager->journalOpen );

      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){



        i64 jrnlOff = journalHdrOffset(pPager);
        u8 zMagic[8];

        /* This block deals with an obscure problem. If the last connection
        ** that wrote to this database was operating in persistent-journal
        ** mode, then the journal file may at this point actually be larger
        ** than Pager.journalOff bytes. If the next thing in the journal
        ** file happens to be a journal-header (written as part of the
        ** previous connections transaction), and a crash or power-failure 
        ** occurs after nRec is updated but before this connection writes 
        ** anything else to the journal file (or commits/rolls back its 
        ** transaction), then SQLite may become confused when doing the 
        ** hot-journal rollback following recovery. It may roll back all
        ** of this connections data, then proceed to rolling back the old,
        ** out-of-date data that follows it. Database corruption.
        **
        ** To work around this, if the journal file does appear to contain
        ** a valid header following Pager.journalOff, then write a 0x00
        ** byte to the start of it to prevent it from being recognized.





        */


        rc = sqlite3OsRead(pPager->jfd, zMagic, 8, jrnlOff);
        if( rc==SQLITE_OK && 0==memcmp(zMagic, aJournalMagic, 8) ){
          static const u8 zerobyte = 0;
          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, jrnlOff);
        }
        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
          return rc;
        }

        /* Write the nRec value into the journal file header. If in
        ** full-synchronous mode, sync the journal first. This ensures that
        ** all data has really hit the disk before nRec is updated to mark
        ** it as a candidate for rollback.
        **
        ** This is not required if the persistent media supports the
        ** SAFE_APPEND property. Because in this case it is not possible 
        ** for garbage data to be appended to the file, the nRec field
        ** is populated with 0xFFFFFFFF when the journal header is written
        ** and never needs to be updated.
        */
        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
          IOTRACE(("JSYNC %p\n", pPager))
          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
          if( rc!=0 ) return rc;
        }

        jrnlOff = pPager->journalHdr + sizeof(aJournalMagic);
        IOTRACE(("JHDR %p %lld %d\n", pPager, jrnlOff, 4));
        rc = write32bits(pPager->jfd, jrnlOff, pPager->nRec);
        if( rc ) return rc;
      }
      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
        IOTRACE(("JSYNC %p\n", pPager))
        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
        );
        if( rc!=0 ) return rc;
      }
      pPager->journalStarted = 1;
    }
    pPager->needSync = 0;


    /* Erase the needSync flag from every page.
    */


    sqlite3PcacheClearSyncFlags(pPager->pPCache);
  }

  return rc;
}

/*

** Given a list of pages (connected by the PgHdr.pDirty pointer) write







** every one of those pages out to the database file. No calls are made






** to the page-cache to mark the pages as clean. It is the responsibility
** of the caller to use PcacheCleanAll() or PcacheMakeClean() to mark







** the pages as clean.




*/
static int pager_write_pagelist(PgHdr *pList){
  Pager *pPager;
  int rc;

  if( pList==0 ) return SQLITE_OK;
  pPager = pList->pPager;

  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
  ** database file. If there is already an EXCLUSIVE lock, the following
  ** calls to sqlite3OsLock() are no-ops.
  **
  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
  ** through an intermediate state PENDING.   A PENDING lock prevents new
  ** readers from attaching to the database but is unsufficient for us to
  ** write.  The idea of a PENDING lock is to prevent new readers from
  ** coming in while we wait for existing readers to clear.
  **
  ** While the pager is in the RESERVED state, the original database file
  ** is unchanged and we can rollback without having to playback the
  ** journal into the original database file.  Once we transition to
  ** EXCLUSIVE, it means the database file has been changed and any rollback
  ** will require a journal playback.
  */

  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  if( rc!=SQLITE_OK ){
    return rc;
  }


  while( pList ){

    /* If the file has not yet been opened, open it now. */
    if( !pPager->fd->pMethods ){
      assert(pPager->tempFile);
      rc = sqlite3PagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
      if( rc ) return rc;
    }




    /* If there are dirty pages in the page cache with page numbers greater
    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
    ** make the file smaller (presumably by auto-vacuum code). Do not write
    ** any such pages to the file.



    */
    if( pList->pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
      i64 offset = (pList->pgno-1)*(i64)pPager->pageSize;
      char *pData = CODEC2(pPager, pList->pData, pList->pgno, 6);

      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
                   PAGERID(pPager), pList->pgno, pager_pagehash(pList)));
      IOTRACE(("PGOUT %p %d\n", pPager, pList->pgno));
      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
      PAGER_INCR(sqlite3_pager_writedb_count);
      PAGER_INCR(pPager->nWrite);



      if( pList->pgno==1 ){
        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
      }
      if( pList->pgno>pPager->dbFileSize ){
        pPager->dbFileSize = pList->pgno;
      }
    }
#ifndef NDEBUG





    else{
      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pList->pgno));
    }
#endif
    if( rc ) return rc;
#ifdef SQLITE_CHECK_PAGES
    pList->pageHash = pager_pagehash(pList);
#endif
    pList = pList->pDirty;
  }

  return SQLITE_OK;
}

/*

** Add the page to the sub-journal. It is the callers responsibility to
** use subjRequiresPage() to check that it is really required before 




** calling this function.



*/
static int subjournalPage(PgHdr *pPg){
  int rc;
  void *pData = pPg->pData;
  Pager *pPager = pPg->pPager;
  i64 offset = pPager->stmtNRec*(4+pPager->pageSize);
  char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);

  PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));

  assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  if( rc==SQLITE_OK ){
    rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  }
  if( rc==SQLITE_OK ){
    pPager->stmtNRec++;
    assert( pPager->nSavepoint>0 );
    rc = addToSavepointBitvecs(pPager, pPg->pgno);

  }
  return rc;
}


/*
** This function is called by the pcache layer when it has reached some
** soft memory limit. The argument is a pointer to a purgeable Pager 

** object. This function attempts to make a single dirty page that has no
** outstanding references (if one exists) clean so that it can be recycled 

** by the pcache layer.










*/
static int pagerStress(void *p, PgHdr *pPg){
  Pager *pPager = (Pager *)p;
  int rc = SQLITE_OK;

  if( pPager->doNotSync ){
    return SQLITE_OK;
  }

  assert( pPg->flags&PGHDR_DIRTY );














  if( pPager->errCode==SQLITE_OK ){




    if( pPg->flags&PGHDR_NEED_SYNC ){
      rc = syncJournal(pPager);
      if( rc==SQLITE_OK && pPager->fullSync && 
        !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
        !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
      ){
        pPager->nRec = 0;
        rc = writeJournalHdr(pPager);
      }
    }
    if( rc==SQLITE_OK ){









      pPg->pDirty = 0;

















      if( pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) ){
        rc = subjournalPage(pPg);
      }


      if( rc==SQLITE_OK ){

        rc = pager_write_pagelist(pPg);
      }
    }
    if( rc!=SQLITE_OK ){
      pager_error(pPager, rc);
    }
  }

  if( rc==SQLITE_OK ){
    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
    sqlite3PcacheMakeClean(pPg);
  }

  return rc;
}


/*
















































































































































































































































































** Return 1 if there is a hot journal on the given pager.
** A hot journal is one that needs to be played back.






**
** If the current size of the database file is 0 but a journal file
** exists, that is probably an old journal left over from a prior
** database with the same name.  Just delete the journal.

**
** Return negative if unable to determine the status of the journal.
**
** This routine does not open the journal file to examine its
** content.  Hence, the journal might contain the name of a master
** journal file that has been deleted, and hence not be hot.  Or
** the header of the journal might be zeroed out.  This routine
** does not discover these cases of a non-hot journal - if the
** journal file exists and is not empty this routine assumes it
** is hot.  The pager_playback() routine will discover that the
** journal file is not really hot and will no-op.






*/
static int hasHotJournal(Pager *pPager, int *pExists){
  sqlite3_vfs *pVfs = pPager->pVfs;
  int rc = SQLITE_OK;
  int exists = 0;
  int locked = 0;

  assert( pPager!=0 );
  assert( pPager->useJournal );

  assert( pPager->fd->pMethods );
  *pExists = 0;
  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  if( rc==SQLITE_OK && exists ){
    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  }
  if( rc==SQLITE_OK && exists && !locked ){
    int nPage;
    rc = sqlite3PagerPagecount(pPager, &nPage);
    if( rc==SQLITE_OK ){
     if( nPage==0 ){
        sqlite3OsDelete(pVfs, pPager->zJournal, 0);
      }else{
        *pExists = 1;

      }
    }
  }
  return rc;
}

/*
** Read the content of page pPg out of the database file.








*/
static int readDbPage(Pager *pPager, PgHdr *pPg, Pgno pgno){


  int rc;

  i64 offset;
  assert( MEMDB==0 );
  assert(pPager->fd->pMethods||pPager->tempFile);
  if( !pPager->fd->pMethods ){

    return SQLITE_IOERR_SHORT_READ;
  }
  offset = (pgno-1)*(i64)pPager->pageSize;
  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, offset);






  PAGER_INCR(sqlite3_pager_readdb_count);
  PAGER_INCR(pPager->nRead);
  IOTRACE(("PGIN %p %d\n", pPager, pgno));
  if( pgno==1 ){
    memcpy(&pPager->dbFileVers, &((u8*)pPg->pData)[24],
                                              sizeof(pPager->dbFileVers));
  }
  CODEC1(pPager, pPg->pData, pPg->pgno, 3);
  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
               PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));

  return rc;
}


/*
** This function is called to obtain the shared lock required before

** data may be read from the pager cache. If the shared lock has already
** been obtained, this function is a no-op.
**


** Immediately after obtaining the shared lock (if required), this function
** checks for a hot-journal file. If one is found, an emergency rollback









** is performed immediately.









*/
static int pagerSharedLock(Pager *pPager){
  int rc = SQLITE_OK;
  int isErrorReset = 0;

  /* If this database is opened for exclusive access, has no outstanding 
  ** page references and is in an error-state, now is the chance to clear
  ** the error. Discard the contents of the pager-cache and treat any
  ** open journal file as a hot-journal.
  */
  if( !MEMDB && pPager->exclusiveMode 
   && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
  ){
    if( pPager->journalOpen ){
      isErrorReset = 1;
    }
    pPager->errCode = SQLITE_OK;
    pager_reset(pPager);
  }

  /* If the pager is still in an error state, do not proceed. The error 
  ** state will be cleared at some point in the future when all page 
  ** references are dropped and the cache can be discarded.
  */
  if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
    return pPager->errCode;
  }

  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
    sqlite3_vfs *pVfs = pPager->pVfs;
    int isHotJournal = 0;
    assert( !MEMDB );
    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
    if( !pPager->noReadlock ){
      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
      if( rc!=SQLITE_OK ){
        assert( pPager->state==PAGER_UNLOCK );







>
>
|
<
<
|
|
>
>
>
>




|
|










|
|
>
>

|
>
|
<
|
>
>
>
>


>
|
<
<
>

|
<

>
>

|
|
>
>
|
|
|




|

|


|
|



<
<
|
>
>
>
>
|
|

>
>

|




<
<
<
<


>
>
>
>
>
|
|
|


|
>


|








>
>
>
>
>
>
>
>
>
>















<









>



<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<















<





|
>
>









<

>


<
|
>
>
|
<
<
|
<
<
<
|
<
<

<
<






|

|
|




|
<

|

<



|

>
>
|
|
>
>
|
<
<
>
|
>
|
>
|
>
>
|
|

<
<
>

<
|
>
>
|
>
|
>

|
>
|
>
>
>


<
<
<
<
<



>
|
|


>
>
>
|
|

















>
>
>
>
>

>
>
|
|

|




















|

<
<
|
|
|







|

<

<

>
|

>
>



|



>
|
>
>
>
>
>
>
>
|
>
>
>
>
>
>
|
|
>
>
>
>
>
>
>
|
>
>
>
>


|
|






|













>

<
<
|
|
>
|
|
<
|
|
|
<
|
>
>
>





>
>
>

|
|
|

|
<
<

|
|
>
>
>
|


|
|

|
<
>
>
>
>
>
|
|

<
<






|



>
|
|
>
>
>
>
|
>
>
>





|










|


>







|
>
|
|
>
|
>
>
>
>
>
>
>
>
>
>





<
<
<
|

>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
>
>
|
>
|
|
|
<
<
<
<
|




>
|




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
>
>
>
>
>
>



|
>
|
<









>
>
>
>
>
>


|
|
|
|
>


>
|




<
|
|
|
|
|
|
|
|
>







|
>
>
>
>
>
>
>
>

|
>
>
|
>
|
|
|
|
>


|
|
>
>
>
>
>
>



<
<
<
<
<

|
>



<

|
>
|
|

>
>
|
|
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>


|
|


|






|















|







33353
33354
33355
33356
33357
33358
33359
33360
33361
33362


33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392

33393
33394
33395
33396
33397
33398
33399
33400
33401


33402
33403
33404

33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429


33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445




33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495

33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
















33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523

33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540

33541
33542
33543
33544

33545
33546
33547
33548


33549



33550


33551


33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566

33567
33568
33569

33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581


33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592


33593
33594

33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610





33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674


33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686

33687

33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756


33757
33758
33759
33760
33761

33762
33763
33764

33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782


33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795

33796
33797
33798
33799
33800
33801
33802
33803


33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872



33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941




33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238

34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268

34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317





34318
34319
34320
34321
34322
34323

34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
# define enable_simulated_io_errors()
#endif

/*
** Read the first N bytes from the beginning of the file into memory
** that pDest points to. 
**
** If the pager was opened on a transient file (zFilename==""), or
** opened on a file less than N bytes in size, the output buffer is
** zeroed and SQLITE_OK returned. The rationale for this is that this 


** function is used to read database headers, and a new transient or
** zero sized database has a header than consists entirely of zeroes.
**
** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
** the error code is returned to the caller and the contents of the
** output buffer undefined.
*/
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  int rc = SQLITE_OK;
  memset(pDest, 0, N);
  assert( isOpen(pPager->fd) || pPager->tempFile );
  if( isOpen(pPager->fd) ){
    IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
    rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
    if( rc==SQLITE_IOERR_SHORT_READ ){
      rc = SQLITE_OK;
    }
  }
  return rc;
}

/*
** Return the total number of pages in the database file associated 
** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
** However, if the file is between 1 and <page-size> bytes in size, then 
** this is considered a 1 page file.
**
** If the pager is in error state when this function is called, then the
** error state error code is returned and *pnPage left unchanged. Or,
** if the file system has to be queried for the size of the file and

** the query attempt returns an IO error, the IO error code is returned
** and *pnPage is left unchanged.
**
** Otherwise, if everything is successful, then SQLITE_OK is returned
** and *pnPage is set to the number of pages in the database.
*/
SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  Pgno nPage;               /* Value to return via *pnPage */



  /* If the pager is already in the error state, return the error code. */
  if( pPager->errCode ){
    return pPager->errCode;

  }

  /* Determine the number of pages in the file. Store this in nPage. */
  if( pPager->dbSizeValid ){
    nPage = pPager->dbSize;
  }else{
    int rc;                 /* Error returned by OsFileSize() */
    i64 n = 0;              /* File size in bytes returned by OsFileSize() */

    assert( isOpen(pPager->fd) || pPager->tempFile );
    if( isOpen(pPager->fd) && (rc = sqlite3OsFileSize(pPager->fd, &n)) ){
      pager_error(pPager, rc);
      return rc;
    }
    if( n>0 && n<pPager->pageSize ){
      nPage = 1;
    }else{
      nPage = (Pgno)(n / pPager->pageSize);
    }
    if( pPager->state!=PAGER_UNLOCK ){
      pPager->dbSize = nPage;
      pPager->dbFileSize = nPage;
      pPager->dbSizeValid = 1;
    }
  }



  /* If the current number of pages in the file is greater than the 
  ** configured maximum pager number, increase the allowed limit so
  ** that the file can be read.
  */
  if( nPage>pPager->mxPgno ){
    pPager->mxPgno = (Pgno)nPage;
  }

  /* Set the output variable and return SQLITE_OK */
  if( pnPage ){
    *pnPage = nPage;
  }
  return SQLITE_OK;
}






/*
** Try to obtain a lock of type locktype on the database file. If
** a similar or greater lock is already held, this function is a no-op
** (returning SQLITE_OK immediately).
**
** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
** the busy callback if the lock is currently not available. Repeat 
** until the busy callback returns false or until the attempt to 
** obtain the lock succeeds.
**
** Return SQLITE_OK on success and an error code if we cannot obtain
** the lock. If the lock is obtained successfully, set the Pager.state 
** variable to locktype before returning.
*/
static int pager_wait_on_lock(Pager *pPager, int locktype){
  int rc;                              /* Return code */

  /* The OS lock values must be the same as the Pager lock values */
  assert( PAGER_SHARED==SHARED_LOCK );
  assert( PAGER_RESERVED==RESERVED_LOCK );
  assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );

  /* If the file is currently unlocked then the size must be unknown */
  assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );

  /* Check that this is either a no-op (because the requested lock is 
  ** already held, or one of the transistions that the busy-handler
  ** may be invoked during, according to the comment above
  ** sqlite3PagerSetBusyhandler().
  */
  assert( (pPager->state>=locktype)
       || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
       || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
  );

  if( pPager->state>=locktype ){
    rc = SQLITE_OK;
  }else{
    do {
      rc = sqlite3OsLock(pPager->fd, locktype);
    }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
    if( rc==SQLITE_OK ){
      pPager->state = (u8)locktype;
      IOTRACE(("LOCK %p %d\n", pPager, locktype))
    }
  }
  return rc;
}


/*
** Truncate the in-memory database file image to nPage pages. This 
** function does not actually modify the database file on disk. It 
** just sets the internal state of the pager object so that the 
** truncation will be done when the current transaction is committed.
*/
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  assert( pPager->dbSizeValid );
  assert( pPager->dbSize>=nPage );
  assert( pPager->state>=PAGER_RESERVED );
  pPager->dbSize = nPage;
}

















/*
** Shutdown the page cache.  Free all memory and close all files.
**
** If a transaction was in progress when this routine is called, that
** transaction is rolled back.  All outstanding pages are invalidated
** and their memory is freed.  Any attempt to use a page associated
** with this page cache after this function returns will likely
** result in a coredump.
**
** This function always succeeds. If a transaction is active an attempt
** is made to roll it back. If an error occurs during the rollback 
** a hot journal may be left in the filesystem but no error is returned
** to the caller.
*/
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){

  disable_simulated_io_errors();
  sqlite3BeginBenignMalloc();
  pPager->errCode = 0;
  pPager->exclusiveMode = 0;
  pager_reset(pPager);
  if( MEMDB ){
    pager_unlock(pPager);
  }else{
    /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
    ** call which may be made from within pagerUnlockAndRollback(). If it
    ** is not -1, then the unsynced portion of an open journal file may
    ** be played back into the database. If a power failure occurs while
    ** this is happening, the database may become corrupt.
    */
    pPager->journalHdr = -1;
    pagerUnlockAndRollback(pPager);
  }

  sqlite3EndBenignMalloc();
  enable_simulated_io_errors();
  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  IOTRACE(("CLOSE %p\n", pPager))

  sqlite3OsClose(pPager->fd);
  sqlite3PageFree(pPager->pTmpSpace);
  sqlite3PcacheClose(pPager->pPCache);



  assert( !pPager->aSavepoint && !pPager->pInJournal );



  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );





  sqlite3_free(pPager);
  return SQLITE_OK;
}

#if !defined(NDEBUG) || defined(SQLITE_TEST)
/*
** Return the page number for page pPg.
*/
SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  return pPg->pgno;
}
#endif

/*
** Increment the reference count for page pPg.

*/
SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  sqlite3PcacheRef(pPg);

}

/*
** Sync the journal. In other words, make sure all the pages that have
** been written to the journal have actually reached the surface of the
** disk and can be restored in the event of a hot-journal rollback.
**
** If the Pager.needSync flag is not set, then this function is a
** no-op. Otherwise, the actions required depend on the journal-mode
** and the device characteristics of the the file-system, as follows:
**
**   * If the journal file is an in-memory journal file, no action need


**     be taken.
**
**   * Otherwise, if the device does not support the SAFE_APPEND property,
**     then the nRec field of the most recently written journal header
**     is updated to contain the number of journal records that have
**     been written following it. If the pager is operating in full-sync
**     mode, then the journal file is synced before this field is updated.
**
**   * If the device does not support the SEQUENTIAL property, then 
**     journal file is synced.
**


** Or, in pseudo-code:
**

**   if( NOT <in-memory journal> ){
**     if( NOT SAFE_APPEND ){
**       if( <full-sync mode> ) xSync(<journal file>);
**       <update nRec field>
**     } 
**     if( NOT SEQUENTIAL ) xSync(<journal file>);
**   }
**
** The Pager.needSync flag is never be set for temporary files, or any
** file operating in no-sync mode (Pager.noSync set to non-zero).
**
** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
** page currently held in memory before returning SQLITE_OK. If an IO
** error is encountered, then the IO error code is returned to the caller.
*/
static int syncJournal(Pager *pPager){





  if( pPager->needSync ){
    assert( !pPager->tempFile );
    if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
      int rc;                              /* Return code */
      const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
      assert( isOpen(pPager->jfd) );

      if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
        /* Variable iNRecOffset is set to the offset in the journal file
        ** of the nRec field of the most recently written journal header.
        ** This field will be updated following the xSync() operation
        ** on the journal file. */
        i64 iNRecOffset = pPager->journalHdr + sizeof(aJournalMagic);

        /* This block deals with an obscure problem. If the last connection
        ** that wrote to this database was operating in persistent-journal
        ** mode, then the journal file may at this point actually be larger
        ** than Pager.journalOff bytes. If the next thing in the journal
        ** file happens to be a journal-header (written as part of the
        ** previous connections transaction), and a crash or power-failure 
        ** occurs after nRec is updated but before this connection writes 
        ** anything else to the journal file (or commits/rolls back its 
        ** transaction), then SQLite may become confused when doing the 
        ** hot-journal rollback following recovery. It may roll back all
        ** of this connections data, then proceed to rolling back the old,
        ** out-of-date data that follows it. Database corruption.
        **
        ** To work around this, if the journal file does appear to contain
        ** a valid header following Pager.journalOff, then write a 0x00
        ** byte to the start of it to prevent it from being recognized.
        **
        ** Variable iNextHdrOffset is set to the offset at which this
        ** problematic header will occur, if it exists. aMagic is used 
        ** as a temporary buffer to inspect the first couple of bytes of
        ** the potential journal header.
        */
        i64 iNextHdrOffset = journalHdrOffset(pPager);
        u8 aMagic[8];
        rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
        if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
          static const u8 zerobyte = 0;
          rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
        }
        if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
          return rc;
        }

        /* Write the nRec value into the journal file header. If in
        ** full-synchronous mode, sync the journal first. This ensures that
        ** all data has really hit the disk before nRec is updated to mark
        ** it as a candidate for rollback.
        **
        ** This is not required if the persistent media supports the
        ** SAFE_APPEND property. Because in this case it is not possible 
        ** for garbage data to be appended to the file, the nRec field
        ** is populated with 0xFFFFFFFF when the journal header is written
        ** and never needs to be updated.
        */
        if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
          PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
          IOTRACE(("JSYNC %p\n", pPager))
          rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
          if( rc!=SQLITE_OK ) return rc;
        }


        IOTRACE(("JHDR %p %lld %d\n", pPager, iNRecOffset, 4));
        rc = write32bits(pPager->jfd, iNRecOffset, pPager->nRec);
        if( rc!=SQLITE_OK ) return rc;
      }
      if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
        PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
        IOTRACE(("JSYNC %p\n", pPager))
        rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
          (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
        );
        if( rc!=SQLITE_OK ) return rc;
      }

    }


    /* The journal file was just successfully synced. Set Pager.needSync 
    ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
    */
    pPager->needSync = 0;
    pPager->journalStarted = 1;
    sqlite3PcacheClearSyncFlags(pPager->pPCache);
  }

  return SQLITE_OK;
}

/*
** The argument is the first in a linked list of dirty pages connected
** by the PgHdr.pDirty pointer. This function writes each one of the
** in-memory pages in the list to the database file. The argument may
** be NULL, representing an empty list. In this case this function is
** a no-op.
**
** The pager must hold at least a RESERVED lock when this function
** is called. Before writing anything to the database file, this lock
** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
** SQLITE_BUSY is returned and no data is written to the database file.
** 
** If the pager is a temp-file pager and the actual file-system file
** is not yet open, it is created and opened before any data is 
** written out.
**
** Once the lock has been upgraded and, if necessary, the file opened,
** the pages are written out to the database file in list order. Writing
** a page is skipped if it meets either of the following criteria:
**
**   * The page number is greater than Pager.dbSize, or
**   * The PGHDR_DONT_WRITE flag is set on the page.
**
** If writing out a page causes the database file to grow, Pager.dbFileSize
** is updated accordingly. If page 1 is written out, then the value cached
** in Pager.dbFileVers[] is updated to match the new value stored in
** the database file.
**
** If everything is successful, SQLITE_OK is returned. If an IO error 
** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
** be obtained, SQLITE_BUSY is returned.
*/
static int pager_write_pagelist(PgHdr *pList){
  Pager *pPager;                       /* Pager object */
  int rc;                              /* Return code */

  if( pList==0 ) return SQLITE_OK;
  pPager = pList->pPager;

  /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
  ** database file. If there is already an EXCLUSIVE lock, the following
  ** call is a no-op.
  **
  ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
  ** through an intermediate state PENDING.   A PENDING lock prevents new
  ** readers from attaching to the database but is unsufficient for us to
  ** write.  The idea of a PENDING lock is to prevent new readers from
  ** coming in while we wait for existing readers to clear.
  **
  ** While the pager is in the RESERVED state, the original database file
  ** is unchanged and we can rollback without having to playback the
  ** journal into the original database file.  Once we transition to
  ** EXCLUSIVE, it means the database file has been changed and any rollback
  ** will require a journal playback.
  */
  assert( pPager->state>=PAGER_RESERVED );
  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);



  /* If the file is a temp-file has not yet been opened, open it now. It
  ** is not possible for rc to be other than SQLITE_OK if this branch
  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  */

  if( !isOpen(pPager->fd) ){
    assert( pPager->tempFile && rc==SQLITE_OK );
    rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);

  }

  while( rc==SQLITE_OK && pList ){
    Pgno pgno = pList->pgno;

    /* If there are dirty pages in the page cache with page numbers greater
    ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
    ** make the file smaller (presumably by auto-vacuum code). Do not write
    ** any such pages to the file.
    **
    ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
    ** set (set by sqlite3PagerDontWrite()).
    */
    if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
      i64 offset = (pgno-1)*(i64)pPager->pageSize;         /* Offset to write */
      char *pData = CODEC2(pPager, pList->pData, pgno, 6); /* Data to write */

      /* Write out the page data. */


      rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);

      /* If page 1 was just written, update Pager.dbFileVers to match
      ** the value now stored in the database file. If writing this 
      ** page caused the database file to grow, update dbFileSize. 
      */
      if( pgno==1 ){
        memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
      }
      if( pgno>pPager->dbFileSize ){
        pPager->dbFileSize = pgno;
      }


      PAGERTRACE(("STORE %d page %d hash(%08x)\n",
                   PAGERID(pPager), pgno, pager_pagehash(pList)));
      IOTRACE(("PGOUT %p %d\n", pPager, pgno));
      PAGER_INCR(sqlite3_pager_writedb_count);
      PAGER_INCR(pPager->nWrite);
    }else{
      PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
    }


#ifdef SQLITE_CHECK_PAGES
    pList->pageHash = pager_pagehash(pList);
#endif
    pList = pList->pDirty;
  }

  return rc;
}

/*
** Append a record of the current state of page pPg to the sub-journal. 
** It is the callers responsibility to use subjRequiresPage() to check 
** that it is really required before calling this function.
**
** If successful, set the bit corresponding to pPg->pgno in the bitvecs
** for all open savepoints before returning.
**
** This function returns SQLITE_OK if everything is successful, an IO
** error code if the attempt to write to the sub-journal fails, or 
** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
** bitvec.
*/
static int subjournalPage(PgHdr *pPg){
  int rc;
  void *pData = pPg->pData;
  Pager *pPager = pPg->pPager;
  i64 offset = pPager->nSubRec*(4+pPager->pageSize);
  char *pData2 = CODEC2(pPager, pData, pPg->pgno, 7);

  PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));

  assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  if( rc==SQLITE_OK ){
    rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  }
  if( rc==SQLITE_OK ){
    pPager->nSubRec++;
    assert( pPager->nSavepoint>0 );
    rc = addToSavepointBitvecs(pPager, pPg->pgno);
    testcase( rc!=SQLITE_OK );
  }
  return rc;
}


/*
** This function is called by the pcache layer when it has reached some
** soft memory limit. The first argument is a pointer to a Pager object
** (cast as a void*). The pager is always 'purgeable' (not an in-memory
** database). The second argument is a reference to a page that is 
** currently dirty but has no outstanding references. The page
** is always associated with the Pager object passed as the first 
** argument.
**
** The job of this function is to make pPg clean by writing its contents
** out to the database file, if possible. This may involve syncing the
** journal file. 
**
** If successful, sqlite3PcacheMakeClean() is called on the page and
** SQLITE_OK returned. If an IO error occurs while trying to make the
** page clean, the IO error code is returned. If the page cannot be
** made clean for some other reason, but no error occurs, then SQLITE_OK
** is returned by sqlite3PcacheMakeClean() is not called.
*/
static int pagerStress(void *p, PgHdr *pPg){
  Pager *pPager = (Pager *)p;
  int rc = SQLITE_OK;




  assert( pPg->pPager==pPager );
  assert( pPg->flags&PGHDR_DIRTY );

  /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
  ** is journalling a set of two or more database pages that are stored
  ** on the same disk sector. Syncing the journal is not allowed while
  ** this is happening as it is important that all members of such a
  ** set of pages are synced to disk together. So, if the page this function
  ** is trying to make clean will require a journal sync and the doNotSync
  ** flag is set, return without doing anything. The pcache layer will
  ** just have to go ahead and allocate a new page buffer instead of
  ** reusing pPg.
  **
  ** Similarly, if the pager has already entered the error state, do not
  ** try to write the contents of pPg to disk.
  */
  if( pPager->errCode || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC) ){
    return SQLITE_OK;
  }

  /* Sync the journal file if required. */
  if( pPg->flags&PGHDR_NEED_SYNC ){
    rc = syncJournal(pPager);
    if( rc==SQLITE_OK && pPager->fullSync && 
      !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
      !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
    ){
      pPager->nRec = 0;
      rc = writeJournalHdr(pPager);
    }
  }

  /* If the page number of this page is larger than the current size of
  ** the database image, it may need to be written to the sub-journal.
  ** This is because the call to pager_write_pagelist() below will not
  ** actually write data to the file in this case.
  **
  ** Consider the following sequence of events:
  **
  **   BEGIN;
  **     <journal page X>
  **     <modify page X>
  **     SAVEPOINT sp;
  **       <shrink database file to Y pages>
  **       pagerStress(page X)
  **     ROLLBACK TO sp;
  **
  ** If (X>Y), then when pagerStress is called page X will not be written
  ** out to the database file, but will be dropped from the cache. Then,
  ** following the "ROLLBACK TO sp" statement, reading page X will read
  ** data from the database file. This will be the copy of page X as it
  ** was when the transaction started, not as it was when "SAVEPOINT sp"
  ** was executed.
  **
  ** The solution is to write the current data for page X into the 
  ** sub-journal file now (if it is not already there), so that it will
  ** be restored to its current value when the "ROLLBACK TO sp" is 
  ** executed.
  */
  if( rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg) ){
    rc = subjournalPage(pPg);
  }

  /* Write the contents of the page out to the database file. */
  if( rc==SQLITE_OK ){
    pPg->pDirty = 0;
    rc = pager_write_pagelist(pPg);
  }





  /* Mark the page as clean. */
  if( rc==SQLITE_OK ){
    PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
    sqlite3PcacheMakeClean(pPg);
  }

  return pager_error(pPager, rc);
}


/*
** Allocate and initialize a new Pager object and put a pointer to it
** in *ppPager. The pager should eventually be freed by passing it
** to sqlite3PagerClose().
**
** The zFilename argument is the path to the database file to open.
** If zFilename is NULL then a randomly-named temporary file is created
** and used as the file to be cached. Temporary files are be deleted
** automatically when they are closed. If zFilename is ":memory:" then 
** all information is held in cache. It is never written to disk. 
** This can be used to implement an in-memory database.
**
** The nExtra parameter specifies the number of bytes of space allocated
** along with each page reference. This space is available to the user
** via the sqlite3PagerGetExtra() API.
**
** The flags argument is used to specify properties that affect the
** operation of the pager. It should be passed some bitwise combination
** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
**
** The vfsFlags parameter is a bitmask to pass to the flags parameter
** of the xOpen() method of the supplied VFS when opening files. 
**
** If the pager object is allocated and the specified file opened 
** successfully, SQLITE_OK is returned and *ppPager set to point to
** the new pager object. If an error occurs, *ppPager is set to NULL
** and error code returned. This function may return SQLITE_NOMEM
** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
** various SQLITE_IO_XXX errors.
*/
SQLITE_PRIVATE int sqlite3PagerOpen(
  sqlite3_vfs *pVfs,       /* The virtual file system to use */
  Pager **ppPager,         /* OUT: Return the Pager structure here */
  const char *zFilename,   /* Name of the database file to open */
  int nExtra,              /* Extra bytes append to each in-memory page */
  int flags,               /* flags controlling this file */
  int vfsFlags             /* flags passed through to sqlite3_vfs.xOpen() */
){
  u8 *pPtr;
  Pager *pPager = 0;       /* Pager object to allocate and return */
  int rc = SQLITE_OK;      /* Return code */
  int tempFile = 0;        /* True for temp files (incl. in-memory files) */
  int memDb = 0;           /* True if this is an in-memory file */
  int readOnly = 0;        /* True if this is a read-only file */
  int journalFileSize;     /* Bytes to allocate for each journal fd */
  char *zPathname = 0;     /* Full path to database file */
  int nPathname = 0;       /* Number of bytes in zPathname */
  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
  int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
  u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */

  /* Figure out how much space is required for each journal file-handle
  ** (there are two of them, the main journal and the sub-journal). This
  ** is the maximum space required for an in-memory journal file handle 
  ** and a regular journal file-handle. Note that a "regular journal-handle"
  ** may be a wrapper capable of caching the first portion of the journal
  ** file in memory to implement the atomic-write optimization (see 
  ** source file journal.c).
  */
  if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
    journalFileSize = sqlite3JournalSize(pVfs);
  }else{
    journalFileSize = sqlite3MemJournalSize();
  }

  /* Set the output variable to NULL in case an error occurs. */
  *ppPager = 0;

  /* Compute and store the full pathname in an allocated buffer pointed
  ** to by zPathname, length nPathname. Or, if this is a temporary file,
  ** leave both nPathname and zPathname set to 0.
  */
  if( zFilename && zFilename[0] ){
    nPathname = pVfs->mxPathname+1;
    zPathname = sqlite3Malloc(nPathname*2);
    if( zPathname==0 ){
      return SQLITE_NOMEM;
    }
#ifndef SQLITE_OMIT_MEMORYDB
    if( strcmp(zFilename,":memory:")==0 ){
      memDb = 1;
      zPathname[0] = 0;
    }else
#endif
    {
      rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
    }

    nPathname = sqlite3Strlen30(zPathname);
    if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
      /* This branch is taken when the journal path required by
      ** the database being opened will be more than pVfs->mxPathname
      ** bytes in length. This means the database cannot be opened,
      ** as it will not be possible to open the journal file or even
      ** check for a hot-journal before reading.
      */
      rc = SQLITE_CANTOPEN;
    }
    if( rc!=SQLITE_OK ){
      sqlite3_free(zPathname);
      return rc;
    }
  }

  /* Allocate memory for the Pager structure, PCache object, the
  ** three file descriptors, the database file name and the journal 
  ** file name. The layout in memory is as follows:
  **
  **     Pager object                    (sizeof(Pager) bytes)
  **     PCache object                   (sqlite3PcacheSize() bytes)
  **     Database file handle            (pVfs->szOsFile bytes)
  **     Sub-journal file handle         (journalFileSize bytes)
  **     Main journal file handle        (journalFileSize bytes)
  **     Database file name              (nPathname+1 bytes)
  **     Journal file name               (nPathname+8+1 bytes)
  */
  pPtr = (u8 *)sqlite3MallocZero(
    sizeof(*pPager) +           /* Pager structure */
    pcacheSize      +           /* PCache object */
    pVfs->szOsFile  +           /* The main db file */
    journalFileSize * 2 +       /* The two journal files */ 
    nPathname + 1 +             /* zFilename */
    nPathname + 8 + 1           /* zJournal */
  );
  if( !pPtr ){
    sqlite3_free(zPathname);
    return SQLITE_NOMEM;
  }
  pPager =              (Pager*)(pPtr);
  pPager->pPCache =    (PCache*)(pPtr += sizeof(*pPager));
  pPager->fd =   (sqlite3_file*)(pPtr += pcacheSize);
  pPager->sjfd = (sqlite3_file*)(pPtr += pVfs->szOsFile);
  pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
  pPager->zFilename =    (char*)(pPtr += journalFileSize);

  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  if( zPathname ){
    pPager->zJournal =   (char*)(pPtr += nPathname + 1);
    memcpy(pPager->zFilename, zPathname, nPathname);
    memcpy(pPager->zJournal, zPathname, nPathname);
    memcpy(&pPager->zJournal[nPathname], "-journal", 8);
    sqlite3_free(zPathname);
  }
  pPager->pVfs = pVfs;
  pPager->vfsFlags = vfsFlags;

  /* Open the pager file.
  */
  if( zFilename && zFilename[0] && !memDb ){
    int fout = 0;                    /* VFS flags returned by xOpen() */
    rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
    readOnly = (fout&SQLITE_OPEN_READONLY);

    /* If the file was successfully opened for read/write access,
    ** choose a default page size in case we have to create the
    ** database file. The default page size is the maximum of:
    **
    **    + SQLITE_DEFAULT_PAGE_SIZE,
    **    + The value returned by sqlite3OsSectorSize()
    **    + The largest page size that can be written atomically.
    */
    if( rc==SQLITE_OK && !readOnly ){
      setSectorSize(pPager);
      assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
      if( szPageDflt<pPager->sectorSize ){
        if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
          szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
        }else{
          szPageDflt = (u16)pPager->sectorSize;
        }
      }
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
      {
        int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
        int ii;
        assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
        assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
        assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
        for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
          if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
            szPageDflt = ii;
          }
        }
      }
#endif
    }
  }else{
    /* If a temporary file is requested, it is not opened immediately.
    ** In this case we accept the default page size and delay actually
    ** opening the file until the first call to OsWrite().
    **
    ** This branch is also run for an in-memory database. An in-memory
    ** database is the same as a temp-file that is never written out to
    ** disk and uses an in-memory rollback journal.
    */ 
    tempFile = 1;
    pPager->state = PAGER_EXCLUSIVE;
  }

  /* The following call to PagerSetPagesize() serves to set the value of 
  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  */
  if( rc==SQLITE_OK ){
    assert( pPager->memDb==0 );
    rc = sqlite3PagerSetPagesize(pPager, &szPageDflt);
    testcase( rc!=SQLITE_OK );
  }

  /* If an error occured in either of the blocks above, free the 
  ** Pager structure and close the file.
  */
  if( rc!=SQLITE_OK ){
    assert( !pPager->pTmpSpace );
    sqlite3OsClose(pPager->fd);
    sqlite3_free(pPager);
    return rc;
  }

  /* Initialize the PCache object. */
  nExtra = FORCE_ALIGNMENT(nExtra);
  sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
                    !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);

  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))

  pPager->useJournal = (u8)useJournal;
  pPager->noReadlock = (noReadlock && readOnly) ?1:0;
  /* pPager->stmtOpen = 0; */
  /* pPager->stmtInUse = 0; */
  /* pPager->nRef = 0; */
  pPager->dbSizeValid = (u8)memDb;
  /* pPager->stmtSize = 0; */
  /* pPager->stmtJSize = 0; */
  /* pPager->nPage = 0; */
  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  /* pPager->state = PAGER_UNLOCK; */
  assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  /* pPager->errMask = 0; */
  pPager->tempFile = (u8)tempFile;
  assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
          || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  pPager->exclusiveMode = (u8)tempFile; 
  pPager->changeCountDone = pPager->tempFile;
  pPager->memDb = (u8)memDb;
  pPager->readOnly = (u8)readOnly;
  /* pPager->needSync = 0; */
  pPager->noSync = (pPager->tempFile || !useJournal) ?1:0;
  pPager->fullSync = pPager->noSync ?0:1;
  pPager->sync_flags = SQLITE_SYNC_NORMAL;
  /* pPager->pFirst = 0; */
  /* pPager->pFirstSynced = 0; */
  /* pPager->pLast = 0; */
  pPager->nExtra = nExtra;
  pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  assert( isOpen(pPager->fd) || tempFile );
  setSectorSize(pPager);
  if( memDb ){
    pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  }
  /* pPager->xBusyHandler = 0; */
  /* pPager->pBusyHandlerArg = 0; */
  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  *ppPager = pPager;
  return SQLITE_OK;
}



/*
** This function is called after transitioning from PAGER_UNLOCK to
** PAGER_SHARED state. It tests if there is a hot journal present in
** the file-system for the given pager. A hot journal is one that 
** needs to be played back. According to this function, a hot-journal
** file exists if the following three criteria are met:
**
**   * The journal file exists in the file system, and
**   * No process holds a RESERVED or greater lock on the database file, and
**   * The database file itself is greater than 0 bytes in size.
**
** If the current size of the database file is 0 but a journal file
** exists, that is probably an old journal left over from a prior
** database with the same name. In this case the journal file is
** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
** is returned.

**
** This routine does not open the journal file to examine its
** content.  Hence, the journal might contain the name of a master
** journal file that has been deleted, and hence not be hot.  Or
** the header of the journal might be zeroed out.  This routine
** does not discover these cases of a non-hot journal - if the
** journal file exists and is not empty this routine assumes it
** is hot.  The pager_playback() routine will discover that the
** journal file is not really hot and will no-op.
**
** If a hot-journal file is found to exist, *pExists is set to 1 and 
** SQLITE_OK returned. If no hot-journal file is present, *pExists is
** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
** to determine whether or not a hot-journal file exists, the IO error
** code is returned and the value of *pExists is undefined.
*/
static int hasHotJournal(Pager *pPager, int *pExists){
  sqlite3_vfs * const pVfs = pPager->pVfs;
  int rc;                       /* Return code */
  int exists = 0;               /* True if a journal file is present */
  int locked = 0;               /* True if some process holds a RESERVED lock */

  assert( pPager!=0 );
  assert( pPager->useJournal );
  assert( isOpen(pPager->fd) );

  *pExists = 0;
  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  if( rc==SQLITE_OK && exists ){
    rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);

    if( rc==SQLITE_OK && !locked ){
      int nPage;
      rc = sqlite3PagerPagecount(pPager, &nPage);
      if( rc==SQLITE_OK ){
       if( nPage==0 ){
          sqlite3OsDelete(pVfs, pPager->zJournal, 0);
        }else{
          *pExists = 1;
        }
      }
    }
  }
  return rc;
}

/*
** Read the content for page pPg out of the database file and into 
** pPg->pData. A shared lock or greater must be held on the database
** file before this function is called.
**
** If page 1 is read, then the value of Pager.dbFileVers[] is set to
** the value read from the database file.
**
** If an IO error occurs, then the IO error is returned to the caller.
** Otherwise, SQLITE_OK is returned.
*/
static int readDbPage(PgHdr *pPg){
  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  Pgno pgno = pPg->pgno;       /* Page number to read */
  int rc;                      /* Return code */
  i64 iOffset;                 /* Byte offset of file to read from */

  assert( pPager->state>=PAGER_SHARED && !MEMDB );

  if( !isOpen(pPager->fd) ){
    assert( pPager->tempFile );
    return SQLITE_IOERR_SHORT_READ;
  }
  iOffset = (pgno-1)*(i64)pPager->pageSize;
  rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
  if( pgno==1 ){
    u8 *dbFileVers = &((u8*)pPg->pData)[24];
    memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  }
  CODEC1(pPager, pPg->pData, pgno, 3);

  PAGER_INCR(sqlite3_pager_readdb_count);
  PAGER_INCR(pPager->nRead);
  IOTRACE(("PGIN %p %d\n", pPager, pgno));





  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
               PAGERID(pPager), pgno, pager_pagehash(pPg)));

  return rc;
}


/*
** This function is called whenever the upper layer requests a database
** page is requested, before the cache is checked for a suitable page
** or any data is read from the database. It performs the following
** two functions:
**
**   1) If the pager is currently in PAGER_UNLOCK state (no lock held
**      on the database file), then an attempt is made to obtain a
**      SHARED lock on the database file. Immediately after obtaining
**      the SHARED lock, the file-system is checked for a hot-journal,
**      which is played back if present. Following any hot-journal 
**      rollback, the contents of the cache are validated by checking
**      the 'change-counter' field of the database file header and
**      discarded if they are found to be invalid.
**
**   2) If the pager is running in exclusive-mode, and there are currently
**      no outstanding references to any pages, and is in the error state,
**      then an attempt is made to clear the error state by discarding
**      the contents of the page cache and rolling back any open journal
**      file.
**
** If the operation described by (2) above is not attempted, and if the
** pager is in an error state other than SQLITE_FULL when this is called,
** the error state error code is returned. It is permitted to read the
** database when in SQLITE_FULL error state.
**
** Otherwise, if everything is successful, SQLITE_OK is returned. If an
** IO error occurs while locking the database, checking for a hot-journal
** file or rolling back a journal file, the IO error code is returned.
*/
static int pagerSharedLock(Pager *pPager){
  int rc = SQLITE_OK;                /* Return code */
  int isErrorReset = 0;              /* True if recovering from error state */

  /* If this database is opened for exclusive access, has no outstanding 
  ** page references and is in an error-state, this is a chance to clear
  ** the error. Discard the contents of the pager-cache and treat any
  ** open journal file as a hot-journal.
  */
  if( !MEMDB && pPager->exclusiveMode 
   && sqlite3PcacheRefCount(pPager->pPCache)==0 && pPager->errCode 
  ){
    if( isOpen(pPager->jfd) ){
      isErrorReset = 1;
    }
    pPager->errCode = SQLITE_OK;
    pager_reset(pPager);
  }

  /* If the pager is still in an error state, do not proceed. The error 
  ** state will be cleared at some point in the future when all page 
  ** references are dropped and the cache can be discarded.
  */
  if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
    return pPager->errCode;
  }

  if( pPager->state==PAGER_UNLOCK || isErrorReset ){
    sqlite3_vfs * const pVfs = pPager->pVfs;
    int isHotJournal = 0;
    assert( !MEMDB );
    assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
    if( !pPager->noReadlock ){
      rc = pager_wait_on_lock(pPager, SHARED_LOCK);
      if( rc!=SQLITE_OK ){
        assert( pPager->state==PAGER_UNLOCK );
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641

33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684

33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
      }
    }
    if( isErrorReset || isHotJournal ){
      /* Get an EXCLUSIVE lock on the database file. At this point it is
      ** important that a RESERVED lock is not obtained on the way to the
      ** EXCLUSIVE lock. If it were, another process might open the
      ** database file, detect the RESERVED lock, and conclude that the
      ** database is safe to read while this process is still rolling it 
      ** back.
      ** 
      ** Because the intermediate RESERVED lock is not requested, the

      ** second process will get to this point in the code and fail to
      ** obtain its own EXCLUSIVE lock on the database file.
      */
      if( pPager->state<EXCLUSIVE_LOCK ){
        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
        if( rc!=SQLITE_OK ){
          rc = pager_error(pPager, rc);
          goto failed;
        }
        pPager->state = PAGER_EXCLUSIVE;
      }
 
      /* Open the journal for read/write access. This is because in 
      ** exclusive-access mode the file descriptor will be kept open and
      ** possibly used for a transaction later on. On some systems, the
      ** OsTruncate() call used in exclusive-access mode also requires
      ** a read/write file handle.
      */
      if( !isErrorReset && pPager->journalOpen==0 ){
        int res;
        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
        if( rc==SQLITE_OK ){
          if( res ){
            int fout = 0;
            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
            assert( !pPager->tempFile );
            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
            assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
              rc = SQLITE_CANTOPEN;
              sqlite3OsClose(pPager->jfd);
            }
          }else{
            /* If the journal does not exist, that means some other process
            ** has already rolled it back */
            rc = SQLITE_BUSY;
          }
        }
      }
      if( rc!=SQLITE_OK ){
        goto failed;
      }
      pPager->journalOpen = 1;

      pPager->journalStarted = 0;
      pPager->journalOff = 0;
      pPager->setMaster = 0;
      pPager->journalHdr = 0;
 
      /* Playback and delete the journal.  Drop the database write
      ** lock and reacquire the read lock. Purge the cache before
      ** playing back the hot-journal so that we don't end up with
      ** an inconsistent cache.
      */
      sqlite3PcacheClear(pPager->pPCache);
      rc = pager_playback(pPager, 1);
      if( rc!=SQLITE_OK ){
        rc = pager_error(pPager, rc);
        goto failed;
      }
      assert(pPager->state==PAGER_SHARED || 
          (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
      );
    }

    if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
      /* The shared-lock has just been acquired on the database file
      ** and there are already pages in the cache (from a previous
      ** read or write transaction).  Check to see if the database







|
|

|
>
|
|
















|








|














|
>
















|
|







34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
      }
    }
    if( isErrorReset || isHotJournal ){
      /* Get an EXCLUSIVE lock on the database file. At this point it is
      ** important that a RESERVED lock is not obtained on the way to the
      ** EXCLUSIVE lock. If it were, another process might open the
      ** database file, detect the RESERVED lock, and conclude that the
      ** database is safe to read while this process is still rolling the 
      ** hot-journal back.
      ** 
      ** Because the intermediate RESERVED lock is not requested, any
      ** other process attempting to access the database file will get to 
      ** this point in the code and fail to obtain its own EXCLUSIVE lock 
      ** on the database file.
      */
      if( pPager->state<EXCLUSIVE_LOCK ){
        rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
        if( rc!=SQLITE_OK ){
          rc = pager_error(pPager, rc);
          goto failed;
        }
        pPager->state = PAGER_EXCLUSIVE;
      }
 
      /* Open the journal for read/write access. This is because in 
      ** exclusive-access mode the file descriptor will be kept open and
      ** possibly used for a transaction later on. On some systems, the
      ** OsTruncate() call used in exclusive-access mode also requires
      ** a read/write file handle.
      */
      if( !isOpen(pPager->jfd) ){
        int res;
        rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
        if( rc==SQLITE_OK ){
          if( res ){
            int fout = 0;
            int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
            assert( !pPager->tempFile );
            rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
            assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
            if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
              rc = SQLITE_CANTOPEN;
              sqlite3OsClose(pPager->jfd);
            }
          }else{
            /* If the journal does not exist, that means some other process
            ** has already rolled it back */
            rc = SQLITE_BUSY;
          }
        }
      }
      if( rc!=SQLITE_OK ){
        goto failed;
      }

      /* TODO: Why are these cleared here? Is it necessary? */
      pPager->journalStarted = 0;
      pPager->journalOff = 0;
      pPager->setMaster = 0;
      pPager->journalHdr = 0;
 
      /* Playback and delete the journal.  Drop the database write
      ** lock and reacquire the read lock. Purge the cache before
      ** playing back the hot-journal so that we don't end up with
      ** an inconsistent cache.
      */
      sqlite3PcacheClear(pPager->pPCache);
      rc = pager_playback(pPager, 1);
      if( rc!=SQLITE_OK ){
        rc = pager_error(pPager, rc);
        goto failed;
      }
      assert( (pPager->state==PAGER_SHARED)
           || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
      );
    }

    if( sqlite3PcachePagecount(pPager->pPCache)>0 ){
      /* The shared-lock has just been acquired on the database file
      ** and there are already pages in the cache (from a previous
      ** read or write transaction).  Check to see if the database
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801


33802
33803
33804



33805
33806
33807

33808



33809
33810

























33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840

33841
33842
33843
33844
33845
33846
33847
    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
    pager_unlock(pPager);
  }
  return rc;
}

/*
** Make sure we have the content for a page.  If the page was
** previously acquired with noContent==1, then the content was
** just initialized to zeros instead of being read from disk.
** But now we need the real data off of disk.  So make sure we
** have it.  Read it in if we do not have it already.
*/
static int pager_get_content(PgHdr *pPg){
  if( pPg->flags&PGHDR_NEED_READ ){
    int rc = readDbPage(pPg->pPager, pPg, pPg->pgno);
    if( rc==SQLITE_OK ){
      pPg->flags &= ~PGHDR_NEED_READ;
    }else{
      return rc;
    }
  }
  return SQLITE_OK;
}

/*
** If the reference count has reached zero, and the pager is not in the
** middle of a write transaction or opened in exclusive mode, unlock it.
*/ 
static void pagerUnlockIfUnused(Pager *pPager){
  if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
    && (!pPager->exclusiveMode || pPager->journalOff>0) 
  ){
    pagerUnlockAndRollback(pPager);
  }
}

/*
** Drop a page from the cache using sqlite3PcacheDrop().
**
** If this means there are now no pages with references to them, a rollback
** occurs and the lock on the database is removed.
*/
static void pagerDropPage(DbPage *pPg){
  Pager *pPager = pPg->pPager;
  sqlite3PcacheDrop(pPg);
  pagerUnlockIfUnused(pPager);
}

/*
** Acquire a page.


**
** A read lock on the disk file is obtained when the first page is acquired. 
** This read lock is dropped when the last page is released.



**
** This routine works for any page number greater than 0.  If the database
** file is smaller than the requested page, then no actual disk

** read occurs and the memory image of the page is initialized to



** all zeros.  The extra data appended to a page is always initialized
** to zeros the first time a page is loaded into memory.

























**
** The acquisition might fail for several reasons.  In all cases,
** an appropriate error code is returned and *ppPage is set to NULL.
**
** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
** to find a page in the in-memory cache first.  If the page is not already
** in memory, this routine goes to disk to read it in whereas Lookup()
** just returns 0.  This routine acquires a read-lock the first time it
** has to go to disk, and could also playback an old journal if necessary.
** Since Lookup() never goes to disk, it never has to deal with locks
** or journal files.
**
** If noContent is false, the page contents are actually read from disk.
** If noContent is true, it means that we do not care about the contents
** 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.
*/
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 = 0;
  int rc;


  assert( pPager->state==PAGER_UNLOCK 
       || sqlite3PcacheRefCount(pPager->pPCache)>0 
       || pgno==1
  );

  /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  ** number greater than this, or zero, is requested.







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|


|
<
<

















|
>
>

<
|
>
>
>

<
|
>
|
>
>
>
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>











<
<
<
<
<
<
<
<
<










>







34526
34527
34528
34529
34530
34531
34532



















34533
34534
34535
34536
34537


34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558

34559
34560
34561
34562
34563

34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607









34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
    /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
    pager_unlock(pPager);
  }
  return rc;
}

/*



















** If the reference count has reached zero, rollback any active
** transaction and unlock the pager.
*/ 
static void pagerUnlockIfUnused(Pager *pPager){
  if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){


    pagerUnlockAndRollback(pPager);
  }
}

/*
** Drop a page from the cache using sqlite3PcacheDrop().
**
** If this means there are now no pages with references to them, a rollback
** occurs and the lock on the database is removed.
*/
static void pagerDropPage(DbPage *pPg){
  Pager *pPager = pPg->pPager;
  sqlite3PcacheDrop(pPg);
  pagerUnlockIfUnused(pPager);
}

/*
** Acquire a reference to page number pgno in pager pPager (a page
** reference has type DbPage*). If the requested reference is 
** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
**

** This function calls pagerSharedLock() to obtain a SHARED lock on
** the database file if such a lock or greater is not already held.
** This may cause hot-journal rollback or a cache purge. See comments
** above function pagerSharedLock() for details.
**

** If the requested page is already in the cache, it is returned. 
** Otherwise, a new page object is allocated and populated with data
** read from the database file. In some cases, the pcache module may
** choose not to allocate a new page object and may reuse an existing
** object with no outstanding references.
**
** The extra data appended to a page is always initialized to zeros the 
** first time a page is loaded into memory. If the page requested is 
** already in the cache when this function is called, then the extra
** data is left as it was when the page object was last used.
**
** If the database image is smaller than the requested page or if a 
** non-zero value is passed as the noContent parameter and the 
** requested page is not already stored in the cache, then no 
** actual disk read occurs. In this case the memory image of the 
** page is initialized to all zeros. 
**
** If noContent is true, it means that we do not care about the contents
** of the page. This occurs in two seperate scenarios:
**
**   a) When reading a free-list leaf page from the database, and
**
**   b) When a savepoint is being rolled back and we need to load
**      a new page into the cache to populate with the data read
**      from the savepoint journal.
**
** If noContent is true, then the data returned is zeroed instead of
** being read from the database. Additionally, the bits corresponding
** to pgno in Pager.pInJournal (bitvec of pages already written to the
** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
** savepoints are set. This means if the page is made writable at any
** point in the future, using a call to sqlite3PagerWrite(), its contents
** will not be journaled. This saves IO.
**
** The acquisition might fail for several reasons.  In all cases,
** an appropriate error code is returned and *ppPage is set to NULL.
**
** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
** to find a page in the in-memory cache first.  If the page is not already
** in memory, this routine goes to disk to read it in whereas Lookup()
** just returns 0.  This routine acquires a read-lock the first time it
** has to go to disk, and could also playback an old journal if necessary.
** Since Lookup() never goes to disk, it never has to deal with locks
** or journal files.









*/
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 = 0;
  int rc;

  assert( assert_pager_state(pPager) );
  assert( pPager->state==PAGER_UNLOCK 
       || sqlite3PcacheRefCount(pPager->pPCache)>0 
       || pgno==1
  );

  /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  ** number greater than this, or zero, is requested.
33865
33866
33867
33868
33869
33870
33871


33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893















33894
33895
33896
33897

33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928


33929
33930
33931
33932
33933
33934
33935
  }
  assert( pPager->state!=PAGER_UNLOCK );

  rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
  if( rc!=SQLITE_OK ){
    return rc;
  }


  if( pPg->pPager==0 ){
    /* The pager cache has created a new page. Its content needs to 
    ** be initialized.
    */
    int nMax;
    PAGER_INCR(pPager->nMiss);
    pPg->pPager = pPager;
    memset(pPg->pExtra, 0, pPager->nExtra);

    rc = sqlite3PagerPagecount(pPager, &nMax);
    if( rc!=SQLITE_OK ){
      sqlite3PagerUnref(pPg);
      return rc;
    }

    if( nMax<(int)pgno || MEMDB || noContent ){
      if( pgno>pPager->mxPgno ){
        sqlite3PagerUnref(pPg);
        return SQLITE_FULL;
      }
      memset(pPg->pData, 0, pPager->pageSize);
      if( noContent ){















        pPg->flags |= PGHDR_NEED_READ;
      }
      IOTRACE(("ZERO %p %d\n", pPager, pgno));
    }else{

      rc = readDbPage(pPager, pPg, pgno);
      if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
        /* sqlite3PagerUnref(pPg); */
        pagerDropPage(pPg);
        return rc;
      }
    }
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
  }else{
    /* The requested page is in the page cache. */
    assert(sqlite3PcacheRefCount(pPager->pPCache)>0 || pgno==1);
    PAGER_INCR(pPager->nHit);
    if( !noContent ){
      rc = pager_get_content(pPg);
      if( rc ){
        sqlite3PagerUnref(pPg);
        return rc;
      }
    }
  }

  *ppPage = pPg;
  return SQLITE_OK;
}

/*
** Acquire a page if it is already in the in-memory cache.  Do
** not read the page from disk.  Return a pointer to the page,
** or 0 if the page is not in cache.


**
** 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.
*/







>
>







<












<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|



>
|

<









<

<
<
<
<
<
<
<









|
>
>







34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658

34659
34660
34661
34662
34663
34664
34665
34666
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
34695
34696
34697
34698
34699
34700
34701
34702

34703







34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
  }
  assert( pPager->state!=PAGER_UNLOCK );

  rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, &pPg);
  if( rc!=SQLITE_OK ){
    return rc;
  }
  assert( pPg->pgno==pgno );
  assert( pPg->pPager==pPager || pPg->pPager==0 );
  if( pPg->pPager==0 ){
    /* The pager cache has created a new page. Its content needs to 
    ** be initialized.
    */
    int nMax;
    PAGER_INCR(pPager->nMiss);
    pPg->pPager = pPager;


    rc = sqlite3PagerPagecount(pPager, &nMax);
    if( rc!=SQLITE_OK ){
      sqlite3PagerUnref(pPg);
      return rc;
    }

    if( nMax<(int)pgno || MEMDB || noContent ){
      if( pgno>pPager->mxPgno ){
        sqlite3PagerUnref(pPg);
        return SQLITE_FULL;
      }

      if( noContent ){
        /* Failure to set the bits in the InJournal bit-vectors is benign.
        ** It merely means that we might do some extra work to journal a 
        ** page that does not need to be journaled.  Nevertheless, be sure 
        ** to test the case where a malloc error occurs while trying to set 
        ** a bit in a bit vector.
        */
        sqlite3BeginBenignMalloc();
        if( pgno<=pPager->dbOrigSize ){
          TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
          testcase( rc==SQLITE_NOMEM );
        }
        TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
        testcase( rc==SQLITE_NOMEM );
        sqlite3EndBenignMalloc();
      }else{
        memset(pPg->pData, 0, pPager->pageSize);
      }
      IOTRACE(("ZERO %p %d\n", pPager, pgno));
    }else{
      assert( pPg->pPager==pPager );
      rc = readDbPage(pPg);
      if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){

        pagerDropPage(pPg);
        return rc;
      }
    }
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
  }else{
    /* The requested page is in the page cache. */

    PAGER_INCR(pPager->nHit);







  }

  *ppPage = pPg;
  return SQLITE_OK;
}

/*
** Acquire a page if it is already in the in-memory cache.  Do
** not read the page from disk.  Return a pointer to the page,
** or 0 if the page is not in cache. Also, return 0 if the 
** pager is in PAGER_UNLOCK state when this function is called,
** or if the pager is in an error state other than SQLITE_FULL.
**
** See also sqlite3PagerGet().  The difference between this routine
** and sqlite3PagerGet() is that _get() will go to the disk and read
** in the page if the page is not already in cache.  This routine
** returns NULL if the page is not in cache or if a disk I/O error 
** has ever happened.
*/
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988

33989
33990
33991













33992
33993


33994
33995

33996
33997
33998
33999
34000
34001
34002










34003

34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019






34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038





34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064

34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080

34081
34082
34083
34084
34085

34086
34087
34088
34089
34090
34091
34092
34093

34094
34095
34096
34097
34098
34099
34100
34101
34102






34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114



34115
34116

34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137

34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
    sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  }

  return pPg;
}

/*
** 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.
*/
SQLITE_PRIVATE int sqlite3PagerUnref(DbPage *pPg){
  if( pPg ){
    Pager *pPager = pPg->pPager;
    sqlite3PcacheRelease(pPg);
    pagerUnlockIfUnused(pPager);
  }
  return SQLITE_OK;
}

/*
** If the main journal file has already been opened, ensure that the
** sub-journal file is open too. If the main journal is not open,
** this function is a no-op.
**
** SQLITE_OK is returned if everything goes according to plan. An 
** SQLITE_IOERR_XXX error code is returned if the call to 
** sqlite3OsOpen() fails.
*/
static int openSubJournal(Pager *pPager){
  int rc = SQLITE_OK;
  if( pPager->journalOpen && !pPager->sjfd->pMethods ){
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3MemJournalOpen(pPager->sjfd);
    }else{
      rc = sqlite3PagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
    }
  }
  return rc;
}

/*

** Create a journal file for pPager.  There should already be a RESERVED
** or EXCLUSIVE lock on the database file when this routine is called.
**













** Return SQLITE_OK if everything.  Return an error code and release the
** write lock if anything goes wrong.


*/
static int pager_open_journal(Pager *pPager){

  sqlite3_vfs *pVfs = pPager->pVfs;
  int flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE);

  int rc;
  assert( pPager->state>=PAGER_RESERVED );
  assert( pPager->useJournal );
  assert( pPager->pInJournal==0 );










  sqlite3PagerPagecount(pPager, 0);

  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  if( pPager->pInJournal==0 ){
    rc = SQLITE_NOMEM;
    goto failed_to_open_journal;
  }

  if( pPager->journalOpen==0 ){
    if( pPager->tempFile ){
      flags |= (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL);
    }else{
      flags |= (SQLITE_OPEN_MAIN_JOURNAL);
    }
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3MemJournalOpen(pPager->jfd);
      rc = SQLITE_OK;
    }else{






#ifdef SQLITE_ENABLE_ATOMIC_WRITE
      rc = sqlite3JournalOpen(
          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
      );
#else
      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
#endif
    }
    assert( rc!=SQLITE_OK || pPager->jfd->pMethods );
    pPager->journalOff = 0;
    pPager->setMaster = 0;
    pPager->journalHdr = 0;
    if( rc!=SQLITE_OK ){
      if( rc==SQLITE_NOMEM ){
        sqlite3OsDelete(pVfs, pPager->zJournal, 0);
      }
      goto failed_to_open_journal;
    }
  }





  pPager->journalOpen = 1;
  pPager->journalStarted = 0;
  pPager->needSync = 0;
  pPager->nRec = 0;
  if( pPager->errCode ){
    rc = pPager->errCode;
    goto failed_to_open_journal;
  }
  pPager->dbOrigSize = pPager->dbSize;

  rc = writeJournalHdr(pPager);

  if( pPager->nSavepoint && rc==SQLITE_OK ){
    rc = openSubJournal(pPager);
  }
  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && rc!=SQLITE_IOERR_NOMEM ){
    rc = pager_end_transaction(pPager, 0);
    if( rc==SQLITE_OK ){
      rc = SQLITE_FULL;
    }
  }
  return rc;

failed_to_open_journal:
  sqlite3BitvecDestroy(pPager->pInJournal);
  pPager->pInJournal = 0;

  return rc;
}

/*
** Acquire a write-lock on the database.  The lock is removed when
** the any of the following happen:
**
**   *  sqlite3PagerCommitPhaseTwo() is called.
**   *  sqlite3PagerRollback() is called.
**   *  sqlite3PagerClose() is called.
**   *  sqlite3PagerUnref() is called to on every outstanding page.
**
** The first parameter to this routine is a pointer to any open page of the
** database file.  Nothing changes about the page - it is used merely to
** acquire a pointer to the Pager structure and as proof that there is
** already a read-lock on the database.

**
** The second parameter indicates how much space in bytes to reserve for a
** master journal file-name at the start of the journal when it is created.
**
** A journal file is opened if this is not a temporary file.  For temporary

** files, the opening of the journal file is deferred until there is an
** actual need to write to the journal.
**
** 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.

*/
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->pInJournal==0 );
    assert( !MEMDB );






    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
    if( rc==SQLITE_OK ){
      pPager->state = PAGER_RESERVED;
      if( exFlag ){
        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
      }
    }
    if( rc!=SQLITE_OK ){
      return rc;
    }
    pPager->dirtyCache = 0;
    PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));



    if( pPager->useJournal && !pPager->tempFile
           && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){

      rc = pager_open_journal(pPager);
    }
  }else if( pPager->journalOpen && pPager->journalOff==0 ){
    /* This happens when the pager was in exclusive-access mode the last
    ** time a (read or write) transaction was successfully concluded
    ** by this connection. Instead of deleting the journal file it was 
    ** kept open and either was truncated to 0 bytes or its header was
    ** overwritten with zeros.
    */
    assert( pPager->nRec==0 );
    assert( pPager->dbOrigSize==0 );
    assert( pPager->pInJournal==0 );
    sqlite3PagerPagecount(pPager, 0);
    pPager->pInJournal = sqlite3BitvecCreate( pPager->dbSize );
    if( !pPager->pInJournal ){
      rc = SQLITE_NOMEM;
    }else{
      pPager->dbOrigSize = pPager->dbSize;
      rc = writeJournalHdr(pPager);
    }
  }

  assert( !pPager->journalOpen || pPager->journalOff>0 || rc!=SQLITE_OK );
  return rc;
}

/*
** Mark a data page as writeable.  The page is written into the journal 
** if it is not there already.  This routine must be called before making
** changes to a page.
**
** The first time this routine is called, the pager creates a new
** journal and acquires a RESERVED lock on the database.  If the RESERVED
** lock could not be acquired, this routine returns SQLITE_BUSY.  The
** calling routine must check for that return value and be careful not to
** change any page data until this routine returns SQLITE_OK.
**
** If the journal file could not be written because the disk is full,
** then this routine returns SQLITE_FULL and does an immediate rollback.
** All subsequent write attempts also return SQLITE_FULL until there
** is a call to sqlite3PagerCommit() or sqlite3PagerRollback() to
** reset.
*/
static int pager_write(PgHdr *pPg){
  void *pData = pPg->pData;
  Pager *pPager = pPg->pPager;
  int rc = SQLITE_OK;

  /* Check for errors
  */
  if( pPager->errCode ){ 
    return pPager->errCode;
  }
  if( pPager->readOnly ){
    return SQLITE_PERM;
  }

  assert( !pPager->setMaster );

  CHECK_PAGE(pPg);

  /* If this page was previously acquired with noContent==1, that means
  ** we didn't really read in the content of the page.  This can happen
  ** (for example) when the page is being moved to the freelist.  But
  ** now we are (perhaps) moving the page off of the freelist for
  ** reuse and we need to know its original content so that content
  ** can be stored in the rollback journal.  So do the read at this
  ** time.
  */
  rc = pager_get_content(pPg);
  if( rc ){
    return rc;
  }

  /* Mark the page as dirty.  If the page has already been written
  ** to the journal then we can return right away.
  */
  sqlite3PcacheMakeDirty(pPg);
  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
    pPager->dirtyCache = 1;
    pPager->dbModified = 1;
  }else{

    /* If we get this far, it means that the page needs to be
    ** written to the transaction journal or the ckeckpoint journal
    ** or both.
    **
    ** First check to see that the transaction journal exists and
    ** create it if it does not.
    */
    assert( pPager->state!=PAGER_UNLOCK );
    rc = sqlite3PagerBegin(pPg, 0);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    assert( pPager->state>=PAGER_RESERVED );
    if( !pPager->journalOpen && pPager->useJournal
          && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
      rc = pager_open_journal(pPager);
      if( rc!=SQLITE_OK ) return rc;
    }
    pPager->dirtyCache = 1;
    pPager->dbModified = 1;
  
    /* The transaction journal now exists and we have a RESERVED or an
    ** EXCLUSIVE lock on the main database file.  Write the current page to
    ** the transaction journal if it is not there already.
    */
    if( !pageInJournal(pPg) && pPager->journalOpen ){
      if( pPg->pgno<=pPager->dbOrigSize ){
        u32 cksum;
        char *pData2;

        /* We should never write to the journal file the page that
        ** contains the database locks.  The following assert verifies
        ** that we do not. */







|






|





<







|
|




|



|






>
|
|

>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>


>
|
<

<



>
>
>
>
>
>
>
>
>
>

>


|
<


|
|
<
<
<
<


<

>
>
>
>
>
>








|
<
<
<
<
<
<
|
<
|
|
>
>
>
>
>
|
|
|
|
|
|
<
<
<
|
|
|
|


<
<
<
<
|
<
<
|
<
|
|
>




|
|

<
<
<
<
<
<
<
|
|
>
|
<
<

|
>
|
|

|
<
<
<
<
>

|
<

<



|
>
>
>
>
>
>







<
<
|
<
<
>
>
>
|
|
>


|









<
<
<
<
<
<
|
|
|
>
|




|
<
<
<
|
|
<
<
<
<
|
<
<
<
|



















<
<
<
<
<
<
<
<
<
<
<
<
<





<











|




|




<






|







34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750

34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792

34793
34794
34795
34796
34797
34798

34799

34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817

34818
34819
34820
34821




34822
34823

34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839






34840

34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853



34854
34855
34856
34857
34858
34859




34860


34861

34862
34863
34864
34865
34866
34867
34868
34869
34870
34871







34872
34873
34874
34875


34876
34877
34878
34879
34880
34881
34882




34883
34884
34885

34886

34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903


34904


34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922






34923
34924
34925
34926
34927
34928
34929
34930
34931
34932



34933
34934




34935



34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955













34956
34957
34958
34959
34960

34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981

34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
    sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  }

  return pPg;
}

/*
** Release a page reference.
**
** If the number of references to the page drop to zero, then the
** page is added to the LRU list.  When all references to all pages
** are released, a rollback occurs and the lock on the database is
** removed.
*/
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  if( pPg ){
    Pager *pPager = pPg->pPager;
    sqlite3PcacheRelease(pPg);
    pagerUnlockIfUnused(pPager);
  }

}

/*
** If the main journal file has already been opened, ensure that the
** sub-journal file is open too. If the main journal is not open,
** this function is a no-op.
**
** SQLITE_OK is returned if everything goes according to plan. 
** An SQLITE_IOERR_XXX error code is returned if a call to 
** sqlite3OsOpen() fails.
*/
static int openSubJournal(Pager *pPager){
  int rc = SQLITE_OK;
  if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3MemJournalOpen(pPager->sjfd);
    }else{
      rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
    }
  }
  return rc;
}

/*
** This function is called at the start of every write transaction.
** There must already be a RESERVED or EXCLUSIVE lock on the database 
** file when this routine is called.
**
** Open the journal file for pager pPager and write a journal header
** to the start of it. If there are active savepoints, open the sub-journal
** as well. This function is only used when the journal file is being 
** opened to write a rollback log for a transaction. It is not used 
** when opening a hot journal file to roll it back.
**
** If the journal file is already open (as it may be in exclusive mode),
** then this function just writes a journal header to the start of the
** already open file. 
**
** Whether or not the journal file is opened by this function, the
** Pager.pInJournal bitvec structure is allocated.
**
** Return SQLITE_OK if everything is successful. Otherwise, return 

** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
** an IO error code if opening or writing the journal file fails.
*/
static int pager_open_journal(Pager *pPager){
  int rc = SQLITE_OK;                        /* Return code */
  sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */



  assert( pPager->state>=PAGER_RESERVED );
  assert( pPager->useJournal );
  assert( pPager->pInJournal==0 );
  
  /* If already in the error state, this function is a no-op. */
  if( pPager->errCode ){
    return pPager->errCode;
  }

  /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
  ** the call to PagerPagecount() can be removed.
  */
  testcase( pPager->dbSizeValid==0 );
  sqlite3PagerPagecount(pPager, 0);

  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  if( pPager->pInJournal==0 ){
    return SQLITE_NOMEM;

  }

  /* Open the journal file if it is not already open. */
  if( !isOpen(pPager->jfd) ){




    if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
      sqlite3MemJournalOpen(pPager->jfd);

    }else{
      const int flags =                   /* VFS flags to open journal file */
        SQLITE_OPEN_READWRITE|SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_CREATE|
        (pPager->tempFile ? 
          (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
          (SQLITE_OPEN_MAIN_JOURNAL)
        );
#ifdef SQLITE_ENABLE_ATOMIC_WRITE
      rc = sqlite3JournalOpen(
          pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
      );
#else
      rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
#endif
    }
    assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );






  }



  /* Write the first journal header to the journal file and open 
  ** the sub-journal if necessary.
  */
  if( rc==SQLITE_OK ){
    /* TODO: Check if all of these are really required. */
    pPager->dbOrigSize = pPager->dbSize;
    pPager->journalStarted = 0;
    pPager->needSync = 0;
    pPager->nRec = 0;
    pPager->journalOff = 0;
    pPager->setMaster = 0;



    pPager->journalHdr = 0;
    rc = writeJournalHdr(pPager);
  }
  if( rc==SQLITE_OK && pPager->nSavepoint ){
    rc = openSubJournal(pPager);
  }







  if( rc!=SQLITE_OK ){

    sqlite3BitvecDestroy(pPager->pInJournal);
    pPager->pInJournal = 0;
  }
  return rc;
}

/*
** Begin a write-transaction on the specified pager object. If a 
** write-transaction has already been opened, this function is a no-op.
**







** If the exFlag argument is false, then acquire at least a RESERVED
** lock on the database file. If exFlag is true, then acquire at least
** an EXCLUSIVE lock. If such a lock is already held, no locking 
** functions need be called.


**
** If this is not a temporary or in-memory file and, the journal file is 
** opened if it has not been already. For a temporary file, the opening 
** of the journal file is deferred until there is an actual need to 
** write to the journal. TODO: Why handle temporary files differently?
**
** If the journal file is opened (or if it is already open), then a




** journal-header is written to the start of it.
*/
SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag){

  int rc = SQLITE_OK;

  assert( pPager->state!=PAGER_UNLOCK );
  if( pPager->state==PAGER_SHARED ){
    assert( pPager->pInJournal==0 );
    assert( !MEMDB && !pPager->tempFile );

    /* Obtain a RESERVED lock on the database file. If the exFlag parameter
    ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
    ** busy-handler callback can be used when upgrading to the EXCLUSIVE
    ** lock, but not when obtaining the RESERVED lock.
    */
    rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
    if( rc==SQLITE_OK ){
      pPager->state = PAGER_RESERVED;
      if( exFlag ){
        rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
      }
    }





    /* If the required locks were successfully obtained, open the journal
    ** file and write the first journal-header to it.
    */
    if( rc==SQLITE_OK && pPager->useJournal
     && pPager->journalMode!=PAGER_JOURNALMODE_OFF 
    ){
      rc = pager_open_journal(pPager);
    }
  }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
    /* This happens when the pager was in exclusive-access mode the last
    ** time a (read or write) transaction was successfully concluded
    ** by this connection. Instead of deleting the journal file it was 
    ** kept open and either was truncated to 0 bytes or its header was
    ** overwritten with zeros.
    */
    assert( pPager->nRec==0 );
    assert( pPager->dbOrigSize==0 );
    assert( pPager->pInJournal==0 );






    rc = pager_open_journal(pPager);
  }

  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
  return rc;
}

/*
** Mark a single data page as writeable. The page is written into the 



** main journal or sub-journal as required. If the page is written into
** one of the journals, the corresponding bit is set in the 




** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs



** of any open savepoints as appropriate.
*/
static int pager_write(PgHdr *pPg){
  void *pData = pPg->pData;
  Pager *pPager = pPg->pPager;
  int rc = SQLITE_OK;

  /* Check for errors
  */
  if( pPager->errCode ){ 
    return pPager->errCode;
  }
  if( pPager->readOnly ){
    return SQLITE_PERM;
  }

  assert( !pPager->setMaster );

  CHECK_PAGE(pPg);














  /* Mark the page as dirty.  If the page has already been written
  ** to the journal then we can return right away.
  */
  sqlite3PcacheMakeDirty(pPg);
  if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){

    pPager->dbModified = 1;
  }else{

    /* If we get this far, it means that the page needs to be
    ** written to the transaction journal or the ckeckpoint journal
    ** or both.
    **
    ** First check to see that the transaction journal exists and
    ** create it if it does not.
    */
    assert( pPager->state!=PAGER_UNLOCK );
    rc = sqlite3PagerBegin(pPager, 0);
    if( rc!=SQLITE_OK ){
      return rc;
    }
    assert( pPager->state>=PAGER_RESERVED );
    if( !isOpen(pPager->jfd) && pPager->useJournal
          && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
      rc = pager_open_journal(pPager);
      if( rc!=SQLITE_OK ) return rc;
    }

    pPager->dbModified = 1;
  
    /* The transaction journal now exists and we have a RESERVED or an
    ** EXCLUSIVE lock on the main database file.  Write the current page to
    ** the transaction journal if it is not there already.
    */
    if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
      if( pPg->pgno<=pPager->dbOrigSize ){
        u32 cksum;
        char *pData2;

        /* We should never write to the journal file the page that
        ** contains the database locks.  The following assert verifies
        ** that we do not. */
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317

34318
34319
34320
34321
34322



34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
      pPager->dbSize++;
    }
  }
  return rc;
}

/*
** This function is used to mark a data-page as writable. It uses 
** pager_write() to open a journal file (if it is not already open)
** 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.



*/
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  int rc = SQLITE_OK;

  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);

  if( nPagePerSector>1 ){
    Pgno nPageCount;          /* Total number of pages in database file */
    Pgno pg1;                 /* First page of the sector pPg is located on. */
    int nPage;                /* Number of pages starting at pg1 to journal */
    int ii;
    int needSync = 0;

    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
    ** header to be written between the pages journaled by this function.
    */
    assert( !MEMDB );
    assert( pPager->doNotSync==0 );
    pPager->doNotSync = 1;







|
|
|
>





>
>
>












|
|







35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
      pPager->dbSize++;
    }
  }
  return rc;
}

/*
** Mark a data page as writeable. This routine must be called before 
** making changes to a page. The caller must check the return value 
** of this function and be careful not to change any page data unless 
** this routine returns SQLITE_OK.
**
** The difference between this function and pager_write() is that this
** function also deals with the special case where 2 or more pages
** fit on a single disk sector. In this case all co-resident pages
** must have been written to the journal file before returning.
**
** If an error occurs, SQLITE_NOMEM or an IO error code is returned
** as appropriate. Otherwise, SQLITE_OK.
*/
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  int rc = SQLITE_OK;

  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;
  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);

  if( nPagePerSector>1 ){
    Pgno nPageCount;          /* Total number of pages in database file */
    Pgno pg1;                 /* First page of the sector pPg is located on. */
    int nPage;                /* Number of pages starting at pg1 to journal */
    int ii;                   /* Loop counter */
    int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */

    /* Set the doNotSync flag to 1. This is because we cannot allow a journal
    ** header to be written between the pages journaled by this function.
    */
    assert( !MEMDB );
    assert( pPager->doNotSync==0 );
    pPager->doNotSync = 1;
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491

34492
34493
34494

34495
34496










34497


34498






34499
34500
34501



34502

34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588

34589
34590
34591
34592
34593
34594



34595


34596
34597
34598
34599
34600
34601
34602
34603
34604




34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622





34623

34624

34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663























34664
34665
34666
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

34695
34696
34697
34698
34699
34700
34701
34702


34703
34704
34705

34706

34707

34708
34709
34710
34711



34712


34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723

34724
34725
34726
34727
34728
34729

34730
34731
34732
34733
34734
34735
34736
34737
34738
34739





34740
34741
34742
34743
34744





34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762



34763

34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792




34793
34794





34795
34796
34797
34798
34799
34800

34801
34802
34803





34804
34805
34806












34807
34808
34809

34810
34811
34812

34813
34814
34815
34816
34817
34818
34819
34820
34821




34822

34823

34824
34825
34826

34827





34828




34829








34830








34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
** A call to this routine tells the pager that it is not necessary to
** write the information on page pPg back to the disk, even though
** that page might be marked as dirty.  This happens, for example, when
** the page has been added as a leaf of the freelist and so its
** content no longer matters.
**
** The overlying software layer calls this routine when all of the data
** on the given page is unused.  The pager marks the page as clean so
** that it does not get written to disk.
**
** Tests show that this optimization, together with the
** sqlite3PagerDontRollback() below, more than double the speed
** of large INSERT operations and quadruple the speed of large DELETEs.
**
** When this routine is called, set the bit corresponding to pDbPage in
** the Pager.pAlwaysRollback bitvec.  Subsequent calls to
** sqlite3PagerDontRollback() for the same page will thereafter be ignored.
** This is necessary to avoid a problem where a page with data is added to
** the freelist during one part of 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.
*/
SQLITE_PRIVATE int sqlite3PagerDontWrite(DbPage *pDbPage){
  PgHdr *pPg = pDbPage;
  Pager *pPager = pPg->pPager;
  int rc;

  if( pPg->pgno>pPager->dbOrigSize ){
    return SQLITE_OK;
  }
  if( pPager->pAlwaysRollback==0 ){
    assert( pPager->pInJournal );
    pPager->pAlwaysRollback = sqlite3BitvecCreate(pPager->dbOrigSize);
    if( !pPager->pAlwaysRollback ){
      return SQLITE_NOMEM;
    }
  }
  rc = sqlite3BitvecSet(pPager->pAlwaysRollback, pPg->pgno);

  if( rc==SQLITE_OK && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
    assert( pPager->state>=PAGER_SHARED );
    if( pPager->dbSize==pPg->pgno && pPager->dbOrigSize<pPager->dbSize ){
      /* If this pages is the last page in the file and the file has grown
      ** during the current transaction, then do NOT mark the page as clean.
      ** When the database file grows, we must make sure that the last page
      ** gets written at least once so that the disk file will be the correct
      ** size. If you do not write this page and the size of the file
      ** on the disk ends up being too small, that can lead to database
      ** corruption during the next transaction.
      */
    }else{
      PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
      IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
      pPg->flags |= PGHDR_DONT_WRITE;
#ifdef SQLITE_CHECK_PAGES
      pPg->pageHash = pager_pagehash(pPg);
#endif
    }
  }
  return rc;
}

/*
** A call to this routine tells the pager that if a rollback occurs,
** it is not necessary to restore the data on the given page.  This

** means that the pager does not have to record the given page in the
** 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.






*/
SQLITE_PRIVATE void sqlite3PagerDontRollback(DbPage *pPg){
  Pager *pPager = pPg->pPager;



  TESTONLY( int rc; )  /* Return value from sqlite3BitvecSet() */


  assert( pPager->state>=PAGER_RESERVED );

  /* If the journal file is not open, or DontWrite() has been called on
  ** this page (DontWrite() sets the Pager.pAlwaysRollback bit), then this
  ** function is a no-op.
  */
  if( pPager->journalOpen==0 
   || sqlite3BitvecTest(pPager->pAlwaysRollback, pPg->pgno)
   || pPg->pgno>pPager->dbOrigSize
  ){
    return;
  }

#ifdef SQLITE_SECURE_DELETE
  if( sqlite3BitvecTest(pPager->pInJournal, pPg->pgno)!=0
   || pPg->pgno>pPager->dbOrigSize ){
    return;
  }
#endif

  /* If SECURE_DELETE is disabled, then there is no way that this
  ** routine can be called on a page for which sqlite3PagerDontWrite()
  ** has not been previously called during the same transaction.
  ** And if DontWrite() has previously been called, the following
  ** conditions must be met.
  **
  ** (Later:)  Not true.  If the database is corrupted by having duplicate
  ** pages on the freelist (ex: corrupt9.test) then the following is not
  ** necessarily true:
  */
  /* assert( !pPg->inJournal && (int)pPg->pgno <= pPager->dbOrigSize ); */

  assert( pPager->pInJournal!=0 );
  pPg->flags &= ~PGHDR_NEED_READ;

  /* Failure to set the bits in the InJournal bit-vectors is benign.
  ** It merely means that we might do some extra work to journal a page
  ** that does not need to be journaled.  Nevertheless, be sure to test the
  ** case where a malloc error occurs while trying to set a bit in a 
  ** bit vector.
  */
  sqlite3BeginBenignMalloc();
  TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  testcase( rc==SQLITE_NOMEM );
  TESTONLY( rc = ) addToSavepointBitvecs(pPager, pPg->pgno);
  testcase( rc==SQLITE_NOMEM );
  sqlite3EndBenignMalloc();


  PAGERTRACE(("DONT_ROLLBACK page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  IOTRACE(("GARBAGE %p %d\n", pPager, pPg->pgno))
}


/*
** This routine is called to increment the database file change-counter,
** stored at byte 24 of the pager file.
*/
static int pager_incr_changecounter(Pager *pPager, int isDirect){
  PgHdr *pPgHdr;
  u32 change_counter;
  int rc = SQLITE_OK;

#ifndef SQLITE_ENABLE_ATOMIC_WRITE
  assert( isDirect==0 );  /* isDirect is only true for atomic writes */
#endif
  if( !pPager->changeCountDone && pPager->dbSize>0 ){
    /* Open page 1 of the file for writing. */
    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
    if( rc!=SQLITE_OK ) return rc;

    if( !isDirect ){
      rc = sqlite3PagerWrite(pPgHdr);
      if( rc!=SQLITE_OK ){
        sqlite3PagerUnref(pPgHdr);
        return rc;
      }
    }

    /* Increment the value just read and write it back to byte 24. */
    change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
    change_counter++;
    put32bits(((char*)pPgHdr->pData)+24, change_counter);

#ifdef SQLITE_ENABLE_ATOMIC_WRITE

    if( isDirect && pPager->fd->pMethods ){
      const void *zBuf = pPgHdr->pData;
      assert( pPager->dbFileSize>0 );
      rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
    }
#endif






    /* Release the page reference. */
    sqlite3PagerUnref(pPgHdr);
    pPager->changeCountDone = 1;
  }
  return rc;
}

/*
** Sync the pager file to disk.




*/
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  int rc;
  if( MEMDB ){
    rc = SQLITE_OK;
  }else{
    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  }
  return rc;
}

/*
** Sync the database file for the pager pPager. zMaster points to the name
** of a master journal file that should be written into the individual
** journal file. zMaster may be NULL, which is interpreted as no master
** journal (a single database transaction).
**
** This routine ensures that the journal is synced, all dirty pages written





** to the database file and the database file synced. The only thing that

** remains to commit the transaction is to delete the journal file (or

** master journal file if specified).
**
** Note that if zMaster==NULL, this does not overwrite a previous value
** passed to an sqlite3PagerCommitPhaseOne() call.
**
** If the final parameter - noSync - is true, then the database file itself
** is not synced. The caller must call sqlite3PagerSync() directly to
** sync the database file before calling CommitPhaseTwo() to delete the
** journal file in this case.
*/
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  Pager *pPager, 
  const char *zMaster, 
  int noSync
){
  int rc = SQLITE_OK;

  if( pPager->errCode ){
    return pPager->errCode;
  }

  /* If no changes have been made, we can leave the transaction early.
  */
  if( pPager->dbModified==0 &&
        (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
          pPager->exclusiveMode!=0) ){
    assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
    return SQLITE_OK;
  }

  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
      pPager->zFilename, zMaster, pPager->dbSize));

  /* 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.
  */
  if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dirtyCache ){
    PgHdr *pPg;
























#ifdef SQLITE_ENABLE_ATOMIC_WRITE
    /* The atomic-write optimization can be used if all of the
    ** following are true:
    **
    **    + The file-system supports the atomic-write property for
    **      blocks of size page-size, and
    **    + This commit is not part of a multi-file transaction, and
    **    + Exactly one page has been modified and store in the journal file.
    **
    ** If the optimization can be used, then the journal file will never
    ** be created for this transaction.
    */
    int useAtomicWrite;
    pPg = sqlite3PcacheDirtyList(pPager->pPCache);
    useAtomicWrite = (
        !zMaster && 
        pPager->journalOpen &&
        pPager->journalOff==jrnlBufferSize(pPager) && 
        pPager->dbSize>=pPager->dbFileSize && 
        (pPg==0 || pPg->pDirty==0)
    );
    assert( pPager->journalOpen || pPager->journalMode==PAGER_JOURNALMODE_OFF );
    if( useAtomicWrite ){
      /* Update the nRec field in the journal file. */
      int offset = pPager->journalHdr + sizeof(aJournalMagic);
      assert(pPager->nRec==1);
      rc = write32bits(pPager->jfd, offset, pPager->nRec);

      /* Update the db file change counter. The following call will modify
      ** the in-memory representation of page 1 to include the updated
      ** change counter and then write page 1 directly to the database

      ** file. Because of the atomic-write property of the host file-system, 
      ** this is safe.
      */
      if( rc==SQLITE_OK ){
        rc = pager_incr_changecounter(pPager, 1);
      }
    }else{
      rc = sqlite3JournalCreate(pPager->jfd);


    }

    if( !useAtomicWrite && rc==SQLITE_OK )

#endif



    /* If a master journal file name has already been written to the
    ** journal file, then no sync is required. This happens when it is
    ** written, then the process fails to upgrade from a RESERVED to an
    ** EXCLUSIVE lock. The next time the process tries to commit the



    ** transaction the m-j name will have already been written.


    */
    if( !pPager->setMaster ){
      rc = pager_incr_changecounter(pPager, 0);
      if( rc!=SQLITE_OK ) goto sync_exit;
      if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
#ifndef SQLITE_OMIT_AUTOVACUUM
        if( pPager->dbSize<pPager->dbOrigSize ){
          /* If this transaction has made the database smaller, then all pages
          ** being discarded by the truncation must be written to the journal
          ** file.
          */

          Pgno i;
          Pgno iSkip = PAGER_MJ_PGNO(pPager);
          Pgno dbSize = pPager->dbSize;
          pPager->dbSize = pPager->dbOrigSize;
          for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
            if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){

              rc = sqlite3PagerGet(pPager, i, &pPg);
              if( rc!=SQLITE_OK ) goto sync_exit;
              rc = sqlite3PagerWrite(pPg);
              sqlite3PagerUnref(pPg);
              if( rc!=SQLITE_OK ) goto sync_exit;
            }
          } 
          pPager->dbSize = dbSize;
        }
#endif





        rc = writeMasterJournal(pPager, zMaster);
        if( rc!=SQLITE_OK ) goto sync_exit;
        rc = syncJournal(pPager);
      }
    }





    if( rc!=SQLITE_OK ) goto sync_exit;

    /* Write all dirty pages to the database file */
    pPg = sqlite3PcacheDirtyList(pPager->pPCache);
    rc = pager_write_pagelist(pPg);
    if( rc!=SQLITE_OK ){
      assert( rc!=SQLITE_IOERR_BLOCKED );
      /* The error might have left the dirty list all fouled up here,
      ** but that does not matter because if the if the dirty list did
      ** get corrupted, then the transaction will roll back and
      ** discard the dirty list.  There is an assert in
      ** pager_get_all_dirty_pages() that verifies that no attempt
      ** is made to use an invalid dirty list.
      */
      goto sync_exit;
    }
    sqlite3PcacheCleanAll(pPager->pPCache);




    if( pPager->dbSize<pPager->dbFileSize ){

      assert( pPager->state>=PAGER_EXCLUSIVE );
      rc = pager_truncate(pPager, pPager->dbSize);
      if( rc!=SQLITE_OK ) goto sync_exit;
    }

    /* Sync the database file. */
    if( !pPager->noSync && !noSync ){
      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
    }
    IOTRACE(("DBSYNC %p\n", pPager))

    pPager->state = PAGER_SYNCED;
  }

sync_exit:
  if( rc==SQLITE_IOERR_BLOCKED ){
    /* pager_incr_changecounter() may attempt to obtain an exclusive
     * lock to spill the cache and return IOERR_BLOCKED. But since 
     * there is no chance the cache is inconsistent, it is
     * better to return SQLITE_BUSY.
     */
    rc = SQLITE_BUSY;
  }
  return rc;
}


/*
** 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.
*/
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  int rc = SQLITE_OK;


  if( pPager->errCode ){
    return pPager->errCode;
  }





  if( pPager->state<PAGER_RESERVED ){
    return SQLITE_ERROR;
  }












  if( pPager->dbModified==0 &&
        (pPager->journalMode!=PAGER_JOURNALMODE_DELETE ||
          pPager->exclusiveMode!=0) ){

    assert( pPager->dirtyCache==0 || pPager->journalOpen==0 );
    return SQLITE_OK;
  }

  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dirtyCache );
  rc = pager_end_transaction(pPager, pPager->setMaster);
  rc = pager_error(pPager, rc);
  return rc;
}

/*
** Rollback all changes.  The database falls back to PAGER_SHARED mode.




** All in-memory cache pages revert to their original data contents.

** The journal is deleted.

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








*/
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  int rc = SQLITE_OK;
  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  if( !pPager->dirtyCache || !pPager->journalOpen ){
    rc = pager_end_transaction(pPager, pPager->setMaster);
  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
    if( pPager->state>=PAGER_EXCLUSIVE ){
      pager_playback(pPager, 0);
    }
    rc = pPager->errCode;
  }else{







|


|
<
|
<
<
<
<
<
<
<
<
<
<
<

|
<

<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
|
|
|

|

|
|
<
|
<

|
<
>
|
<

>
|
|
>
>
>
>
>
>
>
>
>
>
|
>
>
|
>
>
>
>
>
>
|
|
|
>
>
>
|
>


|
|
<
<
<
<
<
<
<
<
<
|
<
<
<
<
|
<
|
<
<
<
<
<
<
<
<
<
<
<

<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
|
|
|
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
|

<
<
<
|
|
|
|
|
|
|

<
>
|
|
|
|
|
|
>
>
>
|
>
>


<





|
>
>
>
>


|
|













|
>
>
>
>
>
|
>
|
>
|










|
|
|

|





<
<
<
<
<
<
<
<
<






|
<

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

<
<
|
<
<
<
<
<
<
<
<
<
|
<
|
<
|
|
|
|
<
<
<
<
<
<
<
|
|
|
>
|
<

<
|
<


>
>
|
|
|
>

>

>
|
|
<
<
>
>
>
|
>
>

<
<
<
<

|
<
|
<
<
>
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|

>
>
>
>
>
|
|
<
|
<
>
>
>
>
>
|

|
<
|


<
<
<
<
<
<
<
|



>
>
>
|
>

|
|


|








|


|
|
|
|







|
>
>
>
>

<
>
>
>
>
>
|
|


|

>



>
>
>
>
>
|


>
>
>
>
>
>
>
>
>
>
>
>
|
|
<
>
|


>

|

|
<



|
>
>
>
>
|
>
|
>

|
<
>
|
>
>
>
>
>
|
>
>
>
>
|
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>


|

|







35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202

35203











35204
35205

35206














35207











35208
35209
35210
35211
35212
35213
35214
35215

35216

35217
35218

35219
35220

35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256









35257




35258

35259











35260


35261












35262
35263


35264
35265
35266



35267













35268
35269



35270
35271
35272
35273
35274
35275
35276
35277

35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292

35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350









35351
35352
35353
35354
35355
35356
35357

35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382


35383









35384

35385

35386
35387
35388
35389







35390
35391
35392
35393
35394

35395

35396

35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410


35411
35412
35413
35414
35415
35416
35417




35418
35419

35420


35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445

35446

35447
35448
35449
35450
35451
35452
35453
35454

35455
35456
35457







35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500

35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537

35538
35539
35540
35541
35542
35543
35544
35545
35546

35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560

35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
** A call to this routine tells the pager that it is not necessary to
** write the information on page pPg back to the disk, even though
** that page might be marked as dirty.  This happens, for example, when
** the page has been added as a leaf of the freelist and so its
** content no longer matters.
**
** The overlying software layer calls this routine when all of the data
** on the given page is unused. The pager marks the page as clean so
** that it does not get written to disk.
**
** Tests show that this optimization can quadruple the speed of large 

** DELETE operations.











*/
SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){

  Pager *pPager = pPg->pPager;














  if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){











    PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
    IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
    pPg->flags |= PGHDR_DONT_WRITE;
#ifdef SQLITE_CHECK_PAGES
    pPg->pageHash = pager_pagehash(pPg);
#endif
  }
}



/*
** This routine is called to increment the value of the database file 

** change-counter, stored as a 4-byte big-endian integer starting at 
** byte offset 24 of the pager file.

**
** If the isDirect flag is zero, then this is done by calling 
** sqlite3PagerWrite() on page 1, then modifying the contents of the
** page data. In this case the file will be updated when the current
** transaction is committed.
**
** The isDirect flag may only be non-zero if the library was compiled
** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
** if isDirect is non-zero, then the database file is updated directly
** by writing an updated version of page 1 using a call to the 
** sqlite3OsWrite() function.
*/
static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  int rc = SQLITE_OK;

  /* Declare and initialize constant integer 'isDirect'. If the
  ** atomic-write optimization is enabled in this build, then isDirect
  ** is initialized to the value passed as the isDirectMode parameter
  ** to this function. Otherwise, it is always set to zero.
  **
  ** The idea is that if the atomic-write optimization is not
  ** enabled at compile time, the compiler can omit the tests of
  ** 'isDirect' below, as well as the block enclosed in the
  ** "if( isDirect )" condition.
  */
#ifndef SQLITE_ENABLE_ATOMIC_WRITE
  const int isDirect = 0;
  assert( isDirectMode==0 );
  UNUSED_PARAMETER(isDirectMode);
#else
  const int isDirect = isDirectMode;
#endif

  assert( pPager->state>=PAGER_RESERVED );
  if( !pPager->changeCountDone && pPager->dbSize>0 ){
    PgHdr *pPgHdr;                /* Reference to page 1 */









    u32 change_counter;           /* Initial value of change-counter field */






    assert( !pPager->tempFile && isOpen(pPager->fd) );














    /* Open page 1 of the file for writing. */












    rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
    assert( pPgHdr==0 || rc==SQLITE_OK );



    /* If page one was fetched successfully, and this function is not
    ** operating in direct-mode, make page 1 writable.



    */













    if( rc==SQLITE_OK && !isDirect ){
      rc = sqlite3PagerWrite(pPgHdr);



    }

    if( rc==SQLITE_OK ){
      /* Increment the value just read and write it back to byte 24. */
      change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
      change_counter++;
      put32bits(((char*)pPgHdr->pData)+24, change_counter);


      /* If running in direct mode, write the contents of page 1 to the file. */
      if( isDirect ){
        const void *zBuf = pPgHdr->pData;
        assert( pPager->dbFileSize>0 );
        rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
      }

      /* If everything worked, set the changeCountDone flag. */
      if( rc==SQLITE_OK ){
        pPager->changeCountDone = 1;
      }
    }

    /* Release the page reference. */
    sqlite3PagerUnref(pPgHdr);

  }
  return rc;
}

/*
** Sync the pager file to disk. This is a no-op for in-memory files
** or pages with the Pager.noSync flag set.
**
** If successful, or called on a pager for which it is a no-op, this
** function returns SQLITE_OK. Otherwise, an IO error code is returned.
*/
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  int rc;                              /* Return code */
  if( MEMDB || pPager->noSync ){
    rc = SQLITE_OK;
  }else{
    rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
  }
  return rc;
}

/*
** Sync the database file for the pager pPager. zMaster points to the name
** of a master journal file that should be written into the individual
** journal file. zMaster may be NULL, which is interpreted as no master
** journal (a single database transaction).
**
** This routine ensures that:
**
**   * The database file change-counter is updated,
**   * the journal is synced (unless the atomic-write optimization is used),
**   * all dirty pages are written to the database file, 
**   * the database file is truncated (if required), and
**   * the database file synced. 
**
** The only thing that remains to commit the transaction is to finalize 
** (delete, truncate or zero the first part of) the journal file (or 
** delete the master journal file if specified).
**
** Note that if zMaster==NULL, this does not overwrite a previous value
** passed to an sqlite3PagerCommitPhaseOne() call.
**
** If the final parameter - noSync - is true, then the database file itself
** is not synced. The caller must call sqlite3PagerSync() directly to
** sync the database file before calling CommitPhaseTwo() to delete the
** journal file in this case.
*/
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  Pager *pPager,                  /* Pager object */
  const char *zMaster,            /* If not NULL, the master journal name */
  int noSync                      /* True to omit the xSync on the db file */
){
  int rc = SQLITE_OK;             /* Return code */

  if( pPager->errCode ){
    return pPager->errCode;
  }










  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
      pPager->zFilename, zMaster, pPager->dbSize));

  /* 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.
  */
  if( pPager->state!=PAGER_SYNCED && !MEMDB && pPager->dbModified ){


    /* The following block updates the change-counter. Exactly how it
    ** does this depends on whether or not the atomic-update optimization
    ** was enabled at compile time, and if this transaction meets the 
    ** runtime criteria to use the operation: 
    **
    **    * The file-system supports the atomic-write property for
    **      blocks of size page-size, and 
    **    * This commit is not part of a multi-file transaction, and
    **    * Exactly one page has been modified and store in the journal file.
    **
    ** If the optimization was not enabled at compile time, then the
    ** pager_incr_changecounter() function is called to update the change
    ** counter in 'indirect-mode'. If the optimization is compiled in but
    ** is not applicable to this transaction, call sqlite3JournalCreate()
    ** to make sure the journal file has actually been created, then call
    ** pager_incr_changecounter() to update the change-counter in indirect
    ** mode. 
    **
    ** Otherwise, if the optimization is both enabled and applicable,
    ** then call pager_incr_changecounter() to update the change-counter
    ** in 'direct' mode. In this case the journal file will never be
    ** created for this transaction.
    */
#ifdef SQLITE_ENABLE_ATOMIC_WRITE


    PgHdr *pPg;









    assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );

    if( !zMaster && isOpen(pPager->jfd) 

     && pPager->journalOff==jrnlBufferSize(pPager) 
     && pPager->dbSize>=pPager->dbFileSize
     && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
    ){







      /* Update the db file change counter via the direct-write method. The 
      ** following call will modify the in-memory representation of page 1 
      ** to include the updated change counter and then write page 1 
      ** directly to the database file. Because of the atomic-write 
      ** property of the host file-system, this is safe.

      */

      rc = pager_incr_changecounter(pPager, 1);

    }else{
      rc = sqlite3JournalCreate(pPager->jfd);
      if( rc==SQLITE_OK ){
        rc = pager_incr_changecounter(pPager, 0);
      }
    }
#else
    rc = pager_incr_changecounter(pPager, 0);
#endif
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;

    /* If this transaction has made the database smaller, then all pages
    ** being discarded by the truncation must be written to the journal
    ** file. This can only happen in auto-vacuum mode.


    **
    ** Before reading the pages with page numbers larger than the 
    ** current value of Pager.dbSize, set dbSize back to the value
    ** that it took at the start of the transaction. Otherwise, the
    ** calls to sqlite3PagerGet() return zeroed pages instead of 
    ** reading data from the database file.
    */




#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pPager->dbSize<pPager->dbOrigSize

     && pPager->journalMode!=PAGER_JOURNALMODE_OFF 


    ){
      Pgno i;                                   /* Iterator variable */
      const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
      const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
      pPager->dbSize = pPager->dbOrigSize;
      for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
        if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
          PgHdr *pPage;             /* Page to journal */
          rc = sqlite3PagerGet(pPager, i, &pPage);
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
          rc = sqlite3PagerWrite(pPage);
          sqlite3PagerUnref(pPage);
          if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
        }
      } 
      pPager->dbSize = dbSize;
    }
#endif

    /* Write the master journal name into the journal file. If a master 
    ** journal file name has already been written to the journal file, 
    ** or if zMaster is NULL (no master journal), then this call is a no-op.
    */
    rc = writeMasterJournal(pPager, zMaster);
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;



    /* Sync the journal file. If the atomic-update optimization is being
    ** used, this call will not create the journal file or perform any
    ** real IO.
    */
    rc = syncJournal(pPager);
    if( rc!=SQLITE_OK ) goto commit_phase_one_exit;

    /* Write all dirty pages to the database file. */

    rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
    if( rc!=SQLITE_OK ){
      assert( rc!=SQLITE_IOERR_BLOCKED );







      goto commit_phase_one_exit;
    }
    sqlite3PcacheCleanAll(pPager->pPCache);

    /* If the file on disk is not the same size as the database image,
    ** then use pager_truncate to grow or shrink the file here.
    */
    if( pPager->dbSize!=pPager->dbFileSize ){
      Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
      assert( pPager->state>=PAGER_EXCLUSIVE );
      rc = pager_truncate(pPager, nNew);
      if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
    }

    /* Finally, sync the database file. */
    if( !pPager->noSync && !noSync ){
      rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
    }
    IOTRACE(("DBSYNC %p\n", pPager))

    pPager->state = PAGER_SYNCED;
  }

commit_phase_one_exit:
  if( rc==SQLITE_IOERR_BLOCKED ){
    /* pager_incr_changecounter() may attempt to obtain an exclusive
    ** lock to spill the cache and return IOERR_BLOCKED. But since 
    ** there is no chance the cache is inconsistent, it is
    ** better to return SQLITE_BUSY.
    **/
    rc = SQLITE_BUSY;
  }
  return rc;
}


/*
** When this function is called, the database file has been completely
** updated to reflect the changes made by the current transaction and
** synced to disk. The journal file still exists in the file-system 
** though, and if a failure occurs at this point it will eventually
** be used as a hot-journal and the current transaction rolled back.
**

** This function finalizes the journal file, either by deleting, 
** truncating or partially zeroing it, so that it cannot be used 
** for hot-journal rollback. Once this is done the transaction is
** irrevocably committed.
**
** If an error occurs, an IO error code is returned and the pager
** moves into the error state. Otherwise, SQLITE_OK is returned.
*/
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  int rc = SQLITE_OK;                  /* Return code */

  /* Do not proceed if the pager is already in the error state. */
  if( pPager->errCode ){
    return pPager->errCode;
  }

  /* This function should not be called if the pager is not in at least
  ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
  ** nice to have this defensive block here anyway.
  */
  if( NEVER(pPager->state<PAGER_RESERVED) ){
    return SQLITE_ERROR;
  }

  /* An optimization. If the database was not actually modified during
  ** this transaction, the pager is running in exclusive-mode and is
  ** using persistent journals, then this function is a no-op.
  **
  ** The start of the journal file currently contains a single journal 
  ** header with the nRec field set to 0. If such a journal is used as
  ** a hot-journal during hot-journal rollback, 0 changes will be made
  ** to the database file. So there is no need to zero the journal 
  ** header. Since the pager is in exclusive mode, there is no need
  ** to drop any locks either.
  */
  if( pPager->dbModified==0 && pPager->exclusiveMode 
   && pPager->journalMode==PAGER_JOURNALMODE_PERSIST

  ){
    assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
    return SQLITE_OK;
  }

  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
  rc = pager_end_transaction(pPager, pPager->setMaster);
  return pager_error(pPager, rc);

}

/*
** Rollback all changes. The database falls back to PAGER_SHARED mode.
**
** This function performs two tasks:
**
**   1) It rolls back the journal file, restoring all database file and 
**      in-memory cache pages to the state they were in when the transaction
**      was opened, and
**   2) It finalizes the journal file, so that it is not used for hot
**      rollback at any point in the future.
**
** subject to the following qualifications:

**
** * If the journal file is not yet open when this function is called,
**   then only (2) is performed. In this case there is no journal file
**   to roll back.
**
** * If in an error state other than SQLITE_FULL, then task (1) is 
**   performed. If successful, task (2). Regardless of the outcome
**   of either, the error state error code is returned to the caller
**   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
**
** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
**   or not (1) is succussful, also attempt (2). If successful, return
**   SQLITE_OK. Otherwise, enter the error state and return the first 
**   error code encountered. 
**
**   In this case there is no chance that the database was written to. 
**   So is safe to finalize the journal file even if the playback 
**   (operation 1) failed. However the pager must enter the error state
**   as the contents of the in-memory cache are now suspect.
**
** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
**   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
**   otherwise enter the error state and return the error code from the 
**   failing operation.
**
**   In this case the database file may have been written to. So if the
**   playback operation did not succeed it would not be safe to finalize
**   the journal file. It needs to be left in the file-system so that
**   some other process can use it to restore the database state (by
**   hot-journal rollback).
*/
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  int rc = SQLITE_OK;                  /* Return code */
  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  if( !pPager->dbModified || !isOpen(pPager->jfd) ){
    rc = pager_end_transaction(pPager, pPager->setMaster);
  }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
    if( pPager->state>=PAGER_EXCLUSIVE ){
      pager_playback(pPager, 0);
    }
    rc = pPager->errCode;
  }else{
34907
34908
34909
34910
34911
34912
34913
34914







34915
34916
34917

34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968




34969
34970
34971
34972
34973












34974
34975

34976
34977
34978


34979
34980
34981
34982
34983

34984
34985
34986






34987
34988
34989
34990
34991
34992





34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
}
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  return MEMDB;
}
#endif

/*
** Ensure that there are at least nSavepoint savepoints open.







*/
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  int rc = SQLITE_OK;


  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
    int ii;
    PagerSavepoint *aNew;

    /* Either there is no active journal or the sub-journal is open or 
    ** the journal is always stored in memory */
    assert( pPager->nSavepoint==0 || pPager->sjfd->pMethods ||
            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );

    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
    ** if the allocation fails. Otherwise, zero the new portion in case a 
    ** malloc failure occurs while populating it in the for(...) loop below.
    */
    aNew = (PagerSavepoint *)sqlite3Realloc(
        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
    );
    if( !aNew ){
      return SQLITE_NOMEM;
    }
    memset(&aNew[pPager->nSavepoint], 0,
        (nSavepoint - pPager->nSavepoint) * sizeof(PagerSavepoint)
    );
    pPager->aSavepoint = aNew;
    ii = pPager->nSavepoint;
    pPager->nSavepoint = nSavepoint;

    /* Populate the PagerSavepoint structures just allocated. */
    for(/* no-op */; ii<nSavepoint; ii++){
      assert( pPager->dbSizeValid );
      aNew[ii].nOrig = pPager->dbSize;
      if( pPager->journalOpen && pPager->journalOff>0 ){
        aNew[ii].iOffset = pPager->journalOff;
      }else{
        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
      }
      aNew[ii].iSubRec = pPager->stmtNRec;
      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
      if( !aNew[ii].pInSavepoint ){
        return SQLITE_NOMEM;
      }
    }

    /* Open the sub-journal, if it is not already opened. */
    rc = openSubJournal(pPager);
  }

  return rc;
}

/*




** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
** that have occured since savepoint iSavepoint was created.
**












** In either case, all savepoints with an index greater than iSavepoint 
** are destroyed.

**
** If there are less than (iSavepoint+1) active savepoints when this 
** function is called it is a no-op.


*/ 
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  int rc = SQLITE_OK;

  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );


  if( iSavepoint<pPager->nSavepoint ){
    int ii;






    int nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
    for(ii=nNew; ii<pPager->nSavepoint; ii++){
      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
    }
    pPager->nSavepoint = nNew;






    if( op==SAVEPOINT_ROLLBACK && pPager->jfd->pMethods ){
      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
      assert(rc!=SQLITE_DONE);
    }
  
    /* If this is a release of the outermost savepoint, truncate 
    ** the sub-journal. */
    if( nNew==0 && op==SAVEPOINT_RELEASE && pPager->sjfd->pMethods ){
      assert( rc==SQLITE_OK );
      rc = sqlite3OsTruncate(pPager->sjfd, 0);
      pPager->stmtNRec = 0;
    }
  }
  return rc;
}

/*
** Return the full pathname of the database file.







|
>
>
>
>
>
>
>


|
>

|
|
|



|












<
|
<

<



|


|




|














>
>
>
>



|

>
>
>
>
>
>
>
>
>
>
>
>
|
|
>

<
|
>
>





>


|
>
>
>
>
>
>
|





>
>
>
>
>
|






|
|


|







35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705

35706

35707

35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758

35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
}
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  return MEMDB;
}
#endif

/*
** Check that there are at least nSavepoint savepoints open. If there are
** currently less than nSavepoints open, then open one or more savepoints
** to make up the difference. If the number of savepoints is already
** equal to nSavepoint, then this function is a no-op.
**
** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
** occurs while opening the sub-journal file, then an IO error code is
** returned. Otherwise, SQLITE_OK.
*/
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  int rc = SQLITE_OK;                       /* Return code */
  int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */

  if( nSavepoint>nCurrent && pPager->useJournal ){
    int ii;                                 /* Iterator variable */
    PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */

    /* Either there is no active journal or the sub-journal is open or 
    ** the journal is always stored in memory */
    assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
            pPager->journalMode==PAGER_JOURNALMODE_MEMORY );

    /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
    ** if the allocation fails. Otherwise, zero the new portion in case a 
    ** malloc failure occurs while populating it in the for(...) loop below.
    */
    aNew = (PagerSavepoint *)sqlite3Realloc(
        pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
    );
    if( !aNew ){
      return SQLITE_NOMEM;
    }

    memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));

    pPager->aSavepoint = aNew;

    pPager->nSavepoint = nSavepoint;

    /* Populate the PagerSavepoint structures just allocated. */
    for(ii=nCurrent; ii<nSavepoint; ii++){
      assert( pPager->dbSizeValid );
      aNew[ii].nOrig = pPager->dbSize;
      if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
        aNew[ii].iOffset = pPager->journalOff;
      }else{
        aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
      }
      aNew[ii].iSubRec = pPager->nSubRec;
      aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
      if( !aNew[ii].pInSavepoint ){
        return SQLITE_NOMEM;
      }
    }

    /* Open the sub-journal, if it is not already opened. */
    rc = openSubJournal(pPager);
  }

  return rc;
}

/*
** This function is called to rollback or release (commit) a savepoint.
** The savepoint to release or rollback need not be the most recently 
** created savepoint.
**
** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
** that have occured since the specified savepoint was created.
**
** The savepoint to rollback or release is identified by parameter 
** iSavepoint. A value of 0 means to operate on the outermost savepoint
** (the first created). A value of (Pager.nSavepoint-1) means operate
** on the most recently created savepoint. If iSavepoint is greater than
** (Pager.nSavepoint-1), then this function is a no-op.
**
** If a negative value is passed to this function, then the current
** transaction is rolled back. This is different to calling 
** sqlite3PagerRollback() because this function does not terminate
** the transaction or unlock the database, it just restores the 
** contents of the database to its original state. 
**
** In any case, all savepoints with an index greater than iSavepoint 
** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
** then savepoint iSavepoint is also destroyed.
**

** This function may return SQLITE_NOMEM if a memory allocation fails,
** or an IO error code if an IO error occurs while rolling back a 
** savepoint. If no errors occur, SQLITE_OK is returned.
*/ 
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  int rc = SQLITE_OK;

  assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );

  if( iSavepoint<pPager->nSavepoint ){
    int ii;            /* Iterator variable */
    int nNew;          /* Number of remaining savepoints after this op. */

    /* Figure out how many savepoints will still be active after this
    ** operation. Store this value in nNew. Then free resources associated 
    ** with any savepoints that are destroyed by this operation.
    */
    nNew = iSavepoint + (op==SAVEPOINT_ROLLBACK);
    for(ii=nNew; ii<pPager->nSavepoint; ii++){
      sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
    }
    pPager->nSavepoint = nNew;

    /* If this is a rollback operation, playback the specified savepoint.
    ** If this is a temp-file, it is possible that the journal file has
    ** not yet been opened. In this case there have been no changes to
    ** the database file, so the playback operation can be skipped.
    */
    if( op==SAVEPOINT_ROLLBACK && isOpen(pPager->jfd) ){
      PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
      rc = pagerPlaybackSavepoint(pPager, pSavepoint);
      assert(rc!=SQLITE_DONE);
    }
  
    /* If this is a release of the outermost savepoint, truncate 
    ** the sub-journal to zero bytes in size. */
    if( nNew==0 && op==SAVEPOINT_RELEASE && isOpen(pPager->sjfd) ){
      assert( rc==SQLITE_OK );
      rc = sqlite3OsTruncate(pPager->sjfd, 0);
      pPager->nSubRec = 0;
    }
  }
  return rc;
}

/*
** Return the full pathname of the database file.
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
** with the pager.  This might return NULL if the file has
** not yet been opened.
*/
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  return pPager->fd;
}

/*
** Return the directory of the database file.
*/
SQLITE_PRIVATE const char *sqlite3PagerDirname(Pager *pPager){
  return pPager->zDirectory;
}

/*
** Return the full pathname of the journal file.
*/
SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  return pPager->zJournal;
}








<
<
<
<
<
<
<







35821
35822
35823
35824
35825
35826
35827







35828
35829
35830
35831
35832
35833
35834
** with the pager.  This might return NULL if the file has
** not yet been opened.
*/
SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  return pPager->fd;
}








/*
** Return the full pathname of the journal file.
*/
SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  return pPager->zJournal;
}

35084
35085
35086
35087
35088
35089
35090



35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111




35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
** has been removed (CREATE INDEX needs to move a page when a statement
** transaction is active).
**
** If the fourth argument, isCommit, is non-zero, then this page is being
** moved as part of a database reorganization just before the transaction 
** is being committed. In this case, it is guaranteed that the database page 
** pPg refers to will not be written to again within this transaction.



*/
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  PgHdr *pPgOld;  /* The page being overwritten. */
  Pgno needSyncPgno = 0;
  int rc;

  assert( pPg->nRef>0 );

  /* If the page being moved is dirty and has not been saved by the latest
  ** savepoint, then save the current contents of the page into the 
  ** sub-journal now. This is required to handle the following scenario:
  **
  **   BEGIN;
  **     <journal page X, then modify it in memory>
  **     SAVEPOINT one;
  **       <Move page X to location Y>
  **     ROLLBACK TO one;
  **
  ** If page X were not written to the sub-journal here, it would not
  ** be possible to restore its contents when the "ROLLBACK TO one"
  ** statement were processed.




  */
  if( pPg->flags&PGHDR_DIRTY 
   && subjRequiresPage(pPg)
   && SQLITE_OK!=(rc = subjournalPage(pPg))
  ){
    return rc;
  }

  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))

  pager_get_content(pPg);

  /* If the journal needs to be sync()ed before page pPg->pgno can
  ** be written to, store pPg->pgno in local variable needSyncPgno.
  **
  ** If the isCommit flag is set, there is no need to remember that
  ** the journal needs to be sync()ed before database page pPg->pgno 
  ** can be written to. The caller has already promised not to write to it.
  */







>
>
>


|
|
|















|
>
>
>
>












<
<







35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
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
** has been removed (CREATE INDEX needs to move a page when a statement
** transaction is active).
**
** If the fourth argument, isCommit, is non-zero, then this page is being
** moved as part of a database reorganization just before the transaction 
** is being committed. In this case, it is guaranteed that the database page 
** pPg refers to will not be written to again within this transaction.
**
** This function may return SQLITE_NOMEM or an IO error code if an error
** occurs. Otherwise, it returns SQLITE_OK.
*/
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  PgHdr *pPgOld;               /* The page being overwritten. */
  Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
  int rc;                      /* Return code */

  assert( pPg->nRef>0 );

  /* If the page being moved is dirty and has not been saved by the latest
  ** savepoint, then save the current contents of the page into the 
  ** sub-journal now. This is required to handle the following scenario:
  **
  **   BEGIN;
  **     <journal page X, then modify it in memory>
  **     SAVEPOINT one;
  **       <Move page X to location Y>
  **     ROLLBACK TO one;
  **
  ** If page X were not written to the sub-journal here, it would not
  ** be possible to restore its contents when the "ROLLBACK TO one"
  ** statement were is processed.
  **
  ** subjournalPage() may need to allocate space to store pPg->pgno into
  ** one or more savepoint bitvecs. This is the reason this function
  ** may return SQLITE_NOMEM.
  */
  if( pPg->flags&PGHDR_DIRTY 
   && subjRequiresPage(pPg)
   && SQLITE_OK!=(rc = subjournalPage(pPg))
  ){
    return rc;
  }

  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
      PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))



  /* If the journal needs to be sync()ed before page pPg->pgno can
  ** be written to, store pPg->pgno in local variable needSyncPgno.
  **
  ** If the isCommit flag is set, there is no need to remember that
  ** the journal needs to be sync()ed before database page pPg->pgno 
  ** can be written to. The caller has already promised not to write to it.
  */
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165

  sqlite3PcacheMove(pPg, pgno);
  if( pPgOld ){
    sqlite3PcacheDrop(pPgOld);
  }

  sqlite3PcacheMakeDirty(pPg);
  pPager->dirtyCache = 1;
  pPager->dbModified = 1;

  if( needSyncPgno ){
    /* If needSyncPgno is non-zero, then the journal file needs to be 
    ** sync()ed before any data is written to database file page needSyncPgno.
    ** Currently, no such page exists in the page-cache and the 
    ** "is journaled" bitvec flag has been set. This needs to be remedied by







<







35944
35945
35946
35947
35948
35949
35950

35951
35952
35953
35954
35955
35956
35957

  sqlite3PcacheMove(pPg, pgno);
  if( pPgOld ){
    sqlite3PcacheDrop(pPgOld);
  }

  sqlite3PcacheMakeDirty(pPg);

  pPager->dbModified = 1;

  if( needSyncPgno ){
    /* If needSyncPgno is non-zero, then the journal file needs to be 
    ** sync()ed before any data is written to database file page needSyncPgno.
    ** Currently, no such page exists in the page-cache and the 
    ** "is journaled" bitvec flag has been set. This needs to be remedied by
35239
35240
35241
35242
35243
35244
35245

35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
** Get/set the journal-mode for this pager. Parameter eMode must be one of:
**
**    PAGER_JOURNALMODE_QUERY
**    PAGER_JOURNALMODE_DELETE
**    PAGER_JOURNALMODE_TRUNCATE
**    PAGER_JOURNALMODE_PERSIST
**    PAGER_JOURNALMODE_OFF

**
** If the parameter is not _QUERY, then the journal-mode is set to the
** value specified.
**
** The returned indicate the current (possibly updated)
** journal-mode.
*/
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
  if( !MEMDB ){
    assert( eMode==PAGER_JOURNALMODE_QUERY
              || eMode==PAGER_JOURNALMODE_DELETE
              || eMode==PAGER_JOURNALMODE_TRUNCATE
              || eMode==PAGER_JOURNALMODE_PERSIST







>




|
<







36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043

36044
36045
36046
36047
36048
36049
36050
** Get/set the journal-mode for this pager. Parameter eMode must be one of:
**
**    PAGER_JOURNALMODE_QUERY
**    PAGER_JOURNALMODE_DELETE
**    PAGER_JOURNALMODE_TRUNCATE
**    PAGER_JOURNALMODE_PERSIST
**    PAGER_JOURNALMODE_OFF
**    PAGER_JOURNALMODE_MEMORY
**
** If the parameter is not _QUERY, then the journal-mode is set to the
** value specified.
**
** The returned indicate the current (possibly updated) journal-mode.

*/
SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
  if( !MEMDB ){
    assert( eMode==PAGER_JOURNALMODE_QUERY
              || eMode==PAGER_JOURNALMODE_DELETE
              || eMode==PAGER_JOURNALMODE_TRUNCATE
              || eMode==PAGER_JOURNALMODE_PERSIST
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btreeInt.h,v 1.38 2008/12/27 15:23:13 danielk1977 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.







|







36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btreeInt.h,v 1.41 2009/01/20 17:06:27 danielk1977 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.
35679
35680
35681
35682
35683
35684
35685

35686
35687
35688
35689
35690
35691
35692
  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
  u8 inTransaction;     /* Transaction state */
  int nTransaction;     /* Number of open transactions (read + write) */
  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */

#ifndef SQLITE_OMIT_SHARED_CACHE
  int nRef;             /* Number of references to this structure */
  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
  BtLock *pLock;        /* List of locks held on this shared-btree struct */
  Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
#endif
  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */







>







36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
  u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
  u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
  u8 inTransaction;     /* Transaction state */
  int nTransaction;     /* Number of open transactions (read + write) */
  void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
  void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
  Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
#ifndef SQLITE_OMIT_SHARED_CACHE
  int nRef;             /* Number of references to this structure */
  BtShared *pNext;      /* Next on a list of sharable BtShared structs */
  BtLock *pLock;        /* List of locks held on this shared-btree struct */
  Btree *pExclusive;    /* Btree with an EXCLUSIVE lock on the whole db */
#endif
  u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
35786
35787
35788
35789
35790
35791
35792

35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
**   should return the error code stored in BtCursor.skip
*/
#define CURSOR_INVALID           0
#define CURSOR_VALID             1
#define CURSOR_REQUIRESEEK       2
#define CURSOR_FAULT             3


/* The database page the PENDING_BYTE occupies. This page is never used.
** TODO: This macro is very similary to PAGER_MJ_PGNO() in pager.c. They
** should possibly be consolidated (presumably in pager.h).
**
** If disk I/O is omitted (meaning that the database is stored purely
** in memory) then there is no pending byte.
*/
#ifdef SQLITE_OMIT_DISKIO
# define PENDING_BYTE_PAGE(pBt)  0x7fffffff
#else
# define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/(pBt)->pageSize)+1))
#endif

/*
** A linked list of the following structures is stored at BtShared.pLock.
** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
** is opened on the table with root page BtShared.iTable. Locks are removed
** from this list when a transaction is committed or rolled back, or when
** a btree handle is closed.







>
|
<
<
<
<
<

<
|
<
<
<







36579
36580
36581
36582
36583
36584
36585
36586
36587





36588

36589



36590
36591
36592
36593
36594
36595
36596
**   should return the error code stored in BtCursor.skip
*/
#define CURSOR_INVALID           0
#define CURSOR_VALID             1
#define CURSOR_REQUIRESEEK       2
#define CURSOR_FAULT             3

/* 
** The database page the PENDING_BYTE occupies. This page is never used.





*/

# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)




/*
** A linked list of the following structures is stored at BtShared.pLock.
** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
** is opened on the table with root page BtShared.iTable. Locks are removed
** from this list when a transaction is committed or rolled back, or when
** a btree handle is closed.
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btree.c,v 1.558 2009/01/10 16:15:21 drh 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.
*/

/*







|







37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** $Id: btree.c,v 1.563 2009/01/31 14:54:07 danielk1977 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.
*/

/*
36513
36514
36515
36516
36517
36518
36519










































































36520
36521
36522
36523
36524
36525
36526
    invalidateOverflowCache(p);
  }
}
#else
  #define invalidateOverflowCache(x)
  #define invalidateAllOverflowCache(x)
#endif











































































/*
** Save the current cursor position in the variables BtCursor.nKey 
** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
*/
static int saveCursorPosition(BtCursor *pCur){
  int rc;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
    invalidateOverflowCache(p);
  }
}
#else
  #define invalidateOverflowCache(x)
  #define invalidateAllOverflowCache(x)
#endif

/*
** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
** when a page that previously contained data becomes a free-list leaf 
** page.
**
** The BtShared.pHasContent bitvec exists to work around an obscure
** bug caused by the interaction of two useful IO optimizations surrounding
** free-list leaf pages:
**
**   1) When all data is deleted from a page and the page becomes
**      a free-list leaf page, the page is not written to the database
**      (as free-list leaf pages contain no meaningful data). Sometimes
**      such a page is not even journalled (as it will not be modified,
**      why bother journalling it?).
**
**   2) When a free-list leaf page is reused, its content is not read
**      from the database or written to the journal file (why should it
**      be, if it is not at all meaningful?).
**
** By themselves, these optimizations work fine and provide a handy
** performance boost to bulk delete or insert operations. However, if
** a page is moved to the free-list and then reused within the same
** transaction, a problem comes up. If the page is not journalled when
** it is moved to the free-list and it is also not journalled when it
** is extracted from the free-list and reused, then the original data
** may be lost. In the event of a rollback, it may not be possible
** to restore the database to its original configuration.
**
** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
** moved to become a free-list leaf page, the corresponding bit is
** set in the bitvec. Whenever a leaf page is extracted from the free-list,
** optimization 2 above is ommitted if the corresponding bit is already
** set in BtShared.pHasContent. The contents of the bitvec are cleared
** at the end of every transaction.
*/
static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  int rc = SQLITE_OK;
  if( !pBt->pHasContent ){
    int nPage;
    rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
    if( rc==SQLITE_OK ){
      pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
      if( !pBt->pHasContent ){
        rc = SQLITE_NOMEM;
      }
    }
  }
  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
    rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  }
  return rc;
}

/*
** Query the BtShared.pHasContent vector.
**
** This function is called when a free-list leaf page is removed from the
** free-list for reuse. It returns false if it is safe to retrieve the
** page from the pager layer with the 'no-content' flag set. True otherwise.
*/
static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  Bitvec *p = pBt->pHasContent;
  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
}

/*
** Clear (destroy) the BtShared.pHasContent bitvec. This should be
** invoked at the conclusion of each write-transaction.
*/
static void btreeClearHasContent(BtShared *pBt){
  sqlite3BitvecDestroy(pBt->pHasContent);
  pBt->pHasContent = 0;
}

/*
** Save the current cursor position in the variables BtCursor.nKey 
** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
*/
static int saveCursorPosition(BtCursor *pCur){
  int rc;
37331
37332
37333
37334
37335
37336
37337















37338
37339
37340
37341
37342
37343
37344

  assert( sqlite3_mutex_held(pBt->mutex) );
  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  if( rc ) return rc;
  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  return SQLITE_OK;
}
















/*
** Return the size of the database file in pages. If there is any kind of
** error, return ((unsigned int)-1).
*/
static Pgno pagerPagecount(BtShared *pBt){
  int nPage = -1;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218

  assert( sqlite3_mutex_held(pBt->mutex) );
  rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
  if( rc ) return rc;
  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  return SQLITE_OK;
}

/*
** Retrieve a page from the pager cache. If the requested page is not
** already in the pager cache return NULL. Initialize the MemPage.pBt and
** MemPage.aData elements if needed.
*/
static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  DbPage *pDbPage;
  assert( sqlite3_mutex_held(pBt->mutex) );
  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  if( pDbPage ){
    return btreePageFromDbPage(pDbPage, pgno, pBt);
  }
  return 0;
}

/*
** Return the size of the database file in pages. If there is any kind of
** error, return ((unsigned int)-1).
*/
static Pgno pagerPagecount(BtShared *pBt){
  int nPage = -1;
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
*/
static int getAndInitPage(
  BtShared *pBt,          /* The database file */
  Pgno pgno,           /* Number of the page to get */
  MemPage **ppPage     /* Write the page pointer here */
){
  int rc;
  DbPage *pDbPage;
  MemPage *pPage;

  assert( sqlite3_mutex_held(pBt->mutex) );
  if( pgno==0 ){
    return SQLITE_CORRUPT_BKPT; 
  }

  /* It is often the case that the page we want is already in cache.
  ** If so, get it directly.  This saves us from having to call
  ** pagerPagecount() to make sure pgno is within limits, which results
  ** in a measureable performance improvements.
  */
  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  if( pDbPage ){
    /* Page is already in cache */
    *ppPage = pPage = btreePageFromDbPage(pDbPage, pgno, pBt);
    rc = SQLITE_OK;
  }else{
    /* Page not in cache.  Acquire it. */
    if( pgno>pagerPagecount(pBt) ){
      return SQLITE_CORRUPT_BKPT; 
    }
    rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);







<












|
|

<







38230
38231
38232
38233
38234
38235
38236

38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251

38252
38253
38254
38255
38256
38257
38258
*/
static int getAndInitPage(
  BtShared *pBt,          /* The database file */
  Pgno pgno,           /* Number of the page to get */
  MemPage **ppPage     /* Write the page pointer here */
){
  int rc;

  MemPage *pPage;

  assert( sqlite3_mutex_held(pBt->mutex) );
  if( pgno==0 ){
    return SQLITE_CORRUPT_BKPT; 
  }

  /* It is often the case that the page we want is already in cache.
  ** If so, get it directly.  This saves us from having to call
  ** pagerPagecount() to make sure pgno is within limits, which results
  ** in a measureable performance improvements.
  */
  *ppPage = pPage = btreePageLookup(pBt, pgno);
  if( pPage ){
    /* Page is already in cache */

    rc = SQLITE_OK;
  }else{
    /* Page not in cache.  Acquire it. */
    if( pgno>pagerPagecount(pBt) ){
      return SQLITE_CORRUPT_BKPT; 
    }
    rc = sqlite3BtreeGetPage(pBt, pgno, ppPage, 0);
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
      }while( pBt->pPage1==0 && rc==SQLITE_OK );
    }

    if( rc==SQLITE_OK && wrflag ){
      if( pBt->readOnly ){
        rc = SQLITE_READONLY;
      }else{
        rc = sqlite3PagerBegin(pBt->pPage1->pDbPage, wrflag>1);
        if( rc==SQLITE_OK ){
          rc = newDatabase(pBt);
        }
      }
    }
  
    if( rc==SQLITE_OK ){







|







39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
      }while( pBt->pPage1==0 && rc==SQLITE_OK );
    }

    if( rc==SQLITE_OK && wrflag ){
      if( pBt->readOnly ){
        rc = SQLITE_READONLY;
      }else{
        rc = sqlite3PagerBegin(pBt->pPager, wrflag>1);
        if( rc==SQLITE_OK ){
          rc = newDatabase(pBt);
        }
      }
    }
  
    if( rc==SQLITE_OK ){
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
  sqlite3BtreeEnter(p);
  pBt->db = p->db;
  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  if( !pBt->autoVacuum ){
    rc = SQLITE_DONE;
  }else{
    invalidateAllOverflowCache(pBt);
    rc = incrVacuumStep(pBt, 0, sqlite3PagerImageSize(pBt->pPager));
  }
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** This routine is called prior to sqlite3PagerCommit when a transaction







|







39476
39477
39478
39479
39480
39481
39482
39483
39484
39485
39486
39487
39488
39489
39490
  sqlite3BtreeEnter(p);
  pBt->db = p->db;
  assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  if( !pBt->autoVacuum ){
    rc = SQLITE_DONE;
  }else{
    invalidateAllOverflowCache(pBt);
    rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
  }
  sqlite3BtreeLeave(p);
  return rc;
}

/*
** This routine is called prior to sqlite3PagerCommit when a transaction
38772
38773
38774
38775
38776
38777
38778

38779
38780
38781
38782
38783
38784
38785
      pBt->inTransaction = TRANS_NONE;
    }
  }

  /* Set the handles current transaction state to TRANS_NONE and unlock
  ** the pager if this call closed the only read or write transaction.
  */

  p->inTrans = TRANS_NONE;
  unlockBtreeIfUnused(pBt);

  btreeIntegrity(p);
  sqlite3BtreeLeave(p);
  return SQLITE_OK;
}







>







39644
39645
39646
39647
39648
39649
39650
39651
39652
39653
39654
39655
39656
39657
39658
      pBt->inTransaction = TRANS_NONE;
    }
  }

  /* Set the handles current transaction state to TRANS_NONE and unlock
  ** the pager if this call closed the only read or write transaction.
  */
  btreeClearHasContent(pBt);
  p->inTrans = TRANS_NONE;
  unlockBtreeIfUnused(pBt);

  btreeIntegrity(p);
  sqlite3BtreeLeave(p);
  return SQLITE_OK;
}
38907
38908
38909
38910
38911
38912
38913

38914
38915
38916
38917
38918
38919
38920
    assert( pBt->nTransaction>0 );
    pBt->nTransaction--;
    if( 0==pBt->nTransaction ){
      pBt->inTransaction = TRANS_NONE;
    }
  }


  p->inTrans = TRANS_NONE;
  pBt->inStmt = 0;
  unlockBtreeIfUnused(pBt);

  btreeIntegrity(p);
  sqlite3BtreeLeave(p);
  return rc;







>







39780
39781
39782
39783
39784
39785
39786
39787
39788
39789
39790
39791
39792
39793
39794
    assert( pBt->nTransaction>0 );
    pBt->nTransaction--;
    if( 0==pBt->nTransaction ){
      pBt->inTransaction = TRANS_NONE;
    }
  }

  btreeClearHasContent(pBt);
  p->inTrans = TRANS_NONE;
  pBt->inStmt = 0;
  unlockBtreeIfUnused(pBt);

  btreeIntegrity(p);
  sqlite3BtreeLeave(p);
  return rc;
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
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
39388
39389
39390
39391
39392
39393
39394
39395
39396
39397
39398
39399
39400
39401
39402
** Given the page number of an overflow page in the database (parameter
** ovfl), this function finds the page number of the next page in the 
** linked list of overflow pages. If possible, it uses the auto-vacuum
** pointer-map data instead of reading the content of page ovfl to do so. 
**
** If an error occurs an SQLite error code is returned. Otherwise:
**
** Unless pPgnoNext is NULL, the page number of the next overflow 
** page in the linked list is written to *pPgnoNext. If page ovfl
** is the last page in its linked list, *pPgnoNext is set to zero. 
**
** If ppPage is not NULL, *ppPage is set to the MemPage* handle
** for page ovfl. The underlying pager page may have been requested
** with the noContent flag set, so the page data accessable via

** this handle may not be trusted.

*/
static int getOverflowPage(
  BtShared *pBt, 
  Pgno ovfl,                   /* Overflow page */
  MemPage **ppPage,            /* OUT: MemPage handle */
  Pgno *pPgnoNext              /* OUT: Next overflow page number */
){
  Pgno next = 0;

  int rc = SQLITE_OK;

  assert( sqlite3_mutex_held(pBt->mutex) );
  /* One of these must not be NULL. Otherwise, why call this function? */
  assert(ppPage || pPgnoNext);

  /* If pPgnoNext is NULL, then this function is being called to obtain
  ** a MemPage* reference only. No page-data is required in this case.
  */
  if( !pPgnoNext ){
    return sqlite3BtreeGetPage(pBt, ovfl, ppPage, 1);
  }

#ifndef SQLITE_OMIT_AUTOVACUUM
  /* Try to find the next page in the overflow list using the
  ** autovacuum pointer-map pages. Guess that the next page in 
  ** the overflow list is page number (ovfl+1). If that guess turns 
  ** out to be wrong, fall back to loading the data of page 
  ** number ovfl to determine the next page number.
  */
  if( pBt->autoVacuum ){
    Pgno pgno;
    Pgno iGuess = ovfl+1;
    u8 eType;

    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
      iGuess++;
    }

    if( iGuess<=pagerPagecount(pBt) ){
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
      if( rc!=SQLITE_OK ){
        return rc;
      }
      if( eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
        next = iGuess;

      }
    }
  }
#endif

  if( next==0 || ppPage ){
    MemPage *pPage = 0;

    rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, next!=0);
    assert(rc==SQLITE_OK || pPage==0);
    if( next==0 && rc==SQLITE_OK ){
      next = get4byte(pPage->aData);
    }



    if( ppPage ){
      *ppPage = pPage;
    }else{
      releasePage(pPage);
    }
  }
  *pPgnoNext = next;

  return rc;
}

/*
** Copy data from a buffer to a page, or from a page to a buffer.
**
** pPayload is a pointer to data stored on database page pDbPage.
** If argument eOp is false, then nByte bytes of data are copied







|
|
|

|
|
|
>
|
>




|



>



<
<
<
<
<
<
|
<
<



















<
<
<
|

>





<
<
|
|




|
>
>
|
|
|
|
|
<
<
<
|







40188
40189
40190
40191
40192
40193
40194
40195
40196
40197
40198
40199
40200
40201
40202
40203
40204
40205
40206
40207
40208
40209
40210
40211
40212
40213
40214
40215
40216






40217


40218
40219
40220
40221
40222
40223
40224
40225
40226
40227
40228
40229
40230
40231
40232
40233
40234
40235
40236



40237
40238
40239
40240
40241
40242
40243
40244


40245
40246
40247
40248
40249
40250
40251
40252
40253
40254
40255
40256
40257
40258



40259
40260
40261
40262
40263
40264
40265
40266
** Given the page number of an overflow page in the database (parameter
** ovfl), this function finds the page number of the next page in the 
** linked list of overflow pages. If possible, it uses the auto-vacuum
** pointer-map data instead of reading the content of page ovfl to do so. 
**
** If an error occurs an SQLite error code is returned. Otherwise:
**
** The page number of the next overflow page in the linked list is 
** written to *pPgnoNext. If page ovfl is the last page in its linked 
** list, *pPgnoNext is set to zero. 
**
** If ppPage is not NULL, and a reference to the MemPage object corresponding
** to page number pOvfl was obtained, then *ppPage is set to point to that
** reference. It is the responsibility of the caller to call releasePage()
** on *ppPage to free the reference. In no reference was obtained (because
** the pointer-map was used to obtain the value for *pPgnoNext), then
** *ppPage is set to zero.
*/
static int getOverflowPage(
  BtShared *pBt, 
  Pgno ovfl,                   /* Overflow page */
  MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
  Pgno *pPgnoNext              /* OUT: Next overflow page number */
){
  Pgno next = 0;
  MemPage *pPage = 0;
  int rc = SQLITE_OK;

  assert( sqlite3_mutex_held(pBt->mutex) );






  assert(pPgnoNext);



#ifndef SQLITE_OMIT_AUTOVACUUM
  /* Try to find the next page in the overflow list using the
  ** autovacuum pointer-map pages. Guess that the next page in 
  ** the overflow list is page number (ovfl+1). If that guess turns 
  ** out to be wrong, fall back to loading the data of page 
  ** number ovfl to determine the next page number.
  */
  if( pBt->autoVacuum ){
    Pgno pgno;
    Pgno iGuess = ovfl+1;
    u8 eType;

    while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
      iGuess++;
    }

    if( iGuess<=pagerPagecount(pBt) ){
      rc = ptrmapGet(pBt, iGuess, &eType, &pgno);



      if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
        next = iGuess;
        rc = SQLITE_DONE;
      }
    }
  }
#endif



  if( rc==SQLITE_OK ){
    rc = sqlite3BtreeGetPage(pBt, ovfl, &pPage, 0);
    assert(rc==SQLITE_OK || pPage==0);
    if( next==0 && rc==SQLITE_OK ){
      next = get4byte(pPage->aData);
    }
  }

  *pPgnoNext = next;
  if( ppPage ){
    *ppPage = pPage;
  }else{
    releasePage(pPage);
  }



  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
}

/*
** Copy data from a buffer to a page, or from a page to a buffer.
**
** pPayload is a pointer to data stored on database page pDbPage.
** If argument eOp is false, then nByte bytes of data are copied
40497
40498
40499
40500
40501
40502
40503

40504
40505
40506
40507
40508
40509
40510
40511
40512
40513
40514
40515
40516
40517
40518
40519

40520
40521
40522
40523
40524
40525
40526
40527
40528
40529
40530
40531
40532
40533
40534
40535
40536
40537
40538




40539
40540
40541
40542
40543
40544
40545
          }
        }else{
          closest = 0;
        }

        iPage = get4byte(&aData[8+closest*4]);
        if( !searchList || iPage==nearby ){

          Pgno nPage;
          *pPgno = iPage;
          nPage = pagerPagecount(pBt);
          if( *pPgno>nPage ){
            /* Free page off the end of the file */
            rc = SQLITE_CORRUPT_BKPT;
            goto end_allocate_page;
          }
          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
                 ": %d more free pages\n",
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
          if( closest<k-1 ){
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
          }
          put4byte(&aData[4], k-1);
          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );

          rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, 1);
          if( rc==SQLITE_OK ){
            sqlite3PagerDontRollback((*ppPage)->pDbPage);
            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
            if( rc!=SQLITE_OK ){
              releasePage(*ppPage);
            }
          }
          searchList = 0;
        }
      }
      releasePage(pPrevTrunk);
      pPrevTrunk = 0;
    }while( searchList );
  }else{
    /* There are no pages on the freelist, so create a new page at the
    ** end of the file */
    int nPage = pagerPagecount(pBt);
    *pPgno = nPage + 1;





#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
      /* If *pPgno refers to a pointer-map page, allocate two new pages
      ** at the end of the file instead of one. The first allocated page
      ** becomes a new pointer-map page, the second is used by the caller.
      */







>
















>
|

<
















>
>
>
>







41361
41362
41363
41364
41365
41366
41367
41368
41369
41370
41371
41372
41373
41374
41375
41376
41377
41378
41379
41380
41381
41382
41383
41384
41385
41386
41387

41388
41389
41390
41391
41392
41393
41394
41395
41396
41397
41398
41399
41400
41401
41402
41403
41404
41405
41406
41407
41408
41409
41410
41411
41412
41413
41414
          }
        }else{
          closest = 0;
        }

        iPage = get4byte(&aData[8+closest*4]);
        if( !searchList || iPage==nearby ){
          int noContent;
          Pgno nPage;
          *pPgno = iPage;
          nPage = pagerPagecount(pBt);
          if( *pPgno>nPage ){
            /* Free page off the end of the file */
            rc = SQLITE_CORRUPT_BKPT;
            goto end_allocate_page;
          }
          TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
                 ": %d more free pages\n",
                 *pPgno, closest+1, k, pTrunk->pgno, n-1));
          if( closest<k-1 ){
            memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
          }
          put4byte(&aData[4], k-1);
          assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
          noContent = !btreeGetHasContent(pBt, *pPgno);
          rc = sqlite3BtreeGetPage(pBt, *pPgno, ppPage, noContent);
          if( rc==SQLITE_OK ){

            rc = sqlite3PagerWrite((*ppPage)->pDbPage);
            if( rc!=SQLITE_OK ){
              releasePage(*ppPage);
            }
          }
          searchList = 0;
        }
      }
      releasePage(pPrevTrunk);
      pPrevTrunk = 0;
    }while( searchList );
  }else{
    /* There are no pages on the freelist, so create a new page at the
    ** end of the file */
    int nPage = pagerPagecount(pBt);
    *pPgno = nPage + 1;

    if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
      (*pPgno)++;
    }

#ifndef SQLITE_OMIT_AUTOVACUUM
    if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
      /* If *pPgno refers to a pointer-map page, allocate two new pages
      ** at the end of the file instead of one. The first allocated page
      ** becomes a new pointer-map page, the second is used by the caller.
      */
40572
40573
40574
40575
40576
40577
40578
40579

40580
40581







40582
40583
40584


40585

40586

40587
40588
40589
40590

40591





40592

40593
40594
40595
40596
40597
40598
40599
40600
40601
40602

40603

40604

40605
40606
40607
40608
40609
40610
40611
40612
40613
40614
40615







40616
40617
40618
40619
40620
40621
40622
40623
40624
40625
40626
40627



40628
40629




40630

40631
40632
40633
40634
40635
40636
40637
40638
40639
40640
40641
40642
40643
40644
40645
40646
40647
40648
40649
40650
40651
40652
40653
40654
40655
40656
40657
40658
40659
40660
40661

40662

40663

40664
40665

40666























40667

40668

40669
40670
40671
40672
40673
40674
40675
40676
40677
    }
    (*ppPage)->isInit = 0;
  }
  return rc;
}

/*
** Add a page of the database file to the freelist.

**
** sqlite3PagerUnref() is NOT called for pPage.







*/
static int freePage(MemPage *pPage){
  BtShared *pBt = pPage->pBt;


  MemPage *pPage1 = pBt->pPage1;

  int rc, n, k;


  /* Prepare the page for freeing */
  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  assert( pPage->pgno>1 );

  pPage->isInit = 0;







  /* Increment the free page count on pPage1 */
  rc = sqlite3PagerWrite(pPage1->pDbPage);
  if( rc ) return rc;
  n = get4byte(&pPage1->aData[36]);
  put4byte(&pPage1->aData[36], n+1);

#ifdef SQLITE_SECURE_DELETE
  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
  ** always fully overwrite deleted information with zeros.
  */

  rc = sqlite3PagerWrite(pPage->pDbPage);

  if( rc ) return rc;

  memset(pPage->aData, 0, pPage->pBt->pageSize);
#endif

  /* If the database supports auto-vacuum, write an entry in the pointer-map
  ** to indicate that the page is free.
  */
  if( ISAUTOVACUUM ){
    rc = ptrmapPut(pBt, pPage->pgno, PTRMAP_FREEPAGE, 0);
    if( rc ) return rc;
  }








  if( n==0 ){
    /* This is the first free page */
    rc = sqlite3PagerWrite(pPage->pDbPage);
    if( rc ) return rc;
    memset(pPage->aData, 0, 8);
    put4byte(&pPage1->aData[32], pPage->pgno);
    TRACE(("FREE-PAGE: %d first\n", pPage->pgno));
  }else{
    /* Other free pages already exist.  Retrive the first trunk page
    ** of the freelist and find out how many leaves it has. */
    MemPage *pTrunk;
    rc = sqlite3BtreeGetPage(pBt, get4byte(&pPage1->aData[32]), &pTrunk, 0);



    if( rc ) return rc;
    k = get4byte(&pTrunk->aData[4]);




    if( k>=pBt->usableSize/4 - 8 ){

      /* The trunk is full.  Turn the page being freed into a new
      ** trunk page with no leaves.
      **
      ** Note that the trunk page is not really full until it contains
      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
      ** coded.  But due to a coding error in versions of SQLite prior to
      ** 3.6.0, databases with freelist trunk pages holding more than
      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
      ** to maintain backwards compatibility with older versions of SQLite,
      ** we will contain to restrict the number of entries to usableSize/4 - 8
      ** for now.  At some point in the future (once everyone has upgraded
      ** to 3.6.0 or later) we should consider fixing the conditional above
      ** to read "usableSize/4-2" instead of "usableSize/4-8".
      */
      rc = sqlite3PagerWrite(pPage->pDbPage);
      if( rc==SQLITE_OK ){
        put4byte(pPage->aData, pTrunk->pgno);
        put4byte(&pPage->aData[4], 0);
        put4byte(&pPage1->aData[32], pPage->pgno);
        TRACE(("FREE-PAGE: %d new trunk page replacing %d\n",
                pPage->pgno, pTrunk->pgno));
      }
    }else if( k<0 ){
      rc = SQLITE_CORRUPT;
    }else{
      /* Add the newly freed page as a leaf on the current trunk */
      rc = sqlite3PagerWrite(pTrunk->pDbPage);
      if( rc==SQLITE_OK ){
        put4byte(&pTrunk->aData[4], k+1);
        put4byte(&pTrunk->aData[8+k*4], pPage->pgno);
#ifndef SQLITE_SECURE_DELETE

        rc = sqlite3PagerDontWrite(pPage->pDbPage);

#endif

      }
      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));

    }























    releasePage(pTrunk);

  }

  return rc;
}

/*
** Free any overflow pages associated with the given Cell.
*/
static int clearCell(MemPage *pPage, unsigned char *pCell){
  BtShared *pBt = pPage->pBt;
  CellInfo info;







|
>

<
>
>
>
>
>
>
>

|
<
>
>
|
>
|
>

<
|
|
>
|
>
>
>
>
>
|
>


|
|
|





>
|
>
|
>







|
|


>
>
>
>
>
>
>
|
|
|
<
<
|
<
<
<
<
<
|
>
>
>
|
|
>
>
>
>
|
>
|
<












<
<
<
<
<
<
<
<
<
<
<
<


|
|

>
|
>

>


>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
|








41441
41442
41443
41444
41445
41446
41447
41448
41449
41450

41451
41452
41453
41454
41455
41456
41457
41458
41459

41460
41461
41462
41463
41464
41465
41466

41467
41468
41469
41470
41471
41472
41473
41474
41475
41476
41477
41478
41479
41480
41481
41482
41483
41484
41485
41486
41487
41488
41489
41490
41491
41492
41493
41494
41495
41496
41497
41498
41499
41500
41501
41502
41503
41504
41505
41506
41507
41508
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
41545
41546
41547
41548
41549
41550
41551
41552
41553
41554
41555
41556
41557
41558
41559
41560
41561
41562
41563
41564
41565
41566
41567
41568
41569
41570
41571
41572
41573
41574
41575
41576
41577
41578
41579
41580
41581
41582
41583
41584
41585
41586
41587
41588
41589
    }
    (*ppPage)->isInit = 0;
  }
  return rc;
}

/*
** This function is used to add page iPage to the database file free-list. 
** It is assumed that the page is not already a part of the free-list.
**

** The value passed as the second argument to this function is optional.
** If the caller happens to have a pointer to the MemPage object 
** corresponding to page iPage handy, it may pass it as the second value. 
** Otherwise, it may pass NULL.
**
** If a pointer to a MemPage object is passed as the second argument,
** its reference count is not altered by this function.
*/
static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){

  MemPage *pTrunk = 0;                /* Free-list trunk page */
  Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
  MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
  MemPage *pPage;                     /* Page being freed. May be NULL. */
  int rc;                             /* Return Code */
  int nFree;                          /* Initial number of pages on free-list */


  assert( sqlite3_mutex_held(pBt->mutex) );
  assert( iPage>1 );
  assert( !pMemPage || pMemPage->pgno==iPage );

  if( pMemPage ){
    pPage = pMemPage;
    sqlite3PagerRef(pPage->pDbPage);
  }else{
    pPage = btreePageLookup(pBt, iPage);
  }

  /* Increment the free page count on pPage1 */
  rc = sqlite3PagerWrite(pPage1->pDbPage);
  if( rc ) goto freepage_out;
  nFree = get4byte(&pPage1->aData[36]);
  put4byte(&pPage1->aData[36], nFree+1);

#ifdef SQLITE_SECURE_DELETE
  /* If the SQLITE_SECURE_DELETE compile-time option is enabled, then
  ** always fully overwrite deleted information with zeros.
  */
  if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
  ){
    goto freepage_out;
  }
  memset(pPage->aData, 0, pPage->pBt->pageSize);
#endif

  /* If the database supports auto-vacuum, write an entry in the pointer-map
  ** to indicate that the page is free.
  */
  if( ISAUTOVACUUM ){
    rc = ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0);
    if( rc ) goto freepage_out;
  }

  /* Now manipulate the actual database free-list structure. There are two
  ** possibilities. If the free-list is currently empty, or if the first
  ** trunk page in the free-list is full, then this page will become a
  ** new free-list trunk page. Otherwise, it will become a leaf of the
  ** first trunk page in the current free-list. This block tests if it
  ** is possible to add the page as a new free-list leaf.
  */
  if( nFree!=0 ){
    int nLeaf;                /* Initial number of leaf cells on trunk page */



    iTrunk = get4byte(&pPage1->aData[32]);





    rc = sqlite3BtreeGetPage(pBt, iTrunk, &pTrunk, 0);
    if( rc!=SQLITE_OK ){
      goto freepage_out;
    }

    nLeaf = get4byte(&pTrunk->aData[4]);
    if( nLeaf<0 ){
      rc = SQLITE_CORRUPT_BKPT;
      goto freepage_out;
    }
    if( nLeaf<pBt->usableSize/4 - 8 ){
      /* In this case there is room on the trunk page to insert the page
      ** being freed as a new leaf.

      **
      ** Note that the trunk page is not really full until it contains
      ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
      ** coded.  But due to a coding error in versions of SQLite prior to
      ** 3.6.0, databases with freelist trunk pages holding more than
      ** usableSize/4 - 8 entries will be reported as corrupt.  In order
      ** to maintain backwards compatibility with older versions of SQLite,
      ** we will contain to restrict the number of entries to usableSize/4 - 8
      ** for now.  At some point in the future (once everyone has upgraded
      ** to 3.6.0 or later) we should consider fixing the conditional above
      ** to read "usableSize/4-2" instead of "usableSize/4-8".
      */












      rc = sqlite3PagerWrite(pTrunk->pDbPage);
      if( rc==SQLITE_OK ){
        put4byte(&pTrunk->aData[4], nLeaf+1);
        put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
#ifndef SQLITE_SECURE_DELETE
        if( pPage ){
          sqlite3PagerDontWrite(pPage->pDbPage);
        }
#endif
        rc = btreeSetHasContent(pBt, iPage);
      }
      TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
      goto freepage_out;
    }
  }

  /* If control flows to this point, then it was not possible to add the
  ** the page being freed as a leaf page of the first trunk in the free-list.
  ** Possibly because the free-list is empty, or possibly because the 
  ** first trunk in the free-list is full. Either way, the page being freed
  ** will become the new first trunk page in the free-list.
  */
  if( (!pPage && (rc = sqlite3BtreeGetPage(pBt, iPage, &pPage, 0)))
   ||            (rc = sqlite3PagerWrite(pPage->pDbPage))
  ){
    goto freepage_out;
  }
  put4byte(pPage->aData, iTrunk);
  put4byte(&pPage->aData[4], 0);
  put4byte(&pPage1->aData[32], iPage);
  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));

freepage_out:
  if( pPage ){
    pPage->isInit = 0;
  }
  releasePage(pPage);
  releasePage(pTrunk);
  return rc;
}
static int freePage(MemPage *pPage){
  return freePage2(pPage->pBt, pPage, pPage->pgno);
}

/*
** Free any overflow pages associated with the given Cell.
*/
static int clearCell(MemPage *pPage, unsigned char *pCell){
  BtShared *pBt = pPage->pBt;
  CellInfo info;
40686
40687
40688
40689
40690
40691
40692

40693
40694
40695
40696
40697
40698
40699

40700

40701

40702

40703
40704
40705
40706
40707
40708
40709
    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
  }
  ovflPgno = get4byte(&pCell[info.iOverflow]);
  ovflPageSize = pBt->usableSize - 4;
  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  assert( ovflPgno==0 || nOvfl>0 );
  while( nOvfl-- ){

    MemPage *pOvfl;
    if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
      return SQLITE_CORRUPT_BKPT;
    }

    rc = getOverflowPage(pBt, ovflPgno, &pOvfl, (nOvfl==0)?0:&ovflPgno);
    if( rc ) return rc;

    rc = freePage(pOvfl);

    sqlite3PagerUnref(pOvfl->pDbPage);

    if( rc ) return rc;

  }
  return SQLITE_OK;
}

/*
** Create the byte sequence used to represent a cell on page pPage
** and write that byte sequence into pCell[].  Overflow pages are







>
|



|
|
|
>
|
>
|
>

>







41598
41599
41600
41601
41602
41603
41604
41605
41606
41607
41608
41609
41610
41611
41612
41613
41614
41615
41616
41617
41618
41619
41620
41621
41622
41623
41624
41625
41626
    return SQLITE_OK;  /* No overflow pages. Return without doing anything */
  }
  ovflPgno = get4byte(&pCell[info.iOverflow]);
  ovflPageSize = pBt->usableSize - 4;
  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  assert( ovflPgno==0 || nOvfl>0 );
  while( nOvfl-- ){
    Pgno iNext;
    MemPage *pOvfl = 0;
    if( ovflPgno==0 || ovflPgno>pagerPagecount(pBt) ){
      return SQLITE_CORRUPT_BKPT;
    }
    if( nOvfl ){
      rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
      if( rc ) return rc;
    }
    rc = freePage2(pBt, pOvfl, ovflPgno);
    if( pOvfl ){
      sqlite3PagerUnref(pOvfl->pDbPage);
    }
    if( rc ) return rc;
    ovflPgno = iNext;
  }
  return SQLITE_OK;
}

/*
** Create the byte sequence used to represent a cell on page pPage
** and write that byte sequence into pCell[].  Overflow pages are
40763
40764
40765
40766
40767
40768
40769

40770

40771
40772
40773
40774
40775
40776
40777
  /* Fill in the payload */
  nPayload = nData + nZero;
  if( pPage->intKey ){
    pSrc = pData;
    nSrc = nData;
    nData = 0;
  }else{ 

    /* TBD:  Perhaps raise SQLITE_CORRUPT if nKey is larger than 31 bits? */

    nPayload += (int)nKey;
    pSrc = pKey;
    nSrc = (int)nKey;
  }
  *pnSize = info.nSize;
  spaceLeft = info.nLocal;
  pPayload = &pCell[nHeader];







>
|
>







41680
41681
41682
41683
41684
41685
41686
41687
41688
41689
41690
41691
41692
41693
41694
41695
41696
  /* Fill in the payload */
  nPayload = nData + nZero;
  if( pPage->intKey ){
    pSrc = pData;
    nSrc = nData;
    nData = 0;
  }else{ 
    if( nKey>0x7fffffff || pKey==0 ){
      return SQLITE_CORRUPT;
    }
    nPayload += (int)nKey;
    pSrc = pKey;
    nSrc = (int)nKey;
  }
  *pnSize = info.nSize;
  spaceLeft = info.nLocal;
  pPayload = &pCell[nHeader];
41685
41686
41687
41688
41689
41690
41691
41692



41693
41694
41695
41696
41697
41698
41699
        ** cell consists of the integer key for the right-most cell of 
        ** the sibling-page assembled above only.
        */
        CellInfo info;
        j--;
        sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
        pCell = pTemp;
        fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);



        pTemp = 0;
      }else{
        pCell -= 4;
        /* Obscure case for non-leaf-data trees: If the cell at pCell was
        ** previously stored on a leaf node, and its reported size was 4
        ** bytes, then it may actually be smaller than this 
        ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of







|
>
>
>







42604
42605
42606
42607
42608
42609
42610
42611
42612
42613
42614
42615
42616
42617
42618
42619
42620
42621
        ** cell consists of the integer key for the right-most cell of 
        ** the sibling-page assembled above only.
        */
        CellInfo info;
        j--;
        sqlite3BtreeParseCellPtr(pNew, apCell[j], &info);
        pCell = pTemp;
        rc = fillInCell(pParent, pCell, 0, info.nKey, 0, 0, 0, &sz);
        if( rc!=SQLITE_OK ){
          goto balance_cleanup;
        }
        pTemp = 0;
      }else{
        pCell -= 4;
        /* Obscure case for non-leaf-data trees: If the cell at pCell was
        ** previously stored on a leaf node, and its reported size was 4
        ** bytes, then it may actually be smaller than this 
        ** (see sqlite3BtreeParseCellPtr(), 4 bytes is the minimum size of
42461
42462
42463
42464
42465
42466
42467
42468
42469
42470
42471
42472
42473
42474
42475
42476
42477
42478
42479
      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
      if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
        releasePage(pRoot);
        return rc;
      }
      assert( eType!=PTRMAP_ROOTPAGE );
      assert( eType!=PTRMAP_FREEPAGE );
      rc = sqlite3PagerWrite(pRoot->pDbPage);
      if( rc!=SQLITE_OK ){
        releasePage(pRoot);
        return rc;
      }
      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
      releasePage(pRoot);

      /* Obtain the page at pgnoRoot */
      if( rc!=SQLITE_OK ){
        return rc;
      }







<
<
<
<
<







43383
43384
43385
43386
43387
43388
43389





43390
43391
43392
43393
43394
43395
43396
      rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
      if( rc!=SQLITE_OK || eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
        releasePage(pRoot);
        return rc;
      }
      assert( eType!=PTRMAP_ROOTPAGE );
      assert( eType!=PTRMAP_FREEPAGE );





      rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
      releasePage(pRoot);

      /* Obtain the page at pgnoRoot */
      if( rc!=SQLITE_OK ){
        return rc;
      }
43326
43327
43328
43329
43330
43331
43332
43333
43334
43335
43336
43337
43338
43339
43340
43341
43342
43343
43344
43345
43346
43347
43348
43349
43350
** open so it is safe to access without the BtShared mutex.
*/
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.
**
** The pager directory name is invariant as long as the pager is
** open so it is safe to access without the BtShared mutex.
*/
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.
**
** The pager journal filename is invariant as long as the pager is
** open so it is safe to access without the BtShared mutex.







<
<
<
<
<
<
<
<
<
<
<







44243
44244
44245
44246
44247
44248
44249











44250
44251
44252
44253
44254
44255
44256
** open so it is safe to access without the BtShared mutex.
*/
SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  assert( p->pBt->pPager!=0 );
  return sqlite3PagerFilename(p->pBt->pPager);
}












/*
** Return the pathname of the journal file for this database. The return
** value of this routine is the same regardless of whether the journal file
** has been created or not.
**
** The pager journal filename is invariant as long as the pager is
** open so it is safe to access without the BtShared mutex.
43422
43423
43424
43425
43426
43427
43428
43429
43430
43431
43432
43433
43434
43435
43436
          ** represent what they do.  Write() really means "put this page in the
          ** rollback journal and mark it as dirty so that it will be written
          ** to the database file later."  DontWrite() undoes the second part of
          ** that and prevents the page from being written to the database. The
          ** page is still on the rollback journal, though.  And that is the 
          ** whole point of this block: to put pages on the rollback journal. 
          */
          rc = sqlite3PagerDontWrite(pDbPage);
        }
        sqlite3PagerUnref(pDbPage);
      }
    }

    /* Overwrite the data in page i of the target database */
    if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){







|







44328
44329
44330
44331
44332
44333
44334
44335
44336
44337
44338
44339
44340
44341
44342
          ** represent what they do.  Write() really means "put this page in the
          ** rollback journal and mark it as dirty so that it will be written
          ** to the database file later."  DontWrite() undoes the second part of
          ** that and prevents the page from being written to the database. The
          ** page is still on the rollback journal, though.  And that is the 
          ** whole point of this block: to put pages on the rollback journal. 
          */
          sqlite3PagerDontWrite(pDbPage);
        }
        sqlite3PagerUnref(pDbPage);
      }
    }

    /* Overwrite the data in page i of the target database */
    if( rc==SQLITE_OK && i!=iSkip && i<=nNewPage ){
43501
43502
43503
43504
43505
43506
43507




43508
43509
43510
43511
43512
43513
43514

    /* Commit phase one syncs the journal file associated with pTo 
    ** containing the original data. It does not sync the database file
    ** itself. After doing this it is safe to use OsTruncate() and other
    ** file APIs on the database file directly.
    */
    pBtTo->db = pTo->db;




    rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 1);
    if( iSize<iNow && rc==SQLITE_OK ){
      rc = sqlite3OsTruncate(pFile, iSize);
    }

    /* The loop that copied data from database pFrom to pTo did not
    ** populate the locking page of database pTo. If the page-size of







>
>
>
>







44407
44408
44409
44410
44411
44412
44413
44414
44415
44416
44417
44418
44419
44420
44421
44422
44423
44424

    /* Commit phase one syncs the journal file associated with pTo 
    ** containing the original data. It does not sync the database file
    ** itself. After doing this it is safe to use OsTruncate() and other
    ** file APIs on the database file directly.
    */
    pBtTo->db = pTo->db;
    if( nFromPageSize==nToPageSize ){
      sqlite3PagerTruncateImage(pBtTo->pPager, nFromPage);
      iNow = iSize;
    }
    rc = sqlite3PagerCommitPhaseOne(pBtTo->pPager, 0, 1);
    if( iSize<iNow && rc==SQLITE_OK ){
      rc = sqlite3OsTruncate(pFile, iSize);
    }

    /* The loop that copied data from database pFrom to pTo did not
    ** populate the locking page of database pTo. If the page-size of
43735
43736
43737
43738
43739
43740
43741
43742
43743
43744
43745
43746
43747
43748
43749
*************************************************************************
**
** This file contains code use to manipulate "Mem" structure.  A "Mem"
** stores a single value in the VDBE.  Mem is an opaque structure visible
** only within the VDBE.  Interface routines refer to a Mem using the
** name sqlite_value
**
** $Id: vdbemem.c,v 1.134 2009/01/05 22:30:39 drh Exp $
*/

/*
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
** P if required.
*/
#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)







|







44645
44646
44647
44648
44649
44650
44651
44652
44653
44654
44655
44656
44657
44658
44659
*************************************************************************
**
** This file contains code use to manipulate "Mem" structure.  A "Mem"
** stores a single value in the VDBE.  Mem is an opaque structure visible
** only within the VDBE.  Interface routines refer to a Mem using the
** name sqlite_value
**
** $Id: vdbemem.c,v 1.136 2009/02/03 15:39:01 drh Exp $
*/

/*
** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
** P if required.
*/
#define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
44587
44588
44589
44590
44591
44592
44593
44594
44595
44596
44597
44598
44599
44600
44601
44602
44603
44604
44605
44606
44607
44608
44609
44610
44611
44612
44613
44614
44615
44616
44617
44618
44619
44620
44621
44622
44623
44624
44625
44626
44627
44628
44629
44630
44631
44632
44633
44634
44635
44636
44637
44638
44639
44640
44641
44642
44643
44644
44645
44646
44647
44648
44649
    }
  }
  pMem->n = amt;

  return rc;
}

#if 0
/*
** Perform various checks on the memory cell pMem. An assert() will
** fail if pMem is internally inconsistent.
*/
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 */
    /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
    assert( (x & MEM_Short)==0 || pMem->z==pMem->zShort );
    assert( (x & MEM_Short)!=0 || pMem->z!=pMem->zShort );
    /* No destructor unless there is MEM_Dyn */
    assert( pMem->xDel==0 || (pMem->flags & MEM_Dyn)!=0 );

    if( (flags & MEM_Str) ){
      assert( pMem->enc==SQLITE_UTF8 || 
              pMem->enc==SQLITE_UTF16BE ||
              pMem->enc==SQLITE_UTF16LE 
      );
      /* If the string is UTF-8 encoded and nul terminated, then pMem->n
      ** must be the length of the string.  (Later:)  If the database file
      ** has been corrupted, '\000' characters might have been inserted
      ** into the middle of the string.  In that case, the sqlite3Strlen30()
      ** might be less.
      */
      if( pMem->enc==SQLITE_UTF8 && (flags & MEM_Term) ){ 
        assert( sqlite3Strlen30(pMem->z)<=pMem->n );
        assert( pMem->z[pMem->n]==0 );
      }
    }
  }else{
    /* Cannot define a string subtype for non-string objects */
    assert( (pMem->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
    assert( pMem->xDel==0 );
  }
  /* MEM_Null excludes all other types */
  assert( (pMem->flags&(MEM_Str|MEM_Int|MEM_Real|MEM_Blob))==0
          || (pMem->flags&MEM_Null)==0 );
  /* If the MEM is both real and integer, the values are equal */
  assert( (pMem->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) 
          || pMem->r==pMem->u.i );
}
#endif

/* This function is only available internally, it is not part of the
** external API. It works in a similar way to sqlite3_value_text(),
** except the data returned is in the encoding specified by the second
** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
** SQLITE_UTF8.
**
** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







45497
45498
45499
45500
45501
45502
45503

















































45504
45505
45506
45507
45508
45509
45510
    }
  }
  pMem->n = amt;

  return rc;
}


















































/* This function is only available internally, it is not part of the
** external API. It works in a similar way to sqlite3_value_text(),
** except the data returned is in the encoding specified by the second
** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
** SQLITE_UTF8.
**
** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
44822
44823
44824
44825
44826
44827
44828
44829
44830
44831
44832
44833
44834
44835
44836
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
**
** $Id: vdbeaux.c,v 1.430 2009/01/07 08:12:16 danielk1977 Exp $
*/



/*
** When debugging the code generator in a symbolic debugger, one can
** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed







|







45683
45684
45685
45686
45687
45688
45689
45690
45691
45692
45693
45694
45695
45696
45697
**
*************************************************************************
** This file contains code used for creating, destroying, and populating
** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
** to version 2.8.7, all this code was combined into the vdbe.c source file.
** But that file was getting too big so this subroutines were split out.
**
** $Id: vdbeaux.c,v 1.434 2009/01/20 17:06:27 danielk1977 Exp $
*/



/*
** When debugging the code generator in a symbolic debugger, one can
** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
45768
45769
45770
45771
45772
45773
45774
45775
45776
45777
45778
45779
45780
45781
45782
45783
45784
45785
45786
45787
45788
45789
45790
45791
45792
45793
45794
45795
45796
45797
45798
45799
45800
45801
45802
45803
45804
SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    const char *z = pOp->p4.z;
    while( 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.
*/
SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( sqlite3IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
    for(i=0; isspace((unsigned char)z[i]); i++){}
    for(j=0; z[i]; i++){
      if( isspace((unsigned char)z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
        z[j++] = z[i];
      }
    }







|



















|

|







46629
46630
46631
46632
46633
46634
46635
46636
46637
46638
46639
46640
46641
46642
46643
46644
46645
46646
46647
46648
46649
46650
46651
46652
46653
46654
46655
46656
46657
46658
46659
46660
46661
46662
46663
46664
46665
SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    const char *z = pOp->p4.z;
    while( sqlite3Isspace(*z) ) z++;
    printf("SQL: [%s]\n", z);
  }
}
#endif

#if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
/*
** Print an IOTRACE message showing SQL content.
*/
SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  int nOp = p->nOp;
  VdbeOp *pOp;
  if( sqlite3IoTrace==0 ) return;
  if( nOp<1 ) return;
  pOp = &p->aOp[0];
  if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
    int i, j;
    char z[1000];
    sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
    for(i=0; sqlite3Isspace(z[i]); i++){}
    for(j=0; z[i]; i++){
      if( sqlite3Isspace(z[i]) ){
        if( z[i-1]!=' ' ){
          z[j++] = ' ';
        }
      }else{
        z[j++] = z[i];
      }
    }
46193
46194
46195
46196
46197
46198
46199
46200
46201
46202
46203

46204
46205
46206
46207
46208
46209
46210
        }
      }
    }

    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
    ** flag is set this is not required.
    */
    zMainFile = sqlite3BtreeGetDirname(db->aDb[0].pBt);
    if( (needSync 
     && (0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL))
     && (rc=sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))!=SQLITE_OK) ){

      sqlite3OsCloseFree(pMaster);
      sqlite3OsDelete(pVfs, zMaster, 0);
      sqlite3DbFree(db, zMaster);
      return rc;
    }

    /* Sync all the db files involved in the transaction. The same call







<
|
|
|
>







47054
47055
47056
47057
47058
47059
47060

47061
47062
47063
47064
47065
47066
47067
47068
47069
47070
47071
        }
      }
    }

    /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
    ** flag is set this is not required.
    */

    if( needSync 
     && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
     && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
    ){
      sqlite3OsCloseFree(pMaster);
      sqlite3OsDelete(pVfs, zMaster, 0);
      sqlite3DbFree(db, zMaster);
      return rc;
    }

    /* Sync all the db files involved in the transaction. The same call
48707
48708
48709
48710
48711
48712
48713
48714
48715
48716
48717
48718
48719
48720
48721
**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.811 2009/01/14 00:55:10 drh Exp $
*/

/*
** The following global variable is incremented every time a cursor
** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
** procedures use this information to make sure that indices are
** working correctly.  This variable has no function other than to







|







49568
49569
49570
49571
49572
49573
49574
49575
49576
49577
49578
49579
49580
49581
49582
**
** Various scripts scan this source file in order to generate HTML
** documentation, headers files, or other derived files.  The formatting
** of the code in this file is, therefore, important.  See other comments
** in this file for details.  If in doubt, do not deviate from existing
** commenting and indentation practices when changing or adding code.
**
** $Id: vdbe.c,v 1.813 2009/02/01 00:29:57 drh Exp $
*/

/*
** The following global variable is incremented every time a cursor
** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
** procedures use this information to make sure that indices are
** working correctly.  This variable has no function other than to
52777
52778
52779
52780
52781
52782
52783
52784
52785
52786
52787
52788
52789
52790
52791
  pC->rowidIsValid = 0;
  break;
}

/* Opcode: IdxInsert P1 P2 P3 * *
**
** Register P2 holds a SQL index key made using the
** MakeIdxRec instructions.  This opcode writes that key
** into the index P1.  Data for the entry is nil.
**
** P3 is a flag that provides a hint to the b-tree layer that this
** insert is likely to be an append.
**
** This instruction only works for indices.  The equivalent instruction
** for tables is OP_Insert.







|







53638
53639
53640
53641
53642
53643
53644
53645
53646
53647
53648
53649
53650
53651
53652
  pC->rowidIsValid = 0;
  break;
}

/* Opcode: IdxInsert P1 P2 P3 * *
**
** Register P2 holds a SQL index key made using the
** MakeRecord instructions.  This opcode writes that key
** into the index P1.  Data for the entry is nil.
**
** P3 is a flag that provides a hint to the b-tree layer that this
** insert is likely to be an append.
**
** This instruction only works for indices.  The equivalent instruction
** for tables is OP_Insert.
52844
52845
52846
52847
52848
52849
52850
52851
52852
52853
52854
52855
52856
52857
52858

/* Opcode: IdxRowid P1 P2 * * *
**
** Write into register P2 an integer which is the last entry in the record at
** the end of the index key pointed to by cursor P1.  This integer should be
** the rowid of the table entry to which this index entry points.
**
** See also: Rowid, MakeIdxRec.
*/
case OP_IdxRowid: {              /* out2-prerelease */
  int i = pOp->p1;
  BtCursor *pCrsr;
  VdbeCursor *pC;

  assert( i>=0 && i<p->nCursor );







|







53705
53706
53707
53708
53709
53710
53711
53712
53713
53714
53715
53716
53717
53718
53719

/* Opcode: IdxRowid P1 P2 * * *
**
** Write into register P2 an integer which is the last entry in the record at
** the end of the index key pointed to by cursor P1.  This integer should be
** the rowid of the table entry to which this index entry points.
**
** See also: Rowid, MakeRecord.
*/
case OP_IdxRowid: {              /* out2-prerelease */
  int i = pOp->p1;
  BtCursor *pCrsr;
  VdbeCursor *pC;

  assert( i>=0 && i<p->nCursor );
54452
54453
54454
54455
54456
54457
54458
54459
54460
54461
54462
54463
54464
54465
54466
54467
54468
54469
54470
54471
54472
54473
54474
54475
54476
54477
54478
54479
54480
54481
54482
54483
54484
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** @(#) $Id: journal.c,v 1.8 2008/05/01 18:01:47 drh Exp $
*/

#ifdef SQLITE_ENABLE_ATOMIC_WRITE

/*
** This file implements a special kind of sqlite3_file object used
** by SQLite to create journal files if the atomic-write optimization
** is enabled.
**
** The distinctive characteristic of this sqlite3_file is that the
** actual on disk file is created lazily. When the file is created,
** the caller specifies a buffer size for an in-memory buffer to
** be used to service read() and write() requests. The actual file
** on disk is not created or populated until either:
**
**   1) The in-memory representation grows too large for the allocated 
**      buffer, or
**   2) The xSync() method is called.
*/



/*
** A JournalFile object is a subclass of sqlite3_file used by
** as an open file handle for journal files.







|

















|







55313
55314
55315
55316
55317
55318
55319
55320
55321
55322
55323
55324
55325
55326
55327
55328
55329
55330
55331
55332
55333
55334
55335
55336
55337
55338
55339
55340
55341
55342
55343
55344
55345
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** @(#) $Id: journal.c,v 1.9 2009/01/20 17:06:27 danielk1977 Exp $
*/

#ifdef SQLITE_ENABLE_ATOMIC_WRITE

/*
** This file implements a special kind of sqlite3_file object used
** by SQLite to create journal files if the atomic-write optimization
** is enabled.
**
** The distinctive characteristic of this sqlite3_file is that the
** actual on disk file is created lazily. When the file is created,
** the caller specifies a buffer size for an in-memory buffer to
** be used to service read() and write() requests. The actual file
** on disk is not created or populated until either:
**
**   1) The in-memory representation grows too large for the allocated 
**      buffer, or
**   2) The sqlite3JournalCreate() function is called.
*/



/*
** A JournalFile object is a subclass of sqlite3_file used by
** as an open file handle for journal files.
54536
54537
54538
54539
54540
54541
54542


54543
54544
54545
54546
54547
54548
54549
54550
54551
  int iAmt,              /* Number of bytes to read */
  sqlite_int64 iOfst     /* Begin reading at this offset */
){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);


  }else{
    assert( iAmt+iOfst<=p->iSize );
    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  }
  return rc;
}

/*
** Write data to the file.







>
>

<







55397
55398
55399
55400
55401
55402
55403
55404
55405
55406

55407
55408
55409
55410
55411
55412
55413
  int iAmt,              /* Number of bytes to read */
  sqlite_int64 iOfst     /* Begin reading at this offset */
){
  int rc = SQLITE_OK;
  JournalFile *p = (JournalFile *)pJfd;
  if( p->pReal ){
    rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  }else if( (iAmt+iOfst)>p->iSize ){
    rc = SQLITE_IOERR_SHORT_READ;
  }else{

    memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  }
  return rc;
}

/*
** Write data to the file.
56245
56246
56247
56248
56249
56250
56251
56252
56253
56254
56255
56256
56257
56258
56259
**    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: expr.c,v 1.409 2009/01/10 13:24:51 drh 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 







|







57107
57108
57109
57110
57111
57112
57113
57114
57115
57116
57117
57118
57119
57120
57121
**    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: expr.c,v 1.410 2009/01/20 16:53:40 danielk1977 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 
57683
57684
57685
57686
57687
57688
57689
57690
57691
57692
57693
57694
57695
57696
57697
**
** The z[] string will probably not be zero-terminated.  But the 
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
  assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
  assert( !z || !isdigit(z[n]) );
  UNUSED_PARAMETER(n);
  if( z ){
    double value;
    char *zV;
    sqlite3AtoF(z, &value);
    if( sqlite3IsNaN(value) ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);







|







58545
58546
58547
58548
58549
58550
58551
58552
58553
58554
58555
58556
58557
58558
58559
**
** The z[] string will probably not be zero-terminated.  But the 
** z[n] character is guaranteed to be something that does not look
** like the continuation of the number.
*/
static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
  assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
  assert( !z || !sqlite3Isdigit(z[n]) );
  UNUSED_PARAMETER(n);
  if( z ){
    double value;
    char *zV;
    sqlite3AtoF(z, &value);
    if( sqlite3IsNaN(value) ){
      sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
57717
57718
57719
57720
57721
57722
57723
57724
57725
57726
57727
57728
57729
57730
57731
  if( pExpr->flags & EP_IntValue ){
    int i = pExpr->iTable;
    if( negFlag ) i = -i;
    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  }else if( (z = (char*)pExpr->token.z)!=0 ){
    int i;
    int n = pExpr->token.n;
    assert( !isdigit(z[n]) );
    if( sqlite3GetInt32(z, &i) ){
      if( negFlag ) i = -i;
      sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
    }else if( sqlite3FitsIn64Bits(z, negFlag) ){
      i64 value;
      char *zV;
      sqlite3Atoi64(z, &value);







|







58579
58580
58581
58582
58583
58584
58585
58586
58587
58588
58589
58590
58591
58592
58593
  if( pExpr->flags & EP_IntValue ){
    int i = pExpr->iTable;
    if( negFlag ) i = -i;
    sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  }else if( (z = (char*)pExpr->token.z)!=0 ){
    int i;
    int n = pExpr->token.n;
    assert( !sqlite3Isdigit(z[n]) );
    if( sqlite3GetInt32(z, &i) ){
      if( negFlag ) i = -i;
      sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
    }else if( sqlite3FitsIn64Bits(z, negFlag) ){
      i64 value;
      char *zV;
      sqlite3Atoi64(z, &value);
59332
59333
59334
59335
59336
59337
59338
59339
59340
59341
59342
59343
59344
59345
59346
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
**
** $Id: alter.c,v 1.51 2008/12/10 19:26:22 drh Exp $
*/

/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE







|







60194
60195
60196
60197
60198
60199
60200
60201
60202
60203
60204
60205
60206
60207
60208
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
**
** $Id: alter.c,v 1.52 2009/01/20 16:53:40 danielk1977 Exp $
*/

/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#ifndef SQLITE_OMIT_ALTERTABLE
59831
59832
59833
59834
59835
59836
59837
59838
59839
59840
59841
59842
59843
59844
59845
    sqlite3ValueFree(pVal);
  }

  /* Modify the CREATE TABLE statement. */
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  if( zCol ){
    char *zEnd = &zCol[pColDef->n-1];
    while( (zEnd>zCol && *zEnd==';') || isspace(*(unsigned char *)zEnd) ){
      *zEnd-- = '\0';
    }
    sqlite3NestedParse(pParse, 
        "UPDATE \"%w\".%s SET "
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
        "WHERE type = 'table' AND name = %Q", 
      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,







|







60693
60694
60695
60696
60697
60698
60699
60700
60701
60702
60703
60704
60705
60706
60707
    sqlite3ValueFree(pVal);
  }

  /* Modify the CREATE TABLE statement. */
  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  if( zCol ){
    char *zEnd = &zCol[pColDef->n-1];
    while( (zEnd>zCol && *zEnd==';') || sqlite3Isspace(*zEnd) ){
      *zEnd-- = '\0';
    }
    sqlite3NestedParse(pParse, 
        "UPDATE \"%w\".%s SET "
          "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
        "WHERE type = 'table' AND name = %Q", 
      zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
61175
61176
61177
61178
61179
61180
61181
61182
61183
61184
61185
61186
61187
61188
61189
**     CREATE INDEX
**     DROP INDEX
**     creating ID lists
**     BEGIN TRANSACTION
**     COMMIT
**     ROLLBACK
**
** $Id: build.c,v 1.511 2008/12/30 06:24:58 danielk1977 Exp $
*/

/*
** This routine is called when a new SQL statement is beginning to
** be parsed.  Initialize the pParse structure as needed.
*/
SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){







|







62037
62038
62039
62040
62041
62042
62043
62044
62045
62046
62047
62048
62049
62050
62051
**     CREATE INDEX
**     DROP INDEX
**     creating ID lists
**     BEGIN TRANSACTION
**     COMMIT
**     ROLLBACK
**
** $Id: build.c,v 1.514 2009/02/03 15:50:34 drh Exp $
*/

/*
** This routine is called when a new SQL statement is beginning to
** be parsed.  Initialize the pParse structure as needed.
*/
SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
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
** quote characters as needed.
*/
static void identPut(char *z, int *pIdx, char *zSignedIdent){
  unsigned char *zIdent = (unsigned char*)zSignedIdent;
  int i, j, needQuote;
  i = *pIdx;
  for(j=0; zIdent[j]; j++){
    if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  }
  needQuote =  zIdent[j]!=0 || isdigit(zIdent[0])
                  || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  if( needQuote ) z[i++] = '"';
  for(j=0; zIdent[j]; j++){
    z[i++] = zIdent[j];
    if( zIdent[j]=='"' ) z[i++] = '"';
  }
  if( needQuote ) z[i++] = '"';
  z[i] = 0;
  *pIdx = i;
}

/*
** Generate a CREATE TABLE statement appropriate for the given
** table.  Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(sqlite3 *db, Table *p, int isTemp){
  int i, k, n;
  char *zStmt;
  char *zSep, *zSep2, *zEnd, *z;
  Column *pCol;
  n = 0;
  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
    n += identLength(pCol->zName);







|

|
















|







63352
63353
63354
63355
63356
63357
63358
63359
63360
63361
63362
63363
63364
63365
63366
63367
63368
63369
63370
63371
63372
63373
63374
63375
63376
63377
63378
63379
63380
63381
63382
63383
63384
63385
** quote characters as needed.
*/
static void identPut(char *z, int *pIdx, char *zSignedIdent){
  unsigned char *zIdent = (unsigned char*)zSignedIdent;
  int i, j, needQuote;
  i = *pIdx;
  for(j=0; zIdent[j]; j++){
    if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  }
  needQuote =  zIdent[j]!=0 || sqlite3Isdigit(zIdent[0])
                  || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  if( needQuote ) z[i++] = '"';
  for(j=0; zIdent[j]; j++){
    z[i++] = zIdent[j];
    if( zIdent[j]=='"' ) z[i++] = '"';
  }
  if( needQuote ) z[i++] = '"';
  z[i] = 0;
  *pIdx = i;
}

/*
** Generate a CREATE TABLE statement appropriate for the given
** table.  Memory to hold the text of the statement is obtained
** from sqliteMalloc() and must be freed by the calling function.
*/
static char *createTableStmt(sqlite3 *db, Table *p){
  int i, k, n;
  char *zStmt;
  char *zSep, *zSep2, *zEnd, *z;
  Column *pCol;
  n = 0;
  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
    n += identLength(pCol->zName);
62538
62539
62540
62541
62542
62543
62544
62545
62546
62547
62548
62549
62550
62551
62552
62553
  }
  n += 35 + 6*p->nCol;
  zStmt = sqlite3Malloc( n );
  if( zStmt==0 ){
    db->mallocFailed = 1;
    return 0;
  }
  sqlite3_snprintf(n, zStmt,
                  !OMIT_TEMPDB&&isTemp ? "CREATE TEMP TABLE ":"CREATE TABLE ");
  k = sqlite3Strlen30(zStmt);
  identPut(zStmt, &k, p->zName);
  zStmt[k++] = '(';
  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
    sqlite3_snprintf(n-k, &zStmt[k], zSep);
    k += sqlite3Strlen30(&zStmt[k]);
    zSep = zSep2;







|
<







63400
63401
63402
63403
63404
63405
63406
63407

63408
63409
63410
63411
63412
63413
63414
  }
  n += 35 + 6*p->nCol;
  zStmt = sqlite3Malloc( n );
  if( zStmt==0 ){
    db->mallocFailed = 1;
    return 0;
  }
  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");

  k = sqlite3Strlen30(zStmt);
  identPut(zStmt, &k, p->zName);
  zStmt[k++] = '(';
  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
    sqlite3_snprintf(n-k, &zStmt[k], zSep);
    k += sqlite3Strlen30(&zStmt[k]);
    zSep = zSep2;
62704
62705
62706
62707
62708
62709
62710
62711
62712
62713
62714
62715
62716
62717
62718
        pSelTab->aCol = 0;
        sqlite3DeleteTable(pSelTab);
      }
    }

    /* Compute the complete text of the CREATE statement */
    if( pSelect ){
      zStmt = createTableStmt(db, p, p->pSchema==db->aDb[1].pSchema);
    }else{
      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
      zStmt = sqlite3MPrintf(db, 
          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
      );
    }








|







63565
63566
63567
63568
63569
63570
63571
63572
63573
63574
63575
63576
63577
63578
63579
        pSelTab->aCol = 0;
        sqlite3DeleteTable(pSelTab);
      }
    }

    /* Compute the complete text of the CREATE statement */
    if( pSelect ){
      zStmt = createTableStmt(db, p);
    }else{
      n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
      zStmt = sqlite3MPrintf(db, 
          "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
      );
    }

62863
62864
62865
62866
62867
62868
62869
62870
62871
62872
62873
62874
62875
62876
62877
  sEnd = pParse->sLastToken;
  if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
    sEnd.z += sEnd.n;
  }
  sEnd.n = 0;
  n = (int)(sEnd.z - pBegin->z);
  z = (const unsigned char*)pBegin->z;
  while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
  sEnd.z = &z[n-1];
  sEnd.n = 1;

  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  sqlite3EndTable(pParse, 0, &sEnd, 0);
  return;
}







|







63724
63725
63726
63727
63728
63729
63730
63731
63732
63733
63734
63735
63736
63737
63738
  sEnd = pParse->sLastToken;
  if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
    sEnd.z += sEnd.n;
  }
  sEnd.n = 0;
  n = (int)(sEnd.z - pBegin->z);
  z = (const unsigned char*)pBegin->z;
  while( n>0 && (z[n-1]==';' || sqlite3Isspace(z[n-1])) ){ n--; }
  sEnd.z = &z[n-1];
  sEnd.n = 1;

  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  sqlite3EndTable(pParse, 0, &sEnd, 0);
  return;
}
64774
64775
64776
64777
64778
64779
64780
64781
64782
64783
64784
64785
64786
64787
64788
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
**
** $Id: callback.c,v 1.34 2008/12/10 21:19:57 drh 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







|







65635
65636
65637
65638
65639
65640
65641
65642
65643
65644
65645
65646
65647
65648
65649
**    May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains functions used to access the internal hash tables
** of user defined functions and collation sequences.
**
** $Id: callback.c,v 1.35 2009/01/31 22:28:49 drh 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
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

/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 1 and 6, as follows:
**

** 1: A variable arguments function that prefers UTF-8 when a UTF-16
**    encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
**    requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality(FuncDef *p, int nArg, u8 enc){
  int match = 0;
  if( p->nArg==-1 || p->nArg==nArg || nArg==-1 ){


    match = 1;
    if( p->nArg==nArg || nArg==-1 ){
      match = 4;
    }
    if( enc==p->iPrefEnc ){
      match += 2;
    }







|

>














|
>
>







65849
65850
65851
65852
65853
65854
65855
65856
65857
65858
65859
65860
65861
65862
65863
65864
65865
65866
65867
65868
65869
65870
65871
65872
65873
65874
65875
65876
65877
65878
65879
65880
65881
65882

/* During the search for the best function definition, this procedure
** is called to test how well the function passed as the first argument
** matches the request for a function with nArg arguments in a system
** that uses encoding enc. The value returned indicates how well the
** request is matched. A higher value indicates a better match.
**
** The returned value is always between 0 and 6, as follows:
**
** 0: Not a match, or if nArg<0 and the function is has no implementation.
** 1: A variable arguments function that prefers UTF-8 when a UTF-16
**    encoding is requested, or vice versa.
** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
**    requested, or vice versa.
** 3: A variable arguments function using the same text encoding.
** 4: A function with the exact number of arguments requested that
**    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
** 5: A function with the exact number of arguments requested that
**    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
** 6: An exact match.
**
*/
static int matchQuality(FuncDef *p, int nArg, u8 enc){
  int match = 0;
  if( p->nArg==-1 || p->nArg==nArg 
   || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
  ){
    match = 1;
    if( p->nArg==nArg || nArg==-1 ){
      match = 4;
    }
    if( enc==p->iPrefEnc ){
      match += 2;
    }
65862
65863
65864
65865
65866
65867
65868
65869
65870
65871
65872
65873
65874
65875
65876
** 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: func.c,v 1.209 2008/12/10 23:04:13 drh Exp $
*/

/*
** Return the collating function associated with a function.
*/
static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  return context->pColl;







|







66726
66727
66728
66729
66730
66731
66732
66733
66734
66735
66736
66737
66738
66739
66740
** 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: func.c,v 1.221 2009/02/03 15:50:34 drh Exp $
*/

/*
** Return the collating function associated with a function.
*/
static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  return context->pColl;
65885
65886
65887
65888
65889
65890
65891
65892
65893
65894
65895
65896
65897
65898
65899
65900
65901

65902
65903
65904
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
  sqlite3_value **argv
){
  int i;
  int mask;    /* 0 for min() or 0xffffffff for max() */
  int iBest;
  CollSeq *pColl;

  if( argc==0 ) return;
  mask = sqlite3_user_data(context)==0 ? 0 : -1;
  pColl = sqlite3GetFuncCollSeq(context);
  assert( pColl );
  assert( mask==-1 || mask==0 );
  iBest = 0;
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  for(i=1; i<argc; i++){
    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){

      iBest = i;
    }
  }
  sqlite3_result_value(context, argv[iBest]);
}

/*
** Return the type of the argument.
*/
static void typeofFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  const char *z = 0;
  UNUSED_PARAMETER(NotUsed);
  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_NULL:    z = "null";    break;
    case SQLITE_INTEGER: z = "integer"; break;
    case SQLITE_TEXT:    z = "text";    break;
    case SQLITE_FLOAT:   z = "real";    break;
    case SQLITE_BLOB:    z = "blob";    break;

  }
  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
}


/*
** Implementation of the length() function







|









>

















<




>







66749
66750
66751
66752
66753
66754
66755
66756
66757
66758
66759
66760
66761
66762
66763
66764
66765
66766
66767
66768
66769
66770
66771
66772
66773
66774
66775
66776
66777
66778
66779
66780
66781
66782
66783

66784
66785
66786
66787
66788
66789
66790
66791
66792
66793
66794
66795
  sqlite3_value **argv
){
  int i;
  int mask;    /* 0 for min() or 0xffffffff for max() */
  int iBest;
  CollSeq *pColl;

  assert( argc>1 );
  mask = sqlite3_user_data(context)==0 ? 0 : -1;
  pColl = sqlite3GetFuncCollSeq(context);
  assert( pColl );
  assert( mask==-1 || mask==0 );
  iBest = 0;
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  for(i=1; i<argc; i++){
    if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
    if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
      testcase( mask==0 );
      iBest = i;
    }
  }
  sqlite3_result_value(context, argv[iBest]);
}

/*
** Return the type of the argument.
*/
static void typeofFunc(
  sqlite3_context *context,
  int NotUsed,
  sqlite3_value **argv
){
  const char *z = 0;
  UNUSED_PARAMETER(NotUsed);
  switch( sqlite3_value_type(argv[0]) ){

    case SQLITE_INTEGER: z = "integer"; break;
    case SQLITE_TEXT:    z = "text";    break;
    case SQLITE_FLOAT:   z = "real";    break;
    case SQLITE_BLOB:    z = "blob";    break;
    default:             z = "null";    break;
  }
  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
}


/*
** Implementation of the length() function
66011
66012
66013
66014
66015
66016
66017

66018
66019





66020
66021
66022
66023
66024
66025
66026
66027
66028
66029
66030
66031
66032
66033
66034
66035
66036




66037
66038
66039
66040
66041
66042
66043

66044
66045
66046
66047


66048








66049
66050

66051
66052
66053
66054
66055
66056
66057
66058
66059
66060
66061
66062
66063
66064
66065
66066
66067
66068
66069
  sqlite3_value **argv
){
  const unsigned char *z;
  const unsigned char *z2;
  int len;
  int p0type;
  i64 p1, p2;


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





  p0type = sqlite3_value_type(argv[0]);
  if( p0type==SQLITE_BLOB ){
    len = sqlite3_value_bytes(argv[0]);
    z = sqlite3_value_blob(argv[0]);
    if( z==0 ) return;
    assert( len==sqlite3_value_bytes(argv[0]) );
  }else{
    z = sqlite3_value_text(argv[0]);
    if( z==0 ) return;
    len = 0;
    for(z2=z; *z2; len++){
      SQLITE_SKIP_UTF8(z2);
    }
  }
  p1 = sqlite3_value_int(argv[1]);
  if( argc==3 ){
    p2 = sqlite3_value_int(argv[2]);




  }else{
    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  }
  if( p1<0 ){
    p1 += len;
    if( p1<0 ){
      p2 += p1;

      p1 = 0;
    }
  }else if( p1>0 ){
    p1--;


  }








  if( p1+p2>len ){
    p2 = len-p1;

  }
  if( p0type!=SQLITE_BLOB ){
    while( *z && p1 ){
      SQLITE_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE_SKIP_UTF8(z2);
    }
    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  }else{
    if( p2<0 ) p2 = 0;
    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  }
}

/*
** Implementation of the round() function
*/







>


>
>
>
>
>

















>
>
>
>







>




>
>

>
>
>
>
>
>
>
>


>











<







66876
66877
66878
66879
66880
66881
66882
66883
66884
66885
66886
66887
66888
66889
66890
66891
66892
66893
66894
66895
66896
66897
66898
66899
66900
66901
66902
66903
66904
66905
66906
66907
66908
66909
66910
66911
66912
66913
66914
66915
66916
66917
66918
66919
66920
66921
66922
66923
66924
66925
66926
66927
66928
66929
66930
66931
66932
66933
66934
66935
66936
66937
66938
66939
66940
66941
66942
66943
66944
66945
66946
66947
66948

66949
66950
66951
66952
66953
66954
66955
  sqlite3_value **argv
){
  const unsigned char *z;
  const unsigned char *z2;
  int len;
  int p0type;
  i64 p1, p2;
  int negP2 = 0;

  assert( argc==3 || argc==2 );
  if( sqlite3_value_type(argv[1])==SQLITE_NULL
   || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  ){
    return;
  }
  p0type = sqlite3_value_type(argv[0]);
  if( p0type==SQLITE_BLOB ){
    len = sqlite3_value_bytes(argv[0]);
    z = sqlite3_value_blob(argv[0]);
    if( z==0 ) return;
    assert( len==sqlite3_value_bytes(argv[0]) );
  }else{
    z = sqlite3_value_text(argv[0]);
    if( z==0 ) return;
    len = 0;
    for(z2=z; *z2; len++){
      SQLITE_SKIP_UTF8(z2);
    }
  }
  p1 = sqlite3_value_int(argv[1]);
  if( argc==3 ){
    p2 = sqlite3_value_int(argv[2]);
    if( p2<0 ){
      p2 = -p2;
      negP2 = 1;
    }
  }else{
    p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  }
  if( p1<0 ){
    p1 += len;
    if( p1<0 ){
      p2 += p1;
      if( p2<0 ) p2 = 0;
      p1 = 0;
    }
  }else if( p1>0 ){
    p1--;
  }else if( p2>0 ){
    p2--;
  }
  if( negP2 ){
    p1 -= p2;
    if( p1<0 ){
      p2 += p1;
      p1 = 0;
    }
  }
  assert( p1>=0 && p2>=0 );
  if( p1+p2>len ){
    p2 = len-p1;
    if( p2<0 ) p2 = 0;
  }
  if( p0type!=SQLITE_BLOB ){
    while( *z && p1 ){
      SQLITE_SKIP_UTF8(z);
      p1--;
    }
    for(z2=z; *z2 && p2; p2--){
      SQLITE_SKIP_UTF8(z2);
    }
    sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  }else{

    sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  }
}

/*
** Implementation of the round() function
*/
66107
66108
66109
66110
66111
66112
66113
66114
66115
66116
66117
66118
66119
66120
66121
66122
66123
66124
66125
66126
66127
66128
66129
66130
66131
66132
66133
66134
66135
66136
66137
66138
66139
66140
66141
66142
66143
66144
66145
66146
66147
66148
66149
66150
66151
66152
66153
/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  char *z1;
  const char *z2;
  int i, n;
  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = (char)toupper(z1[i]);
      }
      sqlite3_result_text(context, z1, -1, sqlite3_free);
    }
  }
}
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  char *z1;
  const char *z2;
  int i, n;
  if( argc<1 || SQLITE_NULL==sqlite3_value_type(argv[0]) ) return;
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = (char)tolower(z1[i]);
      }
      sqlite3_result_text(context, z1, -1, sqlite3_free);
    }
  }
}

/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
** All three do the same thing.  They return the first non-NULL







|









|






|


|









|

|







66993
66994
66995
66996
66997
66998
66999
67000
67001
67002
67003
67004
67005
67006
67007
67008
67009
67010
67011
67012
67013
67014
67015
67016
67017
67018
67019
67020
67021
67022
67023
67024
67025
67026
67027
67028
67029
67030
67031
67032
67033
67034
67035
67036
67037
67038
67039
/*
** Implementation of the upper() and lower() SQL functions.
*/
static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  char *z1;
  const char *z2;
  int i, n;
  UNUSED_PARAMETER(argc);
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = (char)sqlite3Toupper(z1[i]);
      }
      sqlite3_result_text(context, z1, -1, sqlite3_free);
    }
  }
}
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  u8 *z1;
  const char *z2;
  int i, n;
  UNUSED_PARAMETER(argc);
  z2 = (char*)sqlite3_value_text(argv[0]);
  n = sqlite3_value_bytes(argv[0]);
  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  assert( z2==(char*)sqlite3_value_text(argv[0]) );
  if( z2 ){
    z1 = contextMalloc(context, ((i64)n)+1);
    if( z1 ){
      memcpy(z1, z2, n+1);
      for(i=0; z1[i]; i++){
        z1[i] = sqlite3Tolower(z1[i]);
      }
      sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
    }
  }
}

/*
** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
** All three do the same thing.  They return the first non-NULL
66528
66529
66530
66531
66532
66533
66534
66535

66536
66537
66538
66539
66540
66541
66542
66543
66544
66545
66546
66547
** Implementation of the QUOTE() function.  This function takes a single
** argument.  If the argument is numeric, the return value is the same as
** the argument.  If the argument is NULL, the return value is the string
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  if( argc<1 ) return;

  switch( sqlite3_value_type(argv[0]) ){
    case SQLITE_NULL: {
      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
      break;
    }
    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      sqlite3_result_value(context, argv[0]);
      break;
    }
    case SQLITE_BLOB: {
      char *zText = 0;







|
>

<
<
<
<







67414
67415
67416
67417
67418
67419
67420
67421
67422
67423




67424
67425
67426
67427
67428
67429
67430
** Implementation of the QUOTE() function.  This function takes a single
** argument.  If the argument is numeric, the return value is the same as
** the argument.  If the argument is NULL, the return value is the string
** "NULL".  Otherwise, the argument is enclosed in single quotes with
** single-quote escapes.
*/
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  assert( argc==1 );
  UNUSED_PARAMETER(argc);
  switch( sqlite3_value_type(argv[0]) ){




    case SQLITE_INTEGER:
    case SQLITE_FLOAT: {
      sqlite3_result_value(context, argv[0]);
      break;
    }
    case SQLITE_BLOB: {
      char *zText = 0;
66581
66582
66583
66584
66585
66586
66587






66588
66589
66590
66591
66592
66593
66594
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite3_result_text(context, z, j, sqlite3_free);
      }






    }
  }
}

/*
** The hex() function.  Interpret the argument as a blob.  Return
** a hexadecimal rendering as text.







>
>
>
>
>
>







67464
67465
67466
67467
67468
67469
67470
67471
67472
67473
67474
67475
67476
67477
67478
67479
67480
67481
67482
67483
            z[j++] = '\'';
          }
        }
        z[j++] = '\'';
        z[j] = 0;
        sqlite3_result_text(context, z, j, sqlite3_free);
      }
      break;
    }
    default: {
      assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
      sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
      break;
    }
  }
}

/*
** The hex() function.  Interpret the argument as a blob.  Return
** a hexadecimal rendering as text.
66662
66663
66664
66665
66666
66667
66668
66669









66670
66671
66672
66673
66674
66675
66676
  assert( argc==3 );
  UNUSED_PARAMETER(argc);
  zStr = sqlite3_value_text(argv[0]);
  if( zStr==0 ) return;
  nStr = sqlite3_value_bytes(argv[0]);
  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
  zPattern = sqlite3_value_text(argv[1]);
  if( zPattern==0 || zPattern[0]==0 ) return;









  nPattern = sqlite3_value_bytes(argv[1]);
  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
  zRep = sqlite3_value_text(argv[2]);
  if( zRep==0 ) return;
  nRep = sqlite3_value_bytes(argv[2]);
  assert( zRep==sqlite3_value_text(argv[2]) );
  nOut = nStr + 1;







|
>
>
>
>
>
>
>
>
>







67551
67552
67553
67554
67555
67556
67557
67558
67559
67560
67561
67562
67563
67564
67565
67566
67567
67568
67569
67570
67571
67572
67573
67574
  assert( argc==3 );
  UNUSED_PARAMETER(argc);
  zStr = sqlite3_value_text(argv[0]);
  if( zStr==0 ) return;
  nStr = sqlite3_value_bytes(argv[0]);
  assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
  zPattern = sqlite3_value_text(argv[1]);
  if( zPattern==0 ){
    assert( sqlite3_value_type(argv[1])==SQLITE_NULL
            || sqlite3_context_db_handle(context)->mallocFailed );
    return;
  }
  if( zPattern[0]==0 ){
    assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
    sqlite3_result_value(context, argv[0]);
    return;
  }
  nPattern = sqlite3_value_bytes(argv[1]);
  assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
  zRep = sqlite3_value_text(argv[2]);
  if( zRep==0 ) return;
  nRep = sqlite3_value_bytes(argv[2]);
  assert( zRep==sqlite3_value_text(argv[2]) );
  nOut = nStr + 1;
66818
66819
66820
66821
66822
66823
66824
66825
66826
66827
66828
66829
66830
66831
66832
66833
66834
66835
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  };
  assert( argc==1 );
  zIn = (u8*)sqlite3_value_text(argv[0]);
  if( zIn==0 ) zIn = (u8*)"";
  for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
  if( zIn[i] ){
    u8 prevcode = iCode[zIn[i]&0x7f];
    zResult[0] = toupper(zIn[i]);
    for(j=1; j<4 && zIn[i]; i++){
      int code = iCode[zIn[i]&0x7f];
      if( code>0 ){
        if( code!=prevcode ){
          prevcode = code;
          zResult[j++] = code + '0';
        }







|


|







67716
67717
67718
67719
67720
67721
67722
67723
67724
67725
67726
67727
67728
67729
67730
67731
67732
67733
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
    0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
    1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  };
  assert( argc==1 );
  zIn = (u8*)sqlite3_value_text(argv[0]);
  if( zIn==0 ) zIn = (u8*)"";
  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  if( zIn[i] ){
    u8 prevcode = iCode[zIn[i]&0x7f];
    zResult[0] = sqlite3Toupper(zIn[i]);
    for(j=1; j<4 && zIn[i]; i++){
      int code = iCode[zIn[i]&0x7f];
      if( code>0 ){
        if( code!=prevcode ){
          prevcode = code;
          zResult[j++] = code + '0';
        }
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
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zVal;
  StrAccum *pAccum;
  const char *zSep;
  int nVal, nSep, i;

  if( argc==0 || sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));

  if( pAccum ){
    sqlite3 *db = sqlite3_context_db_handle(context);
    pAccum->useMalloc = 1;
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
    if( pAccum->nChar ){
      if( argc>1 ){
        zSep = (char*)sqlite3_value_text(argv[argc-1]);
        nSep = sqlite3_value_bytes(argv[argc-1]);
      }else{
        zSep = ",";
        nSep = 1;
      }
      sqlite3StrAccumAppend(pAccum, zSep, nSep);
    }
    i = 0;
    do{
      zVal = (char*)sqlite3_value_text(argv[i]);
      nVal = sqlite3_value_bytes(argv[i]);
      sqlite3StrAccumAppend(pAccum, zVal, nVal);
      i++;
    }while( i<argc-1 );
  }
}
static void groupConcatFinalize(sqlite3_context *context){
  StrAccum *pAccum;
  pAccum = sqlite3_aggregate_context(context, 0);
  if( pAccum ){
    if( pAccum->tooBig ){







|
>
|







|
|
|






<
<
|
|
|
<
<







67924
67925
67926
67927
67928
67929
67930
67931
67932
67933
67934
67935
67936
67937
67938
67939
67940
67941
67942
67943
67944
67945
67946
67947
67948
67949


67950
67951
67952


67953
67954
67955
67956
67957
67958
67959
  sqlite3_context *context,
  int argc,
  sqlite3_value **argv
){
  const char *zVal;
  StrAccum *pAccum;
  const char *zSep;
  int nVal, nSep;
  assert( argc==1 || argc==2 );
  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));

  if( pAccum ){
    sqlite3 *db = sqlite3_context_db_handle(context);
    pAccum->useMalloc = 1;
    pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
    if( pAccum->nChar ){
      if( argc==2 ){
        zSep = (char*)sqlite3_value_text(argv[1]);
        nSep = sqlite3_value_bytes(argv[1]);
      }else{
        zSep = ",";
        nSep = 1;
      }
      sqlite3StrAccumAppend(pAccum, zSep, nSep);
    }


    zVal = (char*)sqlite3_value_text(argv[0]);
    nVal = sqlite3_value_bytes(argv[0]);
    sqlite3StrAccumAppend(pAccum, zVal, nVal);


  }
}
static void groupConcatFinalize(sqlite3_context *context){
  StrAccum *pAccum;
  pAccum = sqlite3_aggregate_context(context, 0);
  if( pAccum ){
    if( pAccum->tooBig ){
67198
67199
67200
67201
67202
67203
67204
67205
67206
67207
67208
67209
67210
67211
67212
    FUNCTION(upper,              1, 0, 0, upperFunc        ),
    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
    FUNCTION(coalesce,           1, 0, 0, 0                ),
    FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
    FUNCTION(coalesce,           0, 0, 0, 0                ),
    FUNCTION(hex,                1, 0, 0, hexFunc          ),
    FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
    FUNCTION(random,            -1, 0, 0, randomFunc       ),
    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
    FUNCTION(changes,            0, 0, 0, changes          ),
    FUNCTION(total_changes,      0, 0, 0, total_changes    ),







|







68093
68094
68095
68096
68097
68098
68099
68100
68101
68102
68103
68104
68105
68106
68107
    FUNCTION(upper,              1, 0, 0, upperFunc        ),
    FUNCTION(lower,              1, 0, 0, lowerFunc        ),
    FUNCTION(coalesce,           1, 0, 0, 0                ),
    FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ),
    FUNCTION(coalesce,           0, 0, 0, 0                ),
    FUNCTION(hex,                1, 0, 0, hexFunc          ),
    FUNCTION(ifnull,             2, 0, 1, ifnullFunc       ),
    FUNCTION(random,             0, 0, 0, randomFunc       ),
    FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
    FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
    FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
    FUNCTION(quote,              1, 0, 0, quoteFunc        ),
    FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
    FUNCTION(changes,            0, 0, 0, changes          ),
    FUNCTION(total_changes,      0, 0, 0, total_changes    ),
67220
67221
67222
67223
67224
67225
67226
67227

67228
67229
67230
67231
67232
67233
67234
    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
  #endif
    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
    AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
    AGGREGATE(group_concat,     -1, 0, 0, groupConcatStep, groupConcatFinalize),

  
    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #ifdef SQLITE_CASE_SENSITIVE_LIKE
    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #else
    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),







|
>







68115
68116
68117
68118
68119
68120
68121
68122
68123
68124
68125
68126
68127
68128
68129
68130
    FUNCTION(load_extension,     2, 0, 0, loadExt          ),
  #endif
    AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
    AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
    AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
    AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ),
    AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
    AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
    AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
  
    LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #ifdef SQLITE_CASE_SENSITIVE_LIKE
    LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
    LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  #else
    LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
68999
69000
69001
69002
69003
69004
69005
69006
69007
69008
69009
69010
69011
69012
69013
**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: legacy.c,v 1.30 2008/12/10 19:26:24 drh 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.







|







69895
69896
69897
69898
69899
69900
69901
69902
69903
69904
69905
69906
69907
69908
69909
**
*************************************************************************
** Main file for the SQLite library.  The routines in this file
** implement the programmer interface to the library.  Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
**
** $Id: legacy.c,v 1.31 2009/01/20 16:53:40 danielk1977 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.
69098
69099
69100
69101
69102
69103
69104
69105
69106
69107
69108
69109
69110
69111
69112

      if( rc!=SQLITE_ROW ){
        rc = sqlite3_finalize(pStmt);
        pStmt = 0;
        if( rc!=SQLITE_SCHEMA ){
          nRetry = 0;
          zSql = zLeftover;
          while( isspace((unsigned char)zSql[0]) ) zSql++;
        }
        break;
      }
    }

    sqlite3DbFree(db, azCols);
    azCols = 0;







|







69994
69995
69996
69997
69998
69999
70000
70001
70002
70003
70004
70005
70006
70007
70008

      if( rc!=SQLITE_ROW ){
        rc = sqlite3_finalize(pStmt);
        pStmt = 0;
        if( rc!=SQLITE_SCHEMA ){
          nRetry = 0;
          zSql = zLeftover;
          while( sqlite3Isspace(zSql[0]) ) zSql++;
        }
        break;
      }
    }

    sqlite3DbFree(db, azCols);
    azCols = 0;
69144
69145
69146
69147
69148
69149
69150
69151
69152
69153
69154
69155
69156
69157
69158
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
**
** $Id: loadext.c,v 1.57 2008/12/08 18:19:18 drh Exp $
*/

#ifndef SQLITE_CORE
  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
#endif
/************** Include sqlite3ext.h in the middle of loadext.c **************/
/************** Begin file sqlite3ext.h **************************************/







|







70040
70041
70042
70043
70044
70045
70046
70047
70048
70049
70050
70051
70052
70053
70054
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to dynamically load extensions into
** the SQLite library.
**
** $Id: loadext.c,v 1.58 2009/01/20 16:53:40 danielk1977 Exp $
*/

#ifndef SQLITE_CORE
  #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
#endif
/************** Include sqlite3ext.h in the middle of loadext.c **************/
/************** Begin file sqlite3ext.h **************************************/
70130
70131
70132
70133
70134
70135
70136
70137
70138
70139
70140
70141
70142
70143
70144
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the PRAGMA command.
**
** $Id: pragma.c,v 1.201 2009/01/13 20:14:16 drh Exp $
*/

/* Ignore this whole file if pragmas are disabled
*/
#if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)

/*







|







71026
71027
71028
71029
71030
71031
71032
71033
71034
71035
71036
71037
71038
71039
71040
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code used to implement the PRAGMA command.
**
** $Id: pragma.c,v 1.202 2009/01/20 16:53:41 danielk1977 Exp $
*/

/* Ignore this whole file if pragmas are disabled
*/
#if !defined(SQLITE_OMIT_PRAGMA) && !defined(SQLITE_OMIT_PARSER)

/*
70154
70155
70156
70157
70158
70159
70160
70161
70162
70163
70164
70165
70166
70167
70168
static u8 getSafetyLevel(const char *z){
                             /* 123456789 123456789 */
  static const char zText[] = "onoffalseyestruefull";
  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
  int i, n;
  if( isdigit(*z) ){
    return (u8)atoi(z);
  }
  n = sqlite3Strlen30(z);
  for(i=0; i<ArraySize(iLength); i++){
    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
      return iValue[i];
    }







|







71050
71051
71052
71053
71054
71055
71056
71057
71058
71059
71060
71061
71062
71063
71064
static u8 getSafetyLevel(const char *z){
                             /* 123456789 123456789 */
  static const char zText[] = "onoffalseyestruefull";
  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
  int i, n;
  if( sqlite3Isdigit(*z) ){
    return (u8)atoi(z);
  }
  n = sqlite3Strlen30(z);
  for(i=0; i<ArraySize(iLength); i++){
    if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
      return iValue[i];
    }
71567
71568
71569
71570
71571
71572
71573
71574
71575
71576
71577
71578
71579
71580
71581
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
**
** $Id: prepare.c,v 1.104 2009/01/09 02:49:32 drh Exp $
*/

/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(







|







72463
72464
72465
72466
72467
72468
72469
72470
72471
72472
72473
72474
72475
72476
72477
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains the implementation of the sqlite3_prepare()
** interface, and routines that contribute to loading the database schema
** from disk.
**
** $Id: prepare.c,v 1.105 2009/01/20 16:53:41 danielk1977 Exp $
*/

/*
** Fill the InitData structure with an error message that indicates
** that the database is corrupt.
*/
static void corruptSchema(
76568
76569
76570
76571
76572
76573
76574
76575
76576
76577
76578
76579
76580
76581
76582
** This file contains the sqlite3_get_table() and sqlite3_free_table()
** interface routines.  These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
**
** $Id: table.c,v 1.38 2008/12/10 19:26:24 drh Exp $
*/

#ifndef SQLITE_OMIT_GET_TABLE

/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.







|







77464
77465
77466
77467
77468
77469
77470
77471
77472
77473
77474
77475
77476
77477
77478
** This file contains the sqlite3_get_table() and sqlite3_free_table()
** interface routines.  These are just wrappers around the main
** interface routine of sqlite3_exec().
**
** These routines are in a separate files so that they will not be linked
** if they are not used.
**
** $Id: table.c,v 1.39 2009/01/19 20:49:10 drh Exp $
*/

#ifndef SQLITE_OMIT_GET_TABLE

/*
** This structure is used to pass data from sqlite3_get_table() through
** to the callback function is uses to build the result.
76681
76682
76683
76684
76685
76686
76687

76688
76689
76690
76691
76692
76693
76694
){
  int rc;
  TabResult res;

  *pazResult = 0;
  if( pnColumn ) *pnColumn = 0;
  if( pnRow ) *pnRow = 0;

  res.zErrMsg = 0;
  res.nResult = 0;
  res.nRow = 0;
  res.nColumn = 0;
  res.nData = 1;
  res.nAlloc = 20;
  res.rc = SQLITE_OK;







>







77577
77578
77579
77580
77581
77582
77583
77584
77585
77586
77587
77588
77589
77590
77591
){
  int rc;
  TabResult res;

  *pazResult = 0;
  if( pnColumn ) *pnColumn = 0;
  if( pnRow ) *pnRow = 0;
  if( pzErrMsg ) *pzErrMsg = 0;
  res.zErrMsg = 0;
  res.nResult = 0;
  res.nRow = 0;
  res.nColumn = 0;
  res.nData = 1;
  res.nAlloc = 20;
  res.rc = SQLITE_OK;
78311
78312
78313
78314
78315
78316
78317
78318
78319
78320
78321
78322
78323
78324
78325
**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
**
** $Id: vacuum.c,v 1.84 2008/11/17 19:18:55 danielk1977 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){







|







79208
79209
79210
79211
79212
79213
79214
79215
79216
79217
79218
79219
79220
79221
79222
**
*************************************************************************
** This file contains code used to implement the VACUUM command.
**
** Most of the code in this file may be omitted by defining the
** SQLITE_OMIT_VACUUM macro.
**
** $Id: vacuum.c,v 1.85 2009/01/22 23:04:46 drh 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){
78385
78386
78387
78388
78389
78390
78391





78392
78393
78394
78395
78396
78397
78398
78399
78400
78401
78402
78403
78404
78405
78406
78407
78408
78409
78410
  char *zSql = 0;         /* SQL statements */
  int saved_flags;        /* Saved value of the db->flags */
  int saved_nChange;      /* Saved value of db->nChange */
  int saved_nTotalChange; /* Saved value of db->nTotalChange */
  Db *pDb = 0;            /* Database to detach at end of vacuum */
  int isMemDb;            /* True is vacuuming a :memory: database */
  int nRes;






  /* Save the current value of the write-schema flag before setting it. */
  saved_flags = db->flags;
  saved_nChange = db->nChange;
  saved_nTotalChange = db->nTotalChange;
  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;

  if( !db->autoCommit ){
    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
    rc = SQLITE_ERROR;
    goto end_of_vacuum;
  }
  pMain = db->aDb[0].pBt;
  pMainPager = sqlite3BtreePager(pMain);
  isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;

  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  ** can be set to 'off' for this file, as it is not recovered if a crash
  ** occurs anyway. The integrity of the database is maintained by a







>
>
>
>
>







<
<
<
<
<







79282
79283
79284
79285
79286
79287
79288
79289
79290
79291
79292
79293
79294
79295
79296
79297
79298
79299
79300





79301
79302
79303
79304
79305
79306
79307
  char *zSql = 0;         /* SQL statements */
  int saved_flags;        /* Saved value of the db->flags */
  int saved_nChange;      /* Saved value of db->nChange */
  int saved_nTotalChange; /* Saved value of db->nTotalChange */
  Db *pDb = 0;            /* Database to detach at end of vacuum */
  int isMemDb;            /* True is vacuuming a :memory: database */
  int nRes;

  if( !db->autoCommit ){
    sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
    return SQLITE_ERROR;
  }

  /* Save the current value of the write-schema flag before setting it. */
  saved_flags = db->flags;
  saved_nChange = db->nChange;
  saved_nTotalChange = db->nTotalChange;
  db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;






  pMain = db->aDb[0].pBt;
  pMainPager = sqlite3BtreePager(pMain);
  isMemDb = sqlite3PagerFile(pMainPager)->pMethods==0;

  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  ** can be set to 'off' for this file, as it is not recovered if a crash
  ** occurs anyway. The integrity of the database is maintained by a
79459
79460
79461
79462
79463
79464
79465
79466
79467
79468
79469
79470
79471
79472
79473
** This module contains C code that generates VDBE code used to process
** the WHERE clause of SQL statements.  This module is responsible for
** generating the code that loops through a table looking for applicable
** rows.  Indices are selected and used to speed the search when doing
** so is applicable.  Because this module is responsible for selecting
** indices, you might also think of this module as the "query optimizer".
**
** $Id: where.c,v 1.364 2009/01/14 00:55:10 drh Exp $
*/

/*
** Trace output macros
*/
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
SQLITE_PRIVATE int sqlite3WhereTrace = 0;







|







80356
80357
80358
80359
80360
80361
80362
80363
80364
80365
80366
80367
80368
80369
80370
** This module contains C code that generates VDBE code used to process
** the WHERE clause of SQL statements.  This module is responsible for
** generating the code that loops through a table looking for applicable
** rows.  Indices are selected and used to speed the search when doing
** so is applicable.  Because this module is responsible for selecting
** indices, you might also think of this module as the "query optimizer".
**
** $Id: where.c,v 1.366 2009/01/30 05:40:27 shane Exp $
*/

/*
** Trace output macros
*/
#if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
SQLITE_PRIVATE int sqlite3WhereTrace = 0;
81366
81367
81368
81369
81370
81371
81372
81373
81374
81375
81376
81377
81378
81379
81380
      if( pTerm==0 ) break;
      wsFlags |= WHERE_COLUMN_EQ;
      if( pTerm->eOperator & WO_IN ){
        Expr *pExpr = pTerm->pExpr;
        wsFlags |= WHERE_COLUMN_IN;
        if( pExpr->pSelect!=0 ){
          inMultiplier *= 25;
        }else if( ALWAYS(pExpr->pList) ){
          inMultiplier *= pExpr->pList->nExpr + 1;
        }
      }
    }
    nRow = pProbe->aiRowEst[i] * inMultiplier;
    cost = nRow * estLog(inMultiplier);
    nEq = i;







|







82263
82264
82265
82266
82267
82268
82269
82270
82271
82272
82273
82274
82275
82276
82277
      if( pTerm==0 ) break;
      wsFlags |= WHERE_COLUMN_EQ;
      if( pTerm->eOperator & WO_IN ){
        Expr *pExpr = pTerm->pExpr;
        wsFlags |= WHERE_COLUMN_IN;
        if( pExpr->pSelect!=0 ){
          inMultiplier *= 25;
        }else if( pExpr->pList ){
          inMultiplier *= pExpr->pList->nExpr + 1;
        }
      }
    }
    nRow = pProbe->aiRowEst[i] * inMultiplier;
    cost = nRow * estLog(inMultiplier);
    nEq = i;
82569
82570
82571
82572
82573
82574
82575
82576
82577
82578
82579
82580
82581
82582
82583
    pLevel->plan = bestPlan.plan;
    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
      pLevel->iIdxCur = pParse->nTab++;
    }else{
      pLevel->iIdxCur = -1;
    }
    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
    pLevel->iFrom = bestJ;

    /* Check that if the table scanned by this loop iteration had an
    ** INDEXED BY clause attached to it, that the named index is being
    ** used for the scan. If not, then query compilation has failed.
    ** Return an error.
    */
    pIdx = pTabList->a[bestJ].pIndex;







|







83466
83467
83468
83469
83470
83471
83472
83473
83474
83475
83476
83477
83478
83479
83480
    pLevel->plan = bestPlan.plan;
    if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
      pLevel->iIdxCur = pParse->nTab++;
    }else{
      pLevel->iIdxCur = -1;
    }
    notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
    pLevel->iFrom = (u8)bestJ;

    /* Check that if the table scanned by this loop iteration had an
    ** INDEXED BY clause attached to it, that the named index is being
    ** used for the scan. If not, then query compilation has failed.
    ** Return an error.
    */
    pIdx = pTabList->a[bestJ].pIndex;
82969
82970
82971
82972
82973
82974
82975
82976
82977
82978
82979
82980
82981
82982



82983
82984

82985
82986
82987
82988
82989
82990
82991
82992
82993
82994
82995
82996
82997
82998
82999
83000
**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
**    YYNSTATE           the combined number of states.
**    YYNRULE            the number of rules in the grammar
**    YYERRORSYMBOL      is the code number of the error symbol.  If not
**                       defined, then do no error processing.
*/
#define YYCODETYPE unsigned char
#define YYNOCODE 237
#define YYACTIONTYPE unsigned short int
#define YYWILDCARD 62
#define sqlite3ParserTOKENTYPE Token
typedef union {
  int yyinit;
  sqlite3ParserTOKENTYPE yy0;



  SrcList* yy3;
  TriggerStep* yy19;

  struct LikeOp yy150;
  struct LimitVal yy196;
  int yy228;
  struct {int value; int mask;} yy231;
  ExprList* yy258;
  Select* yy387;
  IdList* yy400;
  Expr* yy402;
  struct TrigEvent yy466;
} YYMINORTYPE;
#ifndef YYSTACKDEPTH
#define YYSTACKDEPTH 100
#endif
#define sqlite3ParserARG_SDECL Parse *pParse;
#define sqlite3ParserARG_PDECL ,Parse *pParse
#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse







|

|




>
>
>
|
|
>
|
|
|
|
<
|
<
<
<







83866
83867
83868
83869
83870
83871
83872
83873
83874
83875
83876
83877
83878
83879
83880
83881
83882
83883
83884
83885
83886
83887
83888
83889

83890



83891
83892
83893
83894
83895
83896
83897
**    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
**    YYNSTATE           the combined number of states.
**    YYNRULE            the number of rules in the grammar
**    YYERRORSYMBOL      is the code number of the error symbol.  If not
**                       defined, then do no error processing.
*/
#define YYCODETYPE unsigned char
#define YYNOCODE 238
#define YYACTIONTYPE unsigned short int
#define YYWILDCARD 64
#define sqlite3ParserTOKENTYPE Token
typedef union {
  int yyinit;
  sqlite3ParserTOKENTYPE yy0;
  struct LimitVal yy4;
  ExprList* yy22;
  Expr* yy128;
  SrcList* yy133;
  TriggerStep* yy167;
  IdList* yy288;
  struct {int value; int mask;} yy299;
  struct TrigEvent yy366;
  int yy376;
  struct LikeOp yy450;

  Select* yy465;



} YYMINORTYPE;
#ifndef YYSTACKDEPTH
#define YYSTACKDEPTH 100
#endif
#define sqlite3ParserARG_SDECL Parse *pParse;
#define sqlite3ParserARG_PDECL ,Parse *pParse
#define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
83056
83057
83058
83059
83060
83061
83062
83063
83064
83065
83066
83067
83068
83069
83070
83071
83072
83073
83074
83075
83076
83077
83078
83079

83080
83081
83082
83083
83084
83085
83086
83087
83088
83089
83090
83091
83092
83093

83094
83095
83096
83097
83098
83099
83100
83101
83102
83103
83104
83105
83106
83107

83108
83109
83110
83111
83112
83113
83114
83115
83116
83117
83118
83119
83120
83121
83122
83123
83124
83125
83126
83127

83128
83129
83130
83131
83132
83133
83134

83135

83136
83137
83138
83139
83140

83141
83142
83143
83144
83145
83146
83147
83148
83149
83150
83151
83152
83153
83154
83155
83156
83157
83158
83159
83160
83161
83162
83163
83164
83165
83166
83167
83168
83169
83170
83171
83172
83173
83174
83175
83176
83177
83178
83179
83180
83181
83182
83183
83184
83185
83186
83187
83188
83189
83190
83191
83192
83193
83194
83195
83196
83197
83198
83199
83200
83201
83202
83203
83204
83205
83206
83207
83208
83209
83210
83211
83212

83213
83214
83215
83216
83217
83218
83219
83220
83221
83222
83223
83224
83225
83226
83227
83228
83229
83230
83231
83232
83233
83234

83235
83236
83237
83238
83239
83240
83241

83242
83243
83244
83245
83246
83247

83248
83249
83250
83251
83252
83253
83254
83255

83256
83257
83258
83259
83260
83261
83262

83263
83264
83265
83266
83267
83268
83269
83270
83271
83272
83273
83274
83275
83276
83277
83278
83279
83280
83281
83282
83283
83284
83285
83286
83287
83288
83289
83290
83291
83292
83293
83294
83295
83296
83297
83298
83299
83300
83301
83302
83303
83304
83305
83306
83307
83308
83309
83310
83311
83312
83313
83314
83315
83316
83317
83318
83319
83320
83321
83322
83323
83324
83325
83326
83327
83328
83329
83330
83331
83332
83333
83334
83335
83336
83337
83338
83339
83340
83341
83342
83343
83344
83345
83346
83347
83348
83349
83350
83351
83352
83353
83354
83355
83356
83357
83358
83359
83360
83361
83362
83363
83364
83365
83366
83367
83368
83369
83370
83371
83372
83373
83374
83375
83376
83377
83378
83379
83380
83381
83382
83383
83384
83385
83386
83387
83388
83389
83390
83391
**                     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 */   273,  829,  106,  545,    2,  163,  192,  394,   56,   56,
 /*    10 */    56,   56,  194,   58,   58,   58,   58,   59,   59,   60,
 /*    20 */    60,   60,   61,  194,  423,  196,  401,  407,   63,   58,
 /*    30 */    58,   58,   58,   59,   59,   60,   60,   60,   61,  194,
 /*    40 */   427,  279,  418,  419,   55,   54,  278,  411,  412,  408,
 /*    50 */   408,   57,   57,   56,   56,   56,   56,  318,   58,   58,
 /*    60 */    58,   58,   59,   59,   60,   60,   60,   61,  194,  273,
 /*    70 */   468,  281,  394,  467,  396,   77,   58,   58,   58,   58,
 /*    80 */    59,   59,   60,   60,   60,   61,  194,   59,   59,   60,
 /*    90 */    60,   60,   61,  194,  502,  401,  407,  364,  361,   53,
 /*   100 */   276,  218,   51,  195,  512,   17,  386,  398,  398,  398,
 /*   110 */   425,  302,  159,   55,   54,  278,  411,  412,  408,  408,
 /*   120 */    57,   57,   56,   56,   56,   56,  469,   58,   58,   58,
 /*   130 */    58,   59,   59,   60,   60,   60,   61,  194,  273,  206,
 /*   140 */   432,  427,  502,   97,  281,  155,  102,  234,  323,  239,
 /*   150 */   324,  166,  383,   17,  470,  433,  317,  138,  243,   61,
 /*   160 */   194,  135,  136,  387,  401,  407,  291,  366,  434,  510,
 /*   170 */   474,  468,  191,  385,  343,  396,  137,  511,  346,  189,

 /*   180 */   475,  497,   55,   54,  278,  411,  412,  408,  408,   57,
 /*   190 */    57,   56,   56,   56,   56,  528,   58,   58,   58,   58,
 /*   200 */    59,   59,   60,   60,   60,   61,  194,  273,  398,  398,
 /*   210 */   398,  369,  206,  391,   60,   60,   60,   61,  194,  102,
 /*   220 */   234,  323,  239,  324,  166,  172,  296,  192,  325,  328,
 /*   230 */   329,  243,  219,  401,  407,  369,  527,  358,  167,  330,
 /*   240 */   450,  352,   62,  438,   64,  140,   16,  369,  131,  390,
 /*   250 */    38,   55,   54,  278,  411,  412,  408,  408,   57,   57,
 /*   260 */    56,   56,   56,   56,  503,   58,   58,   58,   58,   59,
 /*   270 */    59,   60,   60,   60,   61,  194,  370,  371,  172,  459,
 /*   280 */   273,  325,  328,  329,  242,  296,  353,  260,  259,  312,
 /*   290 */   199,  296,  330,  275,  296,  193,   62,  192,   64,  140,
 /*   300 */   370,  371,   50,  141,  461,  235,  401,  407,  390,   31,
 /*   310 */   527,  226,  370,  371,  390,   31,  236,  390,   31,   62,

 /*   320 */   284,   64,  140,   72,   55,   54,  278,  411,  412,  408,
 /*   330 */   408,   57,   57,   56,   56,   56,   56,  391,   58,   58,
 /*   340 */    58,   58,   59,   59,   60,   60,   60,   61,  194,  296,
 /*   350 */   310,  319,  450,  273,  242,  320,  314,  463,  139,  310,
 /*   360 */   353,  260,  259,  172,  309,  296,  325,  328,  329,  307,
 /*   370 */   296,  192,  390,   25,  390,    3,  183,  330,  270,  401,
 /*   380 */   407,  425,  501,  159,   62,  145,   64,  140,  390,   32,
 /*   390 */   207,  200,  391,  390,   46,  315,   75,   55,   54,  278,
 /*   400 */   411,  412,  408,  408,   57,   57,   56,   56,   56,   56,
 /*   410 */   391,   58,   58,   58,   58,   59,   59,   60,   60,   60,
 /*   420 */    61,  194,  273,  296,  462,  227,  466,  333,  520,  296,
 /*   430 */   444,    1,  519,  296,  351,  369,  301,  418,  419,  289,
 /*   440 */   225,  415,  402,  403,  342,  183,  390,   26,  401,  407,
 /*   450 */    15,  394,  390,   38,  167,  354,  390,   46,  509,  484,

 /*   460 */   147,  472,  473,  405,  406,  508,   55,   54,  278,  411,
 /*   470 */   412,  408,  408,   57,   57,   56,   56,   56,   56,  391,
 /*   480 */    58,   58,   58,   58,   59,   59,   60,   60,   60,   61,
 /*   490 */   194,  273,  404,  198,  391,  483,  428,  369,  195,  296,
 /*   500 */   370,  371,  290,  351,  432,  369,  148,  146,  297,  275,
 /*   510 */   299,   20,  414,  414,  243,  369,  394,  401,  407,  433,
 /*   520 */   363,    2,  390,   21,  347,  525,  473,  299,  350,  414,
 /*   530 */   414,  254,  434,  450,  306,   55,   54,  278,  411,  412,
 /*   540 */   408,  408,   57,   57,   56,   56,   56,   56,  109,   58,
 /*   550 */    58,   58,   58,   59,   59,   60,   60,   60,   61,  194,
 /*   560 */   273,  248,  370,  371,  246,    5,  110,  296,  445,  296,
 /*   570 */   370,  371,  230,  255,  296,  546,  364,  361,  450,  296,
 /*   580 */   370,  371,  299,  212,  414,  414,  401,  407,  446,  454,
 /*   590 */   390,   29,  390,   48,  208,  368,  447,  390,   47,  252,
 /*   600 */   263,  250,  390,   89,   55,   54,  278,  411,  412,  408,
 /*   610 */   408,   57,   57,   56,   56,   56,   56,  232,   58,   58,
 /*   620 */    58,   58,   59,   59,   60,   60,   60,   61,  194,  273,
 /*   630 */   296,  372,  373,  374,  299,  144,  414,  414,  266,  360,
 /*   640 */   264,  296,  378,  296,  454,  296,  454,  296,  384,  500,
 /*   650 */   163,  280,  394,  390,   87,  401,  407,  497,  192,  299,

 /*   660 */   445,  414,  414,  379,  390,   92,  390,   93,  390,   96,
 /*   670 */   390,   98,  359,   55,   54,  278,  411,  412,  408,  408,
 /*   680 */    57,   57,   56,   56,   56,   56,  296,   58,   58,   58,
 /*   690 */    58,   59,   59,   60,   60,   60,   61,  194,  273,  296,
 /*   700 */    18,  489,  190,  296,  394,  296,  341,  296,  288,  390,
 /*   710 */    14,  296,  162,  146,  296,  350,  296,  394,  421,  421,
 /*   720 */   265,  490,  390,   90,  401,  407,  390,   30,  390,   88,

 /*   730 */   390,   22,  380,  254,  390,   49,  391,  390,   99,  390,

 /*   740 */   100,  242,   55,   65,  278,  411,  412,  408,  408,   57,
 /*   750 */    57,   56,   56,   56,   56,  296,   58,   58,   58,   58,
 /*   760 */    59,   59,   60,   60,   60,   61,  194,  273,  296,  394,
 /*   770 */   185,  424,  296,  283,  296,  535,  296,  285,  390,  101,
 /*   780 */   298,  211,  296,   71,  296,   73,  296,  518,  340,  518,

 /*   790 */   103,  390,   23,  401,  407,  390,   33,  390,   34,  390,
 /*   800 */    24,  168,  169,  170,  254,  390,   35,  390,   36,  390,
 /*   810 */    37,  321,   54,  278,  411,  412,  408,  408,   57,   57,
 /*   820 */    56,   56,   56,   56,  296,   58,   58,   58,   58,   59,
 /*   830 */    59,   60,   60,   60,   61,  194,  273,  296,  389,  522,
 /*   840 */   445,  296,  388,  296,  171,  296,  537,  390,   39,  443,
 /*   850 */   389,  296,  440,  296,  388,  296,  409,  296,  397,  441,
 /*   860 */   390,   40,  401,  407,  390,   41,  390,   27,  390,   28,
 /*   870 */    79,  254,  254,  242,  390,   42,  390,   43,  390,   44,
 /*   880 */   390,   45,  278,  411,  412,  408,  408,   57,   57,   56,
 /*   890 */    56,   56,   56,  242,   58,   58,   58,   58,   59,   59,
 /*   900 */    60,   60,   60,   61,  194,   67,  303,  144,    4,  286,
 /*   910 */   187,  142,  277,  538,  539,  524,  254,  254,  156,  481,
 /*   920 */   300,   67,  303,  254,    4,  478,  479,  308,  277,  287,
 /*   930 */   174,  416,  445,   19,  436,  177,  300,  305,  449,  452,
 /*   940 */   134,  164,  453,  150,  391,  391,  455,  427,  213,  214,
 /*   950 */   215,  153,  217,  305,   95,  789,  488,  487,  209,  210,
 /*   960 */   493,  240,  171,  427,  391,  269,  180,   70,   69,  391,
 /*   970 */   485,  245,  332,  171,  171,  486,   68,  294,  295,  491,
 /*   980 */   523,  396,  171,   70,   69,  460,  531,  532,  164,   86,
 /*   990 */   527,  492,   68,  294,  295,  241,  542,  396,   86,  192,
 /*  1000 */   504,  247,  249,  251,  253,   67,  303,  337,    4,  381,
 /*  1010 */   258,  585,  277,  345,  398,  398,  398,  399,  400,    9,
 /*  1020 */   300,  348,  349,  261,  262,  133,  220,  395,  304,  420,
 /*  1030 */   398,  398,  398,  399,  400,    9,  422,  305,  484,  228,
 /*  1040 */   356,  268,  259,  439,  442,  237,  274,  427,  267,  495,
 /*  1050 */   498,  192,  494,  496,  357,  327,  530,  151,  367,  541,
 /*  1060 */   375,  376,  377,  292,    7,  293,   79,   70,   69,  152,
 /*  1070 */   154,  311,  392,  221,  313,   52,   68,  294,  295,  222,
 /*  1080 */    74,  396,   78,  224,  161,  437,  223,  107,   80,  393,
 /*  1090 */   197,  316,  322,  282,  481,  471,  476,  229,  111,  451,
 /*  1100 */   231,  238,  457,  233,  480,  458,  477,  482,  271,  204,
 /*  1110 */   203,  499,  505,  334,  398,  398,  398,  399,  400,    9,
 /*  1120 */   272,  513,  175,  338,  176,  205,  506,  507,  336,  178,
 /*  1130 */    83,  179,  515,  256,  181,  516,  344,  105,  526,  119,
 /*  1140 */   129,  184,  533,  355,   91,  365,  120,  216,  121,  122,
 /*  1150 */   123,  125,  202,  382,  128,  586,   94,  587,  157,  158,
 /*  1160 */   540,  410,  413,   66,  429,  417,  426,  130,  143,  104,
 /*  1170 */   430,  448,  431,  160,  435,   76,    6,   10,   11,  108,
 /*  1180 */   165,  456,  149,  464,  465,  201,   81,  326,  112,  173,
 /*  1190 */   244,  113,   82,  114,  236,  335,  132,  514,  115,  164,
 /*  1200 */   182,  331,  339,  117,  116,  257,  521,    8,  529,  517,
 /*  1210 */   118,  186,   12,  534,  188,  536,  124,  126,  127,   13,
 /*  1220 */   543,  362,  830,  544,  830,  830,  830,  830,  830,  830,
 /*  1230 */    84,  830,  830,   85,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */    19,  139,  140,  141,  142,   24,  113,   26,   72,   73,
 /*    10 */    74,   75,   87,   77,   78,   79,   80,   81,   82,   83,
 /*    20 */    84,   85,   86,   87,   81,   82,   45,   46,   76,   77,
 /*    30 */    78,   79,   80,   81,   82,   83,   84,   85,   86,   87,
 /*    40 */    61,  165,  166,  167,   63,   64,   65,   66,   67,   68,
 /*    50 */    69,   70,   71,   72,   73,   74,   75,   19,   77,   78,
 /*    60 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   19,
 /*    70 */    91,   19,   91,  170,   95,   25,   77,   78,   79,   80,
 /*    80 */    81,   82,   83,   84,   85,   86,   87,   81,   82,   83,
 /*    90 */    84,   85,   86,   87,  147,   45,   46,    1,    2,   49,
 /*   100 */   151,  154,   22,  227,  157,  158,   26,  128,  129,  130,
 /*   110 */   162,  163,  164,   63,   64,   65,   66,   67,   68,   69,
 /*   120 */    70,   71,   72,   73,   74,   75,  170,   77,   78,   79,
 /*   130 */    80,   81,   82,   83,   84,   85,   86,   87,   19,   87,
 /*   140 */    12,   61,  147,   24,   19,   93,   94,   95,   96,   97,
 /*   150 */    98,   99,  157,  158,  161,   27,  118,   25,  106,   86,
 /*   160 */    87,   81,   82,  170,   45,   46,  143,  144,   40,  182,
 /*   170 */    42,   91,  149,  169,  225,   95,  181,  182,  229,  156,
 /*   180 */    52,  177,   63,   64,   65,   66,   67,   68,   69,   70,
 /*   190 */    71,   72,   73,   74,   75,   11,   77,   78,   79,   80,
 /*   200 */    81,   82,   83,   84,   85,   86,   87,   19,  128,  129,
 /*   210 */   130,   26,   87,  190,   83,   84,   85,   86,   87,   94,
 /*   220 */    95,   96,   97,   98,   99,   93,  147,  113,   96,   97,
 /*   230 */    98,  106,  191,   45,   46,   26,   52,  214,   46,  107,
 /*   240 */   162,  127,  218,  219,  220,  221,   22,   26,   24,  170,

 /*   250 */   171,   63,   64,   65,   66,   67,   68,   69,   70,   71,
 /*   260 */    72,   73,   74,   75,  182,   77,   78,   79,   80,   81,
 /*   270 */    82,   83,   84,   85,   86,   87,   91,   92,   93,  201,
 /*   280 */    19,   96,   97,   98,  147,  147,  102,  103,  104,  210,
 /*   290 */   211,  147,  107,  101,  147,  193,  218,  113,  220,  221,
 /*   300 */    91,   92,  200,  156,   83,   95,   45,   46,  170,  171,
 /*   310 */    52,  147,   91,   92,  170,  171,  106,  170,  171,  218,
 /*   320 */   183,  220,  221,  135,   63,   64,   65,   66,   67,   68,
 /*   330 */    69,   70,   71,   72,   73,   74,   75,  190,   77,   78,
 /*   340 */    79,   80,   81,   82,   83,   84,   85,   86,   87,  147,
 /*   350 */   212,  147,  162,   19,  147,  217,  212,   23,  156,  212,
 /*   360 */   102,  103,  104,   93,  217,  147,   96,   97,   98,  187,
 /*   370 */   147,  113,  170,  171,  170,  171,  156,  107,  159,   45,
 /*   380 */    46,  162,  163,  164,  218,  147,  220,  221,  170,  171,
 /*   390 */   183,  201,  190,  170,  171,  147,  135,   63,   64,   65,
 /*   400 */    66,   67,   68,   69,   70,   71,   72,   73,   74,   75,
 /*   410 */   190,   77,   78,   79,   80,   81,   82,   83,   84,   85,
 /*   420 */    86,   87,   19,  147,   23,  147,   23,   19,   28,  147,
 /*   430 */   204,   22,   32,  147,  214,   26,  165,  166,  167,  216,
 /*   440 */   222,   23,   45,   46,   44,  156,  170,  171,   45,   46,
 /*   450 */   230,   26,  170,  171,   46,  235,  170,  171,  177,  178,
 /*   460 */   156,  186,  187,   66,   67,  184,   63,   64,   65,   66,

 /*   470 */    67,   68,   69,   70,   71,   72,   73,   74,   75,  190,
 /*   480 */    77,   78,   79,   80,   81,   82,   83,   84,   85,   86,
 /*   490 */    87,   19,   95,  211,  190,   23,   23,   26,  227,  147,
 /*   500 */    91,   92,  216,  214,   12,   26,  202,  203,  147,  101,
 /*   510 */   109,   22,  111,  112,  106,   26,   91,   45,   46,   27,
 /*   520 */   141,  142,  170,  171,  235,  186,  187,  109,  147,  111,
 /*   530 */   112,  147,   40,  162,   42,   63,   64,   65,   66,   67,

 /*   540 */    68,   69,   70,   71,   72,   73,   74,   75,   23,   77,
 /*   550 */    78,   79,   80,   81,   82,   83,   84,   85,   86,   87,
 /*   560 */    19,   17,   91,   92,   23,  192,   23,  147,   25,  147,
 /*   570 */    91,   92,  201,  189,  147,    0,    1,    2,  162,  147,
 /*   580 */    91,   92,  109,  145,  111,  112,   45,   46,  117,  147,
 /*   590 */   170,  171,  170,  171,  213,  147,  117,  170,  171,   55,

 /*   600 */    17,   57,  170,  171,   63,   64,   65,   66,   67,   68,
 /*   610 */    69,   70,   71,   72,   73,   74,   75,  201,   77,   78,
 /*   620 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   19,
 /*   630 */   147,    7,    8,    9,  109,   92,  111,  112,   55,   94,
 /*   640 */    57,  147,  147,  147,  147,  147,  147,  147,  168,  169,
 /*   650 */    24,  209,   26,  170,  171,   45,   46,  177,  113,  109,
 /*   660 */   117,  111,  112,  147,  170,  171,  170,  171,  170,  171,
 /*   670 */   170,  171,  127,   63,   64,   65,   66,   67,   68,   69,

 /*   680 */    70,   71,   72,   73,   74,   75,  147,   77,   78,   79,
 /*   690 */    80,   81,   82,   83,   84,   85,   86,   87,   19,  147,
 /*   700 */    22,   33,  156,  147,   26,  147,  209,  147,  209,  170,
 /*   710 */   171,  147,  202,  203,  147,  147,  147,   91,  128,  129,
 /*   720 */   137,   53,  170,  171,   45,   46,  170,  171,  170,  171,
 /*   730 */   170,  171,  147,  147,  170,  171,  190,  170,  171,  170,
 /*   740 */   171,  147,   63,   64,   65,   66,   67,   68,   69,   70,

 /*   750 */    71,   72,   73,   74,   75,  147,   77,   78,   79,   80,
 /*   760 */    81,   82,   83,   84,   85,   86,   87,   19,  147,   91,
 /*   770 */    25,  162,  147,  105,  147,  189,  147,  183,  170,  171,
 /*   780 */    19,  213,  147,  134,  147,  136,  147,  102,  103,  104,
 /*   790 */   147,  170,  171,   45,   46,  170,  171,  170,  171,  170,
 /*   800 */   171,  102,  103,  104,  147,  170,  171,  170,  171,  170,
 /*   810 */   171,   83,   64,   65,   66,   67,   68,   69,   70,   71,
 /*   820 */    72,   73,   74,   75,  147,   77,   78,   79,   80,   81,
 /*   830 */    82,   83,   84,   85,   86,   87,   19,  147,  110,   21,
 /*   840 */    25,  147,  114,  147,   25,  147,  189,  170,  171,   25,
 /*   850 */   110,  147,   30,  147,  114,  147,   95,  147,  147,   37,
 /*   860 */   170,  171,   45,   46,  170,  171,  170,  171,  170,  171,
 /*   870 */   125,  147,  147,  147,  170,  171,  170,  171,  170,  171,
 /*   880 */   170,  171,   65,   66,   67,   68,   69,   70,   71,   72,
 /*   890 */    73,   74,   75,  147,   77,   78,   79,   80,   81,   82,
 /*   900 */    83,   84,   85,   86,   87,   19,   20,   92,   22,  183,
 /*   910 */   156,  156,   26,  189,  189,   97,  147,  147,   22,  100,
 /*   920 */    34,   19,   20,  147,   22,    7,    8,  147,   26,  183,
 /*   930 */   156,   23,  117,   25,  147,  156,   34,   51,  147,   23,
 /*   940 */   116,   25,  147,    5,  190,  190,  147,   61,   10,   11,
 /*   950 */    12,   13,   14,   51,   16,  137,   94,   95,  189,  189,
 /*   960 */    23,  147,   25,   61,  190,  189,  231,   81,   82,  190,
 /*   970 */   147,   23,   23,   25,   25,  179,   90,   91,   92,  179,
 /*   980 */    23,   95,   25,   81,   82,   83,   23,   23,   25,   25,
 /*   990 */    52,  179,   90,   91,   92,  147,   23,   95,   25,  113,
 /*  1000 */   147,  147,  147,  147,  147,   19,   20,  232,   22,  150,
 /*  1010 */   147,  115,   26,  147,  128,  129,  130,  131,  132,  133,
 /*  1020 */    34,  147,  147,  147,  147,  192,  194,  162,  224,  228,
 /*  1030 */   128,  129,  130,  131,  132,  133,  228,   51,  178,  205,
 /*  1040 */   102,  103,  104,  173,  173,  173,  108,   61,  205,  162,
 /*  1050 */   162,  113,  173,  173,  205,  174,  195,    6,  146,  195,
 /*  1060 */   146,  146,   13,  146,   25,  155,  125,   81,   82,  148,
 /*  1070 */   148,  121,  190,  195,  122,  124,   90,   91,   92,  196,
 /*  1080 */   134,   95,  123,  198,  115,  153,  197,  153,  101,  199,
 /*  1090 */   223,  120,  101,   43,  100,  172,  172,  206,   22,  207,
 /*  1100 */   206,  172,  207,  206,  174,  207,  180,  172,  175,   87,
 /*  1110 */   226,  180,  172,   18,  128,  129,  130,  131,  132,  133,
 /*  1120 */   175,  153,  152,   41,  152,  226,  172,  172,  153,  152,
 /*  1130 */   134,  153,  153,  233,  152,  234,  153,   63,  185,   22,
 /*  1140 */   215,  185,  195,   18,  160,    1,  188,   15,  188,  188,
 /*  1150 */   188,  185,  176,   23,  215,  115,  176,  115,  115,  115,
 /*  1160 */   195,   95,  110,   22,   11,   23,   23,   22,   22,   35,
 /*  1170 */    23,  117,   23,   25,   23,   25,  119,   25,  119,   22,
 /*  1180 */   119,  118,  115,   23,   23,   47,   22,   47,   22,   99,
 /*  1190 */    23,   22,   22,   22,  106,   19,   24,   20,  101,   25,
 /*  1200 */   101,   47,   39,   22,   48,  137,   48,    5,    1,   54,
 /*  1210 */   105,  126,   22,    1,  116,   20,  116,  105,  126,   22,
 /*  1220 */   127,    3,  236,    4,  236,  236,  236,  236,  236,  236,
 /*  1230 */    71,  236,  236,   71,
};
#define YY_SHIFT_USE_DFLT (-108)
#define YY_SHIFT_MAX 362
static const short yy_shift_ofst[] = {
 /*     0 */    96,  886,  938,  -19,  886,  986,  986,  185,  258,  986,
 /*    10 */   986,  986,  986,  986,  -48,  184,  209,  425,  -57,  -57,
 /*    20 */  -107,   50,  119,  188,  261,  334,  403,  472,  541,  610,
 /*    30 */   679,  610,  610,  610,  610,  610,  610,  610,  610,  610,
 /*    40 */   610,  610,  610,  610,  610,  610,  610,  748,  817,  817,
 /*    50 */   902,  986,  986,  986,  986,  986,  986,  986,  986,  986,
 /*    60 */   986,  986,  986,  986,  986,  986,  986,  986,  986,  986,
 /*    70 */   986,  986,  986,  986,  986,  986,  986,  986,  986,  986,
 /*    80 */   986,  986,  986,  986,  986,  986,  986,  -64,  -64,   -1,
 /*    90 */    -1,   52,    6,  131,  408,  818,   73,  425,  -75, -108,
 /*   100 */  -108, -108,   80,  125,  128,  128,  575,  626,  209,  626,
 /*   110 */   626,  209,  209,  209,  209,  209,  209,  209,  209,  209,
 /*   120 */   209,  209,  209,  209,  209,  209,  209,  209,  545,  114,
 /*   130 */  -107, -107, -107, -108, -108,  -21,  -21,  132,  270,  401,
 /*   140 */   409,  418,  473,  492,  471,  479,  489,  525,  543,  221,
 /*   150 */   624,  209,  209,  209,  209,  209,  728,  209,  209,  678,
 /*   160 */   209,  209,  815,  209,  209,  209,  209,  209,  668,  668,
 /*   170 */   668,  209,  209,  209,  550,  209,  209,  550,  209,  400,
 /*   180 */   685,  209,  209,  550,  209,  209,  209,  550,  209,  550,
 /*   190 */   550,  224,  740,  824,  425,  590,  590,  649,  822,  822,
 /*   200 */    38,  822,  192,  822,  425,  822,  425,  819,  745,   38,
 /*   210 */    38,  745, 1051, 1051, 1051, 1051, 1049, 1049, 1039, -107,
 /*   220 */   941,  952,  959,  950,  951,  946,  969,  969,  987,  971,
 /*   230 */   987,  971,  987,  971,  991,  991, 1050,  991,  994,  991,
 /*   240 */  1076, 1022, 1022, 1050,  991,  991,  991, 1076, 1095,  969,
 /*   250 */  1095,  969, 1095,  969,  969, 1082,  996, 1095,  969, 1074,
 /*   260 */  1074, 1117,  941, 1125, 1125, 1125, 1125,  941, 1074, 1117,
 /*   270 */  -108, -108, -108,  397,  583,  699,  544,  896,  761,  908,
 /*   280 */   916,  210,  918,  862,  937,  948,  949,  957,  963,  964,
 /*   290 */   973, 1144, 1132, 1130, 1040, 1042, 1043, 1044, 1066, 1052,
 /*   300 */  1141, 1142, 1143, 1145, 1153, 1146, 1147, 1148, 1149, 1151,
 /*   310 */  1150, 1057, 1152, 1059, 1150, 1054, 1157, 1061, 1063, 1067,
 /*   320 */  1160, 1161, 1134, 1138, 1164, 1140, 1166, 1167, 1169, 1170,
 /*   330 */  1154, 1171, 1090, 1088, 1176, 1177, 1172, 1097, 1163, 1155,
 /*   340 */  1156, 1174, 1158, 1068, 1099, 1181, 1202, 1207, 1105, 1159,
 /*   350 */  1162, 1085, 1190, 1098, 1212, 1195, 1100, 1112, 1092, 1197,
 /*   360 */  1093, 1218, 1219,
};
#define YY_REDUCE_USE_DFLT (-139)
#define YY_REDUCE_MAX 272
static const short yy_reduce_ofst[] = {
 /*     0 */  -138,  147,   23,   78,  202,  138,   79,   -5,  220,  218,
 /*    10 */   282,  144,  223,  286,   24,  289,  -53,  219, -124,  271,
 /*    20 */   304,  166,  166,  166,  166,  166,  166,  166,  166,  166,
 /*    30 */   166,  166,  166,  166,  166,  166,  166,  166,  166,  166,
 /*    40 */   166,  166,  166,  166,  166,  166,  166,  166,  166,  166,
 /*    50 */   204,  276,  352,  420,  422,  427,  432,  483,  494,  496,
 /*    60 */   498,  500,  539,  552,  556,  558,  560,  564,  567,  569,
 /*    70 */   608,  621,  625,  627,  629,  635,  637,  639,  677,  690,
 /*    80 */   694,  696,  698,  704,  706,  708,  710,  166,  166,  166,
 /*    90 */   166,  480,  166,  166,  281,  -51,  101,  -52,  101,  101,
 /*   100 */   101,  101,   -7,    4,  275,  339,  379,  190,  442,  371,
 /*   110 */   416,  137,  207,  594,  726,  384,  497,  746,  381,  499,
 /*   120 */   586,  657,  724,  725,  769,  770,  568,  776,  546,  754,
 /*   130 */   755,  774,  779,  102,  510,  -97,  -44,  -13,   82,   41,
 /*   140 */   164,   41,   41,  182,  238,  248,  278,   41,  226,  361,
 /*   150 */   438,  448,  495,  516,  585,  643,  373,  361,  711,  609,
 /*   160 */   780,  787,  226,  791,  795,  799,  814,  823,  796,  800,
 /*   170 */   812,  848,  853,  854,   41,  855,  856,   41,  857,  735,
 /*   180 */   775,  863,  866,   41,  874,  875,  876,   41,  877,   41,
 /*   190 */    41,  859,  833,  832,  865,  801,  808,  804,  870,  871,
 /*   200 */   834,  872,  860,  879,  887,  880,  888,  881,  861,  843,
 /*   210 */   849,  864,  912,  914,  915,  917,  921,  922,  910,  882,
 /*   220 */   878,  883,  889,  885,  890,  867,  932,  934,  891,  892,
 /*   230 */   894,  895,  897,  898,  923,  924,  926,  929,  930,  935,
 /*   240 */   933,  884,  899,  931,  940,  954,  955,  945,  970,  968,
 /*   250 */   972,  975,  977,  978,  979,  900,  901,  982,  983,  953,
 /*   260 */   956,  925,  947,  958,  960,  961,  962,  965,  966,  939,
 /*   270 */   984,  976,  980,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */   551,  784,  828,  672,  828,  784,  828,  828,  828,  782,
 /*    10 */   828,  828,  828,  828,  756,  828,  828,  588,  801,  801,
 /*    20 */   676,  707,  828,  828,  828,  828,  828,  828,  828,  708,
 /*    30 */   828,  786,  781,  777,  779,  778,  785,  709,  698,  705,
 /*    40 */   712,  687,  814,  714,  715,  721,  722,  744,  743,  762,







|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
<
|
|
>
|
|
|
|
|
|
|
|
|
|
<
|
|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
>
|
|
|
|
<
|
|
>
|
>
|
|
|
<
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|


|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
|
|
<
|
|
|
|
>
|
|
<
|
|
|
>
|
|
|
<
|
|
|
|
>
|
|
<
|
|
|
|
>
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|


|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







83953
83954
83955
83956
83957
83958
83959
83960
83961
83962
83963
83964
83965
83966
83967
83968
83969
83970
83971
83972
83973
83974
83975
83976
83977
83978
83979
83980
83981
83982
83983
83984
83985
83986
83987
83988

83989
83990
83991
83992
83993
83994
83995
83996
83997
83998
83999
84000
84001

84002
84003
84004
84005
84006
84007
84008
84009
84010
84011
84012
84013
84014
84015
84016
84017
84018
84019
84020
84021
84022

84023
84024
84025
84026
84027
84028
84029

84030
84031
84032
84033
84034
84035
84036
84037

84038
84039
84040
84041
84042
84043
84044
84045
84046
84047
84048
84049
84050
84051
84052
84053


84054
84055
84056
84057
84058
84059
84060
84061
84062
84063
84064
84065
84066
84067
84068
84069
84070
84071
84072
84073
84074
84075
84076
84077
84078
84079
84080
84081
84082
84083
84084
84085
84086
84087
84088
84089
84090
84091
84092
84093
84094
84095
84096
84097
84098
84099
84100
84101
84102
84103
84104
84105
84106
84107
84108
84109
84110
84111

84112
84113
84114
84115
84116
84117
84118
84119
84120
84121
84122
84123
84124
84125
84126
84127
84128
84129
84130
84131
84132
84133
84134

84135
84136
84137
84138
84139
84140
84141

84142
84143
84144
84145
84146
84147
84148

84149
84150
84151
84152
84153
84154
84155

84156
84157
84158
84159
84160
84161
84162

84163
84164
84165
84166
84167
84168
84169
84170
84171
84172
84173
84174
84175
84176
84177
84178
84179
84180
84181
84182
84183
84184
84185
84186
84187
84188
84189
84190
84191
84192
84193
84194
84195
84196
84197
84198
84199
84200
84201
84202
84203
84204
84205
84206
84207
84208
84209
84210
84211
84212
84213
84214
84215
84216
84217
84218
84219
84220
84221
84222
84223
84224
84225
84226
84227
84228
84229
84230
84231
84232
84233
84234
84235
84236
84237
84238
84239
84240
84241
84242
84243
84244
84245
84246
84247
84248
84249
84250
84251
84252
84253
84254
84255
84256
84257
84258
84259
84260
84261
84262
84263
84264
84265
84266
84267
84268
84269
84270
84271
84272
84273
84274
84275
84276
84277
84278
84279
84280
84281
84282
84283
84284
84285
84286
84287
84288
**                     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 */   273,  829,  106,  545,    2,  163,  192,  394,   56,   56,
 /*    10 */    56,   56,  171,   58,   58,   58,   58,   59,   59,   60,
 /*    20 */    60,   60,   61,  194,   62,  438,   64,  140,  401,  407,
 /*    30 */    63,   58,   58,   58,   58,   59,   59,   60,   60,   60,
 /*    40 */    61,  194,  427,  364,  361,  369,   55,   54,  278,  411,
 /*    50 */   412,  408,  408,   57,   57,   56,   56,   56,   56,  194,
 /*    60 */    58,   58,   58,   58,   59,   59,   60,   60,   60,   61,
 /*    70 */   194,  273,  468,  281,  394,  450,  396,   77,   58,   58,
 /*    80 */    58,   58,   59,   59,   60,   60,   60,   61,  194,  481,
 /*    90 */   394,  369,   59,   59,   60,   60,   60,   61,  194,  401,
 /*   100 */   407,  172,  138,   53,  325,  328,  329,   51,  398,  398,
 /*   110 */   398,  386,  370,  371,  200,  330,  467,   55,   54,  278,
 /*   120 */   411,  412,  408,  408,   57,   57,   56,   56,   56,   56,
 /*   130 */   167,   58,   58,   58,   58,   59,   59,   60,   60,   60,
 /*   140 */    61,  194,  273,  206,  546,  364,  361,   97,  427,  155,
 /*   150 */   102,  234,  323,  239,  324,  166,  281,  394,  370,  371,
 /*   160 */   172,  469,  243,  325,  328,  329,  423,  196,  135,  136,
 /*   170 */   401,  407,  172,  502,  330,  325,  328,  329,  468,  510,
 /*   180 */   218,  454,  396,  512,   17,  275,  330,  454,   55,   54,
 /*   190 */   278,  411,  412,  408,  408,   57,   57,   56,   56,   56,
 /*   200 */    56,  528,   58,   58,   58,   58,   59,   59,   60,   60,
 /*   210 */    60,   61,  194,  273,  398,  398,  398,  270,  470,  502,
 /*   220 */   425,  501,  159,  296,  509,  484,  206,  387,  296,  383,
 /*   230 */    17,  508,  296,  102,  234,  323,  239,  324,  166,  384,
 /*   240 */   500,  401,  407,  280,  527,  243,  390,   31,  497,  341,
 /*   250 */   450,  390,   38,  137,  511,  390,   32,   61,  194,   55,
 /*   260 */    54,  278,  411,  412,  408,  408,   57,   57,   56,   56,
 /*   270 */    56,   56,  432,   58,   58,   58,   58,   59,   59,   60,
 /*   280 */    60,   60,   61,  194,  321,  273,  254,  433,  310,  459,
 /*   290 */   443,  312,  199,  320,  353,  260,  259,  296,  279,  418,

 /*   300 */   419,  296,  434,  296,  306,  192,   62,  225,   64,  140,
 /*   310 */   141,  389,  193,  401,  407,  388,  291,  366,  522,   50,
 /*   320 */   390,   31,  191,  527,  390,   31,  390,   38,  255,  189,
 /*   330 */    72,   55,   54,  278,  411,  412,  408,  408,   57,   57,
 /*   340 */    56,   56,   56,   56,  391,   58,   58,   58,   58,   59,
 /*   350 */    59,   60,   60,   60,   61,  194,  296,  273,  319,  503,
 /*   360 */   195,  463,  314,  391,  462,  139,  310,  198,  301,  418,
 /*   370 */   419,  309,    1,  353,  260,  259,  369,  219,  415,  390,
 /*   380 */    25,  390,    3,  134,  192,  401,  407,  358,  425,  302,
 /*   390 */   159,   60,   60,   60,   61,  194,  524,  454,   62,  391,
 /*   400 */    64,  140,   75,   55,   54,  278,  411,  412,  408,  408,
 /*   410 */    57,   57,   56,   56,   56,   56,  432,   58,   58,   58,
 /*   420 */    58,   59,   59,   60,   60,   60,   61,  194,  273,  226,

 /*   430 */   195,  433,  466,  428,   18,  789,  333,  296,  394,  299,
 /*   440 */   296,  414,  414,  370,  371,  109,  434,  307,  474,  369,
 /*   450 */   402,  403,  299,  183,  414,  414,  401,  407,  475,  288,
 /*   460 */   390,   46,  263,  390,   46,  167,  299,  147,  414,  414,
 /*   470 */   369,  405,  406,  145,   55,   54,  278,  411,  412,  408,
 /*   480 */   408,   57,   57,   56,   56,   56,   56,  391,   58,   58,
 /*   490 */    58,   58,   59,   59,   60,   60,   60,   61,  194,  273,
 /*   500 */   404,  391,  266,  483,  264,  394,  289,  296,  369,  290,
 /*   510 */   110,  351,  445,  148,  146,   20,  370,  371,  489,  369,
 /*   520 */   275,  299,  444,  414,  414,  243,  276,  401,  407,  461,
 /*   530 */   390,   26,  347,  299,  450,  414,  414,  370,  371,  490,
 /*   540 */   254,  163,  446,  394,  242,   55,   54,  278,  411,  412,
 /*   550 */   408,  408,   57,   57,   56,   56,   56,   56,  360,   58,
 /*   560 */    58,   58,   58,   59,   59,   60,   60,   60,   61,  194,
 /*   570 */   273,  183,  296,  230,  246,  370,  371,  192,  156,  296,
 /*   580 */   284,  144,  535,  265,  192,  296,  370,  371,  315,  296,
 /*   590 */   359,  283,  518,  340,  518,  390,   21,  352,  401,  407,
 /*   600 */   343,  447,  390,   29,  346,  391,  445,  248,  390,   48,
 /*   610 */   394,  227,  390,   47,  472,  473,   55,   54,  278,  411,
 /*   620 */   412,  408,  408,   57,   57,   56,   56,   56,   56,  351,
 /*   630 */    58,   58,   58,   58,   59,   59,   60,   60,   60,   61,

 /*   640 */   194,  273,  296,  440,  296,   15,  385,  252,  296,  250,
 /*   650 */   354,  296,  441,  296,  497,  296,   16,  296,  131,  296,
 /*   660 */   350,  296,  168,  169,  170,  390,   89,  390,   87,  401,
 /*   670 */   407,  390,   92,  585,  390,   93,  390,   96,  390,   98,
 /*   680 */   390,   14,  390,   90,  390,   30,  242,   55,   54,  278,
 /*   690 */   411,  412,  408,  408,   57,   57,   56,   56,   56,   56,
 /*   700 */   296,   58,   58,   58,   58,   59,   59,   60,   60,   60,

 /*   710 */    61,  194,  273,  296,  242,  296,  525,  473,  450,  296,
 /*   720 */   297,  296,  207,  390,   88,  296,  208,  389,  296,  212,
 /*   730 */   296,  388,  296,  372,  373,  374,  390,   22,  390,   49,
 /*   740 */   401,  407,  390,   99,  390,  100,  363,    2,  390,  101,
 /*   750 */   285,  390,   23,  390,   33,  390,   34,  232,   55,   65,
 /*   760 */   278,  411,  412,  408,  408,   57,   57,   56,   56,   56,
 /*   770 */    56,  296,   58,   58,   58,   58,   59,   59,   60,   60,
 /*   780 */    60,   61,  194,  273,  296,  520,  296,  254,  242,  519,

 /*   790 */   296,  162,  146,  296,  390,   24,  350,  296,  445,  296,
 /*   800 */   421,  421,  296,  342,  296,  478,  479,  390,   35,  390,
 /*   810 */    36,  401,  407,  390,   37,  368,  390,   39,  254,    5,
 /*   820 */   390,   40,  390,   41,  286,  390,   27,  390,   28,  537,
 /*   830 */    54,  278,  411,  412,  408,  408,   57,   57,   56,   56,
 /*   840 */    56,   56,  296,   58,   58,   58,   58,   59,   59,   60,
 /*   850 */    60,   60,   61,  194,  273,  296,  254,  296,  242,  254,
 /*   860 */   538,  296,  211,  190,  378,  390,   42,  144,   71,  318,
 /*   870 */    73,  254,  185,  298,  416,  452,   19,  164,  390,   43,
 /*   880 */   390,   44,  401,  407,  390,   45,  379,  254,  488,  487,
 /*   890 */   424,  180,  445,  187,  287,  380,  103,  391,  539,  142,
 /*   900 */   174,  209,  278,  411,  412,  408,  408,   57,   57,   56,
 /*   910 */    56,   56,   56,  210,   58,   58,   58,   58,   59,   59,
 /*   920 */    60,   60,   60,   61,  194,   67,  303,  391,    4,  269,
 /*   930 */   397,  177,  277,  391,  391,  235,  493,  245,  171,  171,
 /*   940 */   486,  300,   67,  303,  308,    4,  236,  436,  332,  277,


 /*   950 */   171,  409,  523,  531,  171,  164,  449,  453,  300,  305,
 /*   960 */   532,  542,   86,   86,  455,  391,  240,  485,  491,  427,
 /*   970 */   317,  492,  241,   79,  504,  247,  305,  249,  251,  253,
 /*   980 */   258,  345,  337,  133,  348,  349,  427,  261,  262,   70,
 /*   990 */    69,  395,  381,  304,  420,  220,  422,  439,   68,  294,
 /*  1000 */   295,  228,  530,  396,  484,  495,   70,   69,  460,  498,
 /*  1010 */   267,  357,  151,  541,  367,   68,  294,  295,  442,  237,
 /*  1020 */   396,  192,  494,  496,  375,  376,   67,  303,  327,    4,
 /*  1030 */   292,  377,  293,  277,  152,  398,  398,  398,  399,  400,
 /*  1040 */     9,  154,  300,   79,    7,  313,  392,   74,   78,  311,
 /*  1050 */   161,   52,  398,  398,  398,  399,  400,    9,  150,  221,
 /*  1060 */   305,  222,  393,  213,  214,  215,  153,  217,  223,   95,
 /*  1070 */   427,  224,  437,  107,   80,  229,  316,  451,  231,  322,
 /*  1080 */   197,  457,  233,  471,  476,  282,  477,  458,  238,  481,
 /*  1090 */    70,   69,  111,  204,  482,  480,  334,  499,  175,   68,
 /*  1100 */   294,  295,  513,  176,  396,  336,  178,  527,  271,  203,
 /*  1110 */   272,  205,  505,  506,  507,  179,  515,  338,   83,  181,
 /*  1120 */   256,  344,  516,  105,  119,  129,  355,  533,  526,  184,
 /*  1130 */    91,  540,  365,  120,  202,  121,  398,  398,  398,  399,
 /*  1140 */   400,    9,   94,  122,  125,  123,  382,  216,  586,  587,
 /*  1150 */   157,  158,  128,  410,  413,   66,  130,  356,  268,  259,
 /*  1160 */   417,  426,  429,  274,  143,  160,  430,  431,  192,  435,
 /*  1170 */    76,  448,    6,   10,   11,  108,  149,  456,  464,  465,
 /*  1180 */   165,   81,  112,  113,  201,  326,  104,  244,   82,  114,
 /*  1190 */   173,  236,  335,  132,  514,  115,  164,  182,  339,  331,
 /*  1200 */   257,  117,    8,  529,  116,  118,  186,   12,  517,  188,
 /*  1210 */   534,  536,  521,  124,  126,  127,   13,  362,  543,  544,
 /*  1220 */   830,  830,  830,  830,  830,  830,  830,  830,  830,  830,
 /*  1230 */   830,   84,  830,  830,  830,  830,   85,
};
static const YYCODETYPE yy_lookahead[] = {
 /*     0 */    19,  140,  141,  142,  143,   24,  115,   26,   74,   75,
 /*    10 */    76,   77,   25,   79,   80,   81,   82,   83,   84,   85,
 /*    20 */    86,   87,   88,   89,  219,  220,  221,  222,   47,   48,
 /*    30 */    78,   79,   80,   81,   82,   83,   84,   85,   86,   87,
 /*    40 */    88,   89,   63,    1,    2,   26,   65,   66,   67,   68,
 /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   89,
 /*    60 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,
 /*    70 */    89,   19,   93,   19,   93,  163,   97,   25,   79,   80,
 /*    80 */    81,   82,   83,   84,   85,   86,   87,   88,   89,  102,
 /*    90 */    26,   26,   83,   84,   85,   86,   87,   88,   89,   47,
 /*   100 */    48,   95,   25,   51,   98,   99,  100,   22,  129,  130,
 /*   110 */   131,   26,   93,   94,  202,  109,  171,   65,   66,   67,
 /*   120 */    68,   69,   70,   71,   72,   73,   74,   75,   76,   77,
 /*   130 */    48,   79,   80,   81,   82,   83,   84,   85,   86,   87,
 /*   140 */    88,   89,   19,   89,    0,    1,    2,   24,   63,   95,
 /*   150 */    96,   97,   98,   99,  100,  101,   19,   93,   93,   94,
 /*   160 */    95,  171,  108,   98,   99,  100,   83,   84,   83,   84,
 /*   170 */    47,   48,   95,  148,  109,   98,   99,  100,   93,  183,
 /*   180 */   155,  148,   97,  158,  159,  103,  109,  148,   65,   66,
 /*   190 */    67,   68,   69,   70,   71,   72,   73,   74,   75,   76,
 /*   200 */    77,   11,   79,   80,   81,   82,   83,   84,   85,   86,
 /*   210 */    87,   88,   89,   19,  129,  130,  131,  160,  162,  148,
 /*   220 */   163,  164,  165,  148,  178,  179,   89,  171,  148,  158,
 /*   230 */   159,  185,  148,   96,   97,   98,   99,  100,  101,  169,
 /*   240 */   170,   47,   48,  210,   54,  108,  171,  172,  178,  210,
 /*   250 */   163,  171,  172,  182,  183,  171,  172,   88,   89,   65,
 /*   260 */    66,   67,   68,   69,   70,   71,   72,   73,   74,   75,

 /*   270 */    76,   77,   12,   79,   80,   81,   82,   83,   84,   85,
 /*   280 */    86,   87,   88,   89,   85,   19,  148,   27,  213,  202,
 /*   290 */    25,  211,  212,  218,  104,  105,  106,  148,  166,  167,
 /*   300 */   168,  148,   42,  148,   44,  115,  219,  223,  221,  222,
 /*   310 */   157,  112,  194,   47,   48,  116,  144,  145,   21,  201,
 /*   320 */   171,  172,  150,   54,  171,  172,  171,  172,  190,  157,
 /*   330 */   136,   65,   66,   67,   68,   69,   70,   71,   72,   73,
 /*   340 */    74,   75,   76,   77,  191,   79,   80,   81,   82,   83,
 /*   350 */    84,   85,   86,   87,   88,   89,  148,   19,  148,  183,
 /*   360 */   228,   23,  213,  191,   23,  157,  213,  212,  166,  167,
 /*   370 */   168,  218,   22,  104,  105,  106,   26,  192,   23,  171,
 /*   380 */   172,  171,  172,  118,  115,   47,   48,  215,  163,  164,
 /*   390 */   165,   85,   86,   87,   88,   89,   99,  148,  219,  191,
 /*   400 */   221,  222,  136,   65,   66,   67,   68,   69,   70,   71,
 /*   410 */    72,   73,   74,   75,   76,   77,   12,   79,   80,   81,
 /*   420 */    82,   83,   84,   85,   86,   87,   88,   89,   19,  148,
 /*   430 */   228,   27,   23,   23,   22,  138,   19,  148,   26,  111,
 /*   440 */   148,  113,  114,   93,   94,   23,   42,  188,   44,   26,
 /*   450 */    47,   48,  111,  157,  113,  114,   47,   48,   54,  210,
 /*   460 */   171,  172,   17,  171,  172,   48,  111,  157,  113,  114,
 /*   470 */    26,   68,   69,  148,   65,   66,   67,   68,   69,   70,
 /*   480 */    71,   72,   73,   74,   75,   76,   77,  191,   79,   80,
 /*   490 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   19,

 /*   500 */    97,  191,   57,   23,   59,   93,  217,  148,   26,  217,
 /*   510 */    23,  215,   25,  203,  204,   22,   93,   94,   34,   26,
 /*   520 */   103,  111,  205,  113,  114,  108,  152,   47,   48,   85,
 /*   530 */   171,  172,  236,  111,  163,  113,  114,   93,   94,   55,
 /*   540 */   148,   24,  119,   26,  148,   65,   66,   67,   68,   69,
 /*   550 */    70,   71,   72,   73,   74,   75,   76,   77,   96,   79,
 /*   560 */    80,   81,   82,   83,   84,   85,   86,   87,   88,   89,

 /*   570 */    19,  157,  148,  202,   23,   93,   94,  115,   22,  148,
 /*   580 */   184,   94,  190,  138,  115,  148,   93,   94,  148,  148,
 /*   590 */   128,  107,  104,  105,  106,  171,  172,  128,   47,   48,
 /*   600 */   226,  119,  171,  172,  230,  191,  119,   17,  171,  172,
 /*   610 */    93,  148,  171,  172,  187,  188,   65,   66,   67,   68,
 /*   620 */    69,   70,   71,   72,   73,   74,   75,   76,   77,  215,
 /*   630 */    79,   80,   81,   82,   83,   84,   85,   86,   87,   88,

 /*   640 */    89,   19,  148,   30,  148,  231,  170,   57,  148,   59,
 /*   650 */   236,  148,   39,  148,  178,  148,   22,  148,   24,  148,
 /*   660 */   148,  148,  104,  105,  106,  171,  172,  171,  172,   47,
 /*   670 */    48,  171,  172,  117,  171,  172,  171,  172,  171,  172,
 /*   680 */   171,  172,  171,  172,  171,  172,  148,   65,   66,   67,
 /*   690 */    68,   69,   70,   71,   72,   73,   74,   75,   76,   77,
 /*   700 */   148,   79,   80,   81,   82,   83,   84,   85,   86,   87,

 /*   710 */    88,   89,   19,  148,  148,  148,  187,  188,  163,  148,
 /*   720 */   148,  148,  184,  171,  172,  148,  214,  112,  148,  146,
 /*   730 */   148,  116,  148,    7,    8,    9,  171,  172,  171,  172,
 /*   740 */    47,   48,  171,  172,  171,  172,  142,  143,  171,  172,
 /*   750 */   184,  171,  172,  171,  172,  171,  172,  202,   65,   66,
 /*   760 */    67,   68,   69,   70,   71,   72,   73,   74,   75,   76,
 /*   770 */    77,  148,   79,   80,   81,   82,   83,   84,   85,   86,

 /*   780 */    87,   88,   89,   19,  148,   28,  148,  148,  148,   32,
 /*   790 */   148,  203,  204,  148,  171,  172,  148,  148,   25,  148,
 /*   800 */   129,  130,  148,   46,  148,    7,    8,  171,  172,  171,
 /*   810 */   172,   47,   48,  171,  172,  148,  171,  172,  148,  193,
 /*   820 */   171,  172,  171,  172,  184,  171,  172,  171,  172,  190,
 /*   830 */    66,   67,   68,   69,   70,   71,   72,   73,   74,   75,
 /*   840 */    76,   77,  148,   79,   80,   81,   82,   83,   84,   85,
 /*   850 */    86,   87,   88,   89,   19,  148,  148,  148,  148,  148,
 /*   860 */   190,  148,  214,  157,  148,  171,  172,   94,  135,   19,
 /*   870 */   137,  148,   25,   19,   23,   23,   25,   25,  171,  172,
 /*   880 */   171,  172,   47,   48,  171,  172,  148,  148,   96,   97,
 /*   890 */   163,  232,  119,  157,  184,  148,  148,  191,  190,  157,
 /*   900 */   157,  190,   67,   68,   69,   70,   71,   72,   73,   74,
 /*   910 */    75,   76,   77,  190,   79,   80,   81,   82,   83,   84,
 /*   920 */    85,   86,   87,   88,   89,   19,   20,  191,   22,  190,
 /*   930 */   148,  157,   26,  191,  191,   97,   23,   23,   25,   25,
 /*   940 */   180,   35,   19,   20,  148,   22,  108,  148,   23,   26,
 /*   950 */    25,   97,   23,   23,   25,   25,  148,  148,   35,   53,
 /*   960 */    23,   23,   25,   25,  148,  191,  148,  148,  180,   63,
 /*   970 */   120,  180,  148,  126,  148,  148,   53,  148,  148,  148,
 /*   980 */   148,  148,  233,  193,  148,  148,   63,  148,  148,   83,
 /*   990 */    84,  163,  151,  225,  229,  195,  229,  174,   92,   93,
 /*  1000 */    94,  206,  196,   97,  179,  163,   83,   84,   85,  163,
 /*  1010 */   206,  206,    6,  196,  147,   92,   93,   94,  174,  174,
 /*  1020 */    97,  115,  174,  174,  147,  147,   19,   20,  175,   22,
 /*  1030 */   147,   13,  156,   26,  149,  129,  130,  131,  132,  133,
 /*  1040 */   134,  149,   35,  126,   25,  123,  191,  135,  124,  122,
 /*  1050 */   117,  125,  129,  130,  131,  132,  133,  134,    5,  196,
 /*  1060 */    53,  197,  200,   10,   11,   12,   13,   14,  198,   16,
 /*  1070 */    63,  199,  154,  154,  103,  207,  121,  208,  207,  103,
 /*  1080 */   224,  208,  207,  173,  173,   45,  181,  208,  173,  102,
 /*  1090 */    83,   84,   22,   89,  173,  175,   18,  181,  153,   92,
 /*  1100 */    93,   94,  154,  153,   97,  154,  153,   54,  176,  227,
 /*  1110 */   176,  227,  173,  173,  173,  154,  154,   43,  135,  153,
 /*  1120 */   234,  154,  235,   65,   22,  216,   18,  196,  186,  186,
 /*  1130 */   161,  196,    1,  189,  177,  189,  129,  130,  131,  132,
 /*  1140 */   133,  134,  177,  189,  186,  189,   23,   15,  117,  117,
 /*  1150 */   117,  117,  216,   97,  112,   22,   22,  104,  105,  106,
 /*  1160 */    23,   23,   11,  110,   22,   25,   23,   23,  115,   23,
 /*  1170 */    25,  119,   33,   25,   33,   22,  117,  120,   23,   23,
 /*  1180 */    33,   22,   22,   22,   49,   49,   37,   23,   22,   22,
 /*  1190 */   101,  108,   19,   24,   20,  103,   25,  103,   41,   49,
 /*  1200 */   138,   22,    5,    1,   50,  107,  127,   22,   56,  118,
 /*  1210 */     1,   20,   50,  118,  107,  127,   22,    3,  128,    4,
 /*  1220 */   237,  237,  237,  237,  237,  237,  237,  237,  237,  237,
 /*  1230 */   237,   73,  237,  237,  237,  237,   73,
};
#define YY_SHIFT_USE_DFLT (-110)
#define YY_SHIFT_MAX 362
static const short yy_shift_ofst[] = {
 /*     0 */    42,  906, 1053,  -19,  906, 1007, 1007,   65,  269, 1007,
 /*    10 */  1007, 1007, 1007, 1007,  -48,  190,   19,   64,   83,   83,
 /*    20 */  -109,   52,  123,  194,  266,  338,  409,  480,  551,  622,
 /*    30 */   693,  622,  622,  622,  622,  622,  622,  622,  622,  622,
 /*    40 */   622,  622,  622,  622,  622,  622,  622,  764,  835,  835,
 /*    50 */   923, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007,
 /*    60 */  1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007,
 /*    70 */  1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007, 1007,
 /*    80 */  1007, 1007, 1007, 1007, 1007, 1007, 1007,  -66,  -66,   -1,
 /*    90 */    -1,   54,    9,  306,  417,  297,  169,   64,  -30, -110,
 /*   100 */  -110, -110,   85,  137,  404,  404,  144,  517,   19,  517,
 /*   110 */   517,   19,   19,   19,   19,   19,   19,   19,   19,   19,
 /*   120 */    19,   19,   19,   19,   19,   19,   19,   19,  462,  469,
 /*   130 */  -109, -109, -109, -110, -110,  -21,  -21,   77,    6,  341,
 /*   140 */   350,  355,  410,  260,  423,  482,  493,  422,  487,  444,
 /*   150 */   726,   19,   19,   19,   19,   19,  199,   19,   19,  412,
 /*   160 */    19,   19,  773,   19,   19,   19,   19,   19,  484,  484,
 /*   170 */   484,   19,   19,   19,  328,   19,   19,  328,   19,  757,
 /*   180 */   488,   19,   19,  328,   19,   19,   19,  328,   19,  328,
 /*   190 */   328,  634,  615,  265,   64,  671,  671,  733,  613,  613,
 /*   200 */   850,  613,   82,  613,   64,  613,   64,  -13,  847,  850,
 /*   210 */   850,  847, 1006, 1006, 1006, 1006, 1018, 1018, 1019, -109,
 /*   220 */   917,  922,  924,  927,  926,  912,  933,  933,  971,  955,
 /*   230 */   971,  955,  971,  955,  976,  976, 1040,  976,  987,  976,
 /*   240 */  1070, 1004, 1004, 1040,  976,  976,  976, 1070, 1078,  933,
 /*   250 */  1078,  933, 1078,  933,  933, 1074,  983, 1078,  933, 1058,
 /*   260 */  1058, 1102,  917, 1108, 1108, 1108, 1108,  917, 1058, 1102,
 /*   270 */  -110, -110, -110,  403,  445,  558,  590,  556,  854,  851,
 /*   280 */   852,  838,  798,  792,  913,  914,  925,  929,  930,  937,
 /*   290 */   938, 1131, 1132, 1123, 1031, 1032, 1033, 1034, 1056, 1042,
 /*   300 */  1133, 1137, 1138, 1134, 1151, 1142, 1143, 1140, 1144, 1146,
 /*   310 */  1145, 1139, 1148, 1141, 1145, 1052, 1153, 1147, 1057, 1059,
 /*   320 */  1155, 1156, 1149, 1135, 1159, 1136, 1160, 1164, 1161, 1166,
 /*   330 */  1150, 1167, 1089, 1083, 1173, 1174, 1169, 1092, 1157, 1152,
 /*   340 */  1154, 1171, 1162, 1062, 1094, 1179, 1197, 1202, 1098, 1158,
 /*   350 */  1163, 1079, 1185, 1091, 1209, 1191, 1095, 1107, 1088, 1194,
 /*   360 */  1090, 1214, 1215,
};
#define YY_REDUCE_USE_DFLT (-196)
#define YY_REDUCE_MAX 272
static const short yy_reduce_ofst[] = {
 /*     0 */  -139,  153,  172,   87,  208,   75,   80,   71,  414,   84,
 /*    10 */   155,  149,  289,  292, -195,  296,   25,   57,  132,  202,
 /*    20 */   310,  179,  179,  179,  179,  179,  179,  179,  179,  179,
 /*    30 */   179,  179,  179,  179,  179,  179,  179,  179,  179,  179,
 /*    40 */   179,  179,  179,  179,  179,  179,  179,  179,  179,  179,
 /*    50 */   210,  359,  424,  431,  437,  441,  494,  496,  500,  503,
 /*    60 */   505,  507,  509,  511,  513,  552,  565,  567,  571,  573,
 /*    70 */   577,  580,  582,  584,  623,  636,  638,  642,  645,  649,
 /*    80 */   651,  654,  656,  694,  707,  709,  713,  179,  179,  179,
 /*    90 */   179,   70,  179,  179,   46,  374,  179,  225,  179,  179,
 /*   100 */   179,  179,   56,  476,  427,  529,  604,  -88,   33,  371,
 /*   110 */   555,  396,  538,  566,  640,  138,   39,  710,  512,  249,
 /*   120 */   392,  639,  670,  708,  711,  723,  648,  739,  706,  736,
 /*   130 */   742,  743,  774,  118,  588,  -55,  -10,   -4,  176,  185,
 /*   140 */   281,  185,  185,  259,  325,  440,  463,  185,  317,  572,
 /*   150 */   583,  667,  716,  738,  747,  748,  626,  572,  782,  727,
 /*   160 */   796,  799,  317,  808,  809,  816,  818,  819,  760,  788,
 /*   170 */   791,  824,  826,  827,  185,  829,  830,  185,  831,  659,
 /*   180 */   749,  832,  833,  185,  836,  837,  839,  185,  840,  185,
 /*   190 */   185,  841,  790,  800,  828,  765,  767,  768,  823,  844,
 /*   200 */   795,  845,  825,  848,  842,  849,  846,  853,  806,  804,
 /*   210 */   805,  817,  867,  877,  878,  883,  885,  892,  876,  855,
 /*   220 */   863,  864,  870,  872,  862,  856,  918,  919,  868,  869,
 /*   230 */   871,  873,  875,  879,  910,  911,  905,  915,  920,  921,
 /*   240 */   932,  882,  884,  916,  939,  940,  941,  934,  945,  948,
 /*   250 */   950,  951,  953,  961,  962,  886,  887,  966,  967,  942,
 /*   260 */   943,  909,  931,  944,  946,  954,  956,  935,  958,  936,
 /*   270 */   969,  957,  965,
};
static const YYACTIONTYPE yy_default[] = {
 /*     0 */   551,  784,  828,  672,  828,  784,  828,  828,  828,  782,
 /*    10 */   828,  828,  828,  828,  756,  828,  828,  588,  801,  801,
 /*    20 */   676,  707,  828,  828,  828,  828,  828,  828,  828,  708,
 /*    30 */   828,  786,  781,  777,  779,  778,  785,  709,  698,  705,
 /*    40 */   712,  687,  814,  714,  715,  721,  722,  744,  743,  762,
83462
83463
83464
83465
83466
83467
83468
83469
83470
83471
83472
83473
83474
83475
83476
83477
83478
83479
83480
83481
83482
83483
83484
83485
83486
83487
83488
83489

83490
83491

83492
83493
83494
83495
83496
83497
83498
   26,  /*      BEGIN => ID */
    0,  /* TRANSACTION => nothing */
   26,  /*   DEFERRED => ID */
   26,  /*  IMMEDIATE => ID */
   26,  /*  EXCLUSIVE => ID */
    0,  /*     COMMIT => nothing */
   26,  /*        END => ID */
    0,  /*   ROLLBACK => nothing */
    0,  /*  SAVEPOINT => nothing */
    0,  /*    RELEASE => nothing */
    0,  /*         TO => nothing */
    0,  /*     CREATE => nothing */
    0,  /*      TABLE => nothing */
   26,  /*         IF => ID */
    0,  /*        NOT => nothing */
    0,  /*     EXISTS => nothing */
   26,  /*       TEMP => ID */
    0,  /*         LP => nothing */
    0,  /*         RP => nothing */
    0,  /*         AS => nothing */
    0,  /*      COMMA => nothing */
    0,  /*         ID => nothing */
   26,  /*      ABORT => ID */
   26,  /*      AFTER => ID */
   26,  /*    ANALYZE => ID */
   26,  /*        ASC => ID */
   26,  /*     ATTACH => ID */
   26,  /*     BEFORE => ID */

   26,  /*    CASCADE => ID */
   26,  /*       CAST => ID */

   26,  /*   CONFLICT => ID */
   26,  /*   DATABASE => ID */
   26,  /*       DESC => ID */
   26,  /*     DETACH => ID */
   26,  /*       EACH => ID */
   26,  /*       FAIL => ID */
   26,  /*        FOR => ID */







|
|
|


















>


>







84359
84360
84361
84362
84363
84364
84365
84366
84367
84368
84369
84370
84371
84372
84373
84374
84375
84376
84377
84378
84379
84380
84381
84382
84383
84384
84385
84386
84387
84388
84389
84390
84391
84392
84393
84394
84395
84396
84397
   26,  /*      BEGIN => ID */
    0,  /* TRANSACTION => nothing */
   26,  /*   DEFERRED => ID */
   26,  /*  IMMEDIATE => ID */
   26,  /*  EXCLUSIVE => ID */
    0,  /*     COMMIT => nothing */
   26,  /*        END => ID */
   26,  /*   ROLLBACK => ID */
   26,  /*  SAVEPOINT => ID */
   26,  /*    RELEASE => ID */
    0,  /*         TO => nothing */
    0,  /*     CREATE => nothing */
    0,  /*      TABLE => nothing */
   26,  /*         IF => ID */
    0,  /*        NOT => nothing */
    0,  /*     EXISTS => nothing */
   26,  /*       TEMP => ID */
    0,  /*         LP => nothing */
    0,  /*         RP => nothing */
    0,  /*         AS => nothing */
    0,  /*      COMMA => nothing */
    0,  /*         ID => nothing */
   26,  /*      ABORT => ID */
   26,  /*      AFTER => ID */
   26,  /*    ANALYZE => ID */
   26,  /*        ASC => ID */
   26,  /*     ATTACH => ID */
   26,  /*     BEFORE => ID */
   26,  /*         BY => ID */
   26,  /*    CASCADE => ID */
   26,  /*       CAST => ID */
   26,  /*   COLUMNKW => ID */
   26,  /*   CONFLICT => ID */
   26,  /*   DATABASE => ID */
   26,  /*       DESC => ID */
   26,  /*     DETACH => ID */
   26,  /*       EACH => ID */
   26,  /*       FAIL => ID */
   26,  /*        FOR => ID */
83569
83570
83571
83572
83573
83574
83575
83576
83577
83578
83579
83580
83581
83582
83583
    0,  /*  INTERSECT => nothing */
    0,  /*     SELECT => nothing */
    0,  /*   DISTINCT => nothing */
    0,  /*        DOT => nothing */
    0,  /*       FROM => nothing */
    0,  /*       JOIN => nothing */
    0,  /*    INDEXED => nothing */
    0,  /*         BY => nothing */
    0,  /*      USING => nothing */
    0,  /*      ORDER => nothing */
    0,  /*      GROUP => nothing */
    0,  /*     HAVING => nothing */
    0,  /*      LIMIT => nothing */
    0,  /*      WHERE => nothing */
    0,  /*       INTO => nothing */







<







84468
84469
84470
84471
84472
84473
84474

84475
84476
84477
84478
84479
84480
84481
    0,  /*  INTERSECT => nothing */
    0,  /*     SELECT => nothing */
    0,  /*   DISTINCT => nothing */
    0,  /*        DOT => nothing */
    0,  /*       FROM => nothing */
    0,  /*       JOIN => nothing */
    0,  /*    INDEXED => nothing */

    0,  /*      USING => nothing */
    0,  /*      ORDER => nothing */
    0,  /*      GROUP => nothing */
    0,  /*     HAVING => nothing */
    0,  /*      LIMIT => nothing */
    0,  /*      WHERE => nothing */
    0,  /*       INTO => nothing */
83673
83674
83675
83676
83677
83678
83679
83680
83681

83682
83683
83684
83685
83686
83687
83688
83689
83690
83691
83692
83693
83694
83695
83696
83697
83698
83699
83700
83701
83702
83703
83704
83705
83706
83707
83708
83709
83710
83711
83712
83713
83714
83715
83716
83717
83718
83719
83720
83721
83722
83723
83724
83725
83726
83727
83728
83729
83730

83731
83732
83733
83734
83735
83736
83737
  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
  "CREATE",        "TABLE",         "IF",            "NOT",         
  "EXISTS",        "TEMP",          "LP",            "RP",          
  "AS",            "COMMA",         "ID",            "ABORT",       
  "AFTER",         "ANALYZE",       "ASC",           "ATTACH",      
  "BEFORE",        "CASCADE",       "CAST",          "CONFLICT",    
  "DATABASE",      "DESC",          "DETACH",        "EACH",        

  "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
  "INSTEAD",       "LIKE_KW",       "MATCH",         "KEY",         
  "OF",            "OFFSET",        "PRAGMA",        "RAISE",       
  "REPLACE",       "RESTRICT",      "ROW",           "TRIGGER",     
  "VACUUM",        "VIEW",          "VIRTUAL",       "REINDEX",     
  "RENAME",        "CTIME_KW",      "ANY",           "OR",          
  "AND",           "IS",            "BETWEEN",       "IN",          
  "ISNULL",        "NOTNULL",       "NE",            "EQ",          
  "GT",            "LE",            "LT",            "GE",          
  "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",      
  "RSHIFT",        "PLUS",          "MINUS",         "STAR",        
  "SLASH",         "REM",           "CONCAT",        "COLLATE",     
  "UMINUS",        "UPLUS",         "BITNOT",        "STRING",      
  "JOIN_KW",       "CONSTRAINT",    "DEFAULT",       "NULL",        
  "PRIMARY",       "UNIQUE",        "CHECK",         "REFERENCES",  
  "AUTOINCR",      "ON",            "DELETE",        "UPDATE",      
  "INSERT",        "SET",           "DEFERRABLE",    "FOREIGN",     
  "DROP",          "UNION",         "ALL",           "EXCEPT",      
  "INTERSECT",     "SELECT",        "DISTINCT",      "DOT",         
  "FROM",          "JOIN",          "INDEXED",       "BY",          
  "USING",         "ORDER",         "GROUP",         "HAVING",      
  "LIMIT",         "WHERE",         "INTO",          "VALUES",      
  "INTEGER",       "FLOAT",         "BLOB",          "REGISTER",    
  "VARIABLE",      "CASE",          "WHEN",          "THEN",        
  "ELSE",          "INDEX",         "error",         "input",       
  "cmdlist",       "ecmd",          "explain",       "cmdx",        
  "cmd",           "transtype",     "trans_opt",     "nm",          
  "savepoint_opt",  "create_table",  "create_table_args",  "temp",        
  "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
  "select",        "column",        "columnid",      "type",        
  "carglist",      "id",            "ids",           "typetoken",   
  "typename",      "signed",        "plus_num",      "minus_num",   
  "carg",          "ccons",         "term",          "expr",        
  "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
  "refargs",       "defer_subclause",  "refarg",        "refact",      
  "init_deferred_pred_opt",  "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",        "indexed_opt",   "on_opt",        "using_opt",   
  "joinop2",       "inscollist",    "sortlist",      "sortitem",    
  "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
  "itemlist",      "exprlist",      "likeop",        "escape",      
  "between_op",    "in_op",         "case_operand",  "case_exprlist",
  "case_else",     "uniqueflag",    "collate",       "plus_opt",    
  "number",        "trigger_decl",  "trigger_cmd_list",  "trigger_time",
  "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 

};
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {







|
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>







84571
84572
84573
84574
84575
84576
84577
84578
84579
84580
84581
84582
84583
84584
84585
84586
84587
84588
84589
84590
84591
84592
84593
84594
84595
84596
84597

84598
84599
84600
84601
84602
84603
84604
84605
84606
84607
84608
84609
84610
84611
84612
84613
84614
84615
84616
84617
84618
84619
84620
84621
84622
84623
84624
84625
84626
84627
84628
84629
84630
84631
84632
84633
84634
84635
84636
  "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
  "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
  "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
  "CREATE",        "TABLE",         "IF",            "NOT",         
  "EXISTS",        "TEMP",          "LP",            "RP",          
  "AS",            "COMMA",         "ID",            "ABORT",       
  "AFTER",         "ANALYZE",       "ASC",           "ATTACH",      
  "BEFORE",        "BY",            "CASCADE",       "CAST",        
  "COLUMNKW",      "CONFLICT",      "DATABASE",      "DESC",        
  "DETACH",        "EACH",          "FAIL",          "FOR",         
  "IGNORE",        "INITIALLY",     "INSTEAD",       "LIKE_KW",     
  "MATCH",         "KEY",           "OF",            "OFFSET",      
  "PRAGMA",        "RAISE",         "REPLACE",       "RESTRICT",    
  "ROW",           "TRIGGER",       "VACUUM",        "VIEW",        
  "VIRTUAL",       "REINDEX",       "RENAME",        "CTIME_KW",    
  "ANY",           "OR",            "AND",           "IS",          
  "BETWEEN",       "IN",            "ISNULL",        "NOTNULL",     
  "NE",            "EQ",            "GT",            "LE",          
  "LT",            "GE",            "ESCAPE",        "BITAND",      
  "BITOR",         "LSHIFT",        "RSHIFT",        "PLUS",        
  "MINUS",         "STAR",          "SLASH",         "REM",         
  "CONCAT",        "COLLATE",       "UMINUS",        "UPLUS",       
  "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",  
  "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
  "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
  "DELETE",        "UPDATE",        "INSERT",        "SET",         
  "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       

  "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
  "DISTINCT",      "DOT",           "FROM",          "JOIN",        
  "INDEXED",       "USING",         "ORDER",         "GROUP",       
  "HAVING",        "LIMIT",         "WHERE",         "INTO",        
  "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
  "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
  "THEN",          "ELSE",          "INDEX",         "error",       
  "input",         "cmdlist",       "ecmd",          "explain",     
  "cmdx",          "cmd",           "transtype",     "trans_opt",   
  "nm",            "savepoint_opt",  "create_table",  "create_table_args",
  "temp",          "ifnotexists",   "dbnm",          "columnlist",  
  "conslist_opt",  "select",        "column",        "columnid",    
  "type",          "carglist",      "id",            "ids",         
  "typetoken",     "typename",      "signed",        "plus_num",    
  "minus_num",     "carg",          "ccons",         "term",        
  "expr",          "onconf",        "sortorder",     "autoinc",     
  "idxlist_opt",   "refargs",       "defer_subclause",  "refarg",      
  "refact",        "init_deferred_pred_opt",  "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",        "indexed_opt",   "on_opt",      
  "using_opt",     "joinop2",       "inscollist",    "sortlist",    
  "sortitem",      "nexprlist",     "setlist",       "insert_cmd",  
  "inscollist_opt",  "itemlist",      "exprlist",      "likeop",      
  "escape",        "between_op",    "in_op",         "case_operand",
  "case_exprlist",  "case_else",     "uniqueflag",    "collate",     
  "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
  "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
  "trigger_cmd", 
};
#endif /* NDEBUG */

#ifndef NDEBUG
/* For tracing reduce actions, the names of all rules are required.
*/
static const char *const yyRuleName[] = {
84091
84092
84093
84094
84095
84096
84097
84098
84099
84100
84101
84102
84103
84104
84105
84106
84107
84108
84109
84110
84111
84112
84113
84114
84115
84116
84117
84118
84119
84120
84121
84122
84123
84124
84125
84126
84127
84128
84129
84130
84131
84132
84133
84134
84135
84136
84137
84138
84139
84140
84141
84142
84143
84144
84145
84146
84147
84148
84149
84150
84151
84152
84153
84154
84155
84156
84157
84158
84159
84160
84161
84162
84163
84164
    ** reduce or during error processing or when a parser is 
    ** being destroyed before it is finished parsing.
    **
    ** Note: during a reduce, the only symbols destroyed are those
    ** which appear on the RHS of the rule, but which are not used
    ** inside the C code.
    */
    case 156: /* select */
    case 190: /* oneselect */
{
sqlite3SelectDelete(pParse->db, (yypminor->yy387));
}
      break;
    case 170: /* term */
    case 171: /* expr */
    case 195: /* where_opt */
    case 197: /* having_opt */
    case 206: /* on_opt */
    case 211: /* sortitem */
    case 219: /* escape */
    case 222: /* case_operand */
    case 224: /* case_else */
    case 234: /* when_clause */
{
sqlite3ExprDelete(pParse->db, (yypminor->yy402));
}
      break;
    case 175: /* idxlist_opt */
    case 183: /* idxlist */
    case 193: /* selcollist */
    case 196: /* groupby_opt */
    case 198: /* orderby_opt */
    case 200: /* sclp */
    case 210: /* sortlist */
    case 212: /* nexprlist */
    case 213: /* setlist */
    case 216: /* itemlist */
    case 217: /* exprlist */
    case 223: /* case_exprlist */
{
sqlite3ExprListDelete(pParse->db, (yypminor->yy258));
}
      break;
    case 189: /* fullname */
    case 194: /* from */
    case 202: /* seltablist */
    case 203: /* stl_prefix */
{
sqlite3SrcListDelete(pParse->db, (yypminor->yy3));
}
      break;
    case 207: /* using_opt */
    case 209: /* inscollist */
    case 215: /* inscollist_opt */
{
sqlite3IdListDelete(pParse->db, (yypminor->yy400));
}
      break;
    case 230: /* trigger_cmd_list */
    case 235: /* trigger_cmd */
{
sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy19));
}
      break;
    case 232: /* trigger_event */
{
sqlite3IdListDelete(pParse->db, (yypminor->yy466).b);
}
      break;
    default:  break;   /* If no destructor action specified: do nothing */
  }
}

/*







|
|

|


|
|
|
|
|
|
|
|
|
|

|


|
|
|
|
|
|
|
|
|
|
|
|

|


|
|
|
|

|


|
|
|

|


|
|

|


|

|







84990
84991
84992
84993
84994
84995
84996
84997
84998
84999
85000
85001
85002
85003
85004
85005
85006
85007
85008
85009
85010
85011
85012
85013
85014
85015
85016
85017
85018
85019
85020
85021
85022
85023
85024
85025
85026
85027
85028
85029
85030
85031
85032
85033
85034
85035
85036
85037
85038
85039
85040
85041
85042
85043
85044
85045
85046
85047
85048
85049
85050
85051
85052
85053
85054
85055
85056
85057
85058
85059
85060
85061
85062
85063
    ** reduce or during error processing or when a parser is 
    ** being destroyed before it is finished parsing.
    **
    ** Note: during a reduce, the only symbols destroyed are those
    ** which appear on the RHS of the rule, but which are not used
    ** inside the C code.
    */
    case 157: /* select */
    case 191: /* oneselect */
{
sqlite3SelectDelete(pParse->db, (yypminor->yy465));
}
      break;
    case 171: /* term */
    case 172: /* expr */
    case 196: /* where_opt */
    case 198: /* having_opt */
    case 207: /* on_opt */
    case 212: /* sortitem */
    case 220: /* escape */
    case 223: /* case_operand */
    case 225: /* case_else */
    case 235: /* when_clause */
{
sqlite3ExprDelete(pParse->db, (yypminor->yy128));
}
      break;
    case 176: /* idxlist_opt */
    case 184: /* idxlist */
    case 194: /* selcollist */
    case 197: /* groupby_opt */
    case 199: /* orderby_opt */
    case 201: /* sclp */
    case 211: /* sortlist */
    case 213: /* nexprlist */
    case 214: /* setlist */
    case 217: /* itemlist */
    case 218: /* exprlist */
    case 224: /* case_exprlist */
{
sqlite3ExprListDelete(pParse->db, (yypminor->yy22));
}
      break;
    case 190: /* fullname */
    case 195: /* from */
    case 203: /* seltablist */
    case 204: /* stl_prefix */
{
sqlite3SrcListDelete(pParse->db, (yypminor->yy133));
}
      break;
    case 208: /* using_opt */
    case 210: /* inscollist */
    case 216: /* inscollist_opt */
{
sqlite3IdListDelete(pParse->db, (yypminor->yy288));
}
      break;
    case 231: /* trigger_cmd_list */
    case 236: /* trigger_cmd */
{
sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy167));
}
      break;
    case 233: /* trigger_event */
{
sqlite3IdListDelete(pParse->db, (yypminor->yy366).b);
}
      break;
    default:  break;   /* If no destructor action specified: do nothing */
  }
}

/*
84383
84384
84385
84386
84387
84388
84389
84390
84391
84392
84393
84394
84395
84396
84397

84398

84399




84400
84401
84402
84403
84404
84405
84406
84407
84408
84409
84410
84411
84412
84413
84414
84415
84416



84417
84418
84419
84420
84421
84422
84423
84424
84425
84426
84427
84428
84429
84430
84431
84432
84433
84434
84435
84436
84437
84438

84439
84440


84441
84442
84443
84444
84445
84446
84447
84448
84449
84450
84451
84452
84453
84454
84455
84456
84457
84458
84459
84460
84461
84462
84463
84464
84465
84466
84467
84468
84469
84470
84471
84472
84473
84474
84475


84476
84477
84478
84479

84480
84481
84482
84483
84484
84485
84486
84487
84488
84489
84490
84491
84492
84493
84494
84495
84496
84497
84498
84499
84500
84501
84502
84503
84504
84505
84506
84507
84508
84509
84510
84511
84512
84513
84514
84515
84516
84517
84518
84519
84520
84521
84522
84523
84524
84525
84526
84527
84528
84529
84530
84531
84532
84533
84534
84535
84536
84537
84538
84539
84540
84541
84542
84543
84544
84545
84546
84547
84548
84549
84550
84551
84552
84553
84554
84555
84556
84557
84558
84559
84560
84561
84562
84563
84564
84565
84566
84567
84568
84569
84570
84571
84572
84573
84574
84575
84576
84577
84578
84579
84580
84581
84582
84583
84584
84585
84586
84587
84588
84589
84590
84591
84592
84593
84594
84595
84596
84597
84598
84599
84600
84601
84602
84603
84604
84605
84606
84607
84608
84609
84610
84611
84612
84613
84614
84615
84616
84617
84618
84619
84620
84621
84622
84623
84624
84625
84626
84627
84628
84629
84630
84631
84632
84633
84634
84635
84636
84637
84638
84639
84640
84641
84642
84643
84644
84645
84646
84647
84648
84649
84650
84651
84652
84653
84654
84655
84656
84657
84658
84659
84660
84661
84662
84663
84664
84665
84666
84667
84668
84669
84670



















84671






























































































































































84672
84673
84674
84675
84676
84677
84678
/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {
  { 139, 1 },
  { 140, 2 },
  { 140, 1 },
  { 141, 1 },
  { 141, 3 },
  { 142, 0 },
  { 142, 1 },
  { 142, 3 },

  { 143, 1 },

  { 144, 3 },




  { 146, 0 },
  { 146, 1 },
  { 146, 2 },
  { 145, 0 },
  { 145, 1 },
  { 145, 1 },
  { 145, 1 },
  { 144, 2 },
  { 144, 2 },
  { 144, 2 },
  { 148, 1 },
  { 148, 0 },
  { 144, 2 },
  { 144, 3 },
  { 144, 5 },
  { 144, 2 },
  { 149, 6 },



  { 152, 0 },
  { 152, 3 },
  { 151, 1 },
  { 151, 0 },
  { 150, 4 },
  { 150, 2 },
  { 154, 3 },
  { 154, 1 },
  { 157, 3 },
  { 158, 1 },
  { 161, 1 },
  { 162, 1 },
  { 147, 1 },
  { 147, 1 },
  { 147, 1 },
  { 159, 0 },
  { 159, 1 },
  { 163, 1 },
  { 163, 4 },
  { 163, 6 },
  { 164, 1 },
  { 164, 2 },

  { 165, 1 },
  { 165, 1 },


  { 160, 2 },
  { 160, 0 },
  { 168, 3 },
  { 168, 1 },
  { 169, 2 },
  { 169, 4 },
  { 169, 3 },
  { 169, 3 },
  { 169, 2 },
  { 169, 2 },
  { 169, 3 },
  { 169, 5 },
  { 169, 2 },
  { 169, 4 },
  { 169, 4 },
  { 169, 1 },
  { 169, 2 },
  { 174, 0 },
  { 174, 1 },
  { 176, 0 },
  { 176, 2 },
  { 178, 2 },
  { 178, 3 },
  { 178, 3 },
  { 178, 3 },
  { 179, 2 },
  { 179, 2 },
  { 179, 1 },
  { 179, 1 },
  { 177, 3 },
  { 177, 2 },
  { 180, 0 },
  { 180, 2 },
  { 180, 2 },
  { 155, 0 },


  { 155, 2 },
  { 181, 3 },
  { 181, 2 },
  { 181, 1 },

  { 182, 2 },
  { 182, 7 },
  { 182, 5 },
  { 182, 5 },
  { 182, 10 },
  { 184, 0 },
  { 184, 1 },
  { 172, 0 },
  { 172, 3 },
  { 185, 0 },
  { 185, 2 },
  { 186, 1 },
  { 186, 1 },
  { 186, 1 },
  { 144, 4 },
  { 188, 2 },
  { 188, 0 },
  { 144, 8 },
  { 144, 4 },
  { 144, 1 },
  { 156, 1 },
  { 156, 3 },
  { 191, 1 },
  { 191, 2 },
  { 191, 1 },
  { 190, 9 },
  { 192, 1 },
  { 192, 1 },
  { 192, 0 },
  { 200, 2 },
  { 200, 0 },
  { 193, 3 },
  { 193, 2 },
  { 193, 4 },
  { 201, 2 },
  { 201, 1 },
  { 201, 0 },
  { 194, 0 },
  { 194, 2 },
  { 203, 2 },
  { 203, 0 },
  { 202, 7 },
  { 202, 7 },
  { 202, 7 },
  { 153, 0 },
  { 153, 2 },
  { 189, 2 },
  { 204, 1 },
  { 204, 2 },
  { 204, 3 },
  { 204, 4 },
  { 206, 2 },
  { 206, 0 },
  { 205, 0 },
  { 205, 3 },
  { 205, 2 },
  { 207, 4 },
  { 207, 0 },
  { 198, 0 },
  { 198, 3 },
  { 210, 4 },
  { 210, 2 },
  { 211, 1 },
  { 173, 1 },
  { 173, 1 },
  { 173, 0 },
  { 196, 0 },
  { 196, 3 },
  { 197, 0 },
  { 197, 2 },
  { 199, 0 },
  { 199, 2 },
  { 199, 4 },
  { 199, 4 },
  { 144, 5 },
  { 195, 0 },
  { 195, 2 },
  { 144, 7 },
  { 213, 5 },
  { 213, 3 },
  { 144, 8 },
  { 144, 5 },
  { 144, 6 },
  { 214, 2 },
  { 214, 1 },
  { 216, 3 },
  { 216, 1 },
  { 215, 0 },
  { 215, 3 },
  { 209, 3 },
  { 209, 1 },
  { 171, 1 },
  { 171, 3 },
  { 170, 1 },
  { 171, 1 },
  { 171, 1 },
  { 171, 3 },
  { 171, 5 },
  { 170, 1 },
  { 170, 1 },
  { 171, 1 },
  { 171, 1 },
  { 171, 3 },
  { 171, 6 },
  { 171, 5 },
  { 171, 4 },
  { 170, 1 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 171, 3 },
  { 218, 1 },
  { 218, 2 },
  { 218, 1 },
  { 218, 2 },
  { 219, 2 },
  { 219, 0 },
  { 171, 4 },
  { 171, 2 },
  { 171, 3 },
  { 171, 3 },
  { 171, 4 },
  { 171, 2 },
  { 171, 2 },
  { 171, 2 },
  { 171, 2 },
  { 220, 1 },
  { 220, 2 },
  { 171, 5 },
  { 221, 1 },
  { 221, 2 },
  { 171, 5 },
  { 171, 3 },
  { 171, 5 },
  { 171, 4 },
  { 171, 4 },
  { 171, 5 },
  { 223, 5 },
  { 223, 4 },
  { 224, 2 },
  { 224, 0 },
  { 222, 1 },
  { 222, 0 },
  { 217, 1 },
  { 217, 0 },
  { 212, 3 },
  { 212, 1 },
  { 144, 11 },
  { 225, 1 },
  { 225, 0 },
  { 175, 0 },
  { 175, 3 },
  { 183, 5 },
  { 183, 3 },
  { 226, 0 },
  { 226, 2 },
  { 144, 4 },
  { 166, 2 },
  { 167, 2 },
  { 228, 1 },
  { 227, 1 },
  { 227, 0 },
  { 144, 5 },
  { 229, 11 },
  { 231, 1 },
  { 231, 1 },
  { 231, 2 },
  { 231, 0 },
  { 232, 1 },
  { 232, 1 },
  { 232, 3 },
  { 233, 0 },
  { 233, 3 },
  { 234, 0 },
  { 234, 2 },
  { 230, 3 },
  { 230, 2 },
  { 235, 6 },
  { 235, 8 },
  { 235, 5 },
  { 235, 4 },
  { 235, 1 },
  { 171, 4 },
  { 171, 6 },
  { 187, 1 },
  { 187, 1 },
  { 187, 1 },



















  { 144, 4 },






























































































































































};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.







<
<

|
|
<


>

>
|
>
>
>
>


|
|
|
|
|
<
<
<
|
|
|
|
|
|
|
>
>
>

<
|
|
<
<
|
|
<
|
|

|
|
|
<
|
|
|
<

|
>

|
>
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
<
<
<

|
|
|
<
<
<


|
>
>
|
|

|
>
|
|
|
|
|
|
|
|
|

|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







85282
85283
85284
85285
85286
85287
85288


85289
85290
85291

85292
85293
85294
85295
85296
85297
85298
85299
85300
85301
85302
85303
85304
85305
85306
85307
85308



85309
85310
85311
85312
85313
85314
85315
85316
85317
85318
85319

85320
85321


85322
85323

85324
85325
85326
85327
85328
85329

85330
85331
85332

85333
85334
85335
85336
85337
85338
85339
85340
85341
85342
85343
85344
85345
85346
85347
85348
85349
85350
85351
85352
85353
85354
85355
85356
85357
85358
85359
85360




85361
85362
85363
85364



85365
85366
85367
85368
85369
85370
85371
85372
85373
85374
85375
85376
85377
85378
85379
85380
85381
85382
85383
85384
85385






















































85386













85387














































































85388
85389




























85390
85391
85392
85393
85394
85395
85396
85397
85398
85399
85400
85401
85402
85403
85404
85405
85406
85407
85408
85409
85410
85411
85412
85413
85414
85415
85416
85417
85418
85419
85420
85421
85422
85423
85424
85425
85426
85427
85428
85429
85430
85431
85432
85433
85434
85435
85436
85437
85438
85439
85440
85441
85442
85443
85444
85445
85446
85447
85448
85449
85450
85451
85452
85453
85454
85455
85456
85457
85458
85459
85460
85461
85462
85463
85464
85465
85466
85467
85468
85469
85470
85471
85472
85473
85474
85475
85476
85477
85478
85479
85480
85481
85482
85483
85484
85485
85486
85487
85488
85489
85490
85491
85492
85493
85494
85495
85496
85497
85498
85499
85500
85501
85502
85503
85504
85505
85506
85507
85508
85509
85510
85511
85512
85513
85514
85515
85516
85517
85518
85519
85520
85521
85522
85523
85524
85525
85526
85527
85528
85529
85530
85531
85532
85533
85534
85535
85536
85537
85538
85539
85540
85541
85542
85543
85544
85545
85546
85547
85548
85549
85550
85551
85552
85553
85554
85555
85556
85557
85558
85559
85560
85561
85562
85563
85564
85565
85566
85567
85568
85569
85570
85571
85572
85573
85574
85575
85576
85577
/* The following table contains information about every rule that
** is used during the reduce.
*/
static const struct {
  YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
  unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
} yyRuleInfo[] = {


  { 140, 1 },
  { 141, 2 },
  { 141, 1 },

  { 142, 1 },
  { 142, 3 },
  { 143, 0 },
  { 143, 1 },
  { 143, 3 },
  { 144, 1 },
  { 145, 3 },
  { 147, 0 },
  { 147, 1 },
  { 147, 2 },
  { 146, 0 },
  { 146, 1 },
  { 146, 1 },
  { 146, 1 },
  { 145, 2 },
  { 145, 2 },
  { 145, 2 },



  { 149, 1 },
  { 149, 0 },
  { 145, 2 },
  { 145, 3 },
  { 145, 5 },
  { 145, 2 },
  { 150, 6 },
  { 153, 0 },
  { 153, 3 },
  { 152, 1 },
  { 152, 0 },

  { 151, 4 },
  { 151, 2 },


  { 155, 3 },
  { 155, 1 },

  { 158, 3 },
  { 159, 1 },
  { 162, 1 },
  { 163, 1 },
  { 148, 1 },
  { 148, 1 },

  { 148, 1 },
  { 160, 0 },
  { 160, 1 },

  { 164, 1 },
  { 164, 4 },
  { 164, 6 },
  { 165, 1 },
  { 165, 2 },
  { 166, 1 },
  { 166, 1 },
  { 161, 2 },
  { 161, 0 },
  { 169, 3 },
  { 169, 1 },
  { 170, 2 },
  { 170, 4 },
  { 170, 3 },
  { 170, 3 },
  { 170, 2 },
  { 170, 2 },
  { 170, 3 },
  { 170, 5 },
  { 170, 2 },
  { 170, 4 },
  { 170, 4 },
  { 170, 1 },
  { 170, 2 },
  { 175, 0 },
  { 175, 1 },
  { 177, 0 },
  { 177, 2 },




  { 179, 2 },
  { 179, 3 },
  { 179, 3 },
  { 179, 3 },



  { 180, 2 },
  { 180, 2 },
  { 180, 1 },
  { 180, 1 },
  { 178, 3 },
  { 178, 2 },
  { 181, 0 },
  { 181, 2 },
  { 181, 2 },
  { 156, 0 },
  { 156, 2 },
  { 182, 3 },
  { 182, 2 },
  { 182, 1 },
  { 183, 2 },
  { 183, 7 },
  { 183, 5 },
  { 183, 5 },
  { 183, 10 },
  { 185, 0 },
  { 185, 1 },






















































  { 173, 0 },













  { 173, 3 },














































































  { 186, 0 },
  { 186, 2 },




























  { 187, 1 },
  { 187, 1 },
  { 187, 1 },
  { 145, 4 },
  { 189, 2 },
  { 189, 0 },
  { 145, 8 },
  { 145, 4 },
  { 145, 1 },
  { 157, 1 },
  { 157, 3 },
  { 192, 1 },
  { 192, 2 },
  { 192, 1 },
  { 191, 9 },
  { 193, 1 },
  { 193, 1 },
  { 193, 0 },
  { 201, 2 },
  { 201, 0 },
  { 194, 3 },
  { 194, 2 },
  { 194, 4 },
  { 202, 2 },
  { 202, 1 },
  { 202, 0 },
  { 195, 0 },
  { 195, 2 },
  { 204, 2 },
  { 204, 0 },
  { 203, 7 },
  { 203, 7 },
  { 203, 7 },
  { 154, 0 },
  { 154, 2 },
  { 190, 2 },
  { 205, 1 },
  { 205, 2 },
  { 205, 3 },
  { 205, 4 },
  { 207, 2 },
  { 207, 0 },
  { 206, 0 },
  { 206, 3 },
  { 206, 2 },
  { 208, 4 },
  { 208, 0 },
  { 199, 0 },
  { 199, 3 },
  { 211, 4 },
  { 211, 2 },
  { 212, 1 },
  { 174, 1 },
  { 174, 1 },
  { 174, 0 },
  { 197, 0 },
  { 197, 3 },
  { 198, 0 },
  { 198, 2 },
  { 200, 0 },
  { 200, 2 },
  { 200, 4 },
  { 200, 4 },
  { 145, 5 },
  { 196, 0 },
  { 196, 2 },
  { 145, 7 },
  { 214, 5 },
  { 214, 3 },
  { 145, 8 },
  { 145, 5 },
  { 145, 6 },
  { 215, 2 },
  { 215, 1 },
  { 217, 3 },
  { 217, 1 },
  { 216, 0 },
  { 216, 3 },
  { 210, 3 },
  { 210, 1 },
  { 172, 1 },
  { 172, 3 },
  { 171, 1 },
  { 172, 1 },
  { 172, 1 },
  { 172, 3 },
  { 172, 5 },
  { 171, 1 },
  { 171, 1 },
  { 172, 1 },
  { 172, 1 },
  { 172, 3 },
  { 172, 6 },
  { 172, 5 },
  { 172, 4 },
  { 171, 1 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 172, 3 },
  { 219, 1 },
  { 219, 2 },
  { 219, 1 },
  { 219, 2 },
  { 220, 2 },
  { 220, 0 },
  { 172, 4 },
  { 172, 2 },
  { 172, 3 },
  { 172, 3 },
  { 172, 4 },
  { 172, 2 },
  { 172, 2 },
  { 172, 2 },
  { 172, 2 },
  { 221, 1 },
  { 221, 2 },
  { 172, 5 },
  { 222, 1 },
  { 222, 2 },
  { 172, 5 },
  { 172, 3 },
  { 172, 5 },
  { 172, 4 },
  { 172, 4 },
  { 172, 5 },
  { 224, 5 },
  { 224, 4 },
  { 225, 2 },
  { 225, 0 },
  { 223, 1 },
  { 223, 0 },
  { 218, 1 },
  { 218, 0 },
  { 213, 3 },
  { 213, 1 },
  { 145, 11 },
  { 226, 1 },
  { 226, 0 },
  { 176, 0 },
  { 176, 3 },
  { 184, 5 },
  { 184, 3 },
  { 227, 0 },
  { 227, 2 },
  { 145, 4 },
  { 167, 2 },
  { 168, 2 },
  { 229, 1 },
  { 228, 1 },
  { 228, 0 },
  { 145, 5 },
  { 230, 11 },
  { 232, 1 },
  { 232, 1 },
  { 232, 2 },
  { 232, 0 },
  { 233, 1 },
  { 233, 1 },
  { 233, 3 },
  { 234, 0 },
  { 234, 3 },
  { 235, 0 },
  { 235, 2 },
  { 231, 3 },
  { 231, 2 },
  { 236, 6 },
  { 236, 8 },
  { 236, 5 },
  { 236, 4 },
  { 236, 1 },
  { 172, 4 },
  { 172, 6 },
  { 188, 1 },
  { 188, 1 },
  { 188, 1 },
  { 145, 4 },
};

static void yy_accept(yyParser*);  /* Forward Declaration */

/*
** Perform a reduce action and the shift that must immediately
** follow the reduce.
84764
84765
84766
84767
84768
84769
84770
84771
84772
84773
84774
84775
84776
84777
84778
84779
84780
84781
84782
84783
84784
84785
84786
84787
84788
      case 7: /* explain ::= EXPLAIN QUERY PLAN */
{ sqlite3BeginParse(pParse, 2); }
        break;
      case 8: /* cmdx ::= cmd */
{ sqlite3FinishCoding(pParse); }
        break;
      case 9: /* cmd ::= BEGIN transtype trans_opt */
{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy228);}
        break;
      case 13: /* transtype ::= */
{yygotominor.yy228 = TK_DEFERRED;}
        break;
      case 14: /* transtype ::= DEFERRED */
      case 15: /* transtype ::= IMMEDIATE */
      case 16: /* transtype ::= EXCLUSIVE */
      case 112: /* multiselect_op ::= UNION */
      case 114: /* multiselect_op ::= EXCEPT|INTERSECT */
{yygotominor.yy228 = yymsp[0].major;}
        break;
      case 17: /* cmd ::= COMMIT trans_opt */
      case 18: /* cmd ::= END trans_opt */
{sqlite3CommitTransaction(pParse);}
        break;
      case 19: /* cmd ::= ROLLBACK trans_opt */
{sqlite3RollbackTransaction(pParse);}







|


|






|







85663
85664
85665
85666
85667
85668
85669
85670
85671
85672
85673
85674
85675
85676
85677
85678
85679
85680
85681
85682
85683
85684
85685
85686
85687
      case 7: /* explain ::= EXPLAIN QUERY PLAN */
{ sqlite3BeginParse(pParse, 2); }
        break;
      case 8: /* cmdx ::= cmd */
{ sqlite3FinishCoding(pParse); }
        break;
      case 9: /* cmd ::= BEGIN transtype trans_opt */
{sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy376);}
        break;
      case 13: /* transtype ::= */
{yygotominor.yy376 = TK_DEFERRED;}
        break;
      case 14: /* transtype ::= DEFERRED */
      case 15: /* transtype ::= IMMEDIATE */
      case 16: /* transtype ::= EXCLUSIVE */
      case 112: /* multiselect_op ::= UNION */
      case 114: /* multiselect_op ::= EXCEPT|INTERSECT */
{yygotominor.yy376 = yymsp[0].major;}
        break;
      case 17: /* cmd ::= COMMIT trans_opt */
      case 18: /* cmd ::= END trans_opt */
{sqlite3CommitTransaction(pParse);}
        break;
      case 19: /* cmd ::= ROLLBACK trans_opt */
{sqlite3RollbackTransaction(pParse);}
84800
84801
84802
84803
84804
84805
84806
84807
84808
84809
84810
84811
84812
84813
84814
84815
84816
84817
84818
84819
84820
84821
84822
84823
84824
84825
84826
84827
84828
84829
84830
84831
84832
84833
84834
84835
84836
84837
84838
84839
84840
84841
84842
84843
84844
84845
84846
84847
84848
      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
{
  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
}
        break;
      case 26: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
{
   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy228,0,0,yymsp[-2].minor.yy228);
}
        break;
      case 27: /* ifnotexists ::= */
      case 30: /* temp ::= */
      case 68: /* autoinc ::= */
      case 82: /* init_deferred_pred_opt ::= */
      case 84: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
      case 95: /* defer_subclause_opt ::= */
      case 106: /* ifexists ::= */
      case 117: /* distinct ::= ALL */
      case 118: /* distinct ::= */
      case 220: /* between_op ::= BETWEEN */
      case 223: /* in_op ::= IN */
{yygotominor.yy228 = 0;}
        break;
      case 28: /* ifnotexists ::= IF NOT EXISTS */
      case 29: /* temp ::= TEMP */
      case 69: /* autoinc ::= AUTOINCR */
      case 83: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
      case 105: /* ifexists ::= IF EXISTS */
      case 116: /* distinct ::= DISTINCT */
      case 221: /* between_op ::= NOT BETWEEN */
      case 224: /* in_op ::= NOT IN */
{yygotominor.yy228 = 1;}
        break;
      case 31: /* create_table_args ::= LP columnlist conslist_opt RP */
{
  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
}
        break;
      case 32: /* create_table_args ::= AS select */
{
  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy387);
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
}
        break;
      case 35: /* column ::= columnid type carglist */
{
  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
}







|













|









|








|
|







85699
85700
85701
85702
85703
85704
85705
85706
85707
85708
85709
85710
85711
85712
85713
85714
85715
85716
85717
85718
85719
85720
85721
85722
85723
85724
85725
85726
85727
85728
85729
85730
85731
85732
85733
85734
85735
85736
85737
85738
85739
85740
85741
85742
85743
85744
85745
85746
85747
      case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
{
  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
}
        break;
      case 26: /* create_table ::= CREATE temp TABLE ifnotexists nm dbnm */
{
   sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy376,0,0,yymsp[-2].minor.yy376);
}
        break;
      case 27: /* ifnotexists ::= */
      case 30: /* temp ::= */
      case 68: /* autoinc ::= */
      case 82: /* init_deferred_pred_opt ::= */
      case 84: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
      case 95: /* defer_subclause_opt ::= */
      case 106: /* ifexists ::= */
      case 117: /* distinct ::= ALL */
      case 118: /* distinct ::= */
      case 220: /* between_op ::= BETWEEN */
      case 223: /* in_op ::= IN */
{yygotominor.yy376 = 0;}
        break;
      case 28: /* ifnotexists ::= IF NOT EXISTS */
      case 29: /* temp ::= TEMP */
      case 69: /* autoinc ::= AUTOINCR */
      case 83: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
      case 105: /* ifexists ::= IF EXISTS */
      case 116: /* distinct ::= DISTINCT */
      case 221: /* between_op ::= NOT BETWEEN */
      case 224: /* in_op ::= NOT IN */
{yygotominor.yy376 = 1;}
        break;
      case 31: /* create_table_args ::= LP columnlist conslist_opt RP */
{
  sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
}
        break;
      case 32: /* create_table_args ::= AS select */
{
  sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy465);
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy465);
}
        break;
      case 35: /* column ::= columnid type carglist */
{
  yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
}
84886
84887
84888
84889
84890
84891
84892
84893
84894
84895
84896
84897
84898
84899
84900
84901
84902
84903
84904
84905
84906
84907
84908
84909
84910
84911
84912
84913
84914
84915
84916
84917
84918
84919
84920
84921
84922
84923
84924
84925
84926
84927
84928
84929
84930
84931
84932
84933
84934
84935
84936
84937
84938
84939
84940
84941
84942
84943
84944
84945
84946
84947
84948
84949
84950
84951
84952
84953
84954
84955
84956
84957
84958
84959
84960
84961
84962
84963
84964
84965
84966
84967
84968
84969
84970
84971
84972
84973
84974
84975
84976
84977
84978
84979
84980
84981
84982
84983
84984
84985
84986
84987
84988
84989
84990
84991
84992
84993
84994
84995
84996
84997
84998
84999
85000
85001
85002
85003
85004
85005
85006
85007
85008
85009
85010
85011
85012
85013
85014
85015
85016
85017
85018
85019
85020
85021
85022
85023
85024
85025
85026
85027
85028
85029
85030
85031
85032
85033
85034
85035
85036
85037
85038
85039
85040
85041
85042
85043
85044
85045
85046
85047
85048
85049
85050
85051
85052
85053
85054
85055
85056
85057
85058
85059
85060
85061
85062
85063
85064
85065
85066
85067
85068
85069
85070
85071
85072
85073
85074
85075
85076
85077
85078
85079
85080
85081
85082
85083
85084
85085
85086
85087
85088
85089
85090
85091
85092
85093
85094
85095
85096
85097
85098
85099
85100
85101
85102
85103
85104
85105
85106
85107
85108
85109
85110
85111
85112
85113
85114
85115
85116
85117
85118
85119
85120
85121
85122
85123
85124
85125
85126
85127
85128
85129
85130
85131
85132
85133
85134
85135
85136
85137
85138
85139
85140
85141
85142
85143
85144
85145
85146
85147
85148
85149
85150
85151
85152
85153
85154
85155
85156
85157
85158
85159
85160
85161
85162
85163
85164
85165
85166
85167
85168
85169
85170
85171
85172
85173
85174
85175
85176
85177
85178
85179
85180
85181
85182
85183
85184
85185
85186
85187
85188
85189
85190
85191
85192
85193
85194
85195
85196
85197
85198
85199
85200
85201
85202
85203
85204
85205
85206
85207
85208
85209
85210
85211
85212
85213
85214
85215
85216
85217
85218
85219
85220
85221
85222
85223
85224
85225
85226
85227
85228
85229
85230
85231
85232
85233
85234
85235
85236
85237
85238
85239
85240
85241
85242
85243
85244
85245
85246
85247
85248
85249
85250
85251
85252
85253
85254
85255
85256
85257
85258
85259
85260
85261
85262
85263
85264
85265
85266
85267
85268
85269
85270
85271
85272
85273
85274
85275
85276
85277
85278
85279
85280
85281
85282
85283
85284
85285
85286
85287
85288
85289
85290
85291
85292
85293
85294
85295
85296
85297
85298
85299
85300
85301
85302
85303
85304
85305
85306
85307
85308
85309
85310
85311
85312
85313
85314
85315
85316
85317
85318
85319
85320
85321
85322
85323
85324
85325
85326
85327
85328
85329
85330
85331
85332
85333
85334
85335
85336
85337
85338
85339
85340
85341
85342
85343
85344
85345
85346
85347
85348
85349
85350
85351
85352
85353
85354
85355
85356
85357
85358
85359
85360
85361
85362
85363
85364
85365
85366
85367
85368
85369
85370
85371
85372
85373
85374
85375
85376
85377
85378
85379
85380
85381
85382
85383
85384
85385
85386
85387
85388
85389
85390
85391
85392
85393
85394
85395
85396
85397
85398
85399
85400
85401
85402
85403
85404
85405
85406
85407
85408
85409
85410
85411
85412
85413
85414
85415
85416
85417
85418
85419
85420
85421
85422
85423
85424
85425
85426
85427
85428
85429
85430
85431
85432
85433
85434
85435
85436
85437
85438
85439
85440
85441
85442
85443
85444
85445
85446
85447
85448
85449
85450
85451
85452
85453
85454
85455
85456
85457
85458
85459
85460
85461
85462
85463
85464
85465
85466
85467
85468
85469
85470
85471
85472
85473
85474
85475
85476
85477
85478
85479
85480
85481
85482
85483
85484
85485
85486
85487
85488
85489
85490
85491
85492
85493
85494
85495
85496
85497
85498
85499
85500
85501
85502
85503
85504
85505
85506
85507
85508
85509
85510
85511
85512
85513
85514
85515
85516
85517
85518
85519
85520
85521
85522
85523
85524
85525
85526
85527
85528
85529
85530
85531
85532
85533
85534
85535
85536
85537
85538
85539
85540
85541
85542
85543
85544
85545
85546
85547
85548
85549
85550
85551
85552
85553
85554
85555
85556
85557
85558
85559
85560
85561
85562
85563
85564
85565
85566
85567
85568
85569
85570
85571
85572
85573
85574
85575
85576
85577
85578
85579
85580
85581
85582
85583
85584
85585
85586
85587
85588
85589
85590
85591
85592
85593
85594
85595
85596
85597
85598
85599
85600
85601
85602
85603
85604
85605
85606
85607
85608
85609
85610
85611
85612
85613
85614
85615
85616
85617
85618
85619
85620
85621
85622
85623
85624
85625
85626
85627
85628
85629
85630
85631
85632
85633
85634
85635
85636
85637
85638
85639
85640
85641
85642
85643
85644
85645
85646
85647
85648
85649
85650
85651
85652
85653
85654
85655
85656
85657
85658
85659
85660
85661
85662
85663
85664
85665
85666
85667
85668
85669
85670
85671
85672
}
        break;
      case 48: /* typename ::= typename ids */
{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
        break;
      case 55: /* ccons ::= DEFAULT term */
      case 57: /* ccons ::= DEFAULT PLUS term */
{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy402);}
        break;
      case 56: /* ccons ::= DEFAULT LP expr RP */
{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy402);}
        break;
      case 58: /* ccons ::= DEFAULT MINUS term */
{
  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy402, 0, 0);
  sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy402->span);
  sqlite3AddDefaultValue(pParse,p);
}
        break;
      case 59: /* ccons ::= DEFAULT id */
{
  Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
  sqlite3AddDefaultValue(pParse,p);
}
        break;
      case 61: /* ccons ::= NOT NULL onconf */
{sqlite3AddNotNull(pParse, yymsp[0].minor.yy228);}
        break;
      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy228,yymsp[0].minor.yy228,yymsp[-2].minor.yy228);}
        break;
      case 63: /* ccons ::= UNIQUE onconf */
{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy228,0,0,0,0);}
        break;
      case 64: /* ccons ::= CHECK LP expr RP */
{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy402);}
        break;
      case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy258,yymsp[0].minor.yy228);}
        break;
      case 66: /* ccons ::= defer_subclause */
{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy228);}
        break;
      case 67: /* ccons ::= COLLATE ids */
{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
        break;
      case 70: /* refargs ::= */
{ yygotominor.yy228 = OE_Restrict * 0x010101; }
        break;
      case 71: /* refargs ::= refargs refarg */
{ yygotominor.yy228 = (yymsp[-1].minor.yy228 & ~yymsp[0].minor.yy231.mask) | yymsp[0].minor.yy231.value; }
        break;
      case 72: /* refarg ::= MATCH nm */
{ yygotominor.yy231.value = 0;     yygotominor.yy231.mask = 0x000000; }
        break;
      case 73: /* refarg ::= ON DELETE refact */
{ yygotominor.yy231.value = yymsp[0].minor.yy228;     yygotominor.yy231.mask = 0x0000ff; }
        break;
      case 74: /* refarg ::= ON UPDATE refact */
{ yygotominor.yy231.value = yymsp[0].minor.yy228<<8;  yygotominor.yy231.mask = 0x00ff00; }
        break;
      case 75: /* refarg ::= ON INSERT refact */
{ yygotominor.yy231.value = yymsp[0].minor.yy228<<16; yygotominor.yy231.mask = 0xff0000; }
        break;
      case 76: /* refact ::= SET NULL */
{ yygotominor.yy228 = OE_SetNull; }
        break;
      case 77: /* refact ::= SET DEFAULT */
{ yygotominor.yy228 = OE_SetDflt; }
        break;
      case 78: /* refact ::= CASCADE */
{ yygotominor.yy228 = OE_Cascade; }
        break;
      case 79: /* refact ::= RESTRICT */
{ yygotominor.yy228 = OE_Restrict; }
        break;
      case 80: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
      case 81: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
      case 96: /* defer_subclause_opt ::= defer_subclause */
      case 98: /* onconf ::= ON CONFLICT resolvetype */
      case 100: /* orconf ::= OR resolvetype */
      case 101: /* resolvetype ::= raisetype */
      case 173: /* insert_cmd ::= INSERT orconf */
{yygotominor.yy228 = yymsp[0].minor.yy228;}
        break;
      case 85: /* conslist_opt ::= */
{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
        break;
      case 86: /* conslist_opt ::= COMMA conslist */
{yygotominor.yy0 = yymsp[-1].minor.yy0;}
        break;
      case 91: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy258,yymsp[0].minor.yy228,yymsp[-2].minor.yy228,0);}
        break;
      case 92: /* tcons ::= UNIQUE LP idxlist RP onconf */
{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy258,yymsp[0].minor.yy228,0,0,0,0);}
        break;
      case 93: /* tcons ::= CHECK LP expr RP onconf */
{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy402);}
        break;
      case 94: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
{
    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy258, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy258, yymsp[-1].minor.yy228);
    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy228);
}
        break;
      case 97: /* onconf ::= */
      case 99: /* orconf ::= */
{yygotominor.yy228 = OE_Default;}
        break;
      case 102: /* resolvetype ::= IGNORE */
{yygotominor.yy228 = OE_Ignore;}
        break;
      case 103: /* resolvetype ::= REPLACE */
      case 174: /* insert_cmd ::= REPLACE */
{yygotominor.yy228 = OE_Replace;}
        break;
      case 104: /* cmd ::= DROP TABLE ifexists fullname */
{
  sqlite3DropTable(pParse, yymsp[0].minor.yy3, 0, yymsp[-1].minor.yy228);
}
        break;
      case 107: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
{
  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy387, yymsp[-6].minor.yy228, yymsp[-4].minor.yy228);
}
        break;
      case 108: /* cmd ::= DROP VIEW ifexists fullname */
{
  sqlite3DropTable(pParse, yymsp[0].minor.yy3, 1, yymsp[-1].minor.yy228);
}
        break;
      case 109: /* cmd ::= select */
{
  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  sqlite3Select(pParse, yymsp[0].minor.yy387, &dest);
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy387);
}
        break;
      case 110: /* select ::= oneselect */
{yygotominor.yy387 = yymsp[0].minor.yy387;}
        break;
      case 111: /* select ::= select multiselect_op oneselect */
{
  if( yymsp[0].minor.yy387 ){
    yymsp[0].minor.yy387->op = (u8)yymsp[-1].minor.yy228;
    yymsp[0].minor.yy387->pPrior = yymsp[-2].minor.yy387;
  }else{
    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy387);
  }
  yygotominor.yy387 = yymsp[0].minor.yy387;
}
        break;
      case 113: /* multiselect_op ::= UNION ALL */
{yygotominor.yy228 = TK_ALL;}
        break;
      case 115: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
{
  yygotominor.yy387 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy258,yymsp[-5].minor.yy3,yymsp[-4].minor.yy402,yymsp[-3].minor.yy258,yymsp[-2].minor.yy402,yymsp[-1].minor.yy258,yymsp[-7].minor.yy228,yymsp[0].minor.yy196.pLimit,yymsp[0].minor.yy196.pOffset);
}
        break;
      case 119: /* sclp ::= selcollist COMMA */
      case 245: /* idxlist_opt ::= LP idxlist RP */
{yygotominor.yy258 = yymsp[-1].minor.yy258;}
        break;
      case 120: /* sclp ::= */
      case 148: /* orderby_opt ::= */
      case 156: /* groupby_opt ::= */
      case 238: /* exprlist ::= */
      case 244: /* idxlist_opt ::= */
{yygotominor.yy258 = 0;}
        break;
      case 121: /* selcollist ::= sclp expr as */
{
   yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy258,yymsp[-1].minor.yy402,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
}
        break;
      case 122: /* selcollist ::= sclp STAR */
{
  Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
  yygotominor.yy258 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy258, p, 0);
}
        break;
      case 123: /* selcollist ::= sclp nm DOT STAR */
{
  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy258, pDot, 0);
}
        break;
      case 126: /* as ::= */
{yygotominor.yy0.n = 0;}
        break;
      case 127: /* from ::= */
{yygotominor.yy3 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy3));}
        break;
      case 128: /* from ::= FROM seltablist */
{
  yygotominor.yy3 = yymsp[0].minor.yy3;
  sqlite3SrcListShiftJoinType(yygotominor.yy3);
}
        break;
      case 129: /* stl_prefix ::= seltablist joinop */
{
   yygotominor.yy3 = yymsp[-1].minor.yy3;
   if( yygotominor.yy3 && yygotominor.yy3->nSrc>0 ) yygotominor.yy3->a[yygotominor.yy3->nSrc-1].jointype = (u8)yymsp[0].minor.yy228;
}
        break;
      case 130: /* stl_prefix ::= */
{yygotominor.yy3 = 0;}
        break;
      case 131: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
{
  yygotominor.yy3 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy3,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy402,yymsp[0].minor.yy400);
  sqlite3SrcListIndexedBy(pParse, yygotominor.yy3, &yymsp[-2].minor.yy0);
}
        break;
      case 132: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
{
    yygotominor.yy3 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy3,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy387,yymsp[-1].minor.yy402,yymsp[0].minor.yy400);
  }
        break;
      case 133: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
{
    if( yymsp[-6].minor.yy3==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy402==0 && yymsp[0].minor.yy400==0 ){
      yygotominor.yy3 = yymsp[-4].minor.yy3;
    }else{
      Select *pSubquery;
      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy3);
      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy3,0,0,0,0,0,0,0);
      yygotominor.yy3 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy3,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy402,yymsp[0].minor.yy400);
    }
  }
        break;
      case 134: /* dbnm ::= */
      case 143: /* indexed_opt ::= */
{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
        break;
      case 136: /* fullname ::= nm dbnm */
{yygotominor.yy3 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
        break;
      case 137: /* joinop ::= COMMA|JOIN */
{ yygotominor.yy228 = JT_INNER; }
        break;
      case 138: /* joinop ::= JOIN_KW JOIN */
{ yygotominor.yy228 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
        break;
      case 139: /* joinop ::= JOIN_KW nm JOIN */
{ yygotominor.yy228 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
        break;
      case 140: /* joinop ::= JOIN_KW nm nm JOIN */
{ yygotominor.yy228 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
        break;
      case 141: /* on_opt ::= ON expr */
      case 152: /* sortitem ::= expr */
      case 159: /* having_opt ::= HAVING expr */
      case 166: /* where_opt ::= WHERE expr */
      case 181: /* expr ::= term */
      case 209: /* escape ::= ESCAPE expr */
      case 233: /* case_else ::= ELSE expr */
      case 235: /* case_operand ::= expr */
{yygotominor.yy402 = yymsp[0].minor.yy402;}
        break;
      case 142: /* on_opt ::= */
      case 158: /* having_opt ::= */
      case 165: /* where_opt ::= */
      case 210: /* escape ::= */
      case 234: /* case_else ::= */
      case 236: /* case_operand ::= */
{yygotominor.yy402 = 0;}
        break;
      case 145: /* indexed_opt ::= NOT INDEXED */
{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
        break;
      case 146: /* using_opt ::= USING LP inscollist RP */
      case 178: /* inscollist_opt ::= LP inscollist RP */
{yygotominor.yy400 = yymsp[-1].minor.yy400;}
        break;
      case 147: /* using_opt ::= */
      case 177: /* inscollist_opt ::= */
{yygotominor.yy400 = 0;}
        break;
      case 149: /* orderby_opt ::= ORDER BY sortlist */
      case 157: /* groupby_opt ::= GROUP BY nexprlist */
      case 237: /* exprlist ::= nexprlist */
{yygotominor.yy258 = yymsp[0].minor.yy258;}
        break;
      case 150: /* sortlist ::= sortlist COMMA sortitem sortorder */
{
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy258,yymsp[-1].minor.yy402,0);
  if( yygotominor.yy258 ) yygotominor.yy258->a[yygotominor.yy258->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy228;
}
        break;
      case 151: /* sortlist ::= sortitem sortorder */
{
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy402,0);
  if( yygotominor.yy258 && yygotominor.yy258->a ) yygotominor.yy258->a[0].sortOrder = (u8)yymsp[0].minor.yy228;
}
        break;
      case 153: /* sortorder ::= ASC */
      case 155: /* sortorder ::= */
{yygotominor.yy228 = SQLITE_SO_ASC;}
        break;
      case 154: /* sortorder ::= DESC */
{yygotominor.yy228 = SQLITE_SO_DESC;}
        break;
      case 160: /* limit_opt ::= */
{yygotominor.yy196.pLimit = 0; yygotominor.yy196.pOffset = 0;}
        break;
      case 161: /* limit_opt ::= LIMIT expr */
{yygotominor.yy196.pLimit = yymsp[0].minor.yy402; yygotominor.yy196.pOffset = 0;}
        break;
      case 162: /* limit_opt ::= LIMIT expr OFFSET expr */
{yygotominor.yy196.pLimit = yymsp[-2].minor.yy402; yygotominor.yy196.pOffset = yymsp[0].minor.yy402;}
        break;
      case 163: /* limit_opt ::= LIMIT expr COMMA expr */
{yygotominor.yy196.pOffset = yymsp[-2].minor.yy402; yygotominor.yy196.pLimit = yymsp[0].minor.yy402;}
        break;
      case 164: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
{
  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy3, &yymsp[-1].minor.yy0);
  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy3,yymsp[0].minor.yy402);
}
        break;
      case 167: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
{
  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy3, &yymsp[-3].minor.yy0);
  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy258,"set list"); 
  sqlite3Update(pParse,yymsp[-4].minor.yy3,yymsp[-1].minor.yy258,yymsp[0].minor.yy402,yymsp[-5].minor.yy228);
}
        break;
      case 168: /* setlist ::= setlist COMMA nm EQ expr */
{yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy258,yymsp[0].minor.yy402,&yymsp[-2].minor.yy0);}
        break;
      case 169: /* setlist ::= nm EQ expr */
{yygotominor.yy258 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy402,&yymsp[-2].minor.yy0);}
        break;
      case 170: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
{sqlite3Insert(pParse, yymsp[-5].minor.yy3, yymsp[-1].minor.yy258, 0, yymsp[-4].minor.yy400, yymsp[-7].minor.yy228);}
        break;
      case 171: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
{sqlite3Insert(pParse, yymsp[-2].minor.yy3, 0, yymsp[0].minor.yy387, yymsp[-1].minor.yy400, yymsp[-4].minor.yy228);}
        break;
      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
{sqlite3Insert(pParse, yymsp[-3].minor.yy3, 0, 0, yymsp[-2].minor.yy400, yymsp[-5].minor.yy228);}
        break;
      case 175: /* itemlist ::= itemlist COMMA expr */
      case 239: /* nexprlist ::= nexprlist COMMA expr */
{yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy258,yymsp[0].minor.yy402,0);}
        break;
      case 176: /* itemlist ::= expr */
      case 240: /* nexprlist ::= expr */
{yygotominor.yy258 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy402,0);}
        break;
      case 179: /* inscollist ::= inscollist COMMA nm */
{yygotominor.yy400 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy400,&yymsp[0].minor.yy0);}
        break;
      case 180: /* inscollist ::= nm */
{yygotominor.yy400 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
        break;
      case 182: /* expr ::= LP expr RP */
{yygotominor.yy402 = yymsp[-1].minor.yy402; sqlite3ExprSpan(yygotominor.yy402,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
        break;
      case 183: /* term ::= NULL */
      case 188: /* term ::= INTEGER|FLOAT|BLOB */
      case 189: /* term ::= STRING */
{yygotominor.yy402 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
        break;
      case 184: /* expr ::= ID */
      case 185: /* expr ::= JOIN_KW */
{yygotominor.yy402 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
        break;
      case 186: /* expr ::= nm DOT nm */
{
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
}
        break;
      case 187: /* expr ::= nm DOT nm DOT nm */
{
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
}
        break;
      case 190: /* expr ::= REGISTER */
{yygotominor.yy402 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
        break;
      case 191: /* expr ::= VARIABLE */
{
  Token *pToken = &yymsp[0].minor.yy0;
  Expr *pExpr = yygotominor.yy402 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
  sqlite3ExprAssignVarNumber(pParse, pExpr);
}
        break;
      case 192: /* expr ::= expr COLLATE ids */
{
  yygotominor.yy402 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy402, &yymsp[0].minor.yy0);
}
        break;
      case 193: /* expr ::= CAST LP expr AS typetoken RP */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy402, 0, &yymsp[-1].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
}
        break;
      case 194: /* expr ::= ID LP distinct exprlist RP */
{
  if( yymsp[-1].minor.yy258 && yymsp[-1].minor.yy258->nExpr>SQLITE_MAX_FUNCTION_ARG ){
    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  }
  yygotominor.yy402 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy258, &yymsp[-4].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  if( yymsp[-2].minor.yy228 && yygotominor.yy402 ){
    yygotominor.yy402->flags |= EP_Distinct;
  }
}
        break;
      case 195: /* expr ::= ID LP STAR RP */
{
  yygotominor.yy402 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
}
        break;
      case 196: /* term ::= CTIME_KW */
{
  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  ** treated as functions that return constants */
  yygotominor.yy402 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  if( yygotominor.yy402 ){
    yygotominor.yy402->op = TK_CONST_FUNC;  
    yygotominor.yy402->span = yymsp[0].minor.yy0;
  }
}
        break;
      case 197: /* expr ::= expr AND expr */
      case 198: /* expr ::= expr OR expr */
      case 199: /* expr ::= expr LT|GT|GE|LE expr */
      case 200: /* expr ::= expr EQ|NE expr */
      case 201: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
      case 202: /* expr ::= expr PLUS|MINUS expr */
      case 203: /* expr ::= expr STAR|SLASH|REM expr */
      case 204: /* expr ::= expr CONCAT expr */
{yygotominor.yy402 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy402,yymsp[0].minor.yy402,0);}
        break;
      case 205: /* likeop ::= LIKE_KW */
      case 207: /* likeop ::= MATCH */
{yygotominor.yy150.eOperator = yymsp[0].minor.yy0; yygotominor.yy150.not = 0;}
        break;
      case 206: /* likeop ::= NOT LIKE_KW */
      case 208: /* likeop ::= NOT MATCH */
{yygotominor.yy150.eOperator = yymsp[0].minor.yy0; yygotominor.yy150.not = 1;}
        break;
      case 211: /* expr ::= expr likeop expr escape */
{
  ExprList *pList;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy402, 0);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy402, 0);
  if( yymsp[0].minor.yy402 ){
    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy402, 0);
  }
  yygotominor.yy402 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy150.eOperator);
  if( yymsp[-2].minor.yy150.not ) yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402, &yymsp[-3].minor.yy402->span, &yymsp[-1].minor.yy402->span);
  if( yygotominor.yy402 ) yygotominor.yy402->flags |= EP_InfixFunc;
}
        break;
      case 212: /* expr ::= expr ISNULL|NOTNULL */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-1].minor.yy402->span,&yymsp[0].minor.yy0);
}
        break;
      case 213: /* expr ::= expr IS NULL */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-2].minor.yy402->span,&yymsp[0].minor.yy0);
}
        break;
      case 214: /* expr ::= expr NOT NULL */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-2].minor.yy402->span,&yymsp[0].minor.yy0);
}
        break;
      case 215: /* expr ::= expr IS NOT NULL */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-3].minor.yy402->span,&yymsp[0].minor.yy0);
}
        break;
      case 216: /* expr ::= NOT expr */
      case 217: /* expr ::= BITNOT expr */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy402->span);
}
        break;
      case 218: /* expr ::= MINUS expr */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy402->span);
}
        break;
      case 219: /* expr ::= PLUS expr */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy402->span);
}
        break;
      case 222: /* expr ::= expr between_op expr AND expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy402, 0);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy402, 0);
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy402, 0, 0);
  if( yygotominor.yy402 ){
    yygotominor.yy402->pList = pList;
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  } 
  if( yymsp[-3].minor.yy228 ) yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy402, 0, 0);
  sqlite3ExprSpan(yygotominor.yy402,&yymsp[-4].minor.yy402->span,&yymsp[0].minor.yy402->span);
}
        break;
      case 225: /* expr ::= expr in_op LP exprlist RP */
{
    yygotominor.yy402 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy402, 0, 0);
    if( yygotominor.yy402 ){
      yygotominor.yy402->pList = yymsp[-1].minor.yy258;
      sqlite3ExprSetHeight(pParse, yygotominor.yy402);
    }else{
      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy258);
    }
    if( yymsp[-3].minor.yy228 ) yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy402, 0, 0);
    sqlite3ExprSpan(yygotominor.yy402,&yymsp[-4].minor.yy402->span,&yymsp[0].minor.yy0);
  }
        break;
      case 226: /* expr ::= LP select RP */
{
    yygotominor.yy402 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
    if( yygotominor.yy402 ){
      yygotominor.yy402->pSelect = yymsp[-1].minor.yy387;
      sqlite3ExprSetHeight(pParse, yygotominor.yy402);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
    }
    sqlite3ExprSpan(yygotominor.yy402,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  }
        break;
      case 227: /* expr ::= expr in_op LP select RP */
{
    yygotominor.yy402 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy402, 0, 0);
    if( yygotominor.yy402 ){
      yygotominor.yy402->pSelect = yymsp[-1].minor.yy387;
      sqlite3ExprSetHeight(pParse, yygotominor.yy402);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
    }
    if( yymsp[-3].minor.yy228 ) yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy402, 0, 0);
    sqlite3ExprSpan(yygotominor.yy402,&yymsp[-4].minor.yy402->span,&yymsp[0].minor.yy0);
  }
        break;
      case 228: /* expr ::= expr in_op nm dbnm */
{
    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
    yygotominor.yy402 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy402, 0, 0);
    if( yygotominor.yy402 ){
      yygotominor.yy402->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
      sqlite3ExprSetHeight(pParse, yygotominor.yy402);
    }else{
      sqlite3SrcListDelete(pParse->db, pSrc);
    }
    if( yymsp[-2].minor.yy228 ) yygotominor.yy402 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy402, 0, 0);
    sqlite3ExprSpan(yygotominor.yy402,&yymsp[-3].minor.yy402->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  }
        break;
      case 229: /* expr ::= EXISTS LP select RP */
{
    Expr *p = yygotominor.yy402 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
    if( p ){
      p->pSelect = yymsp[-1].minor.yy387;
      sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
      sqlite3ExprSetHeight(pParse, yygotominor.yy402);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy387);
    }
  }
        break;
      case 230: /* expr ::= CASE case_operand case_exprlist case_else END */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy402, yymsp[-1].minor.yy402, 0);
  if( yygotominor.yy402 ){
    yygotominor.yy402->pList = yymsp[-2].minor.yy258;
    sqlite3ExprSetHeight(pParse, yygotominor.yy402);
  }else{
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy258);
  }
  sqlite3ExprSpan(yygotominor.yy402, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
}
        break;
      case 231: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
{
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy258, yymsp[-2].minor.yy402, 0);
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yygotominor.yy258, yymsp[0].minor.yy402, 0);
}
        break;
      case 232: /* case_exprlist ::= WHEN expr THEN expr */
{
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy402, 0);
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yygotominor.yy258, yymsp[0].minor.yy402, 0);
}
        break;
      case 241: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
{
  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy258, yymsp[-9].minor.yy228,
                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy228);
}
        break;
      case 242: /* uniqueflag ::= UNIQUE */
      case 279: /* raisetype ::= ABORT */
{yygotominor.yy228 = OE_Abort;}
        break;
      case 243: /* uniqueflag ::= */
{yygotominor.yy228 = OE_None;}
        break;
      case 246: /* idxlist ::= idxlist COMMA nm collate sortorder */
{
  Expr *p = 0;
  if( yymsp[-1].minor.yy0.n>0 ){
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  }
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy258, p, &yymsp[-2].minor.yy0);
  sqlite3ExprListCheckLength(pParse, yygotominor.yy258, "index");
  if( yygotominor.yy258 ) yygotominor.yy258->a[yygotominor.yy258->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy228;
}
        break;
      case 247: /* idxlist ::= nm collate sortorder */
{
  Expr *p = 0;
  if( yymsp[-1].minor.yy0.n>0 ){
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  }
  yygotominor.yy258 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
  sqlite3ExprListCheckLength(pParse, yygotominor.yy258, "index");
  if( yygotominor.yy258 ) yygotominor.yy258->a[yygotominor.yy258->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy228;
}
        break;
      case 248: /* collate ::= */
{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
        break;
      case 250: /* cmd ::= DROP INDEX ifexists fullname */
{sqlite3DropIndex(pParse, yymsp[0].minor.yy3, yymsp[-1].minor.yy228);}
        break;
      case 256: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
{
  Token all;
  all.z = yymsp[-3].minor.yy0.z;
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy19, &all);
}
        break;
      case 257: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
{
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy228, yymsp[-4].minor.yy466.a, yymsp[-4].minor.yy466.b, yymsp[-2].minor.yy3, yymsp[0].minor.yy402, yymsp[-10].minor.yy228, yymsp[-8].minor.yy228);
  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
}
        break;
      case 258: /* trigger_time ::= BEFORE */
      case 261: /* trigger_time ::= */
{ yygotominor.yy228 = TK_BEFORE; }
        break;
      case 259: /* trigger_time ::= AFTER */
{ yygotominor.yy228 = TK_AFTER;  }
        break;
      case 260: /* trigger_time ::= INSTEAD OF */
{ yygotominor.yy228 = TK_INSTEAD;}
        break;
      case 262: /* trigger_event ::= DELETE|INSERT */
      case 263: /* trigger_event ::= UPDATE */
{yygotominor.yy466.a = yymsp[0].major; yygotominor.yy466.b = 0;}
        break;
      case 264: /* trigger_event ::= UPDATE OF inscollist */
{yygotominor.yy466.a = TK_UPDATE; yygotominor.yy466.b = yymsp[0].minor.yy400;}
        break;
      case 267: /* when_clause ::= */
{ yygotominor.yy402 = 0; }
        break;
      case 268: /* when_clause ::= WHEN expr */
{ yygotominor.yy402 = yymsp[0].minor.yy402; }
        break;
      case 269: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
{
/*
  if( yymsp[-2].minor.yy19 ){
    yymsp[-2].minor.yy19->pLast->pNext = yymsp[-1].minor.yy19;
  }else{
    yymsp[-2].minor.yy19 = yymsp[-1].minor.yy19;
  }
*/
  assert( yymsp[-2].minor.yy19!=0 );
  yymsp[-2].minor.yy19->pLast->pNext = yymsp[-1].minor.yy19;
  yymsp[-2].minor.yy19->pLast = yymsp[-1].minor.yy19;
  yygotominor.yy19 = yymsp[-2].minor.yy19;
}
        break;
      case 270: /* trigger_cmd_list ::= trigger_cmd SEMI */
{ 
  /* if( yymsp[-1].minor.yy19 ) */
  assert( yymsp[-1].minor.yy19!=0 );
  yymsp[-1].minor.yy19->pLast = yymsp[-1].minor.yy19;
  yygotominor.yy19 = yymsp[-1].minor.yy19;
}
        break;
      case 271: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
{ yygotominor.yy19 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy258, yymsp[0].minor.yy402, yymsp[-4].minor.yy228); }
        break;
      case 272: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
{yygotominor.yy19 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy400, yymsp[-1].minor.yy258, 0, yymsp[-7].minor.yy228);}
        break;
      case 273: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
{yygotominor.yy19 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy400, 0, yymsp[0].minor.yy387, yymsp[-4].minor.yy228);}
        break;
      case 274: /* trigger_cmd ::= DELETE FROM nm where_opt */
{yygotominor.yy19 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy402);}
        break;
      case 275: /* trigger_cmd ::= select */
{yygotominor.yy19 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy387); }
        break;
      case 276: /* expr ::= RAISE LP IGNORE RP */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
  if( yygotominor.yy402 ){
    yygotominor.yy402->iColumn = OE_Ignore;
    sqlite3ExprSpan(yygotominor.yy402, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
  }
}
        break;
      case 277: /* expr ::= RAISE LP raisetype COMMA nm RP */
{
  yygotominor.yy402 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
  if( yygotominor.yy402 ) {
    yygotominor.yy402->iColumn = yymsp[-3].minor.yy228;
    sqlite3ExprSpan(yygotominor.yy402, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  }
}
        break;
      case 278: /* raisetype ::= ROLLBACK */
{yygotominor.yy228 = OE_Rollback;}
        break;
      case 280: /* raisetype ::= FAIL */
{yygotominor.yy228 = OE_Fail;}
        break;
      case 281: /* cmd ::= DROP TRIGGER ifexists fullname */
{
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy3,yymsp[-1].minor.yy228);
}
        break;
  };
  yygoto = yyRuleInfo[yyruleno].lhs;
  yysize = yyRuleInfo[yyruleno].nrhs;
  yypParser->yyidx -= yysize;
  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  if( yyact < YYNSTATE ){
#ifdef NDEBUG
    /* If we are not debugging and the reduce action popped at least
    ** one element off the stack, then we can push the new element back
    ** onto the stack here, and skip the stack overflow test in yy_shift().
    ** That gives a significant speed improvement. */
    if( yysize ){
      yypParser->yyidx++;
      yymsp -= yysize-1;
      yymsp->stateno = yyact;
      yymsp->major = yygoto;
      yymsp->minor = yygotominor;
    }else
#endif
    {
      yy_shift(yypParser,yyact,yygoto,&yygotominor);
    }
  }else{







|


|



|
|










|


|


|


|


|


|





|


|


|


|


|


|


|


|


|


|








|








|


|


|



|
|




|


|



|



|




|




|





|
|



|



|
|
|

|

|



|



|




|






|



|





|







|






|



|
|




|
|



|



|
|




|




|
|


|
|
|








|


|


|


|


|









|







|






|



|




|



|
|




|
|




|


|


|


|


|


|



|
|




|
|
|



|


|


|


|


|



|



|


|


|


|




|



|





|








|



|




|





|




|
|




|


|
|
|
|





|
|






|
|
|
|











|



|



|




|
|
|
|

|
|
|
|




|
|




|
|




|
|




|
|





|
|




|
|




|
|




|
|
|
|
|



|
|




|
|
|
|

|

|
|




|
|
|
|

|

|




|
|
|
|

|

|
|





|
|
|
|



|
|




|

|

|

|





|
|
|
|

|

|




|
|




|
|





|
|




|


|








|
|
|









|
|
|






|






|




|





|


|


|



|


|


|


|




|
|

|


|
|
|
|




|
|
|
|



|


|


|


|


|



|
|
|
|





|
|
|
|




|


|



|
















|
|







85785
85786
85787
85788
85789
85790
85791
85792
85793
85794
85795
85796
85797
85798
85799
85800
85801
85802
85803
85804
85805
85806
85807
85808
85809
85810
85811
85812
85813
85814
85815
85816
85817
85818
85819
85820
85821
85822
85823
85824
85825
85826
85827
85828
85829
85830
85831
85832
85833
85834
85835
85836
85837
85838
85839
85840
85841
85842
85843
85844
85845
85846
85847
85848
85849
85850
85851
85852
85853
85854
85855
85856
85857
85858
85859
85860
85861
85862
85863
85864
85865
85866
85867
85868
85869
85870
85871
85872
85873
85874
85875
85876
85877
85878
85879
85880
85881
85882
85883
85884
85885
85886
85887
85888
85889
85890
85891
85892
85893
85894
85895
85896
85897
85898
85899
85900
85901
85902
85903
85904
85905
85906
85907
85908
85909
85910
85911
85912
85913
85914
85915
85916
85917
85918
85919
85920
85921
85922
85923
85924
85925
85926
85927
85928
85929
85930
85931
85932
85933
85934
85935
85936
85937
85938
85939
85940
85941
85942
85943
85944
85945
85946
85947
85948
85949
85950
85951
85952
85953
85954
85955
85956
85957
85958
85959
85960
85961
85962
85963
85964
85965
85966
85967
85968
85969
85970
85971
85972
85973
85974
85975
85976
85977
85978
85979
85980
85981
85982
85983
85984
85985
85986
85987
85988
85989
85990
85991
85992
85993
85994
85995
85996
85997
85998
85999
86000
86001
86002
86003
86004
86005
86006
86007
86008
86009
86010
86011
86012
86013
86014
86015
86016
86017
86018
86019
86020
86021
86022
86023
86024
86025
86026
86027
86028
86029
86030
86031
86032
86033
86034
86035
86036
86037
86038
86039
86040
86041
86042
86043
86044
86045
86046
86047
86048
86049
86050
86051
86052
86053
86054
86055
86056
86057
86058
86059
86060
86061
86062
86063
86064
86065
86066
86067
86068
86069
86070
86071
86072
86073
86074
86075
86076
86077
86078
86079
86080
86081
86082
86083
86084
86085
86086
86087
86088
86089
86090
86091
86092
86093
86094
86095
86096
86097
86098
86099
86100
86101
86102
86103
86104
86105
86106
86107
86108
86109
86110
86111
86112
86113
86114
86115
86116
86117
86118
86119
86120
86121
86122
86123
86124
86125
86126
86127
86128
86129
86130
86131
86132
86133
86134
86135
86136
86137
86138
86139
86140
86141
86142
86143
86144
86145
86146
86147
86148
86149
86150
86151
86152
86153
86154
86155
86156
86157
86158
86159
86160
86161
86162
86163
86164
86165
86166
86167
86168
86169
86170
86171
86172
86173
86174
86175
86176
86177
86178
86179
86180
86181
86182
86183
86184
86185
86186
86187
86188
86189
86190
86191
86192
86193
86194
86195
86196
86197
86198
86199
86200
86201
86202
86203
86204
86205
86206
86207
86208
86209
86210
86211
86212
86213
86214
86215
86216
86217
86218
86219
86220
86221
86222
86223
86224
86225
86226
86227
86228
86229
86230
86231
86232
86233
86234
86235
86236
86237
86238
86239
86240
86241
86242
86243
86244
86245
86246
86247
86248
86249
86250
86251
86252
86253
86254
86255
86256
86257
86258
86259
86260
86261
86262
86263
86264
86265
86266
86267
86268
86269
86270
86271
86272
86273
86274
86275
86276
86277
86278
86279
86280
86281
86282
86283
86284
86285
86286
86287
86288
86289
86290
86291
86292
86293
86294
86295
86296
86297
86298
86299
86300
86301
86302
86303
86304
86305
86306
86307
86308
86309
86310
86311
86312
86313
86314
86315
86316
86317
86318
86319
86320
86321
86322
86323
86324
86325
86326
86327
86328
86329
86330
86331
86332
86333
86334
86335
86336
86337
86338
86339
86340
86341
86342
86343
86344
86345
86346
86347
86348
86349
86350
86351
86352
86353
86354
86355
86356
86357
86358
86359
86360
86361
86362
86363
86364
86365
86366
86367
86368
86369
86370
86371
86372
86373
86374
86375
86376
86377
86378
86379
86380
86381
86382
86383
86384
86385
86386
86387
86388
86389
86390
86391
86392
86393
86394
86395
86396
86397
86398
86399
86400
86401
86402
86403
86404
86405
86406
86407
86408
86409
86410
86411
86412
86413
86414
86415
86416
86417
86418
86419
86420
86421
86422
86423
86424
86425
86426
86427
86428
86429
86430
86431
86432
86433
86434
86435
86436
86437
86438
86439
86440
86441
86442
86443
86444
86445
86446
86447
86448
86449
86450
86451
86452
86453
86454
86455
86456
86457
86458
86459
86460
86461
86462
86463
86464
86465
86466
86467
86468
86469
86470
86471
86472
86473
86474
86475
86476
86477
86478
86479
86480
86481
86482
86483
86484
86485
86486
86487
86488
86489
86490
86491
86492
86493
86494
86495
86496
86497
86498
86499
86500
86501
86502
86503
86504
86505
86506
86507
86508
86509
86510
86511
86512
86513
86514
86515
86516
86517
86518
86519
86520
86521
86522
86523
86524
86525
86526
86527
86528
86529
86530
86531
86532
86533
86534
86535
86536
86537
86538
86539
86540
86541
86542
86543
86544
86545
86546
86547
86548
86549
86550
86551
86552
86553
86554
86555
86556
86557
86558
86559
86560
86561
86562
86563
86564
86565
86566
86567
86568
86569
86570
86571
}
        break;
      case 48: /* typename ::= typename ids */
{yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
        break;
      case 55: /* ccons ::= DEFAULT term */
      case 57: /* ccons ::= DEFAULT PLUS term */
{sqlite3AddDefaultValue(pParse,yymsp[0].minor.yy128);}
        break;
      case 56: /* ccons ::= DEFAULT LP expr RP */
{sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy128);}
        break;
      case 58: /* ccons ::= DEFAULT MINUS term */
{
  Expr *p = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy128, 0, 0);
  sqlite3ExprSpan(p,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy128->span);
  sqlite3AddDefaultValue(pParse,p);
}
        break;
      case 59: /* ccons ::= DEFAULT id */
{
  Expr *p = sqlite3PExpr(pParse, TK_STRING, 0, 0, &yymsp[0].minor.yy0);
  sqlite3AddDefaultValue(pParse,p);
}
        break;
      case 61: /* ccons ::= NOT NULL onconf */
{sqlite3AddNotNull(pParse, yymsp[0].minor.yy376);}
        break;
      case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
{sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy376,yymsp[0].minor.yy376,yymsp[-2].minor.yy376);}
        break;
      case 63: /* ccons ::= UNIQUE onconf */
{sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy376,0,0,0,0);}
        break;
      case 64: /* ccons ::= CHECK LP expr RP */
{sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy128);}
        break;
      case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
{sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy22,yymsp[0].minor.yy376);}
        break;
      case 66: /* ccons ::= defer_subclause */
{sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy376);}
        break;
      case 67: /* ccons ::= COLLATE ids */
{sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
        break;
      case 70: /* refargs ::= */
{ yygotominor.yy376 = OE_Restrict * 0x010101; }
        break;
      case 71: /* refargs ::= refargs refarg */
{ yygotominor.yy376 = (yymsp[-1].minor.yy376 & ~yymsp[0].minor.yy299.mask) | yymsp[0].minor.yy299.value; }
        break;
      case 72: /* refarg ::= MATCH nm */
{ yygotominor.yy299.value = 0;     yygotominor.yy299.mask = 0x000000; }
        break;
      case 73: /* refarg ::= ON DELETE refact */
{ yygotominor.yy299.value = yymsp[0].minor.yy376;     yygotominor.yy299.mask = 0x0000ff; }
        break;
      case 74: /* refarg ::= ON UPDATE refact */
{ yygotominor.yy299.value = yymsp[0].minor.yy376<<8;  yygotominor.yy299.mask = 0x00ff00; }
        break;
      case 75: /* refarg ::= ON INSERT refact */
{ yygotominor.yy299.value = yymsp[0].minor.yy376<<16; yygotominor.yy299.mask = 0xff0000; }
        break;
      case 76: /* refact ::= SET NULL */
{ yygotominor.yy376 = OE_SetNull; }
        break;
      case 77: /* refact ::= SET DEFAULT */
{ yygotominor.yy376 = OE_SetDflt; }
        break;
      case 78: /* refact ::= CASCADE */
{ yygotominor.yy376 = OE_Cascade; }
        break;
      case 79: /* refact ::= RESTRICT */
{ yygotominor.yy376 = OE_Restrict; }
        break;
      case 80: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
      case 81: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
      case 96: /* defer_subclause_opt ::= defer_subclause */
      case 98: /* onconf ::= ON CONFLICT resolvetype */
      case 100: /* orconf ::= OR resolvetype */
      case 101: /* resolvetype ::= raisetype */
      case 173: /* insert_cmd ::= INSERT orconf */
{yygotominor.yy376 = yymsp[0].minor.yy376;}
        break;
      case 85: /* conslist_opt ::= */
{yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
        break;
      case 86: /* conslist_opt ::= COMMA conslist */
{yygotominor.yy0 = yymsp[-1].minor.yy0;}
        break;
      case 91: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
{sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy22,yymsp[0].minor.yy376,yymsp[-2].minor.yy376,0);}
        break;
      case 92: /* tcons ::= UNIQUE LP idxlist RP onconf */
{sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy22,yymsp[0].minor.yy376,0,0,0,0);}
        break;
      case 93: /* tcons ::= CHECK LP expr RP onconf */
{sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy128);}
        break;
      case 94: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
{
    sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy22, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy22, yymsp[-1].minor.yy376);
    sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy376);
}
        break;
      case 97: /* onconf ::= */
      case 99: /* orconf ::= */
{yygotominor.yy376 = OE_Default;}
        break;
      case 102: /* resolvetype ::= IGNORE */
{yygotominor.yy376 = OE_Ignore;}
        break;
      case 103: /* resolvetype ::= REPLACE */
      case 174: /* insert_cmd ::= REPLACE */
{yygotominor.yy376 = OE_Replace;}
        break;
      case 104: /* cmd ::= DROP TABLE ifexists fullname */
{
  sqlite3DropTable(pParse, yymsp[0].minor.yy133, 0, yymsp[-1].minor.yy376);
}
        break;
      case 107: /* cmd ::= CREATE temp VIEW ifnotexists nm dbnm AS select */
{
  sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy465, yymsp[-6].minor.yy376, yymsp[-4].minor.yy376);
}
        break;
      case 108: /* cmd ::= DROP VIEW ifexists fullname */
{
  sqlite3DropTable(pParse, yymsp[0].minor.yy133, 1, yymsp[-1].minor.yy376);
}
        break;
      case 109: /* cmd ::= select */
{
  SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  sqlite3Select(pParse, yymsp[0].minor.yy465, &dest);
  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy465);
}
        break;
      case 110: /* select ::= oneselect */
{yygotominor.yy465 = yymsp[0].minor.yy465;}
        break;
      case 111: /* select ::= select multiselect_op oneselect */
{
  if( yymsp[0].minor.yy465 ){
    yymsp[0].minor.yy465->op = (u8)yymsp[-1].minor.yy376;
    yymsp[0].minor.yy465->pPrior = yymsp[-2].minor.yy465;
  }else{
    sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy465);
  }
  yygotominor.yy465 = yymsp[0].minor.yy465;
}
        break;
      case 113: /* multiselect_op ::= UNION ALL */
{yygotominor.yy376 = TK_ALL;}
        break;
      case 115: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
{
  yygotominor.yy465 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy22,yymsp[-5].minor.yy133,yymsp[-4].minor.yy128,yymsp[-3].minor.yy22,yymsp[-2].minor.yy128,yymsp[-1].minor.yy22,yymsp[-7].minor.yy376,yymsp[0].minor.yy4.pLimit,yymsp[0].minor.yy4.pOffset);
}
        break;
      case 119: /* sclp ::= selcollist COMMA */
      case 245: /* idxlist_opt ::= LP idxlist RP */
{yygotominor.yy22 = yymsp[-1].minor.yy22;}
        break;
      case 120: /* sclp ::= */
      case 148: /* orderby_opt ::= */
      case 156: /* groupby_opt ::= */
      case 238: /* exprlist ::= */
      case 244: /* idxlist_opt ::= */
{yygotominor.yy22 = 0;}
        break;
      case 121: /* selcollist ::= sclp expr as */
{
   yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy22,yymsp[-1].minor.yy128,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
}
        break;
      case 122: /* selcollist ::= sclp STAR */
{
  Expr *p = sqlite3PExpr(pParse, TK_ALL, 0, 0, 0);
  yygotominor.yy22 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy22, p, 0);
}
        break;
      case 123: /* selcollist ::= sclp nm DOT STAR */
{
  Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy22, pDot, 0);
}
        break;
      case 126: /* as ::= */
{yygotominor.yy0.n = 0;}
        break;
      case 127: /* from ::= */
{yygotominor.yy133 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy133));}
        break;
      case 128: /* from ::= FROM seltablist */
{
  yygotominor.yy133 = yymsp[0].minor.yy133;
  sqlite3SrcListShiftJoinType(yygotominor.yy133);
}
        break;
      case 129: /* stl_prefix ::= seltablist joinop */
{
   yygotominor.yy133 = yymsp[-1].minor.yy133;
   if( yygotominor.yy133 && yygotominor.yy133->nSrc>0 ) yygotominor.yy133->a[yygotominor.yy133->nSrc-1].jointype = (u8)yymsp[0].minor.yy376;
}
        break;
      case 130: /* stl_prefix ::= */
{yygotominor.yy133 = 0;}
        break;
      case 131: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
{
  yygotominor.yy133 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy133,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy128,yymsp[0].minor.yy288);
  sqlite3SrcListIndexedBy(pParse, yygotominor.yy133, &yymsp[-2].minor.yy0);
}
        break;
      case 132: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
{
    yygotominor.yy133 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy133,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy465,yymsp[-1].minor.yy128,yymsp[0].minor.yy288);
  }
        break;
      case 133: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
{
    if( yymsp[-6].minor.yy133==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy128==0 && yymsp[0].minor.yy288==0 ){
      yygotominor.yy133 = yymsp[-4].minor.yy133;
    }else{
      Select *pSubquery;
      sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy133);
      pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy133,0,0,0,0,0,0,0);
      yygotominor.yy133 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy133,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy128,yymsp[0].minor.yy288);
    }
  }
        break;
      case 134: /* dbnm ::= */
      case 143: /* indexed_opt ::= */
{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
        break;
      case 136: /* fullname ::= nm dbnm */
{yygotominor.yy133 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
        break;
      case 137: /* joinop ::= COMMA|JOIN */
{ yygotominor.yy376 = JT_INNER; }
        break;
      case 138: /* joinop ::= JOIN_KW JOIN */
{ yygotominor.yy376 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
        break;
      case 139: /* joinop ::= JOIN_KW nm JOIN */
{ yygotominor.yy376 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
        break;
      case 140: /* joinop ::= JOIN_KW nm nm JOIN */
{ yygotominor.yy376 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
        break;
      case 141: /* on_opt ::= ON expr */
      case 152: /* sortitem ::= expr */
      case 159: /* having_opt ::= HAVING expr */
      case 166: /* where_opt ::= WHERE expr */
      case 181: /* expr ::= term */
      case 209: /* escape ::= ESCAPE expr */
      case 233: /* case_else ::= ELSE expr */
      case 235: /* case_operand ::= expr */
{yygotominor.yy128 = yymsp[0].minor.yy128;}
        break;
      case 142: /* on_opt ::= */
      case 158: /* having_opt ::= */
      case 165: /* where_opt ::= */
      case 210: /* escape ::= */
      case 234: /* case_else ::= */
      case 236: /* case_operand ::= */
{yygotominor.yy128 = 0;}
        break;
      case 145: /* indexed_opt ::= NOT INDEXED */
{yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
        break;
      case 146: /* using_opt ::= USING LP inscollist RP */
      case 178: /* inscollist_opt ::= LP inscollist RP */
{yygotominor.yy288 = yymsp[-1].minor.yy288;}
        break;
      case 147: /* using_opt ::= */
      case 177: /* inscollist_opt ::= */
{yygotominor.yy288 = 0;}
        break;
      case 149: /* orderby_opt ::= ORDER BY sortlist */
      case 157: /* groupby_opt ::= GROUP BY nexprlist */
      case 237: /* exprlist ::= nexprlist */
{yygotominor.yy22 = yymsp[0].minor.yy22;}
        break;
      case 150: /* sortlist ::= sortlist COMMA sortitem sortorder */
{
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy22,yymsp[-1].minor.yy128,0);
  if( yygotominor.yy22 ) yygotominor.yy22->a[yygotominor.yy22->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy376;
}
        break;
      case 151: /* sortlist ::= sortitem sortorder */
{
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy128,0);
  if( yygotominor.yy22 && yygotominor.yy22->a ) yygotominor.yy22->a[0].sortOrder = (u8)yymsp[0].minor.yy376;
}
        break;
      case 153: /* sortorder ::= ASC */
      case 155: /* sortorder ::= */
{yygotominor.yy376 = SQLITE_SO_ASC;}
        break;
      case 154: /* sortorder ::= DESC */
{yygotominor.yy376 = SQLITE_SO_DESC;}
        break;
      case 160: /* limit_opt ::= */
{yygotominor.yy4.pLimit = 0; yygotominor.yy4.pOffset = 0;}
        break;
      case 161: /* limit_opt ::= LIMIT expr */
{yygotominor.yy4.pLimit = yymsp[0].minor.yy128; yygotominor.yy4.pOffset = 0;}
        break;
      case 162: /* limit_opt ::= LIMIT expr OFFSET expr */
{yygotominor.yy4.pLimit = yymsp[-2].minor.yy128; yygotominor.yy4.pOffset = yymsp[0].minor.yy128;}
        break;
      case 163: /* limit_opt ::= LIMIT expr COMMA expr */
{yygotominor.yy4.pOffset = yymsp[-2].minor.yy128; yygotominor.yy4.pLimit = yymsp[0].minor.yy128;}
        break;
      case 164: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
{
  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy133, &yymsp[-1].minor.yy0);
  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy133,yymsp[0].minor.yy128);
}
        break;
      case 167: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
{
  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy133, &yymsp[-3].minor.yy0);
  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy22,"set list"); 
  sqlite3Update(pParse,yymsp[-4].minor.yy133,yymsp[-1].minor.yy22,yymsp[0].minor.yy128,yymsp[-5].minor.yy376);
}
        break;
      case 168: /* setlist ::= setlist COMMA nm EQ expr */
{yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy22,yymsp[0].minor.yy128,&yymsp[-2].minor.yy0);}
        break;
      case 169: /* setlist ::= nm EQ expr */
{yygotominor.yy22 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy128,&yymsp[-2].minor.yy0);}
        break;
      case 170: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
{sqlite3Insert(pParse, yymsp[-5].minor.yy133, yymsp[-1].minor.yy22, 0, yymsp[-4].minor.yy288, yymsp[-7].minor.yy376);}
        break;
      case 171: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
{sqlite3Insert(pParse, yymsp[-2].minor.yy133, 0, yymsp[0].minor.yy465, yymsp[-1].minor.yy288, yymsp[-4].minor.yy376);}
        break;
      case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
{sqlite3Insert(pParse, yymsp[-3].minor.yy133, 0, 0, yymsp[-2].minor.yy288, yymsp[-5].minor.yy376);}
        break;
      case 175: /* itemlist ::= itemlist COMMA expr */
      case 239: /* nexprlist ::= nexprlist COMMA expr */
{yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy22,yymsp[0].minor.yy128,0);}
        break;
      case 176: /* itemlist ::= expr */
      case 240: /* nexprlist ::= expr */
{yygotominor.yy22 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy128,0);}
        break;
      case 179: /* inscollist ::= inscollist COMMA nm */
{yygotominor.yy288 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy288,&yymsp[0].minor.yy0);}
        break;
      case 180: /* inscollist ::= nm */
{yygotominor.yy288 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
        break;
      case 182: /* expr ::= LP expr RP */
{yygotominor.yy128 = yymsp[-1].minor.yy128; sqlite3ExprSpan(yygotominor.yy128,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
        break;
      case 183: /* term ::= NULL */
      case 188: /* term ::= INTEGER|FLOAT|BLOB */
      case 189: /* term ::= STRING */
{yygotominor.yy128 = sqlite3PExpr(pParse, yymsp[0].major, 0, 0, &yymsp[0].minor.yy0);}
        break;
      case 184: /* expr ::= ID */
      case 185: /* expr ::= JOIN_KW */
{yygotominor.yy128 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);}
        break;
      case 186: /* expr ::= nm DOT nm */
{
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
}
        break;
      case 187: /* expr ::= nm DOT nm DOT nm */
{
  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
}
        break;
      case 190: /* expr ::= REGISTER */
{yygotominor.yy128 = sqlite3RegisterExpr(pParse, &yymsp[0].minor.yy0);}
        break;
      case 191: /* expr ::= VARIABLE */
{
  Token *pToken = &yymsp[0].minor.yy0;
  Expr *pExpr = yygotominor.yy128 = sqlite3PExpr(pParse, TK_VARIABLE, 0, 0, pToken);
  sqlite3ExprAssignVarNumber(pParse, pExpr);
}
        break;
      case 192: /* expr ::= expr COLLATE ids */
{
  yygotominor.yy128 = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy128, &yymsp[0].minor.yy0);
}
        break;
      case 193: /* expr ::= CAST LP expr AS typetoken RP */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy128, 0, &yymsp[-1].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
}
        break;
      case 194: /* expr ::= ID LP distinct exprlist RP */
{
  if( yymsp[-1].minor.yy22 && yymsp[-1].minor.yy22->nExpr>SQLITE_MAX_FUNCTION_ARG ){
    sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  }
  yygotominor.yy128 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy22, &yymsp[-4].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  if( yymsp[-2].minor.yy376 && yygotominor.yy128 ){
    yygotominor.yy128->flags |= EP_Distinct;
  }
}
        break;
      case 195: /* expr ::= ID LP STAR RP */
{
  yygotominor.yy128 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
}
        break;
      case 196: /* term ::= CTIME_KW */
{
  /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  ** treated as functions that return constants */
  yygotominor.yy128 = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  if( yygotominor.yy128 ){
    yygotominor.yy128->op = TK_CONST_FUNC;  
    yygotominor.yy128->span = yymsp[0].minor.yy0;
  }
}
        break;
      case 197: /* expr ::= expr AND expr */
      case 198: /* expr ::= expr OR expr */
      case 199: /* expr ::= expr LT|GT|GE|LE expr */
      case 200: /* expr ::= expr EQ|NE expr */
      case 201: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
      case 202: /* expr ::= expr PLUS|MINUS expr */
      case 203: /* expr ::= expr STAR|SLASH|REM expr */
      case 204: /* expr ::= expr CONCAT expr */
{yygotominor.yy128 = sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy128,yymsp[0].minor.yy128,0);}
        break;
      case 205: /* likeop ::= LIKE_KW */
      case 207: /* likeop ::= MATCH */
{yygotominor.yy450.eOperator = yymsp[0].minor.yy0; yygotominor.yy450.not = 0;}
        break;
      case 206: /* likeop ::= NOT LIKE_KW */
      case 208: /* likeop ::= NOT MATCH */
{yygotominor.yy450.eOperator = yymsp[0].minor.yy0; yygotominor.yy450.not = 1;}
        break;
      case 211: /* expr ::= expr likeop expr escape */
{
  ExprList *pList;
  pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy128, 0);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy128, 0);
  if( yymsp[0].minor.yy128 ){
    pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy128, 0);
  }
  yygotominor.yy128 = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy450.eOperator);
  if( yymsp[-2].minor.yy450.not ) yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128, &yymsp[-3].minor.yy128->span, &yymsp[-1].minor.yy128->span);
  if( yygotominor.yy128 ) yygotominor.yy128->flags |= EP_InfixFunc;
}
        break;
      case 212: /* expr ::= expr ISNULL|NOTNULL */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, yymsp[0].major, yymsp[-1].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-1].minor.yy128->span,&yymsp[0].minor.yy0);
}
        break;
      case 213: /* expr ::= expr IS NULL */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_ISNULL, yymsp[-2].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-2].minor.yy128->span,&yymsp[0].minor.yy0);
}
        break;
      case 214: /* expr ::= expr NOT NULL */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-2].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-2].minor.yy128->span,&yymsp[0].minor.yy0);
}
        break;
      case 215: /* expr ::= expr IS NOT NULL */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOTNULL, yymsp[-3].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-3].minor.yy128->span,&yymsp[0].minor.yy0);
}
        break;
      case 216: /* expr ::= NOT expr */
      case 217: /* expr ::= BITNOT expr */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy128->span);
}
        break;
      case 218: /* expr ::= MINUS expr */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy128->span);
}
        break;
      case 219: /* expr ::= PLUS expr */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_UPLUS, yymsp[0].minor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy128->span);
}
        break;
      case 222: /* expr ::= expr between_op expr AND expr */
{
  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy128, 0);
  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy128, 0);
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy128, 0, 0);
  if( yygotominor.yy128 ){
    yygotominor.yy128->pList = pList;
  }else{
    sqlite3ExprListDelete(pParse->db, pList);
  } 
  if( yymsp[-3].minor.yy376 ) yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy128, 0, 0);
  sqlite3ExprSpan(yygotominor.yy128,&yymsp[-4].minor.yy128->span,&yymsp[0].minor.yy128->span);
}
        break;
      case 225: /* expr ::= expr in_op LP exprlist RP */
{
    yygotominor.yy128 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy128, 0, 0);
    if( yygotominor.yy128 ){
      yygotominor.yy128->pList = yymsp[-1].minor.yy22;
      sqlite3ExprSetHeight(pParse, yygotominor.yy128);
    }else{
      sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy22);
    }
    if( yymsp[-3].minor.yy376 ) yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy128, 0, 0);
    sqlite3ExprSpan(yygotominor.yy128,&yymsp[-4].minor.yy128->span,&yymsp[0].minor.yy0);
  }
        break;
      case 226: /* expr ::= LP select RP */
{
    yygotominor.yy128 = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
    if( yygotominor.yy128 ){
      yygotominor.yy128->pSelect = yymsp[-1].minor.yy465;
      sqlite3ExprSetHeight(pParse, yygotominor.yy128);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy465);
    }
    sqlite3ExprSpan(yygotominor.yy128,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  }
        break;
      case 227: /* expr ::= expr in_op LP select RP */
{
    yygotominor.yy128 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy128, 0, 0);
    if( yygotominor.yy128 ){
      yygotominor.yy128->pSelect = yymsp[-1].minor.yy465;
      sqlite3ExprSetHeight(pParse, yygotominor.yy128);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy465);
    }
    if( yymsp[-3].minor.yy376 ) yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy128, 0, 0);
    sqlite3ExprSpan(yygotominor.yy128,&yymsp[-4].minor.yy128->span,&yymsp[0].minor.yy0);
  }
        break;
      case 228: /* expr ::= expr in_op nm dbnm */
{
    SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
    yygotominor.yy128 = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy128, 0, 0);
    if( yygotominor.yy128 ){
      yygotominor.yy128->pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
      sqlite3ExprSetHeight(pParse, yygotominor.yy128);
    }else{
      sqlite3SrcListDelete(pParse->db, pSrc);
    }
    if( yymsp[-2].minor.yy376 ) yygotominor.yy128 = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy128, 0, 0);
    sqlite3ExprSpan(yygotominor.yy128,&yymsp[-3].minor.yy128->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  }
        break;
      case 229: /* expr ::= EXISTS LP select RP */
{
    Expr *p = yygotominor.yy128 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
    if( p ){
      p->pSelect = yymsp[-1].minor.yy465;
      sqlite3ExprSpan(p,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
      sqlite3ExprSetHeight(pParse, yygotominor.yy128);
    }else{
      sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy465);
    }
  }
        break;
      case 230: /* expr ::= CASE case_operand case_exprlist case_else END */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy128, yymsp[-1].minor.yy128, 0);
  if( yygotominor.yy128 ){
    yygotominor.yy128->pList = yymsp[-2].minor.yy22;
    sqlite3ExprSetHeight(pParse, yygotominor.yy128);
  }else{
    sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy22);
  }
  sqlite3ExprSpan(yygotominor.yy128, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
}
        break;
      case 231: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
{
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy22, yymsp[-2].minor.yy128, 0);
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yygotominor.yy22, yymsp[0].minor.yy128, 0);
}
        break;
      case 232: /* case_exprlist ::= WHEN expr THEN expr */
{
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy128, 0);
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yygotominor.yy22, yymsp[0].minor.yy128, 0);
}
        break;
      case 241: /* cmd ::= CREATE uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
{
  sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
                     sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy22, yymsp[-9].minor.yy376,
                      &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy376);
}
        break;
      case 242: /* uniqueflag ::= UNIQUE */
      case 279: /* raisetype ::= ABORT */
{yygotominor.yy376 = OE_Abort;}
        break;
      case 243: /* uniqueflag ::= */
{yygotominor.yy376 = OE_None;}
        break;
      case 246: /* idxlist ::= idxlist COMMA nm collate sortorder */
{
  Expr *p = 0;
  if( yymsp[-1].minor.yy0.n>0 ){
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  }
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy22, p, &yymsp[-2].minor.yy0);
  sqlite3ExprListCheckLength(pParse, yygotominor.yy22, "index");
  if( yygotominor.yy22 ) yygotominor.yy22->a[yygotominor.yy22->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy376;
}
        break;
      case 247: /* idxlist ::= nm collate sortorder */
{
  Expr *p = 0;
  if( yymsp[-1].minor.yy0.n>0 ){
    p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
    sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
  }
  yygotominor.yy22 = sqlite3ExprListAppend(pParse,0, p, &yymsp[-2].minor.yy0);
  sqlite3ExprListCheckLength(pParse, yygotominor.yy22, "index");
  if( yygotominor.yy22 ) yygotominor.yy22->a[yygotominor.yy22->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy376;
}
        break;
      case 248: /* collate ::= */
{yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
        break;
      case 250: /* cmd ::= DROP INDEX ifexists fullname */
{sqlite3DropIndex(pParse, yymsp[0].minor.yy133, yymsp[-1].minor.yy376);}
        break;
      case 256: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
{
  Token all;
  all.z = yymsp[-3].minor.yy0.z;
  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy167, &all);
}
        break;
      case 257: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
{
  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy376, yymsp[-4].minor.yy366.a, yymsp[-4].minor.yy366.b, yymsp[-2].minor.yy133, yymsp[0].minor.yy128, yymsp[-10].minor.yy376, yymsp[-8].minor.yy376);
  yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
}
        break;
      case 258: /* trigger_time ::= BEFORE */
      case 261: /* trigger_time ::= */
{ yygotominor.yy376 = TK_BEFORE; }
        break;
      case 259: /* trigger_time ::= AFTER */
{ yygotominor.yy376 = TK_AFTER;  }
        break;
      case 260: /* trigger_time ::= INSTEAD OF */
{ yygotominor.yy376 = TK_INSTEAD;}
        break;
      case 262: /* trigger_event ::= DELETE|INSERT */
      case 263: /* trigger_event ::= UPDATE */
{yygotominor.yy366.a = yymsp[0].major; yygotominor.yy366.b = 0;}
        break;
      case 264: /* trigger_event ::= UPDATE OF inscollist */
{yygotominor.yy366.a = TK_UPDATE; yygotominor.yy366.b = yymsp[0].minor.yy288;}
        break;
      case 267: /* when_clause ::= */
{ yygotominor.yy128 = 0; }
        break;
      case 268: /* when_clause ::= WHEN expr */
{ yygotominor.yy128 = yymsp[0].minor.yy128; }
        break;
      case 269: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
{
/*
  if( yymsp[-2].minor.yy167 ){
    yymsp[-2].minor.yy167->pLast->pNext = yymsp[-1].minor.yy167;
  }else{
    yymsp[-2].minor.yy167 = yymsp[-1].minor.yy167;
  }
*/
  assert( yymsp[-2].minor.yy167!=0 );
  yymsp[-2].minor.yy167->pLast->pNext = yymsp[-1].minor.yy167;
  yymsp[-2].minor.yy167->pLast = yymsp[-1].minor.yy167;
  yygotominor.yy167 = yymsp[-2].minor.yy167;
}
        break;
      case 270: /* trigger_cmd_list ::= trigger_cmd SEMI */
{ 
  /* if( yymsp[-1].minor.yy167 ) */
  assert( yymsp[-1].minor.yy167!=0 );
  yymsp[-1].minor.yy167->pLast = yymsp[-1].minor.yy167;
  yygotominor.yy167 = yymsp[-1].minor.yy167;
}
        break;
      case 271: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
{ yygotominor.yy167 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy22, yymsp[0].minor.yy128, yymsp[-4].minor.yy376); }
        break;
      case 272: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
{yygotominor.yy167 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy288, yymsp[-1].minor.yy22, 0, yymsp[-7].minor.yy376);}
        break;
      case 273: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
{yygotominor.yy167 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy288, 0, yymsp[0].minor.yy465, yymsp[-4].minor.yy376);}
        break;
      case 274: /* trigger_cmd ::= DELETE FROM nm where_opt */
{yygotominor.yy167 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-1].minor.yy0, yymsp[0].minor.yy128);}
        break;
      case 275: /* trigger_cmd ::= select */
{yygotominor.yy167 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy465); }
        break;
      case 276: /* expr ::= RAISE LP IGNORE RP */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
  if( yygotominor.yy128 ){
    yygotominor.yy128->iColumn = OE_Ignore;
    sqlite3ExprSpan(yygotominor.yy128, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
  }
}
        break;
      case 277: /* expr ::= RAISE LP raisetype COMMA nm RP */
{
  yygotominor.yy128 = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
  if( yygotominor.yy128 ) {
    yygotominor.yy128->iColumn = yymsp[-3].minor.yy376;
    sqlite3ExprSpan(yygotominor.yy128, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  }
}
        break;
      case 278: /* raisetype ::= ROLLBACK */
{yygotominor.yy376 = OE_Rollback;}
        break;
      case 280: /* raisetype ::= FAIL */
{yygotominor.yy376 = OE_Fail;}
        break;
      case 281: /* cmd ::= DROP TRIGGER ifexists fullname */
{
  sqlite3DropTrigger(pParse,yymsp[0].minor.yy133,yymsp[-1].minor.yy376);
}
        break;
  };
  yygoto = yyRuleInfo[yyruleno].lhs;
  yysize = yyRuleInfo[yyruleno].nrhs;
  yypParser->yyidx -= yysize;
  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  if( yyact < YYNSTATE ){
#ifdef NDEBUG
    /* If we are not debugging and the reduce action popped at least
    ** one element off the stack, then we can push the new element back
    ** onto the stack here, and skip the stack overflow test in yy_shift().
    ** That gives a significant speed improvement. */
    if( yysize ){
      yypParser->yyidx++;
      yymsp -= yysize-1;
      yymsp->stateno = (YYACTIONTYPE)yyact;
      yymsp->major = (YYCODETYPE)yygoto;
      yymsp->minor = yygotominor;
    }else
#endif
    {
      yy_shift(yypParser,yyact,yygoto,&yygotominor);
    }
  }else{
85902
85903
85904
85905
85906
85907
85908
85909
85910
85911
85912
85913
85914
85915
85916
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
**
** $Id: tokenize.c,v 1.152 2008/09/01 15:52:11 drh 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







|







86801
86802
86803
86804
86805
86806
86807
86808
86809
86810
86811
86812
86813
86814
86815
*************************************************************************
** An tokenizer for SQL
**
** This file contains C code that splits an SQL input string up into
** individual tokens and sends those tokens one-by-one over to the
** parser for analysis.
**
** $Id: tokenize.c,v 1.153 2009/01/20 16:53:41 danielk1977 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
85955
85956
85957
85958
85959
85960
85961
85962
85963
85964
85965
85966
85967
85968
85969
85970
85971
85972
85973
85974
85975
85976
85977
85978
85979
85980
*/
/************** 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: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.36 2008/12/31 21:52:41 drh 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.
*/
/* Hash score: 134 */
static int keywordCode(const char *z, int n){
  /* zText[] encodes 682 bytes of keywords in 452 bytes */
  /*   BEFOREIGNOREGEXPLAINDEXEDESCAPEACHECKEYCONSTRAINTERSECTABLEFT      */
  /*   HENDEFERRABLELSELECTRANSACTIONATURALIKEXCEPTRIGGERAISEXCLUSIVE     */
  /*   XISTSAVEPOINTOFFSETEMPORARYUNIQUERYBEGINNEREFERENCESBETWEEN        */
  /*   OTNULLIMITCASCADELETECASECOLLATECREATECURRENT_DATEGROUPDATE        */
  /*   IMMEDIATEJOINSERTMATCHAVINGLOBYPLANDEFAULTRELEASEVALUESWHEN        */
  /*   WHERESTRICTABORTAFTERIGHTCASTCOMMITCROSSCURRENT_TIMESTAMP          */
  /*   RIMARYDEFERREDISTINCTDROPFAILFROMFULLIFINSTEADISNULLORDER          */







|








|

|







86854
86855
86856
86857
86858
86859
86860
86861
86862
86863
86864
86865
86866
86867
86868
86869
86870
86871
86872
86873
86874
86875
86876
86877
86878
86879
*/
/************** 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: /sqlite/sqlite/tool/mkkeywordhash.c,v 1.37 2009/02/01 00:00:46 drh 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.
*/
/* Hash score: 135 */
static int keywordCode(const char *z, int n){
  /* zText[] encodes 685 bytes of keywords in 452 bytes */
  /*   BEFOREIGNOREGEXPLAINDEXEDESCAPEACHECKEYCONSTRAINTERSECTABLEFT      */
  /*   HENDEFERRABLELSELECTRANSACTIONATURALIKEXCEPTRIGGERAISEXCLUSIVE     */
  /*   XISTSAVEPOINTOFFSETEMPORARYUNIQUERYBEGINNEREFERENCESBETWEEN        */
  /*   OTNULLIMITCASCADELETECASECOLLATECREATECURRENT_DATEGROUPDATE        */
  /*   IMMEDIATEJOINSERTMATCHAVINGLOBYPLANDEFAULTRELEASEVALUESWHEN        */
  /*   WHERESTRICTABORTAFTERIGHTCASTCOMMITCROSSCURRENT_TIMESTAMP          */
  /*   RIMARYDEFERREDISTINCTDROPFAILFROMFULLIFINSTEADISNULLORDER          */
86004
86005
86006
86007
86008
86009
86010
86011
86012
86013
86014
86015
86016
86017
86018
86019
86020
86021
86022
86023
86024
86025
86026
86027
86028
86029
86030
86031
86032
86033
86034
86035
86036
86037
86038
86039
86040
86041
86042
86043
86044
86045
86046
86047
86048
86049
86050
86051
86052
86053
86054
86055
86056
86057
86058
86059
86060
86061
86062
86063
86064
86065
86066
86067
86068
86069
86070
86071
86072
86073
86074
86075
86076
86077
86078
86079
86080
    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','I','F',
    'I','N','S','T','E','A','D','I','S','N','U','L','L','O','R','D','E','R',
    'O','L','L','B','A','C','K','O','U','T','E','R','O','W','U','N','I','O',
    'N','U','S','I','N','G','V','I','E','W','I','N','I','T','I','A','L','L',
    'Y',
  };
  static const unsigned char aHash[127] = {
      62,  87,  96,  60,   0,  38,   0,   0,  72,   0,  63,   0,   0,
      36,   4,  67,  93,   0,  78,  73,  64,  92,   0,  23,   0,   0,
      33,   0,  99,  75,   0,  19,   0,   0,   1,   0,   0,  55,  56,
       0,  54,  11,   0,  42,  68,  84,   0,  98,  83,   0,   0,  39,
       0,  85,  21,   0,   0,   0, 101,   0,  20,   0,  10,  65,  22,
       0,   0,   0, 103,  88,  46, 102,  43,  12,  58,   0,  69,   0,
      82,  28,   0,  81,   0,   0,   0,  79,   2,  80,  77,  91,   6,
      14,  90,   0,  76,   0,  71,  70,  66,  30,   0, 100,   0,  94,
      48,  40,  50,   0,   0,  16,  34,   0,  97,   0,  15,   0,   0,
      25,   0,  74,  44,  49,   0,  17,  47,   0,  59,
  };
  static const unsigned char aNext[103] = {
       0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,
       0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,  31,
      18,   0,   0,   0,   0,  27,   0,  26,   0,   0,   0,   0,   0,
       0,   0,  51,   0,   0,   8,  41,   0,  35,   0,   0,  37,   0,
       0,   0,   0,  32,   0,   0,   0,   0,   0,   0,   0,   0,  24,
       0,   0,   0,   3,  57,   0,   0,  13,   0,  86,   0,   0,  89,
       0,   7,  61,   0,  29,  95,  52,  45,   0,  53,   0,   0,
  };
  static const unsigned char aLen[103] = {
       6,   7,   3,   6,   6,   7,   7,   5,   4,   6,   4,   5,   3,
      10,   9,   2,   5,   4,   4,   3,  10,   4,   6,  11,   2,   7,
       4,   6,   7,   5,   9,   6,   9,   4,   6,   2,   3,   4,   9,
       2,   6,   5,   5,   5,  10,   7,   7,   3,   4,   5,   7,   3,
       6,   4,   7,   6,  12,   5,   6,   9,   4,   6,   5,   6,   4,
       2,   4,   3,   7,   7,   2,   6,   4,   5,   8,   5,   5,   5,
       4,   6,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,   4,
       2,   7,   6,   5,   8,   5,   3,   5,   5,   4,   9,   3,
  };
  static const unsigned short int aOffset[103] = {
       0,   2,   2,   6,  10,  13,  18,  18,  24,  25,  30,  32,  36,
      39,  46,  46,  54,  57,  60,  62,  64,  73,  75,  80,  89,  90,
      96,  99, 104, 110, 114, 122, 127, 133, 136, 136, 139, 141, 141,
     145, 150, 153, 158, 161, 165, 175, 181, 181, 184, 187, 192, 193,
     197, 203, 207, 214, 220, 232, 235, 241, 250, 252, 258, 262, 267,
     270, 272, 274, 276, 283, 287, 290, 296, 300, 303, 311, 316, 320,
     325, 329, 335, 340, 340, 356, 363, 370, 371, 378, 382, 386, 390,
     394, 396, 403, 409, 413, 421, 425, 428, 433, 438, 442, 447,
  };
  static const unsigned char aCode[103] = {
    TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
    TK_EXPLAIN,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
    TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
    TK_IN,         TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        
    TK_DEFERRABLE, TK_ELSE,       TK_SELECT,     TK_TRANSACTION,TK_ON,         
    TK_JOIN_KW,    TK_LIKE_KW,    TK_EXCEPT,     TK_TRIGGER,    TK_RAISE,      
    TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  TK_INTO,       TK_OFFSET,     
    TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       TK_OR,         
    TK_UNIQUE,     TK_QUERY,      TK_BEGIN,      TK_JOIN_KW,    TK_REFERENCES, 
    TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       TK_LIMIT,      
    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    
    TK_CREATE,     TK_CTIME_KW,   TK_GROUP,      TK_UPDATE,     TK_IMMEDIATE,  
    TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_HAVING,     TK_LIKE_KW,    
    TK_BY,         TK_PLAN,       TK_AND,        TK_DEFAULT,    TK_RELEASE,    
    TK_AS,         TK_VALUES,     TK_WHEN,       TK_WHERE,      TK_RESTRICT,   
    TK_ABORT,      TK_AFTER,      TK_JOIN_KW,    TK_CAST,       TK_COMMIT,     
    TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   
    TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       
    TK_JOIN_KW,    TK_IF,         TK_INSTEAD,    TK_ISNULL,     TK_ORDER,      
    TK_ROLLBACK,   TK_JOIN_KW,    TK_ROW,        TK_UNION,      TK_USING,      
    TK_VIEW,       TK_INITIALLY,  TK_ALL,        
  };
  int h, i;
  if( n<2 ) return TK_ID;
  h = ((charMap(z[0])*4) ^
      (charMap(z[n-1])*3) ^
      n) % 127;
  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){







|
|
|
|
|
|
|
|
|
|

|


|
|
|
|
|
|

|


|
|
|
|
|
|

|


|
|
|
|
|
|

|






|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







86903
86904
86905
86906
86907
86908
86909
86910
86911
86912
86913
86914
86915
86916
86917
86918
86919
86920
86921
86922
86923
86924
86925
86926
86927
86928
86929
86930
86931
86932
86933
86934
86935
86936
86937
86938
86939
86940
86941
86942
86943
86944
86945
86946
86947
86948
86949
86950
86951
86952
86953
86954
86955
86956
86957
86958
86959
86960
86961
86962
86963
86964
86965
86966
86967
86968
86969
86970
86971
86972
86973
86974
86975
86976
86977
86978
86979
    'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','I','F',
    'I','N','S','T','E','A','D','I','S','N','U','L','L','O','R','D','E','R',
    'O','L','L','B','A','C','K','O','U','T','E','R','O','W','U','N','I','O',
    'N','U','S','I','N','G','V','I','E','W','I','N','I','T','I','A','L','L',
    'Y',
  };
  static const unsigned char aHash[127] = {
      63,  88,  97,  61,   0,  39,   0,   0,  73,   0,  64,   0,   0,
      37,   4,  68,  94,   0,  79,  74,  65,  93,   0,  23,   0,   0,
      33,   0, 100,  76,   0,  19,  35,   0,   1,   0,   0,  56,  57,
       0,  55,  11,   0,  43,  69,  85,   0,  99,  84,   0,   0,  40,
       0,  86,  21,   0,   0,   0, 102,   0,  20,   0,  10,  66,  22,
       0,   0,   0, 104,  89,  47, 103,  44,  12,  59,   0,  70,   0,
      83,  28,   0,  82,   0,   0,   0,  80,   2,  81,  78,  92,   6,
      14,  91,   0,  77,   0,  72,  71,  67,  30,   0, 101,   0,  95,
      49,  41,  51,   0,   0,  16,  34,   0,  98,   0,  15,   0,   0,
      25,   0,  75,  45,  50,   0,  17,  48,   0,  60,
  };
  static const unsigned char aNext[104] = {
       0,   0,   0,   0,   0,   0,   0,   0,   0,   9,   0,   0,   0,
       0,   0,   0,   0,   0,   5,   0,   0,   0,   0,   0,   0,   0,
       0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
      31,  18,   0,   0,   0,   0,  27,   0,  26,   0,   0,   0,   0,
       0,   0,   0,  52,   0,   0,   8,  42,   0,  36,   0,   0,  38,
       0,   0,   0,   0,  32,   0,   0,   0,   0,   0,   0,   0,   0,
      24,   0,   0,   0,   3,  58,   0,   0,  13,   0,  87,   0,   0,
      90,   0,   7,  62,   0,  29,  96,  53,  46,   0,  54,   0,   0,
  };
  static const unsigned char aLen[104] = {
       6,   7,   3,   6,   6,   7,   7,   5,   4,   6,   4,   5,   3,
      10,   9,   2,   5,   4,   4,   3,  10,   4,   6,  11,   2,   7,
       4,   6,   7,   5,   9,   6,   9,   4,   2,   6,   2,   3,   4,
       9,   2,   6,   5,   5,   5,  10,   7,   7,   3,   4,   5,   7,
       3,   6,   4,   7,   6,  12,   5,   6,   9,   4,   6,   5,   6,
       4,   2,   4,   3,   7,   7,   2,   6,   4,   5,   8,   5,   5,
       5,   4,   6,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
       4,   2,   7,   6,   5,   8,   5,   3,   5,   5,   4,   9,   3,
  };
  static const unsigned short int aOffset[104] = {
       0,   2,   2,   6,  10,  13,  18,  18,  24,  25,  30,  32,  36,
      39,  46,  46,  54,  57,  60,  62,  64,  73,  75,  80,  89,  90,
      96,  99, 104, 110, 114, 122, 127, 133, 135, 136, 136, 139, 141,
     141, 145, 150, 153, 158, 161, 165, 175, 181, 181, 184, 187, 192,
     193, 197, 203, 207, 214, 220, 232, 235, 241, 250, 252, 258, 262,
     267, 270, 272, 274, 276, 283, 287, 290, 296, 300, 303, 311, 316,
     320, 325, 329, 335, 340, 340, 356, 363, 370, 371, 378, 382, 386,
     390, 394, 396, 403, 409, 413, 421, 425, 428, 433, 438, 442, 447,
  };
  static const unsigned char aCode[104] = {
    TK_BEFORE,     TK_FOREIGN,    TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    
    TK_EXPLAIN,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
    TK_EACH,       TK_CHECK,      TK_KEY,        TK_CONSTRAINT, TK_INTERSECT,  
    TK_IN,         TK_TABLE,      TK_JOIN_KW,    TK_THEN,       TK_END,        
    TK_DEFERRABLE, TK_ELSE,       TK_SELECT,     TK_TRANSACTION,TK_ON,         
    TK_JOIN_KW,    TK_LIKE_KW,    TK_EXCEPT,     TK_TRIGGER,    TK_RAISE,      
    TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  TK_INTO,       TK_TO,         
    TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
    TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_BEGIN,      TK_JOIN_KW,    
    TK_REFERENCES, TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NULL,       
    TK_LIMIT,      TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
    TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_GROUP,      TK_UPDATE,     
    TK_IMMEDIATE,  TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_HAVING,     
    TK_LIKE_KW,    TK_BY,         TK_PLAN,       TK_AND,        TK_DEFAULT,    
    TK_RELEASE,    TK_AS,         TK_VALUES,     TK_WHEN,       TK_WHERE,      
    TK_RESTRICT,   TK_ABORT,      TK_AFTER,      TK_JOIN_KW,    TK_CAST,       
    TK_COMMIT,     TK_JOIN_KW,    TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    
    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         TK_DROP,       TK_FAIL,       
    TK_FROM,       TK_JOIN_KW,    TK_IF,         TK_INSTEAD,    TK_ISNULL,     
    TK_ORDER,      TK_ROLLBACK,   TK_JOIN_KW,    TK_ROW,        TK_UNION,      
    TK_USING,      TK_VIEW,       TK_INITIALLY,  TK_ALL,        
  };
  int h, i;
  if( n<2 ) return TK_ID;
  h = ((charMap(z[0])*4) ^
      (charMap(z[n-1])*3) ^
      n) % 127;
  for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
86109
86110
86111
86112
86113
86114
86115
86116
86117
86118
86119
86120
86121
86122
86123
86124
86125
86126
86127
86128
86129
86130
86131
86132
86133
86134
86135
86136
86137
86138
86139
86140
86141
86142
86143
86144
86145
86146
86147
86148
86149
86150
86151
86152
86153
86154
86155
86156
86157
86158
86159
86160
86161
86162
86163
86164
86165
86166
86167
86168
86169
86170
86171
86172
86173
86174
86175
86176
86177
86178
86179
86180
86181
86182
86183
86184

86185
86186
86187
86188
86189
86190
86191
      testcase( i==27 ); /* TK_EXCEPT */
      testcase( i==28 ); /* TK_TRIGGER */
      testcase( i==29 ); /* TK_RAISE */
      testcase( i==30 ); /* TK_EXCLUSIVE */
      testcase( i==31 ); /* TK_EXISTS */
      testcase( i==32 ); /* TK_SAVEPOINT */
      testcase( i==33 ); /* TK_INTO */
      testcase( i==34 ); /* TK_OFFSET */
      testcase( i==35 ); /* TK_OF */
      testcase( i==36 ); /* TK_SET */
      testcase( i==37 ); /* TK_TEMP */
      testcase( i==38 ); /* TK_TEMP */
      testcase( i==39 ); /* TK_OR */
      testcase( i==40 ); /* TK_UNIQUE */
      testcase( i==41 ); /* TK_QUERY */
      testcase( i==42 ); /* TK_BEGIN */
      testcase( i==43 ); /* TK_JOIN_KW */
      testcase( i==44 ); /* TK_REFERENCES */
      testcase( i==45 ); /* TK_BETWEEN */
      testcase( i==46 ); /* TK_NOTNULL */
      testcase( i==47 ); /* TK_NOT */
      testcase( i==48 ); /* TK_NULL */
      testcase( i==49 ); /* TK_LIMIT */
      testcase( i==50 ); /* TK_CASCADE */
      testcase( i==51 ); /* TK_ASC */
      testcase( i==52 ); /* TK_DELETE */
      testcase( i==53 ); /* TK_CASE */
      testcase( i==54 ); /* TK_COLLATE */
      testcase( i==55 ); /* TK_CREATE */
      testcase( i==56 ); /* TK_CTIME_KW */
      testcase( i==57 ); /* TK_GROUP */
      testcase( i==58 ); /* TK_UPDATE */
      testcase( i==59 ); /* TK_IMMEDIATE */
      testcase( i==60 ); /* TK_JOIN */
      testcase( i==61 ); /* TK_INSERT */
      testcase( i==62 ); /* TK_MATCH */
      testcase( i==63 ); /* TK_HAVING */
      testcase( i==64 ); /* TK_LIKE_KW */
      testcase( i==65 ); /* TK_BY */
      testcase( i==66 ); /* TK_PLAN */
      testcase( i==67 ); /* TK_AND */
      testcase( i==68 ); /* TK_DEFAULT */
      testcase( i==69 ); /* TK_RELEASE */
      testcase( i==70 ); /* TK_AS */
      testcase( i==71 ); /* TK_VALUES */
      testcase( i==72 ); /* TK_WHEN */
      testcase( i==73 ); /* TK_WHERE */
      testcase( i==74 ); /* TK_RESTRICT */
      testcase( i==75 ); /* TK_ABORT */
      testcase( i==76 ); /* TK_AFTER */
      testcase( i==77 ); /* TK_JOIN_KW */
      testcase( i==78 ); /* TK_CAST */
      testcase( i==79 ); /* TK_COMMIT */
      testcase( i==80 ); /* TK_JOIN_KW */
      testcase( i==81 ); /* TK_CTIME_KW */
      testcase( i==82 ); /* TK_CTIME_KW */
      testcase( i==83 ); /* TK_PRIMARY */
      testcase( i==84 ); /* TK_DEFERRED */
      testcase( i==85 ); /* TK_DISTINCT */
      testcase( i==86 ); /* TK_IS */
      testcase( i==87 ); /* TK_DROP */
      testcase( i==88 ); /* TK_FAIL */
      testcase( i==89 ); /* TK_FROM */
      testcase( i==90 ); /* TK_JOIN_KW */
      testcase( i==91 ); /* TK_IF */
      testcase( i==92 ); /* TK_INSTEAD */
      testcase( i==93 ); /* TK_ISNULL */
      testcase( i==94 ); /* TK_ORDER */
      testcase( i==95 ); /* TK_ROLLBACK */
      testcase( i==96 ); /* TK_JOIN_KW */
      testcase( i==97 ); /* TK_ROW */
      testcase( i==98 ); /* TK_UNION */
      testcase( i==99 ); /* TK_USING */
      testcase( i==100 ); /* TK_VIEW */
      testcase( i==101 ); /* TK_INITIALLY */
      testcase( i==102 ); /* TK_ALL */

      return aCode[i];
    }
  }
  return TK_ID;
}
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  return keywordCode((char*)z, n);







|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>







87008
87009
87010
87011
87012
87013
87014
87015
87016
87017
87018
87019
87020
87021
87022
87023
87024
87025
87026
87027
87028
87029
87030
87031
87032
87033
87034
87035
87036
87037
87038
87039
87040
87041
87042
87043
87044
87045
87046
87047
87048
87049
87050
87051
87052
87053
87054
87055
87056
87057
87058
87059
87060
87061
87062
87063
87064
87065
87066
87067
87068
87069
87070
87071
87072
87073
87074
87075
87076
87077
87078
87079
87080
87081
87082
87083
87084
87085
87086
87087
87088
87089
87090
87091
      testcase( i==27 ); /* TK_EXCEPT */
      testcase( i==28 ); /* TK_TRIGGER */
      testcase( i==29 ); /* TK_RAISE */
      testcase( i==30 ); /* TK_EXCLUSIVE */
      testcase( i==31 ); /* TK_EXISTS */
      testcase( i==32 ); /* TK_SAVEPOINT */
      testcase( i==33 ); /* TK_INTO */
      testcase( i==34 ); /* TK_TO */
      testcase( i==35 ); /* TK_OFFSET */
      testcase( i==36 ); /* TK_OF */
      testcase( i==37 ); /* TK_SET */
      testcase( i==38 ); /* TK_TEMP */
      testcase( i==39 ); /* TK_TEMP */
      testcase( i==40 ); /* TK_OR */
      testcase( i==41 ); /* TK_UNIQUE */
      testcase( i==42 ); /* TK_QUERY */
      testcase( i==43 ); /* TK_BEGIN */
      testcase( i==44 ); /* TK_JOIN_KW */
      testcase( i==45 ); /* TK_REFERENCES */
      testcase( i==46 ); /* TK_BETWEEN */
      testcase( i==47 ); /* TK_NOTNULL */
      testcase( i==48 ); /* TK_NOT */
      testcase( i==49 ); /* TK_NULL */
      testcase( i==50 ); /* TK_LIMIT */
      testcase( i==51 ); /* TK_CASCADE */
      testcase( i==52 ); /* TK_ASC */
      testcase( i==53 ); /* TK_DELETE */
      testcase( i==54 ); /* TK_CASE */
      testcase( i==55 ); /* TK_COLLATE */
      testcase( i==56 ); /* TK_CREATE */
      testcase( i==57 ); /* TK_CTIME_KW */
      testcase( i==58 ); /* TK_GROUP */
      testcase( i==59 ); /* TK_UPDATE */
      testcase( i==60 ); /* TK_IMMEDIATE */
      testcase( i==61 ); /* TK_JOIN */
      testcase( i==62 ); /* TK_INSERT */
      testcase( i==63 ); /* TK_MATCH */
      testcase( i==64 ); /* TK_HAVING */
      testcase( i==65 ); /* TK_LIKE_KW */
      testcase( i==66 ); /* TK_BY */
      testcase( i==67 ); /* TK_PLAN */
      testcase( i==68 ); /* TK_AND */
      testcase( i==69 ); /* TK_DEFAULT */
      testcase( i==70 ); /* TK_RELEASE */
      testcase( i==71 ); /* TK_AS */
      testcase( i==72 ); /* TK_VALUES */
      testcase( i==73 ); /* TK_WHEN */
      testcase( i==74 ); /* TK_WHERE */
      testcase( i==75 ); /* TK_RESTRICT */
      testcase( i==76 ); /* TK_ABORT */
      testcase( i==77 ); /* TK_AFTER */
      testcase( i==78 ); /* TK_JOIN_KW */
      testcase( i==79 ); /* TK_CAST */
      testcase( i==80 ); /* TK_COMMIT */
      testcase( i==81 ); /* TK_JOIN_KW */
      testcase( i==82 ); /* TK_CTIME_KW */
      testcase( i==83 ); /* TK_CTIME_KW */
      testcase( i==84 ); /* TK_PRIMARY */
      testcase( i==85 ); /* TK_DEFERRED */
      testcase( i==86 ); /* TK_DISTINCT */
      testcase( i==87 ); /* TK_IS */
      testcase( i==88 ); /* TK_DROP */
      testcase( i==89 ); /* TK_FAIL */
      testcase( i==90 ); /* TK_FROM */
      testcase( i==91 ); /* TK_JOIN_KW */
      testcase( i==92 ); /* TK_IF */
      testcase( i==93 ); /* TK_INSTEAD */
      testcase( i==94 ); /* TK_ISNULL */
      testcase( i==95 ); /* TK_ORDER */
      testcase( i==96 ); /* TK_ROLLBACK */
      testcase( i==97 ); /* TK_JOIN_KW */
      testcase( i==98 ); /* TK_ROW */
      testcase( i==99 ); /* TK_UNION */
      testcase( i==100 ); /* TK_USING */
      testcase( i==101 ); /* TK_VIEW */
      testcase( i==102 ); /* TK_INITIALLY */
      testcase( i==103 ); /* TK_ALL */
      return aCode[i];
    }
  }
  return TK_ID;
}
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  return keywordCode((char*)z, n);
86247
86248
86249
86250
86251
86252
86253
86254
86255
86256
86257
86258
86259
86260
86261
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; isspace(z[i]); i++){}
      *tokenType = TK_SPACE;
      return i;
    }
    case '-': {
      if( z[1]=='-' ){
        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
        *tokenType = TK_SPACE;







|







87147
87148
87149
87150
87151
87152
87153
87154
87155
87156
87157
87158
87159
87160
87161
** Return the length of the token that begins at z[0]. 
** Store the token type in *tokenType before returning.
*/
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  int i, c;
  switch( *z ){
    case ' ': case '\t': case '\n': case '\f': case '\r': {
      for(i=1; sqlite3Isspace(z[i]); i++){}
      *tokenType = TK_SPACE;
      return i;
    }
    case '-': {
      if( z[1]=='-' ){
        for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
        *tokenType = TK_SPACE;
86381
86382
86383
86384
86385
86386
86387
86388
86389
86390
86391
86392
86393
86394
86395
86396
86397
86398
86399
86400
86401
86402
86403
86404
86405
86406
86407
86408
86409
86410
86411
86412
86413
86414
86415
86416
86417
86418
86419
86420
86421
86422
86423
86424
86425
86426
86427
86428
86429
86430
86431
86432
86433
86434
86435
86436
86437
86438
86439
86440
86441
      }else{
        *tokenType = TK_ILLEGAL;
        return i;
      }
    }
    case '.': {
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( !isdigit(z[1]) )
#endif
      {
        *tokenType = TK_DOT;
        return 1;
      }
      /* If the next character is a digit, this is a floating point
      ** number that begins with ".".  Fall thru into the next case */
    }
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {
      *tokenType = TK_INTEGER;
      for(i=0; isdigit(z[i]); i++){}
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( z[i]=='.' ){
        i++;
        while( isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
      if( (z[i]=='e' || z[i]=='E') &&
           ( isdigit(z[i+1]) 
            || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
           )
      ){
        i += 2;
        while( isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
#endif
      while( IdChar(z[i]) ){
        *tokenType = TK_ILLEGAL;
        i++;
      }
      return i;
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
      return i;
    }
    case '?': {
      *tokenType = TK_VARIABLE;
      for(i=1; isdigit(z[i]); i++){}
      return i;
    }
    case '#': {
      for(i=1; isdigit(z[i]); i++){}
      if( i>1 ){
        /* Parameters of the form #NNN (where NNN is a number) are used
        ** internally by sqlite3NestedParse.  */
        *tokenType = TK_REGISTER;
        return i;
      }
      /* Fall through into the next case if the '#' is not followed by







|











|



|



|
|



|
















|



|







87281
87282
87283
87284
87285
87286
87287
87288
87289
87290
87291
87292
87293
87294
87295
87296
87297
87298
87299
87300
87301
87302
87303
87304
87305
87306
87307
87308
87309
87310
87311
87312
87313
87314
87315
87316
87317
87318
87319
87320
87321
87322
87323
87324
87325
87326
87327
87328
87329
87330
87331
87332
87333
87334
87335
87336
87337
87338
87339
87340
87341
      }else{
        *tokenType = TK_ILLEGAL;
        return i;
      }
    }
    case '.': {
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( !sqlite3Isdigit(z[1]) )
#endif
      {
        *tokenType = TK_DOT;
        return 1;
      }
      /* If the next character is a digit, this is a floating point
      ** number that begins with ".".  Fall thru into the next case */
    }
    case '0': case '1': case '2': case '3': case '4':
    case '5': case '6': case '7': case '8': case '9': {
      *tokenType = TK_INTEGER;
      for(i=0; sqlite3Isdigit(z[i]); i++){}
#ifndef SQLITE_OMIT_FLOATING_POINT
      if( z[i]=='.' ){
        i++;
        while( sqlite3Isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
      if( (z[i]=='e' || z[i]=='E') &&
           ( sqlite3Isdigit(z[i+1]) 
            || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
           )
      ){
        i += 2;
        while( sqlite3Isdigit(z[i]) ){ i++; }
        *tokenType = TK_FLOAT;
      }
#endif
      while( IdChar(z[i]) ){
        *tokenType = TK_ILLEGAL;
        i++;
      }
      return i;
    }
    case '[': {
      for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
      *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
      return i;
    }
    case '?': {
      *tokenType = TK_VARIABLE;
      for(i=1; sqlite3Isdigit(z[i]); i++){}
      return i;
    }
    case '#': {
      for(i=1; sqlite3Isdigit(z[i]); i++){}
      if( i>1 ){
        /* Parameters of the form #NNN (where NNN is a number) are used
        ** internally by sqlite3NestedParse.  */
        *tokenType = TK_REGISTER;
        return i;
      }
      /* Fall through into the next case if the '#' is not followed by
86451
86452
86453
86454
86455
86456
86457
86458
86459
86460
86461
86462
86463
86464
86465
      for(i=1; (c=z[i])!=0; i++){
        if( IdChar(c) ){
          n++;
#ifndef SQLITE_OMIT_TCL_VARIABLE
        }else if( c=='(' && n>0 ){
          do{
            i++;
          }while( (c=z[i])!=0 && !isspace(c) && c!=')' );
          if( c==')' ){
            i++;
          }else{
            *tokenType = TK_ILLEGAL;
          }
          break;
        }else if( c==':' && z[i+1]==':' ){







|







87351
87352
87353
87354
87355
87356
87357
87358
87359
87360
87361
87362
87363
87364
87365
      for(i=1; (c=z[i])!=0; i++){
        if( IdChar(c) ){
          n++;
#ifndef SQLITE_OMIT_TCL_VARIABLE
        }else if( c=='(' && n>0 ){
          do{
            i++;
          }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
          if( c==')' ){
            i++;
          }else{
            *tokenType = TK_ILLEGAL;
          }
          break;
        }else if( c==':' && z[i+1]==':' ){
86473
86474
86475
86476
86477
86478
86479
86480
86481
86482
86483
86484
86485
86486
86487
      return i;
    }
#ifndef SQLITE_OMIT_BLOB_LITERAL
    case 'x': case 'X': {
      if( z[1]=='\'' ){
        *tokenType = TK_BLOB;
        for(i=2; (c=z[i])!=0 && c!='\''; i++){
          if( !isxdigit(c) ){
            *tokenType = TK_ILLEGAL;
          }
        }
        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
        if( c ) i++;
        return i;
      }







|







87373
87374
87375
87376
87377
87378
87379
87380
87381
87382
87383
87384
87385
87386
87387
      return i;
    }
#ifndef SQLITE_OMIT_BLOB_LITERAL
    case 'x': case 'X': {
      if( z[1]=='\'' ){
        *tokenType = TK_BLOB;
        for(i=2; (c=z[i])!=0 && c!='\''; i++){
          if( !sqlite3Isxdigit(c) ){
            *tokenType = TK_ILLEGAL;
          }
        }
        if( i%2 || !c ) *tokenType = TK_ILLEGAL;
        if( c ) i++;
        return i;
      }
86935
86936
86937
86938
86939
86940
86941
86942
86943
86944
86945
86946
86947
86948
86949
**
*************************************************************************
** 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: main.c,v 1.521 2009/01/10 16:15:22 drh Exp $
*/

#ifdef SQLITE_ENABLE_FTS3
/************** Include fts3.h in the middle of main.c ***********************/
/************** Begin file fts3.h ********************************************/
/*
** 2006 Oct 10







|







87835
87836
87837
87838
87839
87840
87841
87842
87843
87844
87845
87846
87847
87848
87849
**
*************************************************************************
** 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: main.c,v 1.524 2009/02/03 15:50:34 drh Exp $
*/

#ifdef SQLITE_ENABLE_FTS3
/************** Include fts3.h in the middle of main.c ***********************/
/************** Begin file fts3.h ********************************************/
/*
** 2006 Oct 10
87394
87395
87396
87397
87398
87399
87400










87401
87402



87403
87404
87405
87406
87407
87408
87409
87410
87411
87412
87413
87414
87415
87416
87417
87418
87419
87420
87421

87422
87423
87424
87425
87426
87427
87428
87429

87430
87431
87432

87433
87434
87435
87436
87437
87438
87439
** the lookaside memory.
*/
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  void *pStart;
  if( db->lookaside.nOut ){
    return SQLITE_BUSY;
  }










  if( sz<0 ) sz = 0;
  if( cnt<0 ) cnt = 0;



  if( pBuf==0 ){
    sz = (sz + 7)&~7;
    sqlite3BeginBenignMalloc();
    pStart = sqlite3Malloc( sz*cnt );
    sqlite3EndBenignMalloc();
  }else{
    sz = sz&~7;
    pStart = pBuf;
  }
  if( db->lookaside.bMalloced ){
    sqlite3_free(db->lookaside.pStart);
  }
  db->lookaside.pStart = pStart;
  db->lookaside.pFree = 0;
  db->lookaside.sz = (u16)sz;
  db->lookaside.bMalloced = pBuf==0 ?1:0;
  if( pStart ){
    int i;
    LookasideSlot *p;

    p = (LookasideSlot*)pStart;
    for(i=cnt-1; i>=0; i--){
      p->pNext = db->lookaside.pFree;
      db->lookaside.pFree = p;
      p = (LookasideSlot*)&((u8*)p)[sz];
    }
    db->lookaside.pEnd = p;
    db->lookaside.bEnabled = 1;

  }else{
    db->lookaside.pEnd = 0;
    db->lookaside.bEnabled = 0;

  }
  return SQLITE_OK;
}

/*
** Return the mutex associated with a database connection.
*/







>
>
>
>
>
>
>
>
>
>
|

>
>
>
|








<
<
<



<



>








>



>







88294
88295
88296
88297
88298
88299
88300
88301
88302
88303
88304
88305
88306
88307
88308
88309
88310
88311
88312
88313
88314
88315
88316
88317
88318
88319
88320
88321
88322
88323
88324



88325
88326
88327

88328
88329
88330
88331
88332
88333
88334
88335
88336
88337
88338
88339
88340
88341
88342
88343
88344
88345
88346
88347
88348
88349
88350
88351
** the lookaside memory.
*/
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  void *pStart;
  if( db->lookaside.nOut ){
    return SQLITE_BUSY;
  }
  /* Free any existing lookaside buffer for this handle before
  ** allocating a new one so we don't have to have space for 
  ** both at the same time.
  */
  if( db->lookaside.bMalloced ){
    sqlite3_free(db->lookaside.pStart);
  }
  /* The size of a lookaside slot needs to be larger than a pointer
  ** to be useful.
  */
  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  if( cnt<0 ) cnt = 0;
  if( sz==0 || cnt==0 ){
    sz = 0;
    pStart = 0;
  }else if( pBuf==0 ){
    sz = (sz + 7)&~7;
    sqlite3BeginBenignMalloc();
    pStart = sqlite3Malloc( sz*cnt );
    sqlite3EndBenignMalloc();
  }else{
    sz = sz&~7;
    pStart = pBuf;
  }



  db->lookaside.pStart = pStart;
  db->lookaside.pFree = 0;
  db->lookaside.sz = (u16)sz;

  if( pStart ){
    int i;
    LookasideSlot *p;
    assert( sz > sizeof(LookasideSlot*) );
    p = (LookasideSlot*)pStart;
    for(i=cnt-1; i>=0; i--){
      p->pNext = db->lookaside.pFree;
      db->lookaside.pFree = p;
      p = (LookasideSlot*)&((u8*)p)[sz];
    }
    db->lookaside.pEnd = p;
    db->lookaside.bEnabled = 1;
    db->lookaside.bMalloced = pBuf==0 ?1:0;
  }else{
    db->lookaside.pEnd = 0;
    db->lookaside.bEnabled = 0;
    db->lookaside.bMalloced = 0;
  }
  return SQLITE_OK;
}

/*
** Return the mutex associated with a database connection.
*/
89555
89556
89557
89558
89559
89560
89561
89562



89563
89564
89565
89566
89567
89568
89569
  ** 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







|
>
>
>







90467
90468
90469
90470
90471
90472
90473
90474
90475
90476
90477
90478
90479
90480
90481
90482
90483
90484
  ** the end of the buffer has been reached, or an SQLite error code.
  **
  ** *ppToken should be set to point at a buffer containing the 
  ** normalized version of the token (i.e. after any case-folding and/or
  ** stemming has been performed). *pnBytes should be set to the length
  ** of this buffer in bytes. The input text that generated the token is
  ** identified by the byte offsets returned in *piStartOffset and
  ** *piEndOffset. *piStartOffset should be set to the index of the first
  ** byte of the token in the input buffer. *piEndOffset should be set
  ** to the index of the first byte just past the end of the token in
  ** the input buffer.
  **
  ** The buffer *ppToken is set to point at is managed by the tokenizer
  ** implementation. It is only required to be valid until the next call
  ** to xNext() or xClose(). 
  */
  /* TODO(shess) current implementation requires pInput to be
  ** nul-terminated.  This should either be fixed, or pInput/nBytes
96664
96665
96666
96667
96668
96669
96670
96671
96672

96673
96674
96675
96676
96677
96678
96679
          pRet->pPhrase->aToken[0].isPrefix = 1;
          iEnd++;
        }
        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
          pRet->pPhrase->isNot = 1;
        }
      }
    }
    nConsumed = iEnd;


    pModule->xClose(pCursor);
  }
  
  *pnConsumed = nConsumed;
  *ppExpr = pRet;
  return rc;







<
|
>







97579
97580
97581
97582
97583
97584
97585

97586
97587
97588
97589
97590
97591
97592
97593
97594
          pRet->pPhrase->aToken[0].isPrefix = 1;
          iEnd++;
        }
        if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
          pRet->pPhrase->isNot = 1;
        }
      }

      nConsumed = iEnd;
    }

    pModule->xClose(pCursor);
  }
  
  *pnConsumed = nConsumed;
  *ppExpr = pRet;
  return rc;
Changes to src/sqlite3.h.
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: sqlite.h.in,v 1.421 2008/12/30 06:24:58 danielk1977 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++.







|







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: sqlite.h.in,v 1.422 2009/01/23 16:45:01 danielk1977 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++.
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
**                SQLite is holding pinned pages that can be unpinned
**                by writing their contents to the database file (a
**                relatively expensive operation). In this situation the
**                cache implementation has two choices: it can return NULL,
**                in which case SQLite will attempt to unpin one or more 
**                pages before re-requesting the same page, or it can
**                allocate a new page and return a pointer to it. If a new
**                page is allocated, then it must be completely zeroed before 
**                it is returned.
**   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
**                pinned pages associated with the specific cache passed
**                as the first argument to xFetch() that can be unpinned. The
**                cache implementation should attempt to allocate a new
**                cache entry and return a pointer to it. Again, the new
**                page should be zeroed before it is returned. If the xFetch()
**                method returns NULL when createFlag==2, SQLite assumes that
**                a memory allocation failed and returns SQLITE_NOMEM to the
**                user.
** </table>
**
** xUnpin() is called by SQLite with a pointer to a currently pinned page
** as its second argument. If the third parameter, discard, is non-zero,
** then the page should be evicted from the cache. In this case SQLite 
** assumes that the next time the page is retrieved from the cache using
** the xFetch() method, it will be zeroed. If the discard parameter is







|
|




|
|
|
|
|







6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
**                SQLite is holding pinned pages that can be unpinned
**                by writing their contents to the database file (a
**                relatively expensive operation). In this situation the
**                cache implementation has two choices: it can return NULL,
**                in which case SQLite will attempt to unpin one or more 
**                pages before re-requesting the same page, or it can
**                allocate a new page and return a pointer to it. If a new
**                page is allocated, then the first sizeof(void*) bytes of
**                it (at least) must be zeroed before it is returned.
**   <tr><td>2<td>If createFlag is set to 2, then SQLite is not holding any
**                pinned pages associated with the specific cache passed
**                as the first argument to xFetch() that can be unpinned. The
**                cache implementation should attempt to allocate a new
**                cache entry and return a pointer to it. Again, the first
**                sizeof(void*) bytes of the page should be zeroed before 
**                it is returned. If the xFetch() method returns NULL when 
**                createFlag==2, SQLite assumes that a memory allocation 
**                failed and returns SQLITE_NOMEM to the user.
** </table>
**
** xUnpin() is called by SQLite with a pointer to a currently pinned page
** as its second argument. If the third parameter, discard, is non-zero,
** then the page should be evicted from the cache. In this case SQLite 
** assumes that the next time the page is retrieved from the cache using
** the xFetch() method, it will be zeroed. If the discard parameter is