#include <cerrno>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <mutex>
#include <villagesql/preview/statement_event.h>
#include <villagesql/preview/sys_var.h>
#include <villagesql/vsql.h>
using namespace vsql;
namespace sv = vsql::preview_sys_var;
namespace se = vsql::preview_statement_event;
static bool g_enabled;
static long long g_threshold_ms;
static char *g_log_filename;
static std::mutex g_log_mutex;
static void slow_query_hook(const se::StatementEventArgs &args,
se::StatementEventResult &result) {
if (!g_enabled) return;
if (args.query_time_secs() * 1000.0 < static_cast<double>(g_threshold_ms))
return;
time_t now = static_cast<time_t>(args.query_start_utime() / 1000000);
char ts[32];
struct tm tm_utc;
gmtime_r(&now, &tm_utc);
strftime(ts, sizeof(ts), "%Y-%m-%dT%H:%M:%SZ", &tm_utc);
std::lock_guard<std::mutex> lock(g_log_mutex);
FILE *f = fopen(g_log_filename, "a");
if (f == nullptr) {
result.error_msg("failed to open '%s': %s", g_log_filename,
strerror(errno));
return;
}
fprintf(f, "# Time: %s\n", ts);
fprintf(f, "# User@Host: %s @ %s Id: %lu\n", args.user() ? args.user() : "",
args.client_ip() ? args.client_ip() : "", args.connection_id());
fprintf(f,
"# Schema: %s Query_time: %.6f Lock_time: %.6f"
" Rows_sent: %llu Rows_examined: %llu\n",
args.schema() ? args.schema() : "", args.query_time_secs(),
args.lock_time_secs(), (unsigned long long)args.rows_sent(),
(unsigned long long)args.rows_examined());
fprintf(f, "SET timestamp=%llu;\n", (unsigned long long)now);
auto q = args.query();
fprintf(f, "%.*s;\n", (int)q.size(), q.data());
fclose(f);
}
static auto SYS_VARS = sv::make_capability({
sv::make_bool("enabled", "Enable the slow query log", &g_enabled, false),
sv::make_int("threshold_ms", "Minimum execution time to log, in ms",
&g_threshold_ms, 1000, 0, 3600000),
sv::make_str("log_file", "Path to the slow query log file",
&g_log_filename, "/tmp/vsql_slow_query.log")});
static se::StatementEventCapability<VEF_STATEMENT_EVENT_POSTEXECUTE,
&slow_query_hook>
STATEMENT_EVENT;
VEF_GENERATE_ENTRY_POINTS(
make_extension().with(SYS_VARS).with(STATEMENT_EVENT))