Example #1
0
	void DatabaseManager::registerDatabaseUnit(BaseDatabaseUnitPtr unit)
	{
		if (unit)
		{
			CppSQLite3DB * database = unit->getDatabase();
			if (database)
			{
				return;
			}

			database = new CppSQLite3DB();
			const char * encryption = unit->getEncryption();
			std::string databasePath = CommonUtil::WtoUtf8(unit->getDatabasePath());
			if (!databasePath.empty())
			{
				bool open = false;
				try
				{
					database->open(databasePath.c_str());
					unit->setDatabase(database);
					unit->runUpdateStatements();
					open = true;
				}
				catch (CppSQLite3Exception e)
				{
					LOG_ERR_R(DATABASE_MANAGER_LOG_TAG, _T("Failed to open database, error: %u"), e.errorCode());
					LOG_ERR_D_A(DATABASE_MANAGER_LOG_TAG_A, "Message: %s", e.errorMessage());

					try
					{
						boost::filesystem::copy(databasePath, databasePath + ".backup");
						boost::filesystem::remove(databasePath);
					}
					catch (...)
					{
					}
				}

				if (!open)
				{
					try
					{
						database->create(databasePath.c_str());
						unit->setDatabase(database);
						unit->runCreateStatements();
						open = true;
					}
					catch (CppSQLite3Exception e)
					{
						LOG_ERR_R(DATABASE_MANAGER_LOG_TAG, _T("Failed to create database, error: %u"), e.errorCode());
						LOG_ERR_D_A(DATABASE_MANAGER_LOG_TAG_A, "Message: %s", e.errorMessage());
					}
				}

				if (!open)
				{
					delete database;
					database = nullptr;
				}
			}
		}
	}