Sqlcipher: automatic migrate

GitOrigin-RevId: 209360f2b40a0d05ec53bb55890518e50c05f34a
This commit is contained in:
Arseny Smirnov 2020-08-12 22:36:46 +03:00
parent c66a72fe90
commit b9de1b94d2
2 changed files with 25 additions and 0 deletions

View File

@ -125,6 +125,15 @@ Result<string> SqliteDb::get_pragma(Slice name) {
CHECK(!stmt.can_step());
return std::move(res);
}
Result<string> SqliteDb::get_pragma_string(Slice name) {
TRY_RESULT(stmt, get_statement(PSLICE() << "PRAGMA " << name));
TRY_STATUS(stmt.step());
CHECK(stmt.has_row());
auto res = stmt.view_string(0).str();
TRY_STATUS(stmt.step());
CHECK(!stmt.can_step());
return std::move(res);
}
Result<int32> SqliteDb::user_version() {
TRY_RESULT(get_version_stmt, get_statement("PRAGMA user_version"));
@ -163,6 +172,14 @@ Status SqliteDb::check_encryption() {
}
Result<SqliteDb> SqliteDb::open_with_key(CSlice path, const DbKey &db_key) {
auto res = do_open_with_key(path, db_key, false);
if (res.is_error()) {
return do_open_with_key(path, db_key, true);
}
return res;
}
Result<SqliteDb> SqliteDb::do_open_with_key(CSlice path, const DbKey &db_key, bool with_cipher_migrate) {
SqliteDb db;
TRY_STATUS(db.init(path));
if (!db_key.is_empty()) {
@ -171,6 +188,12 @@ Result<SqliteDb> SqliteDb::open_with_key(CSlice path, const DbKey &db_key) {
}
auto key = db_key_to_sqlcipher_key(db_key);
TRY_STATUS(db.exec(PSLICE() << "PRAGMA key = " << key));
if (with_cipher_migrate) {
TRY_RESULT(code, db.get_pragma_string("cipher_migrate"));
if (code != "0") {
return Status::Error(PSLICE() << "'PRAGMA cipher_migrate' failed - " << code);
}
}
}
TRY_STATUS_PREFIX(db.check_encryption(), "Can't open database: ");
return std::move(db);

View File

@ -50,6 +50,7 @@ class SqliteDb {
Status exec(CSlice cmd) TD_WARN_UNUSED_RESULT;
Result<bool> has_table(Slice table);
Result<string> get_pragma(Slice name);
Result<string> get_pragma_string(Slice name);
Status begin_transaction() TD_WARN_UNUSED_RESULT;
Status commit_transaction() TD_WARN_UNUSED_RESULT;
@ -83,6 +84,7 @@ class SqliteDb {
bool enable_logging_ = false;
Status check_encryption();
static Result<SqliteDb> do_open_with_key(CSlice path, const DbKey &db_key, bool with_cipher_migrate);
};
} // namespace td