PostgreSQL, Pl / pgsql - Как получить доступ к строке запроса, которая выполнила хранимую процедуру, в которой я нахожусь? - PullRequest
1 голос
/ 03 ноября 2019

есть ли способ получить доступ к строке запроса из хранимой процедуры? я имею в виду, что я хотел бы добавить отладку ко многим хранимым процедурам, и было бы замечательно, если бы у меня была некоторая константа, доступная из тела процедуры, в которой была строка запроса.

что-то, что работало быс EXECUTE.

Я прочитал документы и ничего подобного не вижу ...

спасибо!

Ответы [ 2 ]

1 голос
/ 04 ноября 2019

Я согласен с Павлом, что ваше требование не совсем понятно. Тем не менее, я предполагаю, что вы хотите получить оператор, который вызвал процедуру, запущенную в данный момент. Если так, то может быть встроенная функция: Current_Query (). Ниже приведен пример его использования.

 create or replace function what_called_me()
    returns text
    language sql
  as $$
      select current_query();
  $$; 

  select 1 num, 'A' col, what_called_me() sql_statement;   
0 голосов
/ 03 ноября 2019

Я не очень хорошо понимаю, что вам нужно, но, возможно, вам нужен API плагина plpgsql. Этот API плохо документирован, но есть много расширений PostgreSQL, которые используют этот API - PLdebugger, plpgsql_chec, plprofiler и, возможно, другие.

/*
 * A PLpgSQL_plugin structure represents an instrumentation plugin.
 * To instrument PL/pgSQL, a plugin library must access the rendezvous
 * variable "PLpgSQL_plugin" and set it to point to a PLpgSQL_plugin struct.
 * Typically the struct could just be static data in the plugin library.
 * We expect that a plugin would do this at library load time (_PG_init()).
 * It must also be careful to set the rendezvous variable back to NULL
 * if it is unloaded (_PG_fini()).
 *
 * This structure is basically a collection of function pointers --- at
 * various interesting points in pl_exec.c, we call these functions
 * (if the pointers are non-NULL) to give the plugin a chance to watch
 * what we are doing.
 *
 * func_setup is called when we start a function, before we've initialized
 * the local variables defined by the function.
 *
 * func_beg is called when we start a function, after we've initialized
 * the local variables.
 *
 * func_end is called at the end of a function.
 *
 * stmt_beg and stmt_end are called before and after (respectively) each
 * statement.
 *
 * Also, immediately before any call to func_setup, PL/pgSQL fills in the
 * error_callback and assign_expr fields with pointers to its own
 * plpgsql_exec_error_callback and exec_assign_expr functions.  This is
 * a somewhat ad-hoc expedient to simplify life for debugger plugins.
 */
typedef struct PLpgSQL_plugin
{
    /* Function pointers set up by the plugin */
    void        (*func_setup) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
    void        (*func_beg) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
    void        (*func_end) (PLpgSQL_execstate *estate, PLpgSQL_function *func);
    void        (*stmt_beg) (PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);
    void        (*stmt_end) (PLpgSQL_execstate *estate, PLpgSQL_stmt *stmt);

    /* Function pointers set by PL/pgSQL itself */
    void        (*error_callback) (void *arg);
    void        (*assign_expr) (PLpgSQL_execstate *estate, PLpgSQL_datum *target,
                                PLpgSQL_expr *expr);
} PLpgSQL_plugin;

Это необходимо, когда вам действительно нужна подробная информация о том, чтовнутри.

Может быть, вам нужна информация только о выполненных запросах - тогда вы можете посмотреть расширение auto_explain , когда вы установите auto_explain.log_nested_statements в on, тогда запросы из процедуры будут регистрироваться.

...