Merge sqlite-release(3.30.1) into prerelease-integration
[sqlcipher.git] / src / backup.c
blob8035a65dc238338997c86a80f9431e5b4a8aa539
1 /*
2 ** 2009 January 28
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.
11 *************************************************************************
12 ** This file contains the implementation of the sqlite3_backup_XXX()
13 ** API functions and the related features.
15 #include "sqliteInt.h"
16 #include "btreeInt.h"
19 ** Structure allocated for each backup operation.
21 struct sqlite3_backup {
22 sqlite3* pDestDb; /* Destination database handle */
23 Btree *pDest; /* Destination b-tree file */
24 u32 iDestSchema; /* Original schema cookie in destination */
25 int bDestLocked; /* True once a write-transaction is open on pDest */
27 Pgno iNext; /* Page number of the next source page to copy */
28 sqlite3* pSrcDb; /* Source database handle */
29 Btree *pSrc; /* Source b-tree file */
31 int rc; /* Backup process error code */
33 /* These two variables are set by every call to backup_step(). They are
34 ** read by calls to backup_remaining() and backup_pagecount().
36 Pgno nRemaining; /* Number of pages left to copy */
37 Pgno nPagecount; /* Total number of pages to copy */
39 int isAttached; /* True once backup has been registered with pager */
40 sqlite3_backup *pNext; /* Next backup associated with source pager */
44 ** THREAD SAFETY NOTES:
46 ** Once it has been created using backup_init(), a single sqlite3_backup
47 ** structure may be accessed via two groups of thread-safe entry points:
49 ** * Via the sqlite3_backup_XXX() API function backup_step() and
50 ** backup_finish(). Both these functions obtain the source database
51 ** handle mutex and the mutex associated with the source BtShared
52 ** structure, in that order.
54 ** * Via the BackupUpdate() and BackupRestart() functions, which are
55 ** invoked by the pager layer to report various state changes in
56 ** the page cache associated with the source database. The mutex
57 ** associated with the source database BtShared structure will always
58 ** be held when either of these functions are invoked.
60 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
61 ** backup_pagecount() are not thread-safe functions. If they are called
62 ** while some other thread is calling backup_step() or backup_finish(),
63 ** the values returned may be invalid. There is no way for a call to
64 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
65 ** or backup_pagecount().
67 ** Depending on the SQLite configuration, the database handles and/or
68 ** the Btree objects may have their own mutexes that require locking.
69 ** Non-sharable Btrees (in-memory databases for example), do not have
70 ** associated mutexes.
74 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
75 ** in connection handle pDb. If such a database cannot be found, return
76 ** a NULL pointer and write an error message to pErrorDb.
78 ** If the "temp" database is requested, it may need to be opened by this
79 ** function. If an error occurs while doing so, return 0 and write an
80 ** error message to pErrorDb.
82 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
83 int i = sqlite3FindDbName(pDb, zDb);
85 if( i==1 ){
86 Parse sParse;
87 int rc = 0;
88 memset(&sParse, 0, sizeof(sParse));
89 sParse.db = pDb;
90 if( sqlite3OpenTempDatabase(&sParse) ){
91 sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
92 rc = SQLITE_ERROR;
94 sqlite3DbFree(pErrorDb, sParse.zErrMsg);
95 sqlite3ParserReset(&sParse);
96 if( rc ){
97 return 0;
101 if( i<0 ){
102 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
103 return 0;
106 return pDb->aDb[i].pBt;
110 ** Attempt to set the page size of the destination to match the page size
111 ** of the source.
113 static int setDestPgsz(sqlite3_backup *p){
114 int rc;
115 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
116 return rc;
120 ** Check that there is no open read-transaction on the b-tree passed as the
121 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
122 ** is an open read-transaction, return SQLITE_ERROR and leave an error
123 ** message in database handle db.
125 static int checkReadTransaction(sqlite3 *db, Btree *p){
126 if( sqlite3BtreeIsInReadTrans(p) ){
127 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
128 return SQLITE_ERROR;
130 return SQLITE_OK;
134 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
135 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
136 ** a pointer to the new sqlite3_backup object.
138 ** If an error occurs, NULL is returned and an error code and error message
139 ** stored in database handle pDestDb.
141 sqlite3_backup *sqlite3_backup_init(
142 sqlite3* pDestDb, /* Database to write to */
143 const char *zDestDb, /* Name of database within pDestDb */
144 sqlite3* pSrcDb, /* Database connection to read from */
145 const char *zSrcDb /* Name of database within pSrcDb */
147 sqlite3_backup *p; /* Value to return */
149 #ifdef SQLITE_ENABLE_API_ARMOR
150 if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
151 (void)SQLITE_MISUSE_BKPT;
152 return 0;
154 #endif
156 /* BEGIN SQLCIPHER */
157 #ifdef SQLITE_HAS_CODEC
159 extern int sqlcipher_find_db_index(sqlite3*, const char*);
160 extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
161 int srcNKey, destNKey;
162 void *zKey;
164 sqlite3CodecGetKey(pSrcDb, sqlcipher_find_db_index(pSrcDb, zSrcDb), &zKey, &srcNKey);
165 sqlite3CodecGetKey(pDestDb, sqlcipher_find_db_index(pDestDb, zDestDb), &zKey, &destNKey);
166 zKey = NULL;
168 /* either both databases must be plaintext, or both must be encrypted */
169 if((srcNKey == 0 && destNKey > 0) || (srcNKey > 0 && destNKey == 0)) {
170 sqlite3ErrorWithMsg(pDestDb, SQLITE_ERROR, "backup is not supported with encrypted databases");
171 return NULL;
174 #endif
175 /* END SQLCIPHER */
177 /* Lock the source database handle. The destination database
178 ** handle is not locked in this routine, but it is locked in
179 ** sqlite3_backup_step(). The user is required to ensure that no
180 ** other thread accesses the destination handle for the duration
181 ** of the backup operation. Any attempt to use the destination
182 ** database connection while a backup is in progress may cause
183 ** a malfunction or a deadlock.
185 sqlite3_mutex_enter(pSrcDb->mutex);
186 sqlite3_mutex_enter(pDestDb->mutex);
188 if( pSrcDb==pDestDb ){
189 sqlite3ErrorWithMsg(
190 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
192 p = 0;
193 }else {
194 /* Allocate space for a new sqlite3_backup object...
195 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
196 ** call to sqlite3_backup_init() and is destroyed by a call to
197 ** sqlite3_backup_finish(). */
198 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
199 if( !p ){
200 sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
204 /* If the allocation succeeded, populate the new object. */
205 if( p ){
206 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
207 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
208 p->pDestDb = pDestDb;
209 p->pSrcDb = pSrcDb;
210 p->iNext = 1;
211 p->isAttached = 0;
213 if( 0==p->pSrc || 0==p->pDest
214 || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
216 /* One (or both) of the named databases did not exist or an OOM
217 ** error was hit. Or there is a transaction open on the destination
218 ** database. The error has already been written into the pDestDb
219 ** handle. All that is left to do here is free the sqlite3_backup
220 ** structure. */
221 sqlite3_free(p);
222 p = 0;
225 if( p ){
226 p->pSrc->nBackup++;
229 sqlite3_mutex_leave(pDestDb->mutex);
230 sqlite3_mutex_leave(pSrcDb->mutex);
231 return p;
235 ** Argument rc is an SQLite error code. Return true if this error is
236 ** considered fatal if encountered during a backup operation. All errors
237 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
239 static int isFatalError(int rc){
240 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
244 ** Parameter zSrcData points to a buffer containing the data for
245 ** page iSrcPg from the source database. Copy this data into the
246 ** destination database.
248 static int backupOnePage(
249 sqlite3_backup *p, /* Backup handle */
250 Pgno iSrcPg, /* Source database page to backup */
251 const u8 *zSrcData, /* Source database page data */
252 int bUpdate /* True for an update, false otherwise */
254 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
255 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
256 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
257 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
258 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
259 #ifdef SQLITE_HAS_CODEC
260 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
261 ** guaranteed that the shared-mutex is held by this thread, handle
262 ** p->pSrc may not actually be the owner. */
263 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
264 int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
265 #endif
266 int rc = SQLITE_OK;
267 i64 iOff;
269 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
270 assert( p->bDestLocked );
271 assert( !isFatalError(p->rc) );
272 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
273 assert( zSrcData );
275 /* Catch the case where the destination is an in-memory database and the
276 ** page sizes of the source and destination differ.
278 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
279 rc = SQLITE_READONLY;
282 #ifdef SQLITE_HAS_CODEC
283 /* Backup is not possible if the page size of the destination is changing
284 ** and a codec is in use.
286 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
287 rc = SQLITE_READONLY;
290 /* Backup is not possible if the number of bytes of reserve space differ
291 ** between source and destination. If there is a difference, try to
292 ** fix the destination to agree with the source. If that is not possible,
293 ** then the backup cannot proceed.
295 if( nSrcReserve!=nDestReserve ){
296 u32 newPgsz = nSrcPgsz;
297 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
298 if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY;
300 #endif
302 /* This loop runs once for each destination page spanned by the source
303 ** page. For each iteration, variable iOff is set to the byte offset
304 ** of the destination page.
306 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
307 DbPage *pDestPg = 0;
308 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
309 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
310 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
311 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
313 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
314 u8 *zDestData = sqlite3PagerGetData(pDestPg);
315 u8 *zOut = &zDestData[iOff%nDestPgsz];
317 /* Copy the data from the source page into the destination page.
318 ** Then clear the Btree layer MemPage.isInit flag. Both this module
319 ** and the pager code use this trick (clearing the first byte
320 ** of the page 'extra' space to invalidate the Btree layers
321 ** cached parse of the page). MemPage.isInit is marked
322 ** "MUST BE FIRST" for this purpose.
324 memcpy(zOut, zIn, nCopy);
325 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
326 if( iOff==0 && bUpdate==0 ){
327 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
330 sqlite3PagerUnref(pDestPg);
333 return rc;
337 ** If pFile is currently larger than iSize bytes, then truncate it to
338 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
339 ** this function is a no-op.
341 ** Return SQLITE_OK if everything is successful, or an SQLite error
342 ** code if an error occurs.
344 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
345 i64 iCurrent;
346 int rc = sqlite3OsFileSize(pFile, &iCurrent);
347 if( rc==SQLITE_OK && iCurrent>iSize ){
348 rc = sqlite3OsTruncate(pFile, iSize);
350 return rc;
354 ** Register this backup object with the associated source pager for
355 ** callbacks when pages are changed or the cache invalidated.
357 static void attachBackupObject(sqlite3_backup *p){
358 sqlite3_backup **pp;
359 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
360 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
361 p->pNext = *pp;
362 *pp = p;
363 p->isAttached = 1;
367 ** Copy nPage pages from the source b-tree to the destination.
369 int sqlite3_backup_step(sqlite3_backup *p, int nPage){
370 int rc;
371 int destMode; /* Destination journal mode */
372 int pgszSrc = 0; /* Source page size */
373 int pgszDest = 0; /* Destination page size */
375 #ifdef SQLITE_ENABLE_API_ARMOR
376 if( p==0 ) return SQLITE_MISUSE_BKPT;
377 #endif
378 sqlite3_mutex_enter(p->pSrcDb->mutex);
379 sqlite3BtreeEnter(p->pSrc);
380 if( p->pDestDb ){
381 sqlite3_mutex_enter(p->pDestDb->mutex);
384 rc = p->rc;
385 if( !isFatalError(rc) ){
386 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
387 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
388 int ii; /* Iterator variable */
389 int nSrcPage = -1; /* Size of source db in pages */
390 int bCloseTrans = 0; /* True if src db requires unlocking */
392 /* If the source pager is currently in a write-transaction, return
393 ** SQLITE_BUSY immediately.
395 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
396 rc = SQLITE_BUSY;
397 }else{
398 rc = SQLITE_OK;
401 /* If there is no open read-transaction on the source database, open
402 ** one now. If a transaction is opened here, then it will be closed
403 ** before this function exits.
405 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
406 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
407 bCloseTrans = 1;
410 /* If the destination database has not yet been locked (i.e. if this
411 ** is the first call to backup_step() for the current backup operation),
412 ** try to set its page size to the same as the source database. This
413 ** is especially important on ZipVFS systems, as in that case it is
414 ** not possible to create a database file that uses one page size by
415 ** writing to it with another. */
416 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
417 rc = SQLITE_NOMEM;
420 /* Lock the destination database, if it is not locked already. */
421 if( SQLITE_OK==rc && p->bDestLocked==0
422 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
423 (int*)&p->iDestSchema))
425 p->bDestLocked = 1;
428 /* Do not allow backup if the destination database is in WAL mode
429 ** and the page sizes are different between source and destination */
430 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
431 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
432 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
433 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
434 rc = SQLITE_READONLY;
437 /* Now that there is a read-lock on the source database, query the
438 ** source pager for the number of pages in the database.
440 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
441 assert( nSrcPage>=0 );
442 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
443 const Pgno iSrcPg = p->iNext; /* Source page number */
444 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
445 DbPage *pSrcPg; /* Source page object */
446 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
447 if( rc==SQLITE_OK ){
448 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
449 sqlite3PagerUnref(pSrcPg);
452 p->iNext++;
454 if( rc==SQLITE_OK ){
455 p->nPagecount = nSrcPage;
456 p->nRemaining = nSrcPage+1-p->iNext;
457 if( p->iNext>(Pgno)nSrcPage ){
458 rc = SQLITE_DONE;
459 }else if( !p->isAttached ){
460 attachBackupObject(p);
464 /* Update the schema version field in the destination database. This
465 ** is to make sure that the schema-version really does change in
466 ** the case where the source and destination databases have the
467 ** same schema version.
469 if( rc==SQLITE_DONE ){
470 if( nSrcPage==0 ){
471 rc = sqlite3BtreeNewDb(p->pDest);
472 nSrcPage = 1;
474 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
475 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
477 if( rc==SQLITE_OK ){
478 if( p->pDestDb ){
479 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
481 if( destMode==PAGER_JOURNALMODE_WAL ){
482 rc = sqlite3BtreeSetVersion(p->pDest, 2);
485 if( rc==SQLITE_OK ){
486 int nDestTruncate;
487 /* Set nDestTruncate to the final number of pages in the destination
488 ** database. The complication here is that the destination page
489 ** size may be different to the source page size.
491 ** If the source page size is smaller than the destination page size,
492 ** round up. In this case the call to sqlite3OsTruncate() below will
493 ** fix the size of the file. However it is important to call
494 ** sqlite3PagerTruncateImage() here so that any pages in the
495 ** destination file that lie beyond the nDestTruncate page mark are
496 ** journalled by PagerCommitPhaseOne() before they are destroyed
497 ** by the file truncation.
499 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
500 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
501 if( pgszSrc<pgszDest ){
502 int ratio = pgszDest/pgszSrc;
503 nDestTruncate = (nSrcPage+ratio-1)/ratio;
504 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
505 nDestTruncate--;
507 }else{
508 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
510 assert( nDestTruncate>0 );
512 if( pgszSrc<pgszDest ){
513 /* If the source page-size is smaller than the destination page-size,
514 ** two extra things may need to happen:
516 ** * The destination may need to be truncated, and
518 ** * Data stored on the pages immediately following the
519 ** pending-byte page in the source database may need to be
520 ** copied into the destination database.
522 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
523 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
524 Pgno iPg;
525 int nDstPage;
526 i64 iOff;
527 i64 iEnd;
529 assert( pFile );
530 assert( nDestTruncate==0
531 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
532 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
533 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
536 /* This block ensures that all data required to recreate the original
537 ** database has been stored in the journal for pDestPager and the
538 ** journal synced to disk. So at this point we may safely modify
539 ** the database file in any way, knowing that if a power failure
540 ** occurs, the original database will be reconstructed from the
541 ** journal file. */
542 sqlite3PagerPagecount(pDestPager, &nDstPage);
543 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
544 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
545 DbPage *pPg;
546 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
547 if( rc==SQLITE_OK ){
548 rc = sqlite3PagerWrite(pPg);
549 sqlite3PagerUnref(pPg);
553 if( rc==SQLITE_OK ){
554 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
557 /* Write the extra pages and truncate the database file as required */
558 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
559 for(
560 iOff=PENDING_BYTE+pgszSrc;
561 rc==SQLITE_OK && iOff<iEnd;
562 iOff+=pgszSrc
564 PgHdr *pSrcPg = 0;
565 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
566 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
567 if( rc==SQLITE_OK ){
568 u8 *zData = sqlite3PagerGetData(pSrcPg);
569 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
571 sqlite3PagerUnref(pSrcPg);
573 if( rc==SQLITE_OK ){
574 rc = backupTruncateFile(pFile, iSize);
577 /* Sync the database file to disk. */
578 if( rc==SQLITE_OK ){
579 rc = sqlite3PagerSync(pDestPager, 0);
581 }else{
582 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
583 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
586 /* Finish committing the transaction to the destination database. */
587 if( SQLITE_OK==rc
588 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
590 rc = SQLITE_DONE;
595 /* If bCloseTrans is true, then this function opened a read transaction
596 ** on the source database. Close the read transaction here. There is
597 ** no need to check the return values of the btree methods here, as
598 ** "committing" a read-only transaction cannot fail.
600 if( bCloseTrans ){
601 TESTONLY( int rc2 );
602 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
603 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
604 assert( rc2==SQLITE_OK );
607 if( rc==SQLITE_IOERR_NOMEM ){
608 rc = SQLITE_NOMEM_BKPT;
610 p->rc = rc;
612 if( p->pDestDb ){
613 sqlite3_mutex_leave(p->pDestDb->mutex);
615 sqlite3BtreeLeave(p->pSrc);
616 sqlite3_mutex_leave(p->pSrcDb->mutex);
617 return rc;
621 ** Release all resources associated with an sqlite3_backup* handle.
623 int sqlite3_backup_finish(sqlite3_backup *p){
624 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
625 sqlite3 *pSrcDb; /* Source database connection */
626 int rc; /* Value to return */
628 /* Enter the mutexes */
629 if( p==0 ) return SQLITE_OK;
630 pSrcDb = p->pSrcDb;
631 sqlite3_mutex_enter(pSrcDb->mutex);
632 sqlite3BtreeEnter(p->pSrc);
633 if( p->pDestDb ){
634 sqlite3_mutex_enter(p->pDestDb->mutex);
637 /* Detach this backup from the source pager. */
638 if( p->pDestDb ){
639 p->pSrc->nBackup--;
641 if( p->isAttached ){
642 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
643 assert( pp!=0 );
644 while( *pp!=p ){
645 pp = &(*pp)->pNext;
646 assert( pp!=0 );
648 *pp = p->pNext;
651 /* If a transaction is still open on the Btree, roll it back. */
652 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
654 /* Set the error code of the destination database handle. */
655 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
656 if( p->pDestDb ){
657 sqlite3Error(p->pDestDb, rc);
659 /* Exit the mutexes and free the backup context structure. */
660 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
662 sqlite3BtreeLeave(p->pSrc);
663 if( p->pDestDb ){
664 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
665 ** call to sqlite3_backup_init() and is destroyed by a call to
666 ** sqlite3_backup_finish(). */
667 sqlite3_free(p);
669 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
670 return rc;
674 ** Return the number of pages still to be backed up as of the most recent
675 ** call to sqlite3_backup_step().
677 int sqlite3_backup_remaining(sqlite3_backup *p){
678 #ifdef SQLITE_ENABLE_API_ARMOR
679 if( p==0 ){
680 (void)SQLITE_MISUSE_BKPT;
681 return 0;
683 #endif
684 return p->nRemaining;
688 ** Return the total number of pages in the source database as of the most
689 ** recent call to sqlite3_backup_step().
691 int sqlite3_backup_pagecount(sqlite3_backup *p){
692 #ifdef SQLITE_ENABLE_API_ARMOR
693 if( p==0 ){
694 (void)SQLITE_MISUSE_BKPT;
695 return 0;
697 #endif
698 return p->nPagecount;
702 ** This function is called after the contents of page iPage of the
703 ** source database have been modified. If page iPage has already been
704 ** copied into the destination database, then the data written to the
705 ** destination is now invalidated. The destination copy of iPage needs
706 ** to be updated with the new data before the backup operation is
707 ** complete.
709 ** It is assumed that the mutex associated with the BtShared object
710 ** corresponding to the source database is held when this function is
711 ** called.
713 static SQLITE_NOINLINE void backupUpdate(
714 sqlite3_backup *p,
715 Pgno iPage,
716 const u8 *aData
718 assert( p!=0 );
720 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
721 if( !isFatalError(p->rc) && iPage<p->iNext ){
722 /* The backup process p has already copied page iPage. But now it
723 ** has been modified by a transaction on the source pager. Copy
724 ** the new data into the backup.
726 int rc;
727 assert( p->pDestDb );
728 sqlite3_mutex_enter(p->pDestDb->mutex);
729 rc = backupOnePage(p, iPage, aData, 1);
730 sqlite3_mutex_leave(p->pDestDb->mutex);
731 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
732 if( rc!=SQLITE_OK ){
733 p->rc = rc;
736 }while( (p = p->pNext)!=0 );
738 void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
739 if( pBackup ) backupUpdate(pBackup, iPage, aData);
743 ** Restart the backup process. This is called when the pager layer
744 ** detects that the database has been modified by an external database
745 ** connection. In this case there is no way of knowing which of the
746 ** pages that have been copied into the destination database are still
747 ** valid and which are not, so the entire process needs to be restarted.
749 ** It is assumed that the mutex associated with the BtShared object
750 ** corresponding to the source database is held when this function is
751 ** called.
753 void sqlite3BackupRestart(sqlite3_backup *pBackup){
754 sqlite3_backup *p; /* Iterator variable */
755 for(p=pBackup; p; p=p->pNext){
756 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
757 p->iNext = 1;
761 #ifndef SQLITE_OMIT_VACUUM
763 ** Copy the complete content of pBtFrom into pBtTo. A transaction
764 ** must be active for both files.
766 ** The size of file pTo may be reduced by this operation. If anything
767 ** goes wrong, the transaction on pTo is rolled back. If successful, the
768 ** transaction is committed before returning.
770 int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
771 int rc;
772 sqlite3_file *pFd; /* File descriptor for database pTo */
773 sqlite3_backup b;
774 sqlite3BtreeEnter(pTo);
775 sqlite3BtreeEnter(pFrom);
777 assert( sqlite3BtreeIsInTrans(pTo) );
778 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
779 if( pFd->pMethods ){
780 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
781 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
782 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
783 if( rc ) goto copy_finished;
786 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
787 ** to 0. This is used by the implementations of sqlite3_backup_step()
788 ** and sqlite3_backup_finish() to detect that they are being called
789 ** from this function, not directly by the user.
791 memset(&b, 0, sizeof(b));
792 b.pSrcDb = pFrom->db;
793 b.pSrc = pFrom;
794 b.pDest = pTo;
795 b.iNext = 1;
797 #ifdef SQLITE_HAS_CODEC
798 sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
799 #endif
801 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
802 ** file. By passing this as the number of pages to copy to
803 ** sqlite3_backup_step(), we can guarantee that the copy finishes
804 ** within a single call (unless an error occurs). The assert() statement
805 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
806 ** or an error code. */
807 sqlite3_backup_step(&b, 0x7FFFFFFF);
808 assert( b.rc!=SQLITE_OK );
810 rc = sqlite3_backup_finish(&b);
811 if( rc==SQLITE_OK ){
812 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
813 }else{
814 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
817 assert( sqlite3BtreeIsInTrans(pTo)==0 );
818 copy_finished:
819 sqlite3BtreeLeave(pFrom);
820 sqlite3BtreeLeave(pTo);
821 return rc;
823 #endif /* SQLITE_OMIT_VACUUM */