Merge sqlite-release(3.38.2) into prerelease-integration
[sqlcipher.git] / src / backup.c
blobab4eac337b94e071fe2cc58718d53be987e7b296
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 sqlite3ParseObjectInit(&sParse,pDb);
89 if( sqlite3OpenTempDatabase(&sParse) ){
90 sqlite3ErrorWithMsg(pErrorDb, sParse.rc, "%s", sParse.zErrMsg);
91 rc = SQLITE_ERROR;
93 sqlite3DbFree(pErrorDb, sParse.zErrMsg);
94 sqlite3ParseObjectReset(&sParse);
95 if( rc ){
96 return 0;
100 if( i<0 ){
101 sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
102 return 0;
105 return pDb->aDb[i].pBt;
109 ** Attempt to set the page size of the destination to match the page size
110 ** of the source.
112 static int setDestPgsz(sqlite3_backup *p){
113 int rc;
114 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
115 return rc;
119 ** Check that there is no open read-transaction on the b-tree passed as the
120 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
121 ** is an open read-transaction, return SQLITE_ERROR and leave an error
122 ** message in database handle db.
124 static int checkReadTransaction(sqlite3 *db, Btree *p){
125 if( sqlite3BtreeTxnState(p)!=SQLITE_TXN_NONE ){
126 sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
127 return SQLITE_ERROR;
129 return SQLITE_OK;
133 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
134 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
135 ** a pointer to the new sqlite3_backup object.
137 ** If an error occurs, NULL is returned and an error code and error message
138 ** stored in database handle pDestDb.
140 sqlite3_backup *sqlite3_backup_init(
141 sqlite3* pDestDb, /* Database to write to */
142 const char *zDestDb, /* Name of database within pDestDb */
143 sqlite3* pSrcDb, /* Database connection to read from */
144 const char *zSrcDb /* Name of database within pSrcDb */
146 sqlite3_backup *p; /* Value to return */
148 #ifdef SQLITE_ENABLE_API_ARMOR
149 if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
150 (void)SQLITE_MISUSE_BKPT;
151 return 0;
153 #endif
155 /* BEGIN SQLCIPHER */
156 #ifdef SQLITE_HAS_CODEC
158 extern int sqlcipher_find_db_index(sqlite3*, const char*);
159 extern void sqlcipherCodecGetKey(sqlite3*, int, void**, int*);
160 int srcNKey, destNKey;
161 void *zKey;
163 sqlcipherCodecGetKey(pSrcDb, sqlcipher_find_db_index(pSrcDb, zSrcDb), &zKey, &srcNKey);
164 sqlcipherCodecGetKey(pDestDb, sqlcipher_find_db_index(pDestDb, zDestDb), &zKey, &destNKey);
165 zKey = NULL;
167 /* either both databases must be plaintext, or both must be encrypted */
168 if((srcNKey == 0 && destNKey > 0) || (srcNKey > 0 && destNKey == 0)) {
169 sqlite3ErrorWithMsg(pDestDb, SQLITE_ERROR, "backup is not supported with encrypted databases");
170 return NULL;
173 #endif
174 /* END SQLCIPHER */
176 /* Lock the source database handle. The destination database
177 ** handle is not locked in this routine, but it is locked in
178 ** sqlite3_backup_step(). The user is required to ensure that no
179 ** other thread accesses the destination handle for the duration
180 ** of the backup operation. Any attempt to use the destination
181 ** database connection while a backup is in progress may cause
182 ** a malfunction or a deadlock.
184 sqlite3_mutex_enter(pSrcDb->mutex);
185 sqlite3_mutex_enter(pDestDb->mutex);
187 if( pSrcDb==pDestDb ){
188 sqlite3ErrorWithMsg(
189 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
191 p = 0;
192 }else {
193 /* Allocate space for a new sqlite3_backup object...
194 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
195 ** call to sqlite3_backup_init() and is destroyed by a call to
196 ** sqlite3_backup_finish(). */
197 p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
198 if( !p ){
199 sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
203 /* If the allocation succeeded, populate the new object. */
204 if( p ){
205 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
206 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
207 p->pDestDb = pDestDb;
208 p->pSrcDb = pSrcDb;
209 p->iNext = 1;
210 p->isAttached = 0;
212 if( 0==p->pSrc || 0==p->pDest
213 || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
215 /* One (or both) of the named databases did not exist or an OOM
216 ** error was hit. Or there is a transaction open on the destination
217 ** database. The error has already been written into the pDestDb
218 ** handle. All that is left to do here is free the sqlite3_backup
219 ** structure. */
220 sqlite3_free(p);
221 p = 0;
224 if( p ){
225 p->pSrc->nBackup++;
228 sqlite3_mutex_leave(pDestDb->mutex);
229 sqlite3_mutex_leave(pSrcDb->mutex);
230 return p;
234 ** Argument rc is an SQLite error code. Return true if this error is
235 ** considered fatal if encountered during a backup operation. All errors
236 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
238 static int isFatalError(int rc){
239 return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
243 ** Parameter zSrcData points to a buffer containing the data for
244 ** page iSrcPg from the source database. Copy this data into the
245 ** destination database.
247 static int backupOnePage(
248 sqlite3_backup *p, /* Backup handle */
249 Pgno iSrcPg, /* Source database page to backup */
250 const u8 *zSrcData, /* Source database page data */
251 int bUpdate /* True for an update, false otherwise */
253 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
254 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
255 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
256 const int nCopy = MIN(nSrcPgsz, nDestPgsz);
257 const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
258 /* BEGIN SQLCIPHER */
259 #ifdef SQLITE_HAS_CODEC
260 extern void *sqlcipherPagerGetCodec(Pager*);
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 && sqlcipherPagerGetCodec(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 && SQLITE_TXN_NONE==sqlite3BtreeTxnState(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( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
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( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
824 copy_finished:
825 sqlite3BtreeLeave(pFrom);
826 sqlite3BtreeLeave(pTo);
827 return rc;
829 #endif /* SQLITE_OMIT_VACUUM */