#include "DbSqlite.h"

#include <iostream>
#include <string>
#include "common/Spdlogger.h"

DbSqlite::DbSqlite(const char* dbName)
{
	if (SQLITE_OK != sqlite3_open(dbName, &sqlite_))
	{
		Spdlogger::error("open sqlite failed");
	}
	else
	{
		Spdlogger::info("open sqlite success");
	}
}
DbSqlite::~DbSqlite()
{
	this->close();
}

void DbSqlite::open(const char* dbname)
{}

void DbSqlite::close()
{
	if (sqlite_ != nullptr)
	{
		sqlite3_close(sqlite_);
	}
}

bool DbSqlite::exec(const char* sql)
{
	char* errMsg;//操作失败的原因。
	//std::string ssql="CREATE TABLE T_USER(username varchar(30) unique)";
	if (SQLITE_OK != sqlite3_exec(sqlite_, sql, 0, 0, &errMsg))
	{
		Spdlogger::error("create table failed:{}", errMsg);
		return false;
	}
	return true;
}

bool DbSqlite::prepare_step(const char* sql, CallbackSqliteRowData& cb)
{
	sqlite3_stmt* stmt = nullptr;
	if (SQLITE_OK != sqlite3_prepare_v2(sqlite_, sql, -1, &stmt, 0))
	{
		Spdlogger::error("sqlite3_prepare_v2 failed:");
		return false;
	}

	Spdlogger::info("sqlite3 step sql=", sql);
	while (SQLITE_ROW == sqlite3_step(stmt))
	{
		Spdlogger::info("sqlite3_step row data:");
		if (cb) { cb(stmt); }
	}
	sqlite3_finalize(stmt);
	return true;
}

int DbSqlite::get_int(sqlite3_stmt* stmt, int index)
{
	return sqlite3_column_int(stmt, index);
}
double DbSqlite::get_double(sqlite3_stmt* stmt, int index)
{
	return sqlite3_column_double(stmt, index);
}
std::string DbSqlite::get_text(sqlite3_stmt* stmt, int index)
{
	return (char*)sqlite3_column_text(stmt, index);
}
