Replaces use of deprecated WINAPI_FAMILY_APP macro with WINAPI_FAMILY_PC_APP
[sqlcipher.git] / src / backup.c
blobb73ce76bdab4a650a341c2ab0404ce95aa39c284
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 );
276 assert( nSrcPgsz==nDestPgsz || sqlite3PagerIsMemdb(pDestPager)==0 );
278 /* BEGIN SQLCIPHER */
279 #ifdef SQLITE_HAS_CODEC
280 /* Backup is not possible if the page size of the destination is changing
281 ** and a codec is in use.
283 if( nSrcPgsz!=nDestPgsz && sqlcipherPagerGetCodec(pDestPager)!=0 ){
284 rc = SQLITE_READONLY;
287 /* Backup is not possible if the number of bytes of reserve space differ
288 ** between source and destination. If there is a difference, try to
289 ** fix the destination to agree with the source. If that is not possible,
290 ** then the backup cannot proceed.
292 if( nSrcReserve!=nDestReserve ){
293 u32 newPgsz = nSrcPgsz;
294 rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
295 if( rc==SQLITE_OK && newPgsz!=(u32)nSrcPgsz ) rc = SQLITE_READONLY;
297 #endif
298 /* END SQLCIPHER */
300 /* This loop runs once for each destination page spanned by the source
301 ** page. For each iteration, variable iOff is set to the byte offset
302 ** of the destination page.
304 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
305 DbPage *pDestPg = 0;
306 Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
307 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
308 if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
309 && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
311 const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
312 u8 *zDestData = sqlite3PagerGetData(pDestPg);
313 u8 *zOut = &zDestData[iOff%nDestPgsz];
315 /* Copy the data from the source page into the destination page.
316 ** Then clear the Btree layer MemPage.isInit flag. Both this module
317 ** and the pager code use this trick (clearing the first byte
318 ** of the page 'extra' space to invalidate the Btree layers
319 ** cached parse of the page). MemPage.isInit is marked
320 ** "MUST BE FIRST" for this purpose.
322 memcpy(zOut, zIn, nCopy);
323 ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
324 if( iOff==0 && bUpdate==0 ){
325 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
328 sqlite3PagerUnref(pDestPg);
331 return rc;
335 ** If pFile is currently larger than iSize bytes, then truncate it to
336 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
337 ** this function is a no-op.
339 ** Return SQLITE_OK if everything is successful, or an SQLite error
340 ** code if an error occurs.
342 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
343 i64 iCurrent;
344 int rc = sqlite3OsFileSize(pFile, &iCurrent);
345 if( rc==SQLITE_OK && iCurrent>iSize ){
346 rc = sqlite3OsTruncate(pFile, iSize);
348 return rc;
352 ** Register this backup object with the associated source pager for
353 ** callbacks when pages are changed or the cache invalidated.
355 static void attachBackupObject(sqlite3_backup *p){
356 sqlite3_backup **pp;
357 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
358 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
359 p->pNext = *pp;
360 *pp = p;
361 p->isAttached = 1;
365 ** Copy nPage pages from the source b-tree to the destination.
367 int sqlite3_backup_step(sqlite3_backup *p, int nPage){
368 int rc;
369 int destMode; /* Destination journal mode */
370 int pgszSrc = 0; /* Source page size */
371 int pgszDest = 0; /* Destination page size */
373 #ifdef SQLITE_ENABLE_API_ARMOR
374 if( p==0 ) return SQLITE_MISUSE_BKPT;
375 #endif
376 sqlite3_mutex_enter(p->pSrcDb->mutex);
377 sqlite3BtreeEnter(p->pSrc);
378 if( p->pDestDb ){
379 sqlite3_mutex_enter(p->pDestDb->mutex);
382 rc = p->rc;
383 if( !isFatalError(rc) ){
384 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
385 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
386 int ii; /* Iterator variable */
387 int nSrcPage = -1; /* Size of source db in pages */
388 int bCloseTrans = 0; /* True if src db requires unlocking */
390 /* If the source pager is currently in a write-transaction, return
391 ** SQLITE_BUSY immediately.
393 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
394 rc = SQLITE_BUSY;
395 }else{
396 rc = SQLITE_OK;
399 /* If there is no open read-transaction on the source database, open
400 ** one now. If a transaction is opened here, then it will be closed
401 ** before this function exits.
403 if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
404 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
405 bCloseTrans = 1;
408 /* If the destination database has not yet been locked (i.e. if this
409 ** is the first call to backup_step() for the current backup operation),
410 ** try to set its page size to the same as the source database. This
411 ** is especially important on ZipVFS systems, as in that case it is
412 ** not possible to create a database file that uses one page size by
413 ** writing to it with another. */
414 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
415 rc = SQLITE_NOMEM;
418 /* Lock the destination database, if it is not locked already. */
419 if( SQLITE_OK==rc && p->bDestLocked==0
420 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
421 (int*)&p->iDestSchema))
423 p->bDestLocked = 1;
426 /* Do not allow backup if the destination database is in WAL mode
427 ** and the page sizes are different between source and destination */
428 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
429 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
430 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
431 if( SQLITE_OK==rc
432 && (destMode==PAGER_JOURNALMODE_WAL || sqlite3PagerIsMemdb(pDestPager))
433 && pgszSrc!=pgszDest
435 rc = SQLITE_READONLY;
438 /* Now that there is a read-lock on the source database, query the
439 ** source pager for the number of pages in the database.
441 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
442 assert( nSrcPage>=0 );
443 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
444 const Pgno iSrcPg = p->iNext; /* Source page number */
445 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
446 DbPage *pSrcPg; /* Source page object */
447 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
448 if( rc==SQLITE_OK ){
449 rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
450 sqlite3PagerUnref(pSrcPg);
453 p->iNext++;
455 if( rc==SQLITE_OK ){
456 p->nPagecount = nSrcPage;
457 p->nRemaining = nSrcPage+1-p->iNext;
458 if( p->iNext>(Pgno)nSrcPage ){
459 rc = SQLITE_DONE;
460 }else if( !p->isAttached ){
461 attachBackupObject(p);
465 /* Update the schema version field in the destination database. This
466 ** is to make sure that the schema-version really does change in
467 ** the case where the source and destination databases have the
468 ** same schema version.
470 if( rc==SQLITE_DONE ){
471 if( nSrcPage==0 ){
472 rc = sqlite3BtreeNewDb(p->pDest);
473 nSrcPage = 1;
475 if( rc==SQLITE_OK || rc==SQLITE_DONE ){
476 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
478 if( rc==SQLITE_OK ){
479 if( p->pDestDb ){
480 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
482 if( destMode==PAGER_JOURNALMODE_WAL ){
483 rc = sqlite3BtreeSetVersion(p->pDest, 2);
486 if( rc==SQLITE_OK ){
487 int nDestTruncate;
488 /* Set nDestTruncate to the final number of pages in the destination
489 ** database. The complication here is that the destination page
490 ** size may be different to the source page size.
492 ** If the source page size is smaller than the destination page size,
493 ** round up. In this case the call to sqlite3OsTruncate() below will
494 ** fix the size of the file. However it is important to call
495 ** sqlite3PagerTruncateImage() here so that any pages in the
496 ** destination file that lie beyond the nDestTruncate page mark are
497 ** journalled by PagerCommitPhaseOne() before they are destroyed
498 ** by the file truncation.
500 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
501 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
502 if( pgszSrc<pgszDest ){
503 int ratio = pgszDest/pgszSrc;
504 nDestTruncate = (nSrcPage+ratio-1)/ratio;
505 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
506 nDestTruncate--;
508 }else{
509 nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
511 assert( nDestTruncate>0 );
513 if( pgszSrc<pgszDest ){
514 /* If the source page-size is smaller than the destination page-size,
515 ** two extra things may need to happen:
517 ** * The destination may need to be truncated, and
519 ** * Data stored on the pages immediately following the
520 ** pending-byte page in the source database may need to be
521 ** copied into the destination database.
523 const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
524 sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
525 Pgno iPg;
526 int nDstPage;
527 i64 iOff;
528 i64 iEnd;
530 assert( pFile );
531 assert( nDestTruncate==0
532 || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
533 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
534 && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
537 /* This block ensures that all data required to recreate the original
538 ** database has been stored in the journal for pDestPager and the
539 ** journal synced to disk. So at this point we may safely modify
540 ** the database file in any way, knowing that if a power failure
541 ** occurs, the original database will be reconstructed from the
542 ** journal file. */
543 sqlite3PagerPagecount(pDestPager, &nDstPage);
544 for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
545 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
546 DbPage *pPg;
547 rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
548 if( rc==SQLITE_OK ){
549 rc = sqlite3PagerWrite(pPg);
550 sqlite3PagerUnref(pPg);
554 if( rc==SQLITE_OK ){
555 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
558 /* Write the extra pages and truncate the database file as required */
559 iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
560 for(
561 iOff=PENDING_BYTE+pgszSrc;
562 rc==SQLITE_OK && iOff<iEnd;
563 iOff+=pgszSrc
565 PgHdr *pSrcPg = 0;
566 const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
567 rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
568 if( rc==SQLITE_OK ){
569 u8 *zData = sqlite3PagerGetData(pSrcPg);
570 rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
572 sqlite3PagerUnref(pSrcPg);
574 if( rc==SQLITE_OK ){
575 rc = backupTruncateFile(pFile, iSize);
578 /* Sync the database file to disk. */
579 if( rc==SQLITE_OK ){
580 rc = sqlite3PagerSync(pDestPager, 0);
582 }else{
583 sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
584 rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
587 /* Finish committing the transaction to the destination database. */
588 if( SQLITE_OK==rc
589 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
591 rc = SQLITE_DONE;
596 /* If bCloseTrans is true, then this function opened a read transaction
597 ** on the source database. Close the read transaction here. There is
598 ** no need to check the return values of the btree methods here, as
599 ** "committing" a read-only transaction cannot fail.
601 if( bCloseTrans ){
602 TESTONLY( int rc2 );
603 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
604 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
605 assert( rc2==SQLITE_OK );
608 if( rc==SQLITE_IOERR_NOMEM ){
609 rc = SQLITE_NOMEM_BKPT;
611 p->rc = rc;
613 if( p->pDestDb ){
614 sqlite3_mutex_leave(p->pDestDb->mutex);
616 sqlite3BtreeLeave(p->pSrc);
617 sqlite3_mutex_leave(p->pSrcDb->mutex);
618 return rc;
622 ** Release all resources associated with an sqlite3_backup* handle.
624 int sqlite3_backup_finish(sqlite3_backup *p){
625 sqlite3_backup **pp; /* Ptr to head of pagers backup list */
626 sqlite3 *pSrcDb; /* Source database connection */
627 int rc; /* Value to return */
629 /* Enter the mutexes */
630 if( p==0 ) return SQLITE_OK;
631 pSrcDb = p->pSrcDb;
632 sqlite3_mutex_enter(pSrcDb->mutex);
633 sqlite3BtreeEnter(p->pSrc);
634 if( p->pDestDb ){
635 sqlite3_mutex_enter(p->pDestDb->mutex);
638 /* Detach this backup from the source pager. */
639 if( p->pDestDb ){
640 p->pSrc->nBackup--;
642 if( p->isAttached ){
643 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
644 assert( pp!=0 );
645 while( *pp!=p ){
646 pp = &(*pp)->pNext;
647 assert( pp!=0 );
649 *pp = p->pNext;
652 /* If a transaction is still open on the Btree, roll it back. */
653 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
655 /* Set the error code of the destination database handle. */
656 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
657 if( p->pDestDb ){
658 sqlite3Error(p->pDestDb, rc);
660 /* Exit the mutexes and free the backup context structure. */
661 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
663 sqlite3BtreeLeave(p->pSrc);
664 if( p->pDestDb ){
665 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
666 ** call to sqlite3_backup_init() and is destroyed by a call to
667 ** sqlite3_backup_finish(). */
668 sqlite3_free(p);
670 sqlite3LeaveMutexAndCloseZombie(pSrcDb);
671 return rc;
675 ** Return the number of pages still to be backed up as of the most recent
676 ** call to sqlite3_backup_step().
678 int sqlite3_backup_remaining(sqlite3_backup *p){
679 #ifdef SQLITE_ENABLE_API_ARMOR
680 if( p==0 ){
681 (void)SQLITE_MISUSE_BKPT;
682 return 0;
684 #endif
685 return p->nRemaining;
689 ** Return the total number of pages in the source database as of the most
690 ** recent call to sqlite3_backup_step().
692 int sqlite3_backup_pagecount(sqlite3_backup *p){
693 #ifdef SQLITE_ENABLE_API_ARMOR
694 if( p==0 ){
695 (void)SQLITE_MISUSE_BKPT;
696 return 0;
698 #endif
699 return p->nPagecount;
703 ** This function is called after the contents of page iPage of the
704 ** source database have been modified. If page iPage has already been
705 ** copied into the destination database, then the data written to the
706 ** destination is now invalidated. The destination copy of iPage needs
707 ** to be updated with the new data before the backup operation is
708 ** complete.
710 ** It is assumed that the mutex associated with the BtShared object
711 ** corresponding to the source database is held when this function is
712 ** called.
714 static SQLITE_NOINLINE void backupUpdate(
715 sqlite3_backup *p,
716 Pgno iPage,
717 const u8 *aData
719 assert( p!=0 );
721 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
722 if( !isFatalError(p->rc) && iPage<p->iNext ){
723 /* The backup process p has already copied page iPage. But now it
724 ** has been modified by a transaction on the source pager. Copy
725 ** the new data into the backup.
727 int rc;
728 assert( p->pDestDb );
729 sqlite3_mutex_enter(p->pDestDb->mutex);
730 rc = backupOnePage(p, iPage, aData, 1);
731 sqlite3_mutex_leave(p->pDestDb->mutex);
732 assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
733 if( rc!=SQLITE_OK ){
734 p->rc = rc;
737 }while( (p = p->pNext)!=0 );
739 void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
740 if( pBackup ) backupUpdate(pBackup, iPage, aData);
744 ** Restart the backup process. This is called when the pager layer
745 ** detects that the database has been modified by an external database
746 ** connection. In this case there is no way of knowing which of the
747 ** pages that have been copied into the destination database are still
748 ** valid and which are not, so the entire process needs to be restarted.
750 ** It is assumed that the mutex associated with the BtShared object
751 ** corresponding to the source database is held when this function is
752 ** called.
754 void sqlite3BackupRestart(sqlite3_backup *pBackup){
755 sqlite3_backup *p; /* Iterator variable */
756 for(p=pBackup; p; p=p->pNext){
757 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
758 p->iNext = 1;
762 #ifndef SQLITE_OMIT_VACUUM
764 ** Copy the complete content of pBtFrom into pBtTo. A transaction
765 ** must be active for both files.
767 ** The size of file pTo may be reduced by this operation. If anything
768 ** goes wrong, the transaction on pTo is rolled back. If successful, the
769 ** transaction is committed before returning.
771 int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
772 int rc;
773 sqlite3_file *pFd; /* File descriptor for database pTo */
774 sqlite3_backup b;
775 sqlite3BtreeEnter(pTo);
776 sqlite3BtreeEnter(pFrom);
778 assert( sqlite3BtreeTxnState(pTo)==SQLITE_TXN_WRITE );
779 pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
780 if( pFd->pMethods ){
781 i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
782 rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
783 if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
784 if( rc ) goto copy_finished;
787 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
788 ** to 0. This is used by the implementations of sqlite3_backup_step()
789 ** and sqlite3_backup_finish() to detect that they are being called
790 ** from this function, not directly by the user.
792 memset(&b, 0, sizeof(b));
793 b.pSrcDb = pFrom->db;
794 b.pSrc = pFrom;
795 b.pDest = pTo;
796 b.iNext = 1;
798 /* BEGIN SQLCIPHER */
799 #ifdef SQLITE_HAS_CODEC
800 sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
801 #endif
802 /* END SQLCIPHER */
804 /* 0x7FFFFFFF is the hard limit for the number of pages in a database
805 ** file. By passing this as the number of pages to copy to
806 ** sqlite3_backup_step(), we can guarantee that the copy finishes
807 ** within a single call (unless an error occurs). The assert() statement
808 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
809 ** or an error code. */
810 sqlite3_backup_step(&b, 0x7FFFFFFF);
811 assert( b.rc!=SQLITE_OK );
813 rc = sqlite3_backup_finish(&b);
814 if( rc==SQLITE_OK ){
815 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
816 }else{
817 sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
820 assert( sqlite3BtreeTxnState(pTo)!=SQLITE_TXN_WRITE );
821 copy_finished:
822 sqlite3BtreeLeave(pFrom);
823 sqlite3BtreeLeave(pTo);
824 return rc;
826 #endif /* SQLITE_OMIT_VACUUM */