interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / backup.c

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