Add database integrity check 12/161712/2
authorJaemin Ryu <jm77.ryu@samsung.com>
Mon, 27 Nov 2017 05:55:11 +0000 (14:55 +0900)
committerJaemin Ryu <jm77.ryu@samsung.com>
Wed, 29 Nov 2017 05:17:10 +0000 (14:17 +0900)
Change-Id: Ifa3a20b029327828a5ba53b46e7ba00305570a62
Signed-off-by: Jaemin Ryu <jm77.ryu@samsung.com>
include/klay/db/connection.h
src/db/connection.cpp

index 641310bed20e286fcefe21b6ea11956784c9b2fc..a6569c201f5d34f4f54141289598e53b7db75610 100644 (file)
@@ -32,7 +32,7 @@ public:
                ReadWrite = SQLITE_OPEN_READWRITE
        };
 
-       Connection(const std::string& name, const int flags);
+       Connection(const std::string& name, const int flags, bool integrityCheck = true);
        ~Connection();
 
        int exec(const std::string& query);
index 0eac647c903139559c073e11ddf6441de6ccc140..639970a21913519d394a4493026d4056a2b31045 100644 (file)
  *  See the License for the specific language governing permissions and
  *  limitations under the License
  */
+#include <cstring>
+
 #include <klay/exception.h>
 #include <klay/db/connection.h>
 
 namespace database {
 
-Connection::Connection(const std::string& name, const int flags) :
+Connection::Connection(const std::string& name, const int flags, bool integrityCheck) :
        handle(nullptr), filename(name)
 {
        if (::sqlite3_open_v2(filename.c_str(), &handle, flags, NULL)) {
                throw runtime::Exception(getErrorMessage());
        }
+
+       if (integrityCheck) {
+               bool verified = false;
+               sqlite3_stmt *integrity = NULL;
+               if (::sqlite3_prepare_v2(handle, "PRAGMA integrity_check;", -1, &integrity, NULL) == SQLITE_OK ) {
+                       while (::sqlite3_step(integrity) == SQLITE_ROW) {
+                               const unsigned char *result = ::sqlite3_column_text(integrity, 0);
+                               if (result && ::strcmp((const char *)result, (const char *)"ok") == 0) {
+                                       verified = true;
+                                       break;
+                               }
+                       }
+
+                       ::sqlite3_finalize(integrity);
+               }
+
+               if (!verified) {
+                       ::sqlite3_close(handle);
+                       throw runtime::Exception("Malformed database");
+               }
+       }
 }
 
 Connection::~Connection()