xref: /sqlite-3.40.0/src/backup.c (revision 47b7fc78)
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.
10 **
11 *************************************************************************
12 ** This file contains the implementation of the sqlite3_backup_XXX()
13 ** API functions and the related features.
14 */
15 #include "sqliteInt.h"
16 #include "btreeInt.h"
17 
18 /*
19 ** Structure allocated for each backup operation.
20 */
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 */
26 
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 */
30 
31   int rc;                  /* Backup process error code */
32 
33   /* These two variables are set by every call to backup_step(). They are
34   ** read by calls to backup_remaining() and backup_pagecount().
35   */
36   Pgno nRemaining;         /* Number of pages left to copy */
37   Pgno nPagecount;         /* Total number of pages to copy */
38 
39   int isAttached;          /* True once backup has been registered with pager */
40   sqlite3_backup *pNext;   /* Next backup associated with source pager */
41 };
42 
43 /*
44 ** THREAD SAFETY NOTES:
45 **
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:
48 **
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.
53 **
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.
59 **
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().
66 **
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.
71 */
72 
73 /*
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.
77 **
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.
81 */
82 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
83   int i = sqlite3FindDbName(pDb, zDb);
84 
85   if( i==1 ){
86     Parse *pParse;
87     int rc = 0;
88     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
89     if( pParse==0 ){
90       sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
91       rc = SQLITE_NOMEM;
92     }else{
93       pParse->db = pDb;
94       if( sqlite3OpenTempDatabase(pParse) ){
95         sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
96         rc = SQLITE_ERROR;
97       }
98       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
99       sqlite3ParserReset(pParse);
100       sqlite3StackFree(pErrorDb, pParse);
101     }
102     if( rc ){
103       return 0;
104     }
105   }
106 
107   if( i<0 ){
108     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
109     return 0;
110   }
111 
112   return pDb->aDb[i].pBt;
113 }
114 
115 /*
116 ** Attempt to set the page size of the destination to match the page size
117 ** of the source.
118 */
119 static int setDestPgsz(sqlite3_backup *p){
120   int rc;
121   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
122   return rc;
123 }
124 
125 /*
126 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
127 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
128 ** a pointer to the new sqlite3_backup object.
129 **
130 ** If an error occurs, NULL is returned and an error code and error message
131 ** stored in database handle pDestDb.
132 */
133 sqlite3_backup *sqlite3_backup_init(
134   sqlite3* pDestDb,                     /* Database to write to */
135   const char *zDestDb,                  /* Name of database within pDestDb */
136   sqlite3* pSrcDb,                      /* Database connection to read from */
137   const char *zSrcDb                    /* Name of database within pSrcDb */
138 ){
139   sqlite3_backup *p;                    /* Value to return */
140 
141 #ifdef SQLITE_ENABLE_API_ARMOR
142   if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
143     (void)SQLITE_MISUSE_BKPT;
144     return 0;
145   }
146 #endif
147 
148   /* Lock the source database handle. The destination database
149   ** handle is not locked in this routine, but it is locked in
150   ** sqlite3_backup_step(). The user is required to ensure that no
151   ** other thread accesses the destination handle for the duration
152   ** of the backup operation.  Any attempt to use the destination
153   ** database connection while a backup is in progress may cause
154   ** a malfunction or a deadlock.
155   */
156   sqlite3_mutex_enter(pSrcDb->mutex);
157   sqlite3_mutex_enter(pDestDb->mutex);
158 
159   if( pSrcDb==pDestDb ){
160     sqlite3ErrorWithMsg(
161         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
162     );
163     p = 0;
164   }else {
165     /* Allocate space for a new sqlite3_backup object...
166     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
167     ** call to sqlite3_backup_init() and is destroyed by a call to
168     ** sqlite3_backup_finish(). */
169     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
170     if( !p ){
171       sqlite3Error(pDestDb, SQLITE_NOMEM);
172     }
173   }
174 
175   /* If the allocation succeeded, populate the new object. */
176   if( p ){
177     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
178     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
179     p->pDestDb = pDestDb;
180     p->pSrcDb = pSrcDb;
181     p->iNext = 1;
182     p->isAttached = 0;
183 
184     if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
185       /* One (or both) of the named databases did not exist or an OOM
186       ** error was hit.  The error has already been written into the
187       ** pDestDb handle.  All that is left to do here is free the
188       ** sqlite3_backup structure.
189       */
190       sqlite3_free(p);
191       p = 0;
192     }
193   }
194   if( p ){
195     p->pSrc->nBackup++;
196   }
197 
198   sqlite3_mutex_leave(pDestDb->mutex);
199   sqlite3_mutex_leave(pSrcDb->mutex);
200   return p;
201 }
202 
203 /*
204 ** Argument rc is an SQLite error code. Return true if this error is
205 ** considered fatal if encountered during a backup operation. All errors
206 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
207 */
208 static int isFatalError(int rc){
209   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
210 }
211 
212 /*
213 ** Parameter zSrcData points to a buffer containing the data for
214 ** page iSrcPg from the source database. Copy this data into the
215 ** destination database.
216 */
217 static int backupOnePage(
218   sqlite3_backup *p,              /* Backup handle */
219   Pgno iSrcPg,                    /* Source database page to backup */
220   const u8 *zSrcData,             /* Source database page data */
221   int bUpdate                     /* True for an update, false otherwise */
222 ){
223   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
224   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
225   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
226   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
227   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
228 #ifdef SQLITE_HAS_CODEC
229   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
230   ** guaranteed that the shared-mutex is held by this thread, handle
231   ** p->pSrc may not actually be the owner.  */
232   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
233   int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
234 #endif
235   int rc = SQLITE_OK;
236   i64 iOff;
237 
238   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
239   assert( p->bDestLocked );
240   assert( !isFatalError(p->rc) );
241   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
242   assert( zSrcData );
243 
244   /* Catch the case where the destination is an in-memory database and the
245   ** page sizes of the source and destination differ.
246   */
247   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
248     rc = SQLITE_READONLY;
249   }
250 
251 #ifdef SQLITE_HAS_CODEC
252   /* Backup is not possible if the page size of the destination is changing
253   ** and a codec is in use.
254   */
255   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
256     rc = SQLITE_READONLY;
257   }
258 
259   /* Backup is not possible if the number of bytes of reserve space differ
260   ** between source and destination.  If there is a difference, try to
261   ** fix the destination to agree with the source.  If that is not possible,
262   ** then the backup cannot proceed.
263   */
264   if( nSrcReserve!=nDestReserve ){
265     u32 newPgsz = nSrcPgsz;
266     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
267     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
268   }
269 #endif
270 
271   /* This loop runs once for each destination page spanned by the source
272   ** page. For each iteration, variable iOff is set to the byte offset
273   ** of the destination page.
274   */
275   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
276     DbPage *pDestPg = 0;
277     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
278     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
279     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
280      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
281     ){
282       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
283       u8 *zDestData = sqlite3PagerGetData(pDestPg);
284       u8 *zOut = &zDestData[iOff%nDestPgsz];
285 
286       /* Copy the data from the source page into the destination page.
287       ** Then clear the Btree layer MemPage.isInit flag. Both this module
288       ** and the pager code use this trick (clearing the first byte
289       ** of the page 'extra' space to invalidate the Btree layers
290       ** cached parse of the page). MemPage.isInit is marked
291       ** "MUST BE FIRST" for this purpose.
292       */
293       memcpy(zOut, zIn, nCopy);
294       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
295       if( iOff==0 && bUpdate==0 ){
296         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
297       }
298     }
299     sqlite3PagerUnref(pDestPg);
300   }
301 
302   return rc;
303 }
304 
305 /*
306 ** If pFile is currently larger than iSize bytes, then truncate it to
307 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
308 ** this function is a no-op.
309 **
310 ** Return SQLITE_OK if everything is successful, or an SQLite error
311 ** code if an error occurs.
312 */
313 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
314   i64 iCurrent;
315   int rc = sqlite3OsFileSize(pFile, &iCurrent);
316   if( rc==SQLITE_OK && iCurrent>iSize ){
317     rc = sqlite3OsTruncate(pFile, iSize);
318   }
319   return rc;
320 }
321 
322 /*
323 ** Register this backup object with the associated source pager for
324 ** callbacks when pages are changed or the cache invalidated.
325 */
326 static void attachBackupObject(sqlite3_backup *p){
327   sqlite3_backup **pp;
328   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
329   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
330   p->pNext = *pp;
331   *pp = p;
332   p->isAttached = 1;
333 }
334 
335 /*
336 ** Copy nPage pages from the source b-tree to the destination.
337 */
338 int sqlite3_backup_step(sqlite3_backup *p, int nPage){
339   int rc;
340   int destMode;       /* Destination journal mode */
341   int pgszSrc = 0;    /* Source page size */
342   int pgszDest = 0;   /* Destination page size */
343 
344 #ifdef SQLITE_ENABLE_API_ARMOR
345   if( p==0 ) return SQLITE_MISUSE_BKPT;
346 #endif
347   sqlite3_mutex_enter(p->pSrcDb->mutex);
348   sqlite3BtreeEnter(p->pSrc);
349   if( p->pDestDb ){
350     sqlite3_mutex_enter(p->pDestDb->mutex);
351   }
352 
353   rc = p->rc;
354   if( !isFatalError(rc) ){
355     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
356     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
357     int ii;                            /* Iterator variable */
358     int nSrcPage = -1;                 /* Size of source db in pages */
359     int bCloseTrans = 0;               /* True if src db requires unlocking */
360 
361     /* If the source pager is currently in a write-transaction, return
362     ** SQLITE_BUSY immediately.
363     */
364     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
365       rc = SQLITE_BUSY;
366     }else{
367       rc = SQLITE_OK;
368     }
369 
370     /* Lock the destination database, if it is not locked already. */
371     if( SQLITE_OK==rc && p->bDestLocked==0
372      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
373     ){
374       p->bDestLocked = 1;
375       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
376     }
377 
378     /* If there is no open read-transaction on the source database, open
379     ** one now. If a transaction is opened here, then it will be closed
380     ** before this function exits.
381     */
382     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
383       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
384       bCloseTrans = 1;
385     }
386 
387     /* Do not allow backup if the destination database is in WAL mode
388     ** and the page sizes are different between source and destination */
389     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
390     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
391     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
392     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
393       rc = SQLITE_READONLY;
394     }
395 
396     /* Now that there is a read-lock on the source database, query the
397     ** source pager for the number of pages in the database.
398     */
399     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
400     assert( nSrcPage>=0 );
401     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
402       const Pgno iSrcPg = p->iNext;                 /* Source page number */
403       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
404         DbPage *pSrcPg;                             /* Source page object */
405         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
406                                  PAGER_GET_READONLY);
407         if( rc==SQLITE_OK ){
408           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
409           sqlite3PagerUnref(pSrcPg);
410         }
411       }
412       p->iNext++;
413     }
414     if( rc==SQLITE_OK ){
415       p->nPagecount = nSrcPage;
416       p->nRemaining = nSrcPage+1-p->iNext;
417       if( p->iNext>(Pgno)nSrcPage ){
418         rc = SQLITE_DONE;
419       }else if( !p->isAttached ){
420         attachBackupObject(p);
421       }
422     }
423 
424     /* Update the schema version field in the destination database. This
425     ** is to make sure that the schema-version really does change in
426     ** the case where the source and destination databases have the
427     ** same schema version.
428     */
429     if( rc==SQLITE_DONE ){
430       if( nSrcPage==0 ){
431         rc = sqlite3BtreeNewDb(p->pDest);
432         nSrcPage = 1;
433       }
434       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
435         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
436       }
437       if( rc==SQLITE_OK ){
438         if( p->pDestDb ){
439           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
440         }
441         if( destMode==PAGER_JOURNALMODE_WAL ){
442           rc = sqlite3BtreeSetVersion(p->pDest, 2);
443         }
444       }
445       if( rc==SQLITE_OK ){
446         int nDestTruncate;
447         /* Set nDestTruncate to the final number of pages in the destination
448         ** database. The complication here is that the destination page
449         ** size may be different to the source page size.
450         **
451         ** If the source page size is smaller than the destination page size,
452         ** round up. In this case the call to sqlite3OsTruncate() below will
453         ** fix the size of the file. However it is important to call
454         ** sqlite3PagerTruncateImage() here so that any pages in the
455         ** destination file that lie beyond the nDestTruncate page mark are
456         ** journalled by PagerCommitPhaseOne() before they are destroyed
457         ** by the file truncation.
458         */
459         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
460         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
461         if( pgszSrc<pgszDest ){
462           int ratio = pgszDest/pgszSrc;
463           nDestTruncate = (nSrcPage+ratio-1)/ratio;
464           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
465             nDestTruncate--;
466           }
467         }else{
468           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
469         }
470         assert( nDestTruncate>0 );
471 
472         if( pgszSrc<pgszDest ){
473           /* If the source page-size is smaller than the destination page-size,
474           ** two extra things may need to happen:
475           **
476           **   * The destination may need to be truncated, and
477           **
478           **   * Data stored on the pages immediately following the
479           **     pending-byte page in the source database may need to be
480           **     copied into the destination database.
481           */
482           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
483           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
484           Pgno iPg;
485           int nDstPage;
486           i64 iOff;
487           i64 iEnd;
488 
489           assert( pFile );
490           assert( nDestTruncate==0
491               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
492                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
493              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
494           ));
495 
496           /* This block ensures that all data required to recreate the original
497           ** database has been stored in the journal for pDestPager and the
498           ** journal synced to disk. So at this point we may safely modify
499           ** the database file in any way, knowing that if a power failure
500           ** occurs, the original database will be reconstructed from the
501           ** journal file.  */
502           sqlite3PagerPagecount(pDestPager, &nDstPage);
503           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
504             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
505               DbPage *pPg;
506               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
507               if( rc==SQLITE_OK ){
508                 rc = sqlite3PagerWrite(pPg);
509                 sqlite3PagerUnref(pPg);
510               }
511             }
512           }
513           if( rc==SQLITE_OK ){
514             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
515           }
516 
517           /* Write the extra pages and truncate the database file as required */
518           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
519           for(
520             iOff=PENDING_BYTE+pgszSrc;
521             rc==SQLITE_OK && iOff<iEnd;
522             iOff+=pgszSrc
523           ){
524             PgHdr *pSrcPg = 0;
525             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
526             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
527             if( rc==SQLITE_OK ){
528               u8 *zData = sqlite3PagerGetData(pSrcPg);
529               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
530             }
531             sqlite3PagerUnref(pSrcPg);
532           }
533           if( rc==SQLITE_OK ){
534             rc = backupTruncateFile(pFile, iSize);
535           }
536 
537           /* Sync the database file to disk. */
538           if( rc==SQLITE_OK ){
539             rc = sqlite3PagerSync(pDestPager, 0);
540           }
541         }else{
542           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
543           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
544         }
545 
546         /* Finish committing the transaction to the destination database. */
547         if( SQLITE_OK==rc
548          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
549         ){
550           rc = SQLITE_DONE;
551         }
552       }
553     }
554 
555     /* If bCloseTrans is true, then this function opened a read transaction
556     ** on the source database. Close the read transaction here. There is
557     ** no need to check the return values of the btree methods here, as
558     ** "committing" a read-only transaction cannot fail.
559     */
560     if( bCloseTrans ){
561       TESTONLY( int rc2 );
562       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
563       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
564       assert( rc2==SQLITE_OK );
565     }
566 
567     if( rc==SQLITE_IOERR_NOMEM ){
568       rc = SQLITE_NOMEM;
569     }
570     p->rc = rc;
571   }
572   if( p->pDestDb ){
573     sqlite3_mutex_leave(p->pDestDb->mutex);
574   }
575   sqlite3BtreeLeave(p->pSrc);
576   sqlite3_mutex_leave(p->pSrcDb->mutex);
577   return rc;
578 }
579 
580 /*
581 ** Release all resources associated with an sqlite3_backup* handle.
582 */
583 int sqlite3_backup_finish(sqlite3_backup *p){
584   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
585   sqlite3 *pSrcDb;                     /* Source database connection */
586   int rc;                              /* Value to return */
587 
588   /* Enter the mutexes */
589   if( p==0 ) return SQLITE_OK;
590   pSrcDb = p->pSrcDb;
591   sqlite3_mutex_enter(pSrcDb->mutex);
592   sqlite3BtreeEnter(p->pSrc);
593   if( p->pDestDb ){
594     sqlite3_mutex_enter(p->pDestDb->mutex);
595   }
596 
597   /* Detach this backup from the source pager. */
598   if( p->pDestDb ){
599     p->pSrc->nBackup--;
600   }
601   if( p->isAttached ){
602     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
603     while( *pp!=p ){
604       pp = &(*pp)->pNext;
605     }
606     *pp = p->pNext;
607   }
608 
609   /* If a transaction is still open on the Btree, roll it back. */
610   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
611 
612   /* Set the error code of the destination database handle. */
613   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
614   if( p->pDestDb ){
615     sqlite3Error(p->pDestDb, rc);
616 
617     /* Exit the mutexes and free the backup context structure. */
618     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
619   }
620   sqlite3BtreeLeave(p->pSrc);
621   if( p->pDestDb ){
622     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
623     ** call to sqlite3_backup_init() and is destroyed by a call to
624     ** sqlite3_backup_finish(). */
625     sqlite3_free(p);
626   }
627   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
628   return rc;
629 }
630 
631 /*
632 ** Return the number of pages still to be backed up as of the most recent
633 ** call to sqlite3_backup_step().
634 */
635 int sqlite3_backup_remaining(sqlite3_backup *p){
636 #ifdef SQLITE_ENABLE_API_ARMOR
637   if( p==0 ){
638     (void)SQLITE_MISUSE_BKPT;
639     return 0;
640   }
641 #endif
642   return p->nRemaining;
643 }
644 
645 /*
646 ** Return the total number of pages in the source database as of the most
647 ** recent call to sqlite3_backup_step().
648 */
649 int sqlite3_backup_pagecount(sqlite3_backup *p){
650 #ifdef SQLITE_ENABLE_API_ARMOR
651   if( p==0 ){
652     (void)SQLITE_MISUSE_BKPT;
653     return 0;
654   }
655 #endif
656   return p->nPagecount;
657 }
658 
659 /*
660 ** This function is called after the contents of page iPage of the
661 ** source database have been modified. If page iPage has already been
662 ** copied into the destination database, then the data written to the
663 ** destination is now invalidated. The destination copy of iPage needs
664 ** to be updated with the new data before the backup operation is
665 ** complete.
666 **
667 ** It is assumed that the mutex associated with the BtShared object
668 ** corresponding to the source database is held when this function is
669 ** called.
670 */
671 void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
672   sqlite3_backup *p;                   /* Iterator variable */
673   for(p=pBackup; p; p=p->pNext){
674     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
675     if( !isFatalError(p->rc) && iPage<p->iNext ){
676       /* The backup process p has already copied page iPage. But now it
677       ** has been modified by a transaction on the source pager. Copy
678       ** the new data into the backup.
679       */
680       int rc;
681       assert( p->pDestDb );
682       sqlite3_mutex_enter(p->pDestDb->mutex);
683       rc = backupOnePage(p, iPage, aData, 1);
684       sqlite3_mutex_leave(p->pDestDb->mutex);
685       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
686       if( rc!=SQLITE_OK ){
687         p->rc = rc;
688       }
689     }
690   }
691 }
692 
693 /*
694 ** Restart the backup process. This is called when the pager layer
695 ** detects that the database has been modified by an external database
696 ** connection. In this case there is no way of knowing which of the
697 ** pages that have been copied into the destination database are still
698 ** valid and which are not, so the entire process needs to be restarted.
699 **
700 ** It is assumed that the mutex associated with the BtShared object
701 ** corresponding to the source database is held when this function is
702 ** called.
703 */
704 void sqlite3BackupRestart(sqlite3_backup *pBackup){
705   sqlite3_backup *p;                   /* Iterator variable */
706   for(p=pBackup; p; p=p->pNext){
707     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
708     p->iNext = 1;
709   }
710 }
711 
712 #ifndef SQLITE_OMIT_VACUUM
713 /*
714 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
715 ** must be active for both files.
716 **
717 ** The size of file pTo may be reduced by this operation. If anything
718 ** goes wrong, the transaction on pTo is rolled back. If successful, the
719 ** transaction is committed before returning.
720 */
721 int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
722   int rc;
723   sqlite3_file *pFd;              /* File descriptor for database pTo */
724   sqlite3_backup b;
725   sqlite3BtreeEnter(pTo);
726   sqlite3BtreeEnter(pFrom);
727 
728   assert( sqlite3BtreeIsInTrans(pTo) );
729   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
730   if( pFd->pMethods ){
731     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
732     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
733     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
734     if( rc ) goto copy_finished;
735   }
736 
737   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
738   ** to 0. This is used by the implementations of sqlite3_backup_step()
739   ** and sqlite3_backup_finish() to detect that they are being called
740   ** from this function, not directly by the user.
741   */
742   memset(&b, 0, sizeof(b));
743   b.pSrcDb = pFrom->db;
744   b.pSrc = pFrom;
745   b.pDest = pTo;
746   b.iNext = 1;
747 
748   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
749   ** file. By passing this as the number of pages to copy to
750   ** sqlite3_backup_step(), we can guarantee that the copy finishes
751   ** within a single call (unless an error occurs). The assert() statement
752   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
753   ** or an error code.
754   */
755   sqlite3_backup_step(&b, 0x7FFFFFFF);
756   assert( b.rc!=SQLITE_OK );
757   rc = sqlite3_backup_finish(&b);
758   if( rc==SQLITE_OK ){
759     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
760   }else{
761     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
762   }
763 
764   assert( sqlite3BtreeIsInTrans(pTo)==0 );
765 copy_finished:
766   sqlite3BtreeLeave(pFrom);
767   sqlite3BtreeLeave(pTo);
768   return rc;
769 }
770 #endif /* SQLITE_OMIT_VACUUM */
771