Search code examples
c++sqlitecmakectest

How can I test through CTest if an SQLite table exists and get the response?


This is my main code:

   sqlite3 *db;
   sqlite3_stmt * stmt;
   string sqlstatement = "CREATE TABLE IF NOT EXISTS accounts (account_id integer primary key, balance integer not null)";

   if (sqlite3_open("test.db", &db) == SQLITE_OK)
   {
    sqlite3_prepare( db, sqlstatement.c_str(), -1, &stmt, NULL );//preparing the statement
    sqlite3_step( stmt );//executing the statement
   }

   sqlite3_finalize(stmt);
   sqlite3_close(db);

   return 0;

and this is my CMakeLists.txt:

cmake_minimum_required(VERSION 2.8.12.2)
enable_testing()
set(TEST_EXE_NAME tests)
add_executable(test main.cpp)
add_executable(${TEST_EXE_NAME} tests.cpp)
add_test(NAME "tests" COMMAND ${TEST_EXE_NAME})
target_link_libraries(tests sqlite3)

How can I have another C++ test file, test.cpp, which tests if the table mentioned in main was successfully created?

My test file has the following code:

string sql = ".tables";
sqlite3 *db;
sqlite3_stmt * stmt;

int rc=0;
if (sqlite3_open("test.db", &db) == SQLITE_OK) {
    rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
    rc = sqlite3_step(stmt);

}
return 0;

How can I get the response from ".tables"?


Solution

  • sqlite3* database;
    sqlite3_open("test.db", &database);
    sqlite3_stmt *statement;
    if(sqlite3_prepare_v2(database, "select * from accounts;", -1, &statement, 0) == SQLITE_OK)
    {
        return 0;
    }
    else {
        return -1;
    
    }