persistentstorage/sql/SQLite/vacuum.c
changeset 0 08ec8eefde2f
equal deleted inserted replaced
-1:000000000000 0:08ec8eefde2f
       
     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 ** $Id: vacuum.c,v 1.81 2008/07/08 19:34:07 drh Exp $
       
    18 */
       
    19 #include "sqliteInt.h"
       
    20 #include "vdbeInt.h"
       
    21 
       
    22 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
       
    23 /*
       
    24 ** Execute zSql on database db. Return an error code.
       
    25 */
       
    26 static int execSql(sqlite3 *db, const char *zSql){
       
    27   sqlite3_stmt *pStmt;
       
    28   if( !zSql ){
       
    29     return SQLITE_NOMEM;
       
    30   }
       
    31   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
       
    32     return sqlite3_errcode(db);
       
    33   }
       
    34   while( SQLITE_ROW==sqlite3_step(pStmt) ){}
       
    35   return sqlite3_finalize(pStmt);
       
    36 }
       
    37 
       
    38 /*
       
    39 ** Execute zSql on database db. The statement returns exactly
       
    40 ** one column. Execute this as SQL on the same database.
       
    41 */
       
    42 static int execExecSql(sqlite3 *db, const char *zSql){
       
    43   sqlite3_stmt *pStmt;
       
    44   int rc;
       
    45 
       
    46   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
       
    47   if( rc!=SQLITE_OK ) return rc;
       
    48 
       
    49   while( SQLITE_ROW==sqlite3_step(pStmt) ){
       
    50     rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0));
       
    51     if( rc!=SQLITE_OK ){
       
    52       sqlite3_finalize(pStmt);
       
    53       return rc;
       
    54     }
       
    55   }
       
    56 
       
    57   return sqlite3_finalize(pStmt);
       
    58 }
       
    59 
       
    60 /*
       
    61 ** The non-standard VACUUM command is used to clean up the database,
       
    62 ** collapse free space, etc.  It is modelled after the VACUUM command
       
    63 ** in PostgreSQL.
       
    64 **
       
    65 ** In version 1.0.x of SQLite, the VACUUM command would call
       
    66 ** gdbm_reorganize() on all the database tables.  But beginning
       
    67 ** with 2.0.0, SQLite no longer uses GDBM so this command has
       
    68 ** become a no-op.
       
    69 */
       
    70 void sqlite3Vacuum(Parse *pParse){
       
    71   Vdbe *v = sqlite3GetVdbe(pParse);
       
    72   if( v ){
       
    73     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
       
    74   }
       
    75   return;
       
    76 }
       
    77 
       
    78 /*
       
    79 ** This routine implements the OP_Vacuum opcode of the VDBE.
       
    80 */
       
    81 int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
       
    82   int rc = SQLITE_OK;     /* Return code from service routines */
       
    83   Btree *pMain;           /* The database being vacuumed */
       
    84   Btree *pTemp;           /* The temporary database we vacuum into */
       
    85   char *zSql = 0;         /* SQL statements */
       
    86   int saved_flags;        /* Saved value of the db->flags */
       
    87   int saved_nChange;      /* Saved value of db->nChange */
       
    88   int saved_nTotalChange; /* Saved value of db->nTotalChange */
       
    89   Db *pDb = 0;            /* Database to detach at end of vacuum */
       
    90   int nRes;
       
    91 
       
    92   /* Save the current value of the write-schema flag before setting it. */
       
    93   saved_flags = db->flags;
       
    94   saved_nChange = db->nChange;
       
    95   saved_nTotalChange = db->nTotalChange;
       
    96   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
       
    97 
       
    98   if( !db->autoCommit ){
       
    99     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
       
   100     rc = SQLITE_ERROR;
       
   101     goto end_of_vacuum;
       
   102   }
       
   103   pMain = db->aDb[0].pBt;
       
   104 
       
   105   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
       
   106   ** can be set to 'off' for this file, as it is not recovered if a crash
       
   107   ** occurs anyway. The integrity of the database is maintained by a
       
   108   ** (possibly synchronous) transaction opened on the main database before
       
   109   ** sqlite3BtreeCopyFile() is called.
       
   110   **
       
   111   ** An optimisation would be to use a non-journaled pager.
       
   112   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
       
   113   ** that actually made the VACUUM run slower.  Very little journalling
       
   114   ** actually occurs when doing a vacuum since the vacuum_db is initially
       
   115   ** empty.  Only the journal header is written.  Apparently it takes more
       
   116   ** time to parse and run the PRAGMA to turn journalling off than it does
       
   117   ** to write the journal header file.
       
   118   */
       
   119   zSql = "ATTACH '' AS vacuum_db;";
       
   120   rc = execSql(db, zSql);
       
   121   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   122   pDb = &db->aDb[db->nDb-1];
       
   123   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
       
   124   pTemp = db->aDb[db->nDb-1].pBt;
       
   125 
       
   126   nRes = sqlite3BtreeGetReserve(pMain);
       
   127 
       
   128   /* A VACUUM cannot change the pagesize of an encrypted database. */
       
   129 #ifdef SQLITE_HAS_CODEC
       
   130   if( db->nextPagesize ){
       
   131     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
       
   132     int nKey;
       
   133     char *zKey;
       
   134     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
       
   135     if( nKey ) db->nextPagesize = 0;
       
   136   }
       
   137 #endif
       
   138 
       
   139   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes)
       
   140    || sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes)
       
   141    || db->mallocFailed 
       
   142   ){
       
   143     rc = SQLITE_NOMEM;
       
   144     goto end_of_vacuum;
       
   145   }
       
   146   rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF");
       
   147   if( rc!=SQLITE_OK ){
       
   148     goto end_of_vacuum;
       
   149   }
       
   150 
       
   151 #ifndef SQLITE_OMIT_AUTOVACUUM
       
   152   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
       
   153                                            sqlite3BtreeGetAutoVacuum(pMain));
       
   154 #endif
       
   155 
       
   156   /* Begin a transaction */
       
   157   rc = execSql(db, "BEGIN EXCLUSIVE;");
       
   158   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   159 
       
   160   /* Query the schema of the main database. Create a mirror schema
       
   161   ** in the temporary database.
       
   162   */
       
   163   rc = execExecSql(db, 
       
   164       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
       
   165       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
       
   166       "   AND rootpage>0"
       
   167   );
       
   168   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   169   rc = execExecSql(db, 
       
   170       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
       
   171       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
       
   172   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   173   rc = execExecSql(db, 
       
   174       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
       
   175       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
       
   176   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   177 
       
   178   /* Loop through the tables in the main database. For each, do
       
   179   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy
       
   180   ** the contents to the temporary database.
       
   181   */
       
   182   rc = execExecSql(db, 
       
   183       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
       
   184       "|| ' SELECT * FROM ' || quote(name) || ';'"
       
   185       "FROM sqlite_master "
       
   186       "WHERE type = 'table' AND name!='sqlite_sequence' "
       
   187       "  AND rootpage>0"
       
   188 
       
   189   );
       
   190   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   191 
       
   192   /* Copy over the sequence table
       
   193   */
       
   194   rc = execExecSql(db, 
       
   195       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
       
   196       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
       
   197   );
       
   198   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   199   rc = execExecSql(db, 
       
   200       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
       
   201       "|| ' SELECT * FROM ' || quote(name) || ';' "
       
   202       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
       
   203   );
       
   204   if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   205 
       
   206 
       
   207   /* Copy the triggers, views, and virtual tables from the main database
       
   208   ** over to the temporary database.  None of these objects has any
       
   209   ** associated storage, so all we have to do is copy their entries
       
   210   ** from the SQLITE_MASTER table.
       
   211   */
       
   212   rc = execSql(db,
       
   213       "INSERT INTO vacuum_db.sqlite_master "
       
   214       "  SELECT type, name, tbl_name, rootpage, sql"
       
   215       "    FROM sqlite_master"
       
   216       "   WHERE type='view' OR type='trigger'"
       
   217       "      OR (type='table' AND rootpage=0)"
       
   218   );
       
   219   if( rc ) goto end_of_vacuum;
       
   220 
       
   221   /* At this point, unless the main db was completely empty, there is now a
       
   222   ** transaction open on the vacuum database, but not on the main database.
       
   223   ** Open a btree level transaction on the main database. This allows a
       
   224   ** call to sqlite3BtreeCopyFile(). The main database btree level
       
   225   ** transaction is then committed, so the SQL level never knows it was
       
   226   ** opened for writing. This way, the SQL transaction used to create the
       
   227   ** temporary database never needs to be committed.
       
   228   */
       
   229   if( rc==SQLITE_OK ){
       
   230     u32 meta;
       
   231     int i;
       
   232 
       
   233     /* This array determines which meta meta values are preserved in the
       
   234     ** vacuum.  Even entries are the meta value number and odd entries
       
   235     ** are an increment to apply to the meta value after the vacuum.
       
   236     ** The increment is used to increase the schema cookie so that other
       
   237     ** connections to the same database will know to reread the schema.
       
   238     */
       
   239     static const unsigned char aCopy[] = {
       
   240        1, 1,    /* Add one to the old schema cookie */
       
   241        3, 0,    /* Preserve the default page cache size */
       
   242        5, 0,    /* Preserve the default text encoding */
       
   243        6, 0,    /* Preserve the user version */
       
   244     };
       
   245 
       
   246     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
       
   247     assert( 1==sqlite3BtreeIsInTrans(pMain) );
       
   248 
       
   249     /* Copy Btree meta values */
       
   250     for(i=0; i<sizeof(aCopy)/sizeof(aCopy[0]); i+=2){
       
   251       rc = sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
       
   252       if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   253       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
       
   254       if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   255     }
       
   256 
       
   257     rc = sqlite3BtreeCopyFile(pMain, pTemp);
       
   258     if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   259     rc = sqlite3BtreeCommit(pTemp);
       
   260     if( rc!=SQLITE_OK ) goto end_of_vacuum;
       
   261     rc = sqlite3BtreeCommit(pMain);
       
   262   }
       
   263 
       
   264   if( rc==SQLITE_OK ){
       
   265     rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes);
       
   266   }
       
   267 
       
   268 end_of_vacuum:
       
   269   /* Restore the original value of db->flags */
       
   270   db->flags = saved_flags;
       
   271   db->nChange = saved_nChange;
       
   272   db->nTotalChange = saved_nTotalChange;
       
   273 
       
   274   /* Currently there is an SQL level transaction open on the vacuum
       
   275   ** database. No locks are held on any other files (since the main file
       
   276   ** was committed at the btree level). So it safe to end the transaction
       
   277   ** by manually setting the autoCommit flag to true and detaching the
       
   278   ** vacuum database. The vacuum_db journal file is deleted when the pager
       
   279   ** is closed by the DETACH.
       
   280   */
       
   281   db->autoCommit = 1;
       
   282 
       
   283   if( pDb ){
       
   284     sqlite3BtreeClose(pDb->pBt);
       
   285     pDb->pBt = 0;
       
   286     pDb->pSchema = 0;
       
   287   }
       
   288 
       
   289   sqlite3ResetInternalSchema(db, 0);
       
   290 
       
   291   return rc;
       
   292 }
       
   293 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */