From 872459a7cc525eb87a2dc5a82f1b137493186080 Mon Sep 17 00:00:00 2001 From: Alexander Sulfrian Date: Sun, 10 Jan 2010 21:46:58 +0100 Subject: added function for testing if table exists in database --- src/base/database.cpp | 20 ++++++++++++++++++++ src/base/database.hpp | 8 ++++++++ test/base/database.cpp | 12 ++++++++++++ 3 files changed, 40 insertions(+) diff --git a/src/base/database.cpp b/src/base/database.cpp index 96f40745..ec2e8493 100644 --- a/src/base/database.cpp +++ b/src/base/database.cpp @@ -82,6 +82,26 @@ namespace usdx sqlite3_finalize(sqliteStatement); } + const bool StatDatabase::sqlite_table_exists(const std::string table) + { + std::string sql = "select [name] from [sqlite_master] where [type] = 'table' and [tbl_name] = ?1;"; + sqlite3_stmt *sqliteStatement = sqlite_prepare(sql); + + // bind table name to parameter 1 and execute statement + sqlite3_bind_text(sqliteStatement, 1, table.c_str(), table.length(), SQLITE_TRANSIENT); + int rc = sqlite3_step(sqliteStatement); + + // if rc is SQLITE_ROW, than result has at lease one row and so + // the table exists + bool result = false; + if (rc == SQLITE_ROW) { + result = true; + } + + sqlite3_finalize(sqliteStatement); + return result; + } + void StatDatabase::init(const std::string filename) { LOG4CXX_DEBUG(log, "Initializing Database: " << filename); diff --git a/src/base/database.hpp b/src/base/database.hpp index 3bf699ad..d5313609 100644 --- a/src/base/database.hpp +++ b/src/base/database.hpp @@ -72,6 +72,14 @@ namespace usdx */ void sqlite_exec(const std::string sqlStatement); + /** + * Check if the given table exists in the database. + * + * @param table Name to check if exists + * @return true, if table exists, false if not + */ + const bool sqlite_table_exists(const std::string table); + // Singleton StatDatabase(std::string filename); diff --git a/test/base/database.cpp b/test/base/database.cpp index 5738c56c..fdf4a3dd 100644 --- a/test/base/database.cpp +++ b/test/base/database.cpp @@ -41,6 +41,8 @@ namespace usdx CPPUNIT_TEST(testSizeOfTime_t); CPPUNIT_TEST(testGetStatReset); CPPUNIT_TEST(testFormatDate); + CPPUNIT_TEST(testTableExists); + CPPUNIT_TEST(testTableNotExists); CPPUNIT_TEST_SUITE_END(); private: StatDatabase *db; @@ -90,6 +92,16 @@ namespace usdx StatDatabase::get_instance()->format_date(buf, 9, 1262433600); CPPUNIT_ASSERT( strcmp(buf, "13.02.09") ); } + + void testTableExists() + { + CPPUNIT_ASSERT( true == StatDatabase::get_instance()->sqlite_table_exists("us_songs") ); + } + + void testTableNotExists() + { + CPPUNIT_ASSERT( false == StatDatabase::get_instance()->sqlite_table_exists("abc") ); + } }; CPPUNIT_TEST_SUITE_REGISTRATION(StatDatabaseTest); -- cgit v1.2.3