#include "dbms_trace.hpp"
|
|
#include <cstdio>
|
#include <cstdint>
|
#include <cstring>
|
#include <limits>
|
#include <string>
|
#include <utility>
|
|
extern "C"
|
{
|
#include "access/htup_details.h"
|
#include "catalog/pg_type_d.h"
|
#include "funcapi.h"
|
#include "plpgsql.h"
|
#include "utils/builtins.h"
|
#include "utils/tuplestore.h"
|
}
|
|
namespace
|
{
|
constexpr int32 kTracePause = 4096;
|
constexpr int32 kTraceResume = 8192;
|
constexpr int32 kTraceStop = 16384;
|
|
constexpr int32 kControlMask = kTracePause | kTraceResume | kTraceStop;
|
|
PLpgSQL_plugin g_dbms_trace_plpgsql_plugin;
|
bool g_dbms_trace_plpgsql_plugin_installed = false;
|
|
const char* trace_event_type_label(const char* event_type);
|
|
bool is_trace_enabled(const DbmsTraceSessionState& state)
|
{
|
return state.enabled;
|
}
|
|
/* Сравнивает имя SQL-атрибута без учёта регистра. */
|
bool
|
dbms_trace_attr_name_is(Form_pg_attribute attr, const char* expected)
|
{
|
return pg_strcasecmp(NameStr(attr->attname), expected) == 0;
|
}
|
|
/* Выдаёт ошибку о неподдерживаемой выходной колонке DBMS_TRACE. */
|
void
|
dbms_trace_unsupported_column_error(const char* function_name, const char* colname)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("unsupported DBMS_TRACE %s output column \"%s\"",
|
function_name,
|
colname)));
|
}
|
|
/* Выдаёт ошибку о неподдерживаемом типе выходной колонки DBMS_TRACE. */
|
void
|
dbms_trace_unsupported_type_error(const char* function_name, const char* colname, Oid typid)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_DATATYPE_MISMATCH),
|
errmsg("unsupported type %s for DBMS_TRACE %s output column \"%s\"",
|
format_type_be(typid),
|
function_name,
|
colname)));
|
}
|
|
/* Проверяет, что int64 помещается в int32 для SQL-колонки. */
|
int32
|
dbms_trace_checked_int64_to_int32(int64 value, const char* function_name, const char* colname)
|
{
|
if (value < std::numeric_limits<int32>::min() ||
|
value > std::numeric_limits<int32>::max())
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
|
errmsg("value out of range for DBMS_TRACE %s output column \"%s\"",
|
function_name,
|
colname)));
|
}
|
|
return static_cast<int32>(value);
|
}
|
|
/* Формирует текстовый Datum для согласованной SQL-колонки. */
|
Datum
|
dbms_trace_text_datum_or_null(const char* value, Oid typid, bool* isnull, const char* function_name, const char* colname)
|
{
|
if (value == nullptr || value[0] == '\0')
|
{
|
*isnull = true;
|
return static_cast<Datum>(0);
|
}
|
|
if (typid != TEXTOID)
|
dbms_trace_unsupported_type_error(function_name, colname, typid);
|
|
*isnull = false;
|
return CStringGetTextDatum(value);
|
}
|
|
/* Формирует текстовый Datum из std::string для согласованной SQL-колонки. */
|
Datum
|
dbms_trace_text_datum_or_null(const std::string& value,
|
Oid typid,
|
bool* isnull,
|
const char* function_name,
|
const char* colname)
|
{
|
return dbms_trace_text_datum_or_null(value.empty() ? nullptr : value.c_str(),
|
typid,
|
isnull,
|
function_name,
|
colname);
|
}
|
|
/* Формирует целочисленный Datum для int32 SQL-колонки. */
|
Datum
|
dbms_trace_int32_datum(int32 value, Oid typid, const char* function_name, const char* colname)
|
{
|
if (typid != INT4OID)
|
dbms_trace_unsupported_type_error(function_name, colname, typid);
|
|
return Int32GetDatum(value);
|
}
|
|
/* Формирует целочисленный Datum для int64/int32 SQL-колонки. */
|
Datum
|
dbms_trace_int64_datum(int64 value, Oid typid, const char* function_name, const char* colname)
|
{
|
if (typid == INT8OID)
|
return Int64GetDatum(value);
|
if (typid == INT4OID)
|
return Int32GetDatum(dbms_trace_checked_int64_to_int32(value, function_name, colname));
|
|
dbms_trace_unsupported_type_error(function_name, colname, typid);
|
return static_cast<Datum>(0);
|
}
|
|
/* Формирует timestamptz Datum для SQL-колонки времени. */
|
Datum
|
dbms_trace_timestamptz_datum(TimestampTz value, Oid typid, const char* function_name, const char* colname)
|
{
|
if (typid != TIMESTAMPTZOID)
|
dbms_trace_unsupported_type_error(function_name, colname, typid);
|
|
return TimestampTzGetDatum(value);
|
}
|
|
/* Формирует bool Datum для булевой SQL-колонки. */
|
Datum
|
dbms_trace_bool_datum(bool value, Oid typid, const char* function_name, const char* colname)
|
{
|
if (typid != BOOLOID)
|
dbms_trace_unsupported_type_error(function_name, colname, typid);
|
|
return BoolGetDatum(value);
|
}
|
|
/* Проверяет, завершён ли run. */
|
bool
|
dbms_trace_run_is_closed(const DbmsTraceRun& run)
|
{
|
return !run.is_active && run.ended_at != 0;
|
}
|
|
/* Заполняет одну строку SQL-результата trace runs по фактическому descriptor. */
|
void
|
dbms_trace_fill_run_row(const DbmsTraceRun& run, TupleDesc tupdesc, Datum* values, bool* nulls)
|
{
|
const char* function_name = "run";
|
|
for (int attno = 0; attno < tupdesc->natts; ++attno)
|
{
|
Form_pg_attribute attr = TupleDescAttr(tupdesc, attno);
|
const char* colname = NameStr(attr->attname);
|
const Oid typid = attr->atttypid;
|
|
nulls[attno] = true;
|
values[attno] = static_cast<Datum>(0);
|
|
if (attr->attisdropped)
|
continue;
|
|
if (dbms_trace_attr_name_is(attr, "run_id"))
|
{
|
values[attno] = dbms_trace_int64_datum(run.run_id, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "trace_mask") ||
|
dbms_trace_attr_name_is(attr, "trace_level"))
|
{
|
values[attno] = dbms_trace_int32_datum(run.trace_mask, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "started_at"))
|
{
|
values[attno] = dbms_trace_timestamptz_datum(run.started_at, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "ended_at"))
|
{
|
if (dbms_trace_run_is_closed(run))
|
{
|
values[attno] = dbms_trace_timestamptz_datum(run.ended_at, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
}
|
else if (dbms_trace_attr_name_is(attr, "event_count"))
|
{
|
values[attno] = dbms_trace_int32_datum(run.event_count, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "is_active"))
|
{
|
values[attno] = dbms_trace_bool_datum(run.is_active, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else
|
dbms_trace_unsupported_column_error(function_name, colname);
|
}
|
}
|
|
/* Заполняет одну строку SQL-результата trace events по фактическому descriptor. */
|
void
|
dbms_trace_fill_event_row(const DbmsTraceEvent& event, TupleDesc tupdesc, Datum* values, bool* nulls)
|
{
|
const char* function_name = "event";
|
|
for (int attno = 0; attno < tupdesc->natts; ++attno)
|
{
|
Form_pg_attribute attr = TupleDescAttr(tupdesc, attno);
|
const char* colname = NameStr(attr->attname);
|
const Oid typid = attr->atttypid;
|
|
nulls[attno] = true;
|
values[attno] = static_cast<Datum>(0);
|
|
if (attr->attisdropped)
|
continue;
|
|
if (dbms_trace_attr_name_is(attr, "event_type"))
|
{
|
values[attno] = dbms_trace_text_datum_or_null(trace_event_type_label(event.event_type.c_str()),
|
typid,
|
&nulls[attno],
|
function_name,
|
colname);
|
}
|
else if (dbms_trace_attr_name_is(attr, "run_id"))
|
{
|
values[attno] = dbms_trace_int64_datum(event.run_id, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "event_seq"))
|
{
|
values[attno] = dbms_trace_int64_datum(event.event_seq, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "event_time") ||
|
dbms_trace_attr_name_is(attr, "event_timestamp") ||
|
dbms_trace_attr_name_is(attr, "timestamp"))
|
{
|
values[attno] = dbms_trace_timestamptz_datum(event.timestamp, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "unit_name"))
|
{
|
values[attno] = dbms_trace_text_datum_or_null(event.unit_name,
|
typid,
|
&nulls[attno],
|
function_name,
|
colname);
|
}
|
else if (dbms_trace_attr_name_is(attr, "subprogram_name"))
|
{
|
values[attno] = dbms_trace_text_datum_or_null(event.subprogram_name,
|
typid,
|
&nulls[attno],
|
function_name,
|
colname);
|
}
|
else if (dbms_trace_attr_name_is(attr, "nesting_depth"))
|
{
|
values[attno] = dbms_trace_int32_datum(event.nesting_depth, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
else if (dbms_trace_attr_name_is(attr, "line_no"))
|
{
|
if (event.line_no != 0)
|
{
|
values[attno] = dbms_trace_int32_datum(event.line_no, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
}
|
else if (dbms_trace_attr_name_is(attr, "sql_text"))
|
{
|
values[attno] = dbms_trace_text_datum_or_null(event.sql_text,
|
typid,
|
&nulls[attno],
|
function_name,
|
colname);
|
}
|
else if (dbms_trace_attr_name_is(attr, "error_code"))
|
{
|
if (event.error_code != 0)
|
{
|
values[attno] = dbms_trace_int32_datum(event.error_code, typid, function_name, colname);
|
nulls[attno] = false;
|
}
|
}
|
else if (dbms_trace_attr_name_is(attr, "comment"))
|
{
|
values[attno] = dbms_trace_text_datum_or_null(event.comment,
|
typid,
|
&nulls[attno],
|
function_name,
|
colname);
|
}
|
else
|
dbms_trace_unsupported_column_error(function_name, colname);
|
}
|
}
|
|
/* Нормализует внутренние коды событий для SQL-вывода. */
|
const char*
|
trace_event_type_label(const char* event_type)
|
{
|
if (event_type == nullptr)
|
return "";
|
|
if (std::strcmp(event_type, "SET") == 0)
|
return "SET_TRACE";
|
if (std::strcmp(event_type, "CLEAR") == 0)
|
return "CLEAR_TRACE";
|
return event_type;
|
}
|
|
/* Проверяет, что маска содержит только управляющие флаги. */
|
bool is_control_only(int32 trace_mask)
|
{
|
return (trace_mask & kControlMask) != 0 && (trace_mask & ~kControlMask) == 0;
|
}
|
|
/* Собирает базовую структуру trace event с общими полями. */
|
DbmsTraceEvent
|
make_trace_event(DbmsTraceSessionState& state, const char* event_type, TimestampTz timestamp)
|
{
|
DbmsTraceEvent event{};
|
event.event_type = event_type != nullptr ? event_type : "";
|
event.run_id = state.active_run_id;
|
event.event_seq = state.next_event_seq++;
|
event.timestamp = timestamp;
|
return event;
|
}
|
|
/* Возвращает активный run для текущего состояния сессии. */
|
DbmsTraceRun*
|
current_trace_run(DbmsTraceSessionState& state)
|
{
|
if (!state.enabled || state.active_run_id == 0 || state.trace_runs.empty())
|
return nullptr;
|
|
DbmsTraceRun& run = state.trace_runs.back();
|
if (run.run_id != state.active_run_id)
|
return nullptr;
|
|
return &run;
|
}
|
|
/* Добавляет обычное trace-событие в историю сессии. */
|
void append_trace_event(DbmsTraceSessionState& state,
|
const char* event_type,
|
const std::string& comment,
|
TimestampTz timestamp)
|
{
|
DbmsTraceEvent event = make_trace_event(state, event_type, timestamp);
|
event.comment = comment;
|
state.trace_rows.emplace_back(std::move(event));
|
if (DbmsTraceRun* run = current_trace_run(state))
|
run->event_count++;
|
}
|
|
/* Извлекает имя unit из signature функции. */
|
std::string
|
derive_unit_name(const char* fn_signature)
|
{
|
if (fn_signature == nullptr || fn_signature[0] == '\0')
|
return std::string();
|
|
const std::string signature(fn_signature);
|
const std::string::size_type open_paren = signature.find('(');
|
if (open_paren == std::string::npos)
|
return signature;
|
|
return signature.substr(0, open_paren);
|
}
|
|
/* Извлекает имя subprogram из signature функции. */
|
std::string
|
derive_subprogram_name(const char* fn_signature)
|
{
|
if (fn_signature == nullptr || fn_signature[0] == '\0')
|
return std::string();
|
|
const std::string signature(fn_signature);
|
const std::string::size_type open_paren = signature.find('(');
|
const std::string::size_type name_end = open_paren == std::string::npos ? signature.size() : open_paren;
|
const std::string::size_type dot = signature.rfind('.', name_end);
|
const std::string::size_type name_begin = dot == std::string::npos ? 0 : dot + 1;
|
|
return signature.substr(name_begin, name_end - name_begin);
|
}
|
|
/* Создаёт запись о новом run. */
|
void
|
open_trace_run(DbmsTraceSessionState& state, int32 trace_level, TimestampTz timestamp)
|
{
|
DbmsTraceRun run{};
|
run.run_id = state.active_run_id;
|
run.trace_mask = trace_level;
|
run.started_at = timestamp;
|
run.ended_at = 0;
|
run.event_count = 0;
|
run.is_active = true;
|
state.trace_runs.emplace_back(run);
|
}
|
|
/* Закрывает текущий run по timestamp завершения. */
|
void
|
close_trace_run(DbmsTraceSessionState& state, TimestampTz timestamp)
|
{
|
DbmsTraceRun* run = current_trace_run(state);
|
if (run == nullptr)
|
return;
|
|
run->ended_at = timestamp;
|
run->is_active = false;
|
}
|
|
/* Добавляет PL/pgSQL CALL или RETURN событие. */
|
void
|
append_plpgsql_trace_event(DbmsTraceSessionState& state,
|
const char* event_type,
|
PLpgSQL_function* func,
|
const char* comment_prefix)
|
{
|
if (!state.enabled || state.active_run_id == 0 || func == nullptr)
|
return;
|
|
TimestampTz timestamp = GetCurrentTimestamp();
|
DbmsTraceEvent event = make_trace_event(state, event_type, timestamp);
|
event.unit_name = derive_unit_name(func->fn_signature);
|
event.subprogram_name = derive_subprogram_name(func->fn_signature);
|
event.comment = comment_prefix != nullptr ? comment_prefix : "";
|
if (func->fn_signature != nullptr && func->fn_signature[0] != '\0')
|
{
|
if (!event.comment.empty())
|
event.comment.push_back(' ');
|
event.comment += func->fn_signature;
|
}
|
state.trace_rows.emplace_back(std::move(event));
|
if (DbmsTraceRun* run = current_trace_run(state))
|
run->event_count++;
|
}
|
|
/* Хук начала PL/pgSQL-функции. */
|
void
|
dbms_trace_plpgsql_func_beg(PLpgSQL_execstate* estate, PLpgSQL_function* func)
|
{
|
(void) estate;
|
auto& state = dbms_trace_session_state();
|
append_plpgsql_trace_event(state,
|
"CALL",
|
func,
|
"PL/pgSQL function entered");
|
}
|
|
/* Хук завершения PL/pgSQL-функции. */
|
void
|
dbms_trace_plpgsql_func_end(PLpgSQL_execstate* estate, PLpgSQL_function* func)
|
{
|
(void) estate;
|
auto& state = dbms_trace_session_state();
|
append_plpgsql_trace_event(state,
|
"RETURN",
|
func,
|
"PL/pgSQL function exited");
|
}
|
|
/* Устанавливает обработчики PL/pgSQL один раз на backend. */
|
void
|
dbms_trace_install_plpgsql_plugin()
|
{
|
if (g_dbms_trace_plpgsql_plugin_installed)
|
return;
|
|
void** rendezvous = find_rendezvous_variable("PLpgSQL_plugin");
|
if (rendezvous == nullptr)
|
return;
|
|
g_dbms_trace_plpgsql_plugin.func_setup = nullptr;
|
g_dbms_trace_plpgsql_plugin.func_beg = dbms_trace_plpgsql_func_beg;
|
g_dbms_trace_plpgsql_plugin.func_end = dbms_trace_plpgsql_func_end;
|
g_dbms_trace_plpgsql_plugin.stmt_beg = nullptr;
|
g_dbms_trace_plpgsql_plugin.stmt_end = nullptr;
|
|
*reinterpret_cast<PLpgSQL_plugin**>(rendezvous) = &g_dbms_trace_plpgsql_plugin;
|
g_dbms_trace_plpgsql_plugin_installed = true;
|
}
|
} // namespace
|
|
/*
|
* Семантика выполнения DBMS_TRACE.
|
*
|
* Пакет хранит локальное состояние сессии и историю строк трассировки для
|
* `SET_PLSQL_TRACE` / `CLEAR_PLSQL_TRACE`.
|
*
|
* Остальные public entrypoints остаются явными заглушками, чтобы SQL-клиенты
|
* получали предсказуемую ошибку "not implemented" вместо отсутствующей
|
* поверхности.
|
*/
|
|
static DbmsTraceSessionState g_dbms_trace_session_state{false, 0};
|
|
/* Возвращает backend-local состояние DBMS_TRACE. */
|
DbmsTraceSessionState&
|
dbms_trace_session_state()
|
{
|
return g_dbms_trace_session_state;
|
}
|
|
PG_FUNCTION_INFO_V1(dbms_trace_set_plsql_trace);
|
PG_FUNCTION_INFO_V1(dbms_trace_clear_plsql_trace);
|
PG_FUNCTION_INFO_V1(dbms_trace_is_enabled);
|
PG_FUNCTION_INFO_V1(dbms_trace_get_plsql_trace_level);
|
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_version);
|
PG_FUNCTION_INFO_V1(dbms_trace_get_version);
|
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_runs);
|
PG_FUNCTION_INFO_V1(dbms_trace_plsql_trace_events);
|
|
/// @brief Версия RUDB пакета DBMS_TRACE (Oracle DBMS_TRACE пакет)
|
#define RUDB_DBMS_TRACE_VERSION "1.0.0"
|
|
Datum dbms_trace_set_plsql_trace(PG_FUNCTION_ARGS)
|
{
|
if (PG_ARGISNULL(0))
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("SET_PLSQL_TRACE requires a trace level")));
|
}
|
|
int32 trace_level = PG_GETARG_INT32(0);
|
const bool enabled = DatumGetBool(
|
DirectFunctionCall0(dbms_trace_is_enabled));
|
|
if (is_control_only(trace_level))
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("control trace flags cannot be combined with regular trace flags")));
|
}
|
|
auto& state = dbms_trace_session_state();
|
if (!enabled)
|
{
|
dbms_trace_install_plpgsql_plugin();
|
TimestampTz timestamp = GetCurrentTimestamp();
|
state.enabled = true;
|
state.active_run_id = state.next_run_id++;
|
state.next_event_seq = 1;
|
open_trace_run(state, trace_level, timestamp);
|
|
append_trace_event(state,
|
"SET",
|
std::string("SET_PLSQL_TRACE trace_level=") + std::to_string(trace_level),
|
timestamp);
|
}
|
else if (!state.trace_runs.empty())
|
{
|
state.trace_runs.back().trace_mask = trace_level;
|
}
|
|
state.trace_mask = trace_level;
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_trace_clear_plsql_trace(PG_FUNCTION_ARGS)
|
{
|
auto& state = dbms_trace_session_state();
|
const bool enabled = DatumGetBool(
|
DirectFunctionCall0(dbms_trace_is_enabled));
|
if (enabled)
|
{
|
TimestampTz timestamp = GetCurrentTimestamp();
|
append_trace_event(state,
|
"CLEAR",
|
"CLEAR_PLSQL_TRACE",
|
timestamp);
|
close_trace_run(state, timestamp);
|
}
|
state.enabled = false;
|
state.trace_mask = 0;
|
state.active_run_id = 0;
|
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_trace_is_enabled(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_BOOL(is_trace_enabled(dbms_trace_session_state()));
|
}
|
|
/* Генерирует ошибку для не реализованных entrypoints. */
|
static void
|
dbms_trace_not_implemented(const char* function_name)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("%s is not implemented yet", function_name)));
|
}
|
|
Datum dbms_trace_get_plsql_trace_level(PG_FUNCTION_ARGS)
|
{
|
dbms_trace_not_implemented("DBMS_TRACE.GET_PLSQL_TRACE_LEVEL");
|
PG_RETURN_INT32(0);
|
}
|
|
Datum dbms_trace_plsql_trace_version(PG_FUNCTION_ARGS)
|
{
|
dbms_trace_not_implemented("DBMS_TRACE.PLSQL_TRACE_VERSION");
|
PG_RETURN_VOID();
|
}
|
|
Datum dbms_trace_get_version(PG_FUNCTION_ARGS)
|
{
|
PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_TRACE_VERSION));
|
}
|
|
/*
|
* SQL-доступ к строкам запуска трассировки поверх локальной истории сессии.
|
*/
|
Datum dbms_trace_plsql_trace_runs(PG_FUNCTION_ARGS)
|
{
|
ReturnSetInfo* rsinfo = reinterpret_cast<ReturnSetInfo*>(fcinfo->resultinfo);
|
if (rsinfo == nullptr || !IsA(rsinfo, ReturnSetInfo))
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("set-valued function called in context that cannot accept a set")));
|
|
InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
|
TupleDesc tupdesc = rsinfo->setDesc;
|
|
for (const DbmsTraceRun& run : dbms_trace_session_state().trace_runs)
|
{
|
Datum* values = reinterpret_cast<Datum*>(palloc0(sizeof(Datum) * tupdesc->natts));
|
bool* nulls = reinterpret_cast<bool*>(palloc(sizeof(bool) * tupdesc->natts));
|
|
dbms_trace_fill_run_row(run, tupdesc, values, nulls);
|
tuplestore_putvalues(rsinfo->setResult, tupdesc, values, nulls);
|
|
pfree(values);
|
pfree(nulls);
|
}
|
|
PG_RETURN_NULL();
|
}
|
|
/*
|
* SQL-доступ к событиям трассировки поверх локальной истории сессии.
|
*/
|
Datum dbms_trace_plsql_trace_events(PG_FUNCTION_ARGS)
|
{
|
ReturnSetInfo* rsinfo = reinterpret_cast<ReturnSetInfo*>(fcinfo->resultinfo);
|
if (rsinfo == nullptr || !IsA(rsinfo, ReturnSetInfo))
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("set-valued function called in context that cannot accept a set")));
|
|
InitMaterializedSRF(fcinfo, MAT_SRF_USE_EXPECTED_DESC | MAT_SRF_BLESS);
|
TupleDesc tupdesc = rsinfo->setDesc;
|
|
for (const DbmsTraceEvent& event : dbms_trace_session_state().trace_rows)
|
{
|
Datum* values = reinterpret_cast<Datum*>(palloc0(sizeof(Datum) * tupdesc->natts));
|
bool* nulls = reinterpret_cast<bool*>(palloc(sizeof(bool) * tupdesc->natts));
|
|
dbms_trace_fill_event_row(event, tupdesc, values, nulls);
|
tuplestore_putvalues(rsinfo->setResult, tupdesc, values, nulls);
|
|
pfree(values);
|
pfree(nulls);
|
}
|
|
PG_RETURN_NULL();
|
}
|
|
/* Снимает debug snapshot для регрессионных проверок. */
|
extern "C" void
|
dbms_trace_get_debug_snapshot(DbmsTraceDebugSnapshot* out)
|
{
|
if (out == nullptr)
|
{
|
return;
|
}
|
|
auto& state = dbms_trace_session_state();
|
*out = DbmsTraceDebugSnapshot{};
|
out->enabled = state.enabled;
|
out->trace_mask = state.trace_mask;
|
out->active_run_id = state.active_run_id;
|
out->next_run_id = state.next_run_id;
|
out->next_event_seq = state.next_event_seq;
|
out->trace_rows_count = static_cast<int32>(state.trace_rows.size());
|
if (!state.trace_rows.empty())
|
{
|
const std::string& last_event = state.trace_rows.back().event_type;
|
std::snprintf(out->last_event_type,
|
sizeof(out->last_event_type),
|
"%s",
|
last_event.c_str());
|
}
|
}
|