xref: /sqlite-3.40.0/src/vacuum.c (revision 3b328522)
1 /*
2 ** 2003 April 6
3 **
4 ** The author disclaims copyright to this source code.  In place of
5 ** a legal notice, here is a blessing:
6 **
7 **    May you do good and not evil.
8 **    May you find forgiveness for yourself and forgive others.
9 **    May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains code used to implement the VACUUM command.
13 **
14 ** Most of the code in this file may be omitted by defining the
15 ** SQLITE_OMIT_VACUUM macro.
16 */
17 #include "sqliteInt.h"
18 #include "vdbeInt.h"
19 
20 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
21 
22 /*
23 ** Execute zSql on database db.
24 **
25 ** If zSql returns rows, then each row will have exactly one
26 ** column.  (This will only happen if zSql begins with "SELECT".)
27 ** Take each row of result and call execSql() again recursively.
28 **
29 ** The execSqlF() routine does the same thing, except it accepts
30 ** a format string as its third argument
31 */
32 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
33   sqlite3_stmt *pStmt;
34   int rc;
35 
36   /* printf("SQL: [%s]\n", zSql); fflush(stdout); */
37   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
38   if( rc!=SQLITE_OK ) return rc;
39   while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
40     const char *zSubSql = (const char*)sqlite3_column_text(pStmt,0);
41     assert( sqlite3_strnicmp(zSql,"SELECT",6)==0 );
42     if( zSubSql ){
43       assert( zSubSql[0]!='S' );
44       rc = execSql(db, pzErrMsg, zSubSql);
45       if( rc!=SQLITE_OK ) break;
46     }
47   }
48   assert( rc!=SQLITE_ROW );
49   if( rc==SQLITE_DONE ) rc = SQLITE_OK;
50   if( rc ){
51     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
52   }
53   (void)sqlite3_finalize(pStmt);
54   return rc;
55 }
56 static int execSqlF(sqlite3 *db, char **pzErrMsg, const char *zSql, ...){
57   char *z;
58   va_list ap;
59   int rc;
60   va_start(ap, zSql);
61   z = sqlite3VMPrintf(db, zSql, ap);
62   va_end(ap);
63   if( z==0 ) return SQLITE_NOMEM;
64   rc = execSql(db, pzErrMsg, z);
65   sqlite3DbFree(db, z);
66   return rc;
67 }
68 
69 /*
70 ** The VACUUM command is used to clean up the database,
71 ** collapse free space, etc.  It is modelled after the VACUUM command
72 ** in PostgreSQL.  The VACUUM command works as follows:
73 **
74 **   (1)  Create a new transient database file
75 **   (2)  Copy all content from the database being vacuumed into
76 **        the new transient database file
77 **   (3)  Copy content from the transient database back into the
78 **        original database.
79 **
80 ** The transient database requires temporary disk space approximately
81 ** equal to the size of the original database.  The copy operation of
82 ** step (3) requires additional temporary disk space approximately equal
83 ** to the size of the original database for the rollback journal.
84 ** Hence, temporary disk space that is approximately 2x the size of the
85 ** original database is required.  Every page of the database is written
86 ** approximately 3 times:  Once for step (2) and twice for step (3).
87 ** Two writes per page are required in step (3) because the original
88 ** database content must be written into the rollback journal prior to
89 ** overwriting the database with the vacuumed content.
90 **
91 ** Only 1x temporary space and only 1x writes would be required if
92 ** the copy of step (3) were replaced by deleting the original database
93 ** and renaming the transient database as the original.  But that will
94 ** not work if other processes are attached to the original database.
95 ** And a power loss in between deleting the original and renaming the
96 ** transient would cause the database file to appear to be deleted
97 ** following reboot.
98 */
99 void sqlite3Vacuum(Parse *pParse, Token *pNm){
100   Vdbe *v = sqlite3GetVdbe(pParse);
101   int iDb = 0;
102   if( v==0 ) return;
103   if( pNm ){
104 #ifndef SQLITE_BUG_COMPATIBLE_20160819
105     /* Default behavior:  Report an error if the argument to VACUUM is
106     ** not recognized */
107     iDb = sqlite3TwoPartName(pParse, pNm, pNm, &pNm);
108     if( iDb<0 ) return;
109 #else
110     /* When SQLITE_BUG_COMPATIBLE_20160819 is defined, unrecognized arguments
111     ** to VACUUM are silently ignored.  This is a back-out of a bug fix that
112     ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
113     ** The buggy behavior is required for binary compatibility with some
114     ** legacy applications. */
115     iDb = sqlite3FindDb(pParse->db, pNm);
116     if( iDb<0 ) iDb = 0;
117 #endif
118   }
119   if( iDb!=1 ){
120     sqlite3VdbeAddOp1(v, OP_Vacuum, iDb);
121     sqlite3VdbeUsesBtree(v, iDb);
122   }
123   return;
124 }
125 
126 /*
127 ** This routine implements the OP_Vacuum opcode of the VDBE.
128 */
129 int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db, int iDb){
130   int rc = SQLITE_OK;     /* Return code from service routines */
131   Btree *pMain;           /* The database being vacuumed */
132   Btree *pTemp;           /* The temporary database we vacuum into */
133   int saved_flags;        /* Saved value of the db->flags */
134   int saved_nChange;      /* Saved value of db->nChange */
135   int saved_nTotalChange; /* Saved value of db->nTotalChange */
136   u8 saved_mTrace;        /* Saved trace settings */
137   Db *pDb = 0;            /* Database to detach at end of vacuum */
138   int isMemDb;            /* True if vacuuming a :memory: database */
139   int nRes;               /* Bytes of reserved space at the end of each page */
140   int nDb;                /* Number of attached databases */
141   const char *zDbMain;    /* Schema name of database to vacuum */
142 
143   if( !db->autoCommit ){
144     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
145     return SQLITE_ERROR;
146   }
147   if( db->nVdbeActive>1 ){
148     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
149     return SQLITE_ERROR;
150   }
151 
152   /* Save the current value of the database flags so that it can be
153   ** restored before returning. Then set the writable-schema flag, and
154   ** disable CHECK and foreign key constraints.  */
155   saved_flags = db->flags;
156   saved_nChange = db->nChange;
157   saved_nTotalChange = db->nTotalChange;
158   saved_mTrace = db->mTrace;
159   db->flags |= (SQLITE_WriteSchema | SQLITE_IgnoreChecks
160                  | SQLITE_PreferBuiltin | SQLITE_Vacuum);
161   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder | SQLITE_CountRows);
162   db->mTrace = 0;
163 
164   zDbMain = db->aDb[iDb].zDbSName;
165   pMain = db->aDb[iDb].pBt;
166   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
167 
168   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
169   ** can be set to 'off' for this file, as it is not recovered if a crash
170   ** occurs anyway. The integrity of the database is maintained by a
171   ** (possibly synchronous) transaction opened on the main database before
172   ** sqlite3BtreeCopyFile() is called.
173   **
174   ** An optimisation would be to use a non-journaled pager.
175   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
176   ** that actually made the VACUUM run slower.  Very little journalling
177   ** actually occurs when doing a vacuum since the vacuum_db is initially
178   ** empty.  Only the journal header is written.  Apparently it takes more
179   ** time to parse and run the PRAGMA to turn journalling off than it does
180   ** to write the journal header file.
181   */
182   nDb = db->nDb;
183   rc = execSql(db, pzErrMsg, "ATTACH''AS vacuum_db");
184   if( rc!=SQLITE_OK ) goto end_of_vacuum;
185   assert( (db->nDb-1)==nDb );
186   pDb = &db->aDb[nDb];
187   assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
188   pTemp = pDb->pBt;
189 
190   /* The call to execSql() to attach the temp database has left the file
191   ** locked (as there was more than one active statement when the transaction
192   ** to read the schema was concluded. Unlock it here so that this doesn't
193   ** cause problems for the call to BtreeSetPageSize() below.  */
194   sqlite3BtreeCommit(pTemp);
195 
196   nRes = sqlite3BtreeGetOptimalReserve(pMain);
197 
198   /* A VACUUM cannot change the pagesize of an encrypted database. */
199 #ifdef SQLITE_HAS_CODEC
200   if( db->nextPagesize ){
201     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
202     int nKey;
203     char *zKey;
204     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
205     if( nKey ) db->nextPagesize = 0;
206   }
207 #endif
208 
209   sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
210   sqlite3BtreeSetSpillSize(pTemp, sqlite3BtreeSetSpillSize(pMain,0));
211   sqlite3BtreeSetPagerFlags(pTemp, PAGER_SYNCHRONOUS_OFF|PAGER_CACHESPILL);
212 
213   /* Begin a transaction and take an exclusive lock on the main database
214   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
215   ** to ensure that we do not try to change the page-size on a WAL database.
216   */
217   rc = execSql(db, pzErrMsg, "BEGIN");
218   if( rc!=SQLITE_OK ) goto end_of_vacuum;
219   rc = sqlite3BtreeBeginTrans(pMain, 2);
220   if( rc!=SQLITE_OK ) goto end_of_vacuum;
221 
222   /* Do not attempt to change the page size for a WAL database */
223   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
224                                                ==PAGER_JOURNALMODE_WAL ){
225     db->nextPagesize = 0;
226   }
227 
228   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
229    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
230    || NEVER(db->mallocFailed)
231   ){
232     rc = SQLITE_NOMEM_BKPT;
233     goto end_of_vacuum;
234   }
235 
236 #ifndef SQLITE_OMIT_AUTOVACUUM
237   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
238                                            sqlite3BtreeGetAutoVacuum(pMain));
239 #endif
240 
241   /* Query the schema of the main database. Create a mirror schema
242   ** in the temporary database.
243   */
244   db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
245   rc = execSqlF(db, pzErrMsg,
246       "SELECT sql FROM \"%w\".sqlite_master"
247       " WHERE type='table'AND name<>'sqlite_sequence'"
248       " AND coalesce(rootpage,1)>0",
249       zDbMain
250   );
251   if( rc!=SQLITE_OK ) goto end_of_vacuum;
252   rc = execSqlF(db, pzErrMsg,
253       "SELECT sql FROM \"%w\".sqlite_master"
254       " WHERE type='index' AND length(sql)>10",
255       zDbMain
256   );
257   if( rc!=SQLITE_OK ) goto end_of_vacuum;
258   db->init.iDb = 0;
259 
260   /* Loop through the tables in the main database. For each, do
261   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
262   ** the contents to the temporary database.
263   */
264   rc = execSqlF(db, pzErrMsg,
265       "SELECT'INSERT INTO vacuum_db.'||quote(name)"
266       "||' SELECT*FROM\"%w\".'||quote(name)"
267       "FROM vacuum_db.sqlite_master "
268       "WHERE type='table'AND coalesce(rootpage,1)>0",
269       zDbMain
270   );
271   assert( (db->flags & SQLITE_Vacuum)!=0 );
272   db->flags &= ~SQLITE_Vacuum;
273   if( rc!=SQLITE_OK ) goto end_of_vacuum;
274 
275   /* Copy the triggers, views, and virtual tables from the main database
276   ** over to the temporary database.  None of these objects has any
277   ** associated storage, so all we have to do is copy their entries
278   ** from the SQLITE_MASTER table.
279   */
280   rc = execSqlF(db, pzErrMsg,
281       "INSERT INTO vacuum_db.sqlite_master"
282       " SELECT*FROM \"%w\".sqlite_master"
283       " WHERE type IN('view','trigger')"
284       " OR(type='table'AND rootpage=0)",
285       zDbMain
286   );
287   if( rc ) goto end_of_vacuum;
288 
289   /* At this point, there is a write transaction open on both the
290   ** vacuum database and the main database. Assuming no error occurs,
291   ** both transactions are closed by this block - the main database
292   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
293   ** call to sqlite3BtreeCommit().
294   */
295   {
296     u32 meta;
297     int i;
298 
299     /* This array determines which meta meta values are preserved in the
300     ** vacuum.  Even entries are the meta value number and odd entries
301     ** are an increment to apply to the meta value after the vacuum.
302     ** The increment is used to increase the schema cookie so that other
303     ** connections to the same database will know to reread the schema.
304     */
305     static const unsigned char aCopy[] = {
306        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
307        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
308        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
309        BTREE_USER_VERSION,       0,  /* Preserve the user version */
310        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
311     };
312 
313     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
314     assert( 1==sqlite3BtreeIsInTrans(pMain) );
315 
316     /* Copy Btree meta values */
317     for(i=0; i<ArraySize(aCopy); i+=2){
318       /* GetMeta() and UpdateMeta() cannot fail in this context because
319       ** we already have page 1 loaded into cache and marked dirty. */
320       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
321       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
322       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
323     }
324 
325     rc = sqlite3BtreeCopyFile(pMain, pTemp);
326     if( rc!=SQLITE_OK ) goto end_of_vacuum;
327     rc = sqlite3BtreeCommit(pTemp);
328     if( rc!=SQLITE_OK ) goto end_of_vacuum;
329 #ifndef SQLITE_OMIT_AUTOVACUUM
330     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
331 #endif
332   }
333 
334   assert( rc==SQLITE_OK );
335   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
336 
337 end_of_vacuum:
338   /* Restore the original value of db->flags */
339   db->init.iDb = 0;
340   db->flags = saved_flags;
341   db->nChange = saved_nChange;
342   db->nTotalChange = saved_nTotalChange;
343   db->mTrace = saved_mTrace;
344   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
345 
346   /* Currently there is an SQL level transaction open on the vacuum
347   ** database. No locks are held on any other files (since the main file
348   ** was committed at the btree level). So it safe to end the transaction
349   ** by manually setting the autoCommit flag to true and detaching the
350   ** vacuum database. The vacuum_db journal file is deleted when the pager
351   ** is closed by the DETACH.
352   */
353   db->autoCommit = 1;
354 
355   if( pDb ){
356     sqlite3BtreeClose(pDb->pBt);
357     pDb->pBt = 0;
358     pDb->pSchema = 0;
359   }
360 
361   /* This both clears the schemas and reduces the size of the db->aDb[]
362   ** array. */
363   sqlite3ResetAllSchemasOfConnection(db);
364 
365   return rc;
366 }
367 
368 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
369