Commit 2bd051da by Paul Fitzpatrick Committed by Kewde

add backup api that can be run incrementally (#1116)

This exposes the sqlite3 backup api as described at https://sqlite.org/backup.html.

This implementation draws on https://github.com/mapbox/node-sqlite3/pull/883,
extending it to create a backup object that can be used in the background,
without leaving the database locked for an extended period of time.  This is
crucial for making backups of large live databases in a non-disruptive manner.
Example usage:

```
var db = new sqlite3.Database('live.db');
var backup = db.backup('backup.db');
...
// in event loop, move backup forward when we have time.
if (backup.idle) { backup.step(NPAGES); }
if (backup.completed) { /* success! backup made */  }
if (backup.failed)    { /* sadness! backup broke */ }
// do other work in event loop - fine to modify live.db
...
```

Here is how sqlite's backup api is exposed:

 * `sqlite3_backup_init`: This is implemented as `db.backup(filename, [callback])`
   or `db.backup(filename, destDbName, sourceDbName, filenameIsDest, [callback])`.
 * `sqlite3_backup_step`: This is implemented as `backup.step(pages, [callback])`.
 * `sqlite3_backup_finish`: This is implemented as `backup.finish([callback])`.
 * `sqlite3_backup_remaining`: This is implemented as a `backup.remaining` getter.
 * `sqlite3_backup_pagecount`: This is implemented as a `backup.pageCount` getter.

Some conveniences are added in the node api.

There are the following read-only properties:
 * `backup.completed` is set to `true` when the backup succeeeds.
 * `backup.failed` is set to `true` when the backup has a fatal error.
 * `backup.idle` is set to `true` when no operation is currently in progress or
   queued for the backup.
 * `backup.remaining` is an integer with the remaining number of pages after the
   last call to `backup.step` (-1 if `step` not yet called).
 * `backup.pageCount` is an integer with the total number of pages measured during
   the last call to `backup.step` (-1 if `step` not yet called).

There is the following writable property:
 * `backup.retryErrors`: an array of sqlite3 error codes that are treated as
   non-fatal - meaning, if they occur, backup.failed is not set, and the backup
   may continue.  By default, this is `[sqlite3.BUSY, sqlite3.LOCKED]`.

The `db.backup(filename, [callback])` shorthand is sufficient for making a
backup of a database opened by node-sqlite3.  If using attached or temporary
databases, or moving data in the opposite direction, the more complete
(but daunting) `db.backup(filename, destDbName, sourceDbName, filenameIsDest, [callback])`
signature is provided.

A backup will finish automatically when it succeeds or a fatal error
occurs, meaning it is not necessary to call `db.finish()`.
By default, SQLITE_LOCKED and SQLITE_BUSY errors are not treated as
failures, and the backup will continue if they occur.  The set of errors
that are tolerated can be controlled by setting `backup.retryErrors`.
To disable automatic finishing and stick strictly to sqlite's raw api,
set `backup.retryErrors` to `[]`.  In that case, it is necessary to call
`backup.finish()`.

In the same way as node-sqlite3 databases and statements, backup methods
can be called safely without callbacks, due to an internal call queue.  So
for example this naive code will correctly back up a db, if there are
no errors:
```
var backup = db.backup('backup.db');
backup.step(-1);
backup.finish();
```
parent 4a8b4bdc
...@@ -32,6 +32,7 @@ ...@@ -32,6 +32,7 @@
] ]
], ],
"sources": [ "sources": [
"src/backup.cc",
"src/database.cc", "src/database.cc",
"src/node_sqlite3.cc", "src/node_sqlite3.cc",
"src/statement.cc" "src/statement.cc"
......
...@@ -59,9 +59,11 @@ sqlite3.cached = { ...@@ -59,9 +59,11 @@ sqlite3.cached = {
var Database = sqlite3.Database; var Database = sqlite3.Database;
var Statement = sqlite3.Statement; var Statement = sqlite3.Statement;
var Backup = sqlite3.Backup;
inherits(Database, EventEmitter); inherits(Database, EventEmitter);
inherits(Statement, EventEmitter); inherits(Statement, EventEmitter);
inherits(Backup, EventEmitter);
// Database#prepare(sql, [bind1, bind2, ...], [callback]) // Database#prepare(sql, [bind1, bind2, ...], [callback])
Database.prototype.prepare = normalizeMethod(function(statement, params) { Database.prototype.prepare = normalizeMethod(function(statement, params) {
...@@ -99,6 +101,23 @@ Database.prototype.map = normalizeMethod(function(statement, params) { ...@@ -99,6 +101,23 @@ Database.prototype.map = normalizeMethod(function(statement, params) {
return this; return this;
}); });
// Database#backup(filename, [callback])
// Database#backup(filename, destName, sourceName, filenameIsDest, [callback])
Database.prototype.backup = function() {
var backup;
if (arguments.length <= 2) {
// By default, we write the main database out to the main database of the named file.
// This is the most likely use of the backup api.
backup = new Backup(this, arguments[0], 'main', 'main', true, arguments[1]);
} else {
// Otherwise, give the user full control over the sqlite3_backup_init arguments.
backup = new Backup(this, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]);
}
// Per the sqlite docs, exclude the following errors as non-fatal by default.
backup.retryErrors = [sqlite3.BUSY, sqlite3.LOCKED];
return backup;
};
Statement.prototype.map = function() { Statement.prototype.map = function() {
var params = Array.prototype.slice.call(arguments); var params = Array.prototype.slice.call(arguments);
var callback = params.pop(); var callback = params.pop();
......
This diff is collapsed. Click to expand it.
#ifndef NODE_SQLITE3_SRC_BACKUP_H
#define NODE_SQLITE3_SRC_BACKUP_H
#include "database.h"
#include <string>
#include <queue>
#include <set>
#include <sqlite3.h>
#include <nan.h>
using namespace v8;
using namespace node;
namespace node_sqlite3 {
/**
*
* A class for managing an sqlite3_backup object. For consistency
* with other node-sqlite3 classes, it maintains an internal queue
* of calls.
*
* Intended usage from node:
*
* var db = new sqlite3.Database('live.db');
* var backup = db.backup('backup.db');
* ...
* // in event loop, move backup forward when we have time.
* if (backup.idle) { backup.step(NPAGES); }
* if (backup.completed) { ... success ... }
* if (backup.failed) { ... sadness ... }
* // do other work in event loop - fine to modify live.db
* ...
*
* Here is how sqlite's backup api is exposed:
*
* - `sqlite3_backup_init`: This is implemented as
* `db.backup(filename, [callback])` or
* `db.backup(filename, destDbName, sourceDbName, filenameIsDest, [callback])`.
* - `sqlite3_backup_step`: `backup.step(pages, [callback])`.
* - `sqlite3_backup_finish`: `backup.finish([callback])`.
* - `sqlite3_backup_remaining`: `backup.remaining`.
* - `sqlite3_backup_pagecount`: `backup.pageCount`.
*
* There are the following read-only properties:
*
* - `backup.completed` is set to `true` when the backup
* succeeeds.
* - `backup.failed` is set to `true` when the backup
* has a fatal error.
* - `backup.idle` is set to `true` when no operation
* is currently in progress or queued for the backup.
* - `backup.remaining` is an integer with the remaining
* number of pages after the last call to `backup.step`
* (-1 if `step` not yet called).
* - `backup.pageCount` is an integer with the total number
* of pages measured during the last call to `backup.step`
* (-1 if `step` not yet called).
*
* There is the following writable property:
*
* - `backup.retryErrors`: an array of sqlite3 error codes
* that are treated as non-fatal - meaning, if they occur,
* backup.failed is not set, and the backup may continue.
* By default, this is `[sqlite3.BUSY, sqlite3.LOCKED]`.
*
* The `db.backup(filename, [callback])` shorthand is sufficient
* for making a backup of a database opened by node-sqlite3. If
* using attached or temporary databases, or moving data in the
* opposite direction, the more complete (but daunting)
* `db.backup(filename, destDbName, sourceDbName, filenameIsDest, [callback])`
* signature is provided.
*
* A backup will finish automatically when it succeeds or a fatal
* error occurs, meaning it is not necessary to call `db.finish()`.
* By default, SQLITE_LOCKED and SQLITE_BUSY errors are not
* treated as failures, and the backup will continue if they
* occur. The set of errors that are tolerated can be controlled
* by setting `backup.retryErrors`. To disable automatic
* finishing and stick strictly to sqlite's raw api, set
* `backup.retryErrors` to `[]`. In that case, it is necessary
* to call `backup.finish()`.
*
* In the same way as node-sqlite3 databases and statements,
* backup methods can be called safely without callbacks, due
* to an internal call queue. So for example this naive code
* will correctly back up a db, if there are no errors:
*
* var backup = db.backup('backup.db');
* backup.step(-1);
* backup.finish();
*
*/
class Backup : public Nan::ObjectWrap {
public:
static Nan::Persistent<FunctionTemplate> constructor_template;
static NAN_MODULE_INIT(Init);
static NAN_METHOD(New);
struct Baton {
uv_work_t request;
Backup* backup;
Nan::Persistent<Function> callback;
Baton(Backup* backup_, Local<Function> cb_) : backup(backup_) {
backup->Ref();
request.data = this;
callback.Reset(cb_);
}
virtual ~Baton() {
backup->Unref();
callback.Reset();
}
};
struct InitializeBaton : Database::Baton {
Backup* backup;
std::string filename;
std::string sourceName;
std::string destName;
bool filenameIsDest;
InitializeBaton(Database* db_, Local<Function> cb_, Backup* backup_) :
Baton(db_, cb_), backup(backup_), filenameIsDest(true) {
backup->Ref();
}
virtual ~InitializeBaton() {
backup->Unref();
if (!db->IsOpen() && db->IsLocked()) {
// The database handle was closed before the backup could be opened.
backup->FinishAll();
}
}
};
struct StepBaton : Baton {
int pages;
std::set<int> retryErrorsSet;
StepBaton(Backup* backup_, Local<Function> cb_, int pages_) :
Baton(backup_, cb_), pages(pages_) {}
};
typedef void (*Work_Callback)(Baton* baton);
struct Call {
Call(Work_Callback cb_, Baton* baton_) : callback(cb_), baton(baton_) {};
Work_Callback callback;
Baton* baton;
};
Backup(Database* db_) : Nan::ObjectWrap(),
db(db_),
_handle(NULL),
_otherDb(NULL),
_destDb(NULL),
inited(false),
locked(true),
completed(false),
failed(false),
remaining(-1),
pageCount(-1),
finished(false) {
db->Ref();
}
~Backup() {
if (!finished) {
FinishAll();
}
retryErrors.Reset();
}
WORK_DEFINITION(Step);
WORK_DEFINITION(Finish);
static NAN_GETTER(IdleGetter);
static NAN_GETTER(CompletedGetter);
static NAN_GETTER(FailedGetter);
static NAN_GETTER(PageCountGetter);
static NAN_GETTER(RemainingGetter);
static NAN_GETTER(FatalErrorGetter);
static NAN_GETTER(RetryErrorGetter);
static NAN_SETTER(FatalErrorSetter);
static NAN_SETTER(RetryErrorSetter);
protected:
static void Work_BeginInitialize(Database::Baton* baton);
static void Work_Initialize(uv_work_t* req);
static void Work_AfterInitialize(uv_work_t* req);
void Schedule(Work_Callback callback, Baton* baton);
void Process();
void CleanQueue();
template <class T> static void Error(T* baton);
void FinishAll();
void FinishSqlite();
void GetRetryErrors(std::set<int>& retryErrorsSet);
Database* db;
sqlite3_backup* _handle;
sqlite3* _otherDb;
sqlite3* _destDb;
int status;
std::string message;
bool inited;
bool locked;
bool completed;
bool failed;
int remaining;
int pageCount;
bool finished;
std::queue<Call*> queue;
Nan::Persistent<Array> retryErrors;
};
}
#endif
...@@ -98,6 +98,7 @@ public: ...@@ -98,6 +98,7 @@ public:
typedef Async<UpdateInfo, Database> AsyncUpdate; typedef Async<UpdateInfo, Database> AsyncUpdate;
friend class Statement; friend class Statement;
friend class Backup;
protected: protected:
Database() : Nan::ObjectWrap(), Database() : Nan::ObjectWrap(),
......
...@@ -31,6 +31,11 @@ const char* sqlite_authorizer_string(int type); ...@@ -31,6 +31,11 @@ const char* sqlite_authorizer_string(int type);
} \ } \
Nan::Utf8String var(info[i]); Nan::Utf8String var(info[i]);
#define REQUIRE_ARGUMENT_INTEGER(i, var) \
if (info.Length() <= (i) || !info[i]->IsInt32()) { \
return Nan::ThrowTypeError("Argument " #i " must be an integer"); \
} \
int var(Nan::To<int32_t>(info[i]).FromJust());
#define OPTIONAL_ARGUMENT_FUNCTION(i, var) \ #define OPTIONAL_ARGUMENT_FUNCTION(i, var) \
Local<Function> var; \ Local<Function> var; \
...@@ -74,6 +79,10 @@ const char* sqlite_authorizer_string(int type); ...@@ -74,6 +79,10 @@ const char* sqlite_authorizer_string(int type);
Nan::SetAccessor((target)->InstanceTemplate(), \ Nan::SetAccessor((target)->InstanceTemplate(), \
Nan::New(name).ToLocalChecked(), (function)); Nan::New(name).ToLocalChecked(), (function));
#define NODE_SET_SETTER(target, name, getter, setter) \
Nan::SetAccessor((target)->InstanceTemplate(), \
Nan::New(name).ToLocalChecked(), getter, setter);
#define GET_STRING(source, name, property) \ #define GET_STRING(source, name, property) \
Nan::Utf8String name(Nan::Get(source, \ Nan::Utf8String name(Nan::Get(source, \
Nan::New(prop).ToLocalChecked()).ToLocalChecked()); Nan::New(prop).ToLocalChecked()).ToLocalChecked());
...@@ -134,6 +143,32 @@ const char* sqlite_authorizer_string(int type); ...@@ -134,6 +143,32 @@ const char* sqlite_authorizer_string(int type);
stmt->db->Process(); \ stmt->db->Process(); \
delete baton; delete baton;
#define BACKUP_BEGIN(type) \
assert(baton); \
assert(baton->backup); \
assert(!baton->backup->locked); \
assert(!baton->backup->finished); \
assert(baton->backup->inited); \
baton->backup->locked = true; \
baton->backup->db->pending++; \
int status = uv_queue_work(uv_default_loop(), \
&baton->request, \
Work_##type, reinterpret_cast<uv_after_work_cb>(Work_After##type)); \
assert(status == 0);
#define BACKUP_INIT(type) \
type* baton = static_cast<type*>(req->data); \
Backup* backup = baton->backup;
#define BACKUP_END() \
assert(backup->locked); \
assert(backup->db->pending); \
backup->locked = false; \
backup->db->pending--; \
backup->Process(); \
backup->db->Process(); \
delete baton;
#define DELETE_FIELD(field) \ #define DELETE_FIELD(field) \
if (field != NULL) { \ if (field != NULL) { \
switch ((field)->type) { \ switch ((field)->type) { \
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
#include "macros.h" #include "macros.h"
#include "database.h" #include "database.h"
#include "statement.h" #include "statement.h"
#include "backup.h"
using namespace node_sqlite3; using namespace node_sqlite3;
...@@ -17,6 +18,7 @@ NAN_MODULE_INIT(RegisterModule) { ...@@ -17,6 +18,7 @@ NAN_MODULE_INIT(RegisterModule) {
Database::Init(target); Database::Init(target);
Statement::Init(target); Statement::Init(target);
Backup::Init(target);
DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY);
DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment