vacuum.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  20. /*
  21. ** Finalize a prepared statement. If there was an error, store the
  22. ** text of the error message in *pzErrMsg. Return the result code.
  23. */
  24. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  25. int rc;
  26. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  27. if( rc ){
  28. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  29. }
  30. return rc;
  31. }
  32. /*
  33. ** Execute zSql on database db. Return an error code.
  34. */
  35. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  36. sqlite3_stmt *pStmt;
  37. VVA_ONLY( int rc; )
  38. if( !zSql ){
  39. return SQLITE_NOMEM;
  40. }
  41. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  42. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  43. return sqlite3_errcode(db);
  44. }
  45. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  46. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  47. return vacuumFinalize(db, pStmt, pzErrMsg);
  48. }
  49. /*
  50. ** Execute zSql on database db. The statement returns exactly
  51. ** one column. Execute this as SQL on the same database.
  52. */
  53. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  54. sqlite3_stmt *pStmt;
  55. int rc;
  56. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  57. if( rc!=SQLITE_OK ) return rc;
  58. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  59. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  60. if( rc!=SQLITE_OK ){
  61. vacuumFinalize(db, pStmt, pzErrMsg);
  62. return rc;
  63. }
  64. }
  65. return vacuumFinalize(db, pStmt, pzErrMsg);
  66. }
  67. /*
  68. ** The VACUUM command is used to clean up the database,
  69. ** collapse free space, etc. It is modelled after the VACUUM command
  70. ** in PostgreSQL. The VACUUM command works as follows:
  71. **
  72. ** (1) Create a new transient database file
  73. ** (2) Copy all content from the database being vacuumed into
  74. ** the new transient database file
  75. ** (3) Copy content from the transient database back into the
  76. ** original database.
  77. **
  78. ** The transient database requires temporary disk space approximately
  79. ** equal to the size of the original database. The copy operation of
  80. ** step (3) requires additional temporary disk space approximately equal
  81. ** to the size of the original database for the rollback journal.
  82. ** Hence, temporary disk space that is approximately 2x the size of the
  83. ** orginal database is required. Every page of the database is written
  84. ** approximately 3 times: Once for step (2) and twice for step (3).
  85. ** Two writes per page are required in step (3) because the original
  86. ** database content must be written into the rollback journal prior to
  87. ** overwriting the database with the vacuumed content.
  88. **
  89. ** Only 1x temporary space and only 1x writes would be required if
  90. ** the copy of step (3) were replace by deleting the original database
  91. ** and renaming the transient database as the original. But that will
  92. ** not work if other processes are attached to the original database.
  93. ** And a power loss in between deleting the original and renaming the
  94. ** transient would cause the database file to appear to be deleted
  95. ** following reboot.
  96. */
  97. void sqlite3Vacuum(Parse *pParse){
  98. Vdbe *v = sqlite3GetVdbe(pParse);
  99. if( v ){
  100. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  101. sqlite3VdbeUsesBtree(v, 0);
  102. }
  103. return;
  104. }
  105. /*
  106. ** This routine implements the OP_Vacuum opcode of the VDBE.
  107. */
  108. int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  109. int rc = SQLITE_OK; /* Return code from service routines */
  110. Btree *pMain; /* The database being vacuumed */
  111. Btree *pTemp; /* The temporary database we vacuum into */
  112. char *zSql = 0; /* SQL statements */
  113. int saved_flags; /* Saved value of the db->flags */
  114. int saved_nChange; /* Saved value of db->nChange */
  115. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  116. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  117. Db *pDb = 0; /* Database to detach at end of vacuum */
  118. int isMemDb; /* True if vacuuming a :memory: database */
  119. int nRes; /* Bytes of reserved space at the end of each page */
  120. int nDb; /* Number of attached databases */
  121. if( !db->autoCommit ){
  122. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  123. return SQLITE_ERROR;
  124. }
  125. if( db->nVdbeActive>1 ){
  126. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  127. return SQLITE_ERROR;
  128. }
  129. /* Save the current value of the database flags so that it can be
  130. ** restored before returning. Then set the writable-schema flag, and
  131. ** disable CHECK and foreign key constraints. */
  132. saved_flags = db->flags;
  133. saved_nChange = db->nChange;
  134. saved_nTotalChange = db->nTotalChange;
  135. saved_xTrace = db->xTrace;
  136. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  137. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  138. db->xTrace = 0;
  139. pMain = db->aDb[0].pBt;
  140. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  141. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  142. ** can be set to 'off' for this file, as it is not recovered if a crash
  143. ** occurs anyway. The integrity of the database is maintained by a
  144. ** (possibly synchronous) transaction opened on the main database before
  145. ** sqlite3BtreeCopyFile() is called.
  146. **
  147. ** An optimisation would be to use a non-journaled pager.
  148. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  149. ** that actually made the VACUUM run slower. Very little journalling
  150. ** actually occurs when doing a vacuum since the vacuum_db is initially
  151. ** empty. Only the journal header is written. Apparently it takes more
  152. ** time to parse and run the PRAGMA to turn journalling off than it does
  153. ** to write the journal header file.
  154. */
  155. nDb = db->nDb;
  156. if( sqlite3TempInMemory(db) ){
  157. zSql = "ATTACH ':memory:' AS vacuum_db;";
  158. }else{
  159. zSql = "ATTACH '' AS vacuum_db;";
  160. }
  161. rc = execSql(db, pzErrMsg, zSql);
  162. if( db->nDb>nDb ){
  163. pDb = &db->aDb[db->nDb-1];
  164. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  165. }
  166. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  167. pTemp = db->aDb[db->nDb-1].pBt;
  168. /* The call to execSql() to attach the temp database has left the file
  169. ** locked (as there was more than one active statement when the transaction
  170. ** to read the schema was concluded. Unlock it here so that this doesn't
  171. ** cause problems for the call to BtreeSetPageSize() below. */
  172. sqlite3BtreeCommit(pTemp);
  173. nRes = sqlite3BtreeGetReserve(pMain);
  174. /* A VACUUM cannot change the pagesize of an encrypted database. */
  175. #ifdef SQLITE_HAS_CODEC
  176. if( db->nextPagesize ){
  177. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  178. int nKey;
  179. char *zKey;
  180. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  181. if( nKey ) db->nextPagesize = 0;
  182. }
  183. #endif
  184. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  185. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  186. /* Begin a transaction and take an exclusive lock on the main database
  187. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  188. ** to ensure that we do not try to change the page-size on a WAL database.
  189. */
  190. rc = execSql(db, pzErrMsg, "BEGIN;");
  191. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  192. rc = sqlite3BtreeBeginTrans(pMain, 2);
  193. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  194. /* Do not attempt to change the page size for a WAL database */
  195. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  196. ==PAGER_JOURNALMODE_WAL ){
  197. db->nextPagesize = 0;
  198. }
  199. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  200. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  201. || NEVER(db->mallocFailed)
  202. ){
  203. rc = SQLITE_NOMEM;
  204. goto end_of_vacuum;
  205. }
  206. #ifndef SQLITE_OMIT_AUTOVACUUM
  207. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  208. sqlite3BtreeGetAutoVacuum(pMain));
  209. #endif
  210. /* Query the schema of the main database. Create a mirror schema
  211. ** in the temporary database.
  212. */
  213. rc = execExecSql(db, pzErrMsg,
  214. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  215. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  216. " AND rootpage>0"
  217. );
  218. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  219. rc = execExecSql(db, pzErrMsg,
  220. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  221. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  222. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  223. rc = execExecSql(db, pzErrMsg,
  224. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  225. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  226. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  227. /* Loop through the tables in the main database. For each, do
  228. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  229. ** the contents to the temporary database.
  230. */
  231. rc = execExecSql(db, pzErrMsg,
  232. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  233. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  234. "FROM main.sqlite_master "
  235. "WHERE type = 'table' AND name!='sqlite_sequence' "
  236. " AND rootpage>0"
  237. );
  238. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  239. /* Copy over the sequence table
  240. */
  241. rc = execExecSql(db, pzErrMsg,
  242. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  243. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  244. );
  245. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  246. rc = execExecSql(db, pzErrMsg,
  247. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  248. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  249. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  250. );
  251. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  252. /* Copy the triggers, views, and virtual tables from the main database
  253. ** over to the temporary database. None of these objects has any
  254. ** associated storage, so all we have to do is copy their entries
  255. ** from the SQLITE_MASTER table.
  256. */
  257. rc = execSql(db, pzErrMsg,
  258. "INSERT INTO vacuum_db.sqlite_master "
  259. " SELECT type, name, tbl_name, rootpage, sql"
  260. " FROM main.sqlite_master"
  261. " WHERE type='view' OR type='trigger'"
  262. " OR (type='table' AND rootpage=0)"
  263. );
  264. if( rc ) goto end_of_vacuum;
  265. /* At this point, there is a write transaction open on both the
  266. ** vacuum database and the main database. Assuming no error occurs,
  267. ** both transactions are closed by this block - the main database
  268. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  269. ** call to sqlite3BtreeCommit().
  270. */
  271. {
  272. u32 meta;
  273. int i;
  274. /* This array determines which meta meta values are preserved in the
  275. ** vacuum. Even entries are the meta value number and odd entries
  276. ** are an increment to apply to the meta value after the vacuum.
  277. ** The increment is used to increase the schema cookie so that other
  278. ** connections to the same database will know to reread the schema.
  279. */
  280. static const unsigned char aCopy[] = {
  281. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  282. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  283. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  284. BTREE_USER_VERSION, 0, /* Preserve the user version */
  285. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  286. };
  287. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  288. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  289. /* Copy Btree meta values */
  290. for(i=0; i<ArraySize(aCopy); i+=2){
  291. /* GetMeta() and UpdateMeta() cannot fail in this context because
  292. ** we already have page 1 loaded into cache and marked dirty. */
  293. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  294. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  295. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  296. }
  297. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  298. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  299. rc = sqlite3BtreeCommit(pTemp);
  300. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  301. #ifndef SQLITE_OMIT_AUTOVACUUM
  302. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  303. #endif
  304. }
  305. assert( rc==SQLITE_OK );
  306. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  307. end_of_vacuum:
  308. /* Restore the original value of db->flags */
  309. db->flags = saved_flags;
  310. db->nChange = saved_nChange;
  311. db->nTotalChange = saved_nTotalChange;
  312. db->xTrace = saved_xTrace;
  313. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  314. /* Currently there is an SQL level transaction open on the vacuum
  315. ** database. No locks are held on any other files (since the main file
  316. ** was committed at the btree level). So it safe to end the transaction
  317. ** by manually setting the autoCommit flag to true and detaching the
  318. ** vacuum database. The vacuum_db journal file is deleted when the pager
  319. ** is closed by the DETACH.
  320. */
  321. db->autoCommit = 1;
  322. if( pDb ){
  323. sqlite3BtreeClose(pDb->pBt);
  324. pDb->pBt = 0;
  325. pDb->pSchema = 0;
  326. }
  327. /* This both clears the schemas and reduces the size of the db->aDb[]
  328. ** array. */
  329. sqlite3ResetAllSchemasOfConnection(db);
  330. return rc;
  331. }
  332. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */