#include "call_log.h" #include "utils/Log.h" #include "base/strings.hpp" static int QueryCountCallback(void* user_data, int columns, char** column_values, char** column_names) { if (columns != 1) { LOGE("columns not match"); return 0; } *((int*)user_data) = atoi(column_values[0]); return 0; } int GetCallLogCount() { SQLite lite; if (0 != lite.Open(CALL_LOG_DATABASE)) { return -1; } int n = 0; lite.Exec("SELECT count(*) from log", QueryCountCallback, &n); lite.Close(); return n; } int PutCallLog(const CallLogEntry& log) { SQLite lite; if (0 != lite.Open(CALL_LOG_DATABASE)) { return -1; } //创建表,确保表存在 std::string sql = "CREATE TABLE if not exists log(" "id integer PRIMARY KEY AUTOINCREMENT NOT NULL, " "uri char(64) NOT NULL, " "contact char(64) NOT NULL, " "duration unsigned int NOT NULL, " "created_at unsigned int NOT NULL);"; if (0 != lite.Exec(sql, NULL, NULL)) { return -1; } if (0 != lite.Exec("BEGIN TRANSACTION;", NULL, NULL)) { return -1; } std::string str = base::format( "INSERT INTO log ('uri', 'contact', 'duration', 'created_at')" " values ('%s', '%s', %d, %u);", log.uri.c_str(), log.contact.c_str(), log.duration, time(NULL)); if (0 != lite.Exec(str, NULL, NULL)) { lite.Exec("ROLLBACK;", NULL, NULL); return -1; } if (0 != lite.Exec("END TRANSACTION;", NULL, NULL)) { return -1; } lite.Close(); return 0; } static int QueryRowCallback(void* user_data, int columns, char** column_values, char** column_names) { if (columns != 5) { LOGE("columns not match"); return 0; } CallLogEntries* entries = (CallLogEntries*)user_data; CallLogEntry entry; entry.id = atoi(column_values[0]); entry.uri = column_values[1]; entry.contact = column_values[2]; entry.duration = atoi(column_values[3]); entry.created_at = atoi(column_values[4]); entries->push_back(entry); return 0; } int GetCallLog(CallLogEntries* records) { SQLite lite; if (0 != lite.Open(CALL_LOG_DATABASE)) { return -1; } if (0 != lite.Exec("SELECT * from log", QueryRowCallback, records)) { return -1; } return lite.Close(); } int DeleteOldCallLog(int n) { SQLite lite; if (0 != lite.Open(CALL_LOG_DATABASE)) { return -1; } int ret = lite.Exec( base::format( "delete from log where id in(select id from log order by id limit %d)", n), NULL, NULL); lite.Close(); return ret; }