Merge sqlite-release(3.33.0) into prerelease-integration
[sqlcipher.git] / src / backup.c
blob99ad72e1131ff0262ef4cac7a445cf8b8d38d26b
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),0,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 /* BEGIN SQLCIPHER */
260 #ifdef SQLITE_HAS_CODEC
261 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
262 ** guaranteed that the shared-mutex is held by this thread, handle
263 ** p->pSrc may not actually be the owner. */
264 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
265 int nDestReserve = sqlite3BtreeGetRequestedReserve(p->pDest);
266 #endif
267 /* END SQLCIPHER */
268 int rc = SQLITE_OK;
269 i64 iOff;
271 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
272 assert( p->bDestLocked );
273 assert( !isFatalError(p->rc) );
274 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
275 assert( zSrcData );
277 /* Catch the case where the destination is an in-memory database and the
278 ** page sizes of the source and destination differ.
280 if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
281 rc = SQLITE_READONLY;
284 /* BEGIN SQLCIPHER */
285 #ifdef SQLITE_HAS_CODEC
286 /* Backup is not possible if the page size of the destination is changing
287 ** and a codec is in use.
289 if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
290 rc = SQLITE_READONLY;
293 /* Backup is not possible if the number of bytes of reserve space differ
294 ** between source and destination. If there is a difference, try to
295 ** fix the destination to agree with the source. If that is not possible,
296 ** then the backup cannot proceed.
298 if( nSrcReserve!=nDestReserve ){
299 u32 newPgsz = nSrcPgsz;
300 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
301 if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY;
303 #endif
304 /* END SQLCIPHER */
306 /* This loop runs once for each destination page spanned by the source
307 ** page. For each iteration, variable iOff is set to the byte offset
308 ** of the destination page.
310 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
311 DbPage *pDestPg = 0;
312 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
313 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
314 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
315 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
317 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
318 u8 *zDestData = sqlite3PagerGetData(pDestPg);
319 u8 *zOut = &zDestData[iOff%nDestPgsz];
321 /* Copy the data from the source page into the destination page.
322 ** Then clear the Btree layer MemPage.isInit flag. Both this module
323 ** and the pager code use this trick (clearing the first byte
324 ** of the page 'extra' space to invalidate the Btree layers
325 ** cached parse of the page). MemPage.isInit is marked
326 ** "MUST BE FIRST" for this purpose.
328 memcpy(zOut, zIn, nCopy);
329 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
330 if( iOff==0 && bUpdate==0 ){
331 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
334 sqlite3PagerUnref(pDestPg);
337 return rc;
341 ** If pFile is currently larger than iSize bytes, then truncate it to
342 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
343 ** this function is a no-op.
345 ** Return SQLITE_OK if everything is successful, or an SQLite error
346 ** code if an error occurs.
348 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
349 i64 iCurrent;
350 int rc = sqlite3OsFileSize(pFile, &iCurrent);
351 if( rc==SQLITE_OK && iCurrent>iSize ){
352 rc = sqlite3OsTruncate(pFile, iSize);
354 return rc;
358 ** Register this backup object with the associated source pager for
359 ** callbacks when pages are changed or the cache invalidated.
361 static void attachBackupObject(sqlite3_backup *p){
362 sqlite3_backup **pp;
363 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
364 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
365 p->pNext = *pp;
366 *pp = p;
367 p->isAttached = 1;
371 ** Copy nPage pages from the source b-tree to the destination.
373 int sqlite3_backup_step(sqlite3_backup *p, int nPage){
374 int rc;
375 int destMode; /* Destination journal mode */
376 int pgszSrc = 0; /* Source page size */
377 int pgszDest = 0; /* Destination page size */
379 #ifdef SQLITE_ENABLE_API_ARMOR
380 if( p==0 ) return SQLITE_MISUSE_BKPT;
381 #endif
382 sqlite3_mutex_enter(p->pSrcDb->mutex);
383 sqlite3BtreeEnter(p->pSrc);
384 if( p->pDestDb ){
385 sqlite3_mutex_enter(p->pDestDb->mutex);
388 rc = p->rc;
389 if( !isFatalError(rc) ){
390 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
391 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
392 int ii; /* Iterator variable */
393 int nSrcPage = -1; /* Size of source db in pages */
394 int bCloseTrans = 0; /* True if src db requires unlocking */
396 /* If the source pager is currently in a write-transaction, return
397 ** SQLITE_BUSY immediately.
399 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
400 rc = SQLITE_BUSY;
401 }else{
402 rc = SQLITE_OK;
405 /* If there is no open read-transaction on the source database, open
406 ** one now. If a transaction is opened here, then it will be closed
407 ** before this function exits.
409 if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
410 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
411 bCloseTrans = 1;
414 /* If the destination database has not yet been locked (i.e. if this
415 ** is the first call to backup_step() for the current backup operation),
416 ** try to set its page size to the same as the source database. This
417 ** is especially important on ZipVFS systems, as in that case it is
418 ** not possible to create a database file that uses one page size by
419 ** writing to it with another. */
420 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
421 rc = SQLITE_NOMEM;
424 /* Lock the destination database, if it is not locked already. */
425 if( SQLITE_OK==rc && p->bDestLocked==0
426 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
427 (int*)&p->iDestSchema))
429 p->bDestLocked = 1;
432 /* Do not allow backup if the destination database is in WAL mode
433 ** and the page sizes are different between source and destination */
434 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
435 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
436 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
437 if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
438 rc = SQLITE_READONLY;
441 /* Now that there is a read-lock on the source database, query the
442 ** source pager for the number of pages in the database.
444 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
445 assert( nSrcPage>=0 );
446 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
447 const Pgno iSrcPg = p->iNext; /* Source page number */
448 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
449 DbPage *pSrcPg; /* Source page object */
450 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
451 if( rc==SQLITE_OK ){
452 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
453 sqlite3PagerUnref(pSrcPg);
456 p->iNext++;
458 if( rc==SQLITE_OK ){
459 p->nPagecount = nSrcPage;
460 p->nRemaining = nSrcPage+1-p->iNext;
461 if( p->iNext>(Pgno)nSrcPage ){
462 rc = SQLITE_DONE;
463 }else if( !p->isAttached ){
464 attachBackupObject(p);
468 /* Update the schema version field in the destination database. This
469 ** is to make sure that the schema-version really does change in
470 ** the case where the source and destination databases have the
471 ** same schema version.
473 if( rc==SQLITE_DONE ){
474 if( nSrcPage==0 ){
475 rc = sqlite3BtreeNewDb(p->pDest);
476 nSrcPage = 1;
478 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
479 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
481 if( rc==SQLITE_OK ){
482 if( p->pDestDb ){
483 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
485 if( destMode==PAGER_JOURNALMODE_WAL ){
486 rc = sqlite3BtreeSetVersion(p->pDest, 2);
489 if( rc==SQLITE_OK ){
490 int nDestTruncate;
491 /* Set nDestTruncate to the final number of pages in the destination
492 ** database. The complication here is that the destination page
493 ** size may be different to the source page size.
495 ** If the source page size is smaller than the destination page size,
496 ** round up. In this case the call to sqlite3OsTruncate() below will
497 ** fix the size of the file. However it is important to call
498 ** sqlite3PagerTruncateImage() here so that any pages in the
499 ** destination file that lie beyond the nDestTruncate page mark are
500 ** journalled by PagerCommitPhaseOne() before they are destroyed
501 ** by the file truncation.
503 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
504 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
505 if( pgszSrc<pgszDest ){
506 int ratio = pgszDest/pgszSrc;
507 nDestTruncate = (nSrcPage+ratio-1)/ratio;
508 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
509 nDestTruncate--;
511 }else{
512 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
514 assert( nDestTruncate>0 );
516 if( pgszSrc<pgszDest ){
517 /* If the source page-size is smaller than the destination page-size,
518 ** two extra things may need to happen:
520 ** * The destination may need to be truncated, and
522 ** * Data stored on the pages immediately following the
523 ** pending-byte page in the source database may need to be
524 ** copied into the destination database.
526 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
527 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
528 Pgno iPg;
529 int nDstPage;
530 i64 iOff;
531 i64 iEnd;
533 assert( pFile );
534 assert( nDestTruncate==0
535 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
536 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
537 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
540 /* This block ensures that all data required to recreate the original
541 ** database has been stored in the journal for pDestPager and the
542 ** journal synced to disk. So at this point we may safely modify
543 ** the database file in any way, knowing that if a power failure
544 ** occurs, the original database will be reconstructed from the
545 ** journal file. */
546 sqlite3PagerPagecount(pDestPager, &nDstPage);
547 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
548 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
549 DbPage *pPg;
550 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
551 if( rc==SQLITE_OK ){
552 rc = sqlite3PagerWrite(pPg);
553 sqlite3PagerUnref(pPg);
557 if( rc==SQLITE_OK ){
558 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
561 /* Write the extra pages and truncate the database file as required */
562 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
563 for(
564 iOff=PENDING_BYTE+pgszSrc;
565 rc==SQLITE_OK && iOff<iEnd;
566 iOff+=pgszSrc
568 PgHdr *pSrcPg = 0;
569 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
570 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
571 if( rc==SQLITE_OK ){
572 u8 *zData = sqlite3PagerGetData(pSrcPg);
573 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
575 sqlite3PagerUnref(pSrcPg);
577 if( rc==SQLITE_OK ){
578 rc = backupTruncateFile(pFile, iSize);
581 /* Sync the database file to disk. */
582 if( rc==SQLITE_OK ){
583 rc = sqlite3PagerSync(pDestPager, 0);
585 }else{
586 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
587 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
590 /* Finish committing the transaction to the destination database. */
591 if( SQLITE_OK==rc
592 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
594 rc = SQLITE_DONE;
599 /* If bCloseTrans is true, then this function opened a read transaction
600 ** on the source database. Close the read transaction here. There is
601 ** no need to check the return values of the btree methods here, as
602 ** "committing" a read-only transaction cannot fail.
604 if( bCloseTrans ){
605 TESTONLY( int rc2 );
606 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
607 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
608 assert( rc2==SQLITE_OK );
611 if( rc==SQLITE_IOERR_NOMEM ){
612 rc = SQLITE_NOMEM_BKPT;
614 p->rc = rc;
616 if( p->pDestDb ){
617 sqlite3_mutex_leave(p->pDestDb->mutex);
619 sqlite3BtreeLeave(p->pSrc);
620 sqlite3_mutex_leave(p->pSrcDb->mutex);
621 return rc;
625 ** Release all resources associated with an sqlite3_backup* handle.
627 int sqlite3_backup_finish(sqlite3_backup *p){
628 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
629 sqlite3 *pSrcDb; /* Source database connection */
630 int rc; /* Value to return */
632 /* Enter the mutexes */
633 if( p==0 ) return SQLITE_OK;
634 pSrcDb = p->pSrcDb;
635 sqlite3_mutex_enter(pSrcDb->mutex);
636 sqlite3BtreeEnter(p->pSrc);
637 if( p->pDestDb ){
638 sqlite3_mutex_enter(p->pDestDb->mutex);
641 /* Detach this backup from the source pager. */
642 if( p->pDestDb ){
643 p->pSrc->nBackup--;
645 if( p->isAttached ){
646 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
647 assert( pp!=0 );
648 while( *pp!=p ){
649 pp = &(*pp)->pNext;
650 assert( pp!=0 );
652 *pp = p->pNext;
655 /* If a transaction is still open on the Btree, roll it back. */
656 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
658 /* Set the error code of the destination database handle. */
659 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
660 if( p->pDestDb ){
661 sqlite3Error(p->pDestDb, rc);
663 /* Exit the mutexes and free the backup context structure. */
664 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
666 sqlite3BtreeLeave(p->pSrc);
667 if( p->pDestDb ){
668 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
669 ** call to sqlite3_backup_init() and is destroyed by a call to
670 ** sqlite3_backup_finish(). */
671 sqlite3_free(p);
673 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
674 return rc;
678 ** Return the number of pages still to be backed up as of the most recent
679 ** call to sqlite3_backup_step().
681 int sqlite3_backup_remaining(sqlite3_backup *p){
682 #ifdef SQLITE_ENABLE_API_ARMOR
683 if( p==0 ){
684 (void)SQLITE_MISUSE_BKPT;
685 return 0;
687 #endif
688 return p->nRemaining;
692 ** Return the total number of pages in the source database as of the most
693 ** recent call to sqlite3_backup_step().
695 int sqlite3_backup_pagecount(sqlite3_backup *p){
696 #ifdef SQLITE_ENABLE_API_ARMOR
697 if( p==0 ){
698 (void)SQLITE_MISUSE_BKPT;
699 return 0;
701 #endif
702 return p->nPagecount;
706 ** This function is called after the contents of page iPage of the
707 ** source database have been modified. If page iPage has already been
708 ** copied into the destination database, then the data written to the
709 ** destination is now invalidated. The destination copy of iPage needs
710 ** to be updated with the new data before the backup operation is
711 ** complete.
713 ** It is assumed that the mutex associated with the BtShared object
714 ** corresponding to the source database is held when this function is
715 ** called.
717 static SQLITE_NOINLINE void backupUpdate(
718 sqlite3_backup *p,
719 Pgno iPage,
720 const u8 *aData
722 assert( p!=0 );
724 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
725 if( !isFatalError(p->rc) && iPage<p->iNext ){
726 /* The backup process p has already copied page iPage. But now it
727 ** has been modified by a transaction on the source pager. Copy
728 ** the new data into the backup.
730 int rc;
731 assert( p->pDestDb );
732 sqlite3_mutex_enter(p->pDestDb->mutex);
733 rc = backupOnePage(p, iPage, aData, 1);
734 sqlite3_mutex_leave(p->pDestDb->mutex);
735 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
736 if( rc!=SQLITE_OK ){
737 p->rc = rc;
740 }while( (p = p->pNext)!=0 );
742 void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
743 if( pBackup ) backupUpdate(pBackup, iPage, aData);
747 ** Restart the backup process. This is called when the pager layer
748 ** detects that the database has been modified by an external database
749 ** connection. In this case there is no way of knowing which of the
750 ** pages that have been copied into the destination database are still
751 ** valid and which are not, so the entire process needs to be restarted.
753 ** It is assumed that the mutex associated with the BtShared object
754 ** corresponding to the source database is held when this function is
755 ** called.
757 void sqlite3BackupRestart(sqlite3_backup *pBackup){
758 sqlite3_backup *p; /* Iterator variable */
759 for(p=pBackup; p; p=p->pNext){
760 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
761 p->iNext = 1;
765 #ifndef SQLITE_OMIT_VACUUM
767 ** Copy the complete content of pBtFrom into pBtTo. A transaction
768 ** must be active for both files.
770 ** The size of file pTo may be reduced by this operation. If anything
771 ** goes wrong, the transaction on pTo is rolled back. If successful, the
772 ** transaction is committed before returning.
774 int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
775 int rc;
776 sqlite3_file *pFd; /* File descriptor for database pTo */
777 sqlite3_backup b;
778 sqlite3BtreeEnter(pTo);
779 sqlite3BtreeEnter(pFrom);
781 assert( sqlite3BtreeIsInTrans(pTo) );
782 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
783 if( pFd->pMethods ){
784 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
785 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
786 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
787 if( rc ) goto copy_finished;
790 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
791 ** to 0. This is used by the implementations of sqlite3_backup_step()
792 ** and sqlite3_backup_finish() to detect that they are being called
793 ** from this function, not directly by the user.
795 memset(&b, 0, sizeof(b));
796 b.pSrcDb = pFrom->db;
797 b.pSrc = pFrom;
798 b.pDest = pTo;
799 b.iNext = 1;
801 /* BEGIN SQLCIPHER */
802 #ifdef SQLITE_HAS_CODEC
803 sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
804 #endif
805 /* END SQLCIPHER */
807 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
808 ** file. By passing this as the number of pages to copy to
809 ** sqlite3_backup_step(), we can guarantee that the copy finishes
810 ** within a single call (unless an error occurs). The assert() statement
811 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
812 ** or an error code. */
813 sqlite3_backup_step(&b, 0x7FFFFFFF);
814 assert( b.rc!=SQLITE_OK );
816 rc = sqlite3_backup_finish(&b);
817 if( rc==SQLITE_OK ){
818 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
819 }else{
820 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
823 assert( sqlite3BtreeIsInTrans(pTo)==0 );
824 copy_finished:
825 sqlite3BtreeLeave(pFrom);
826 sqlite3BtreeLeave(pTo);
827 return rc;
829 #endif /* SQLITE_OMIT_VACUUM */