#include "dbms_output.hpp"
|
|
extern "C"
|
{
|
#include "utils/builtins.h"
|
#include "utils/elog.h"
|
|
#include "funcapi.h"
|
#include "access/heapam.h"
|
#include "access/htup_details.h"
|
#include "catalog/pg_type.h"
|
#include "lib/stringinfo.h"
|
|
#include "utils/memutils.h"
|
#include "utils/array.h"
|
#include "utils/builtins.h"
|
#include "utils/lsyscache.h"
|
#include "utils/datetime.h"
|
#include "utils/date.h"
|
#include "utils/timestamp.h"
|
#include "utils/guc.h"
|
}
|
|
extern "C"
|
{
|
PG_FUNCTION_INFO_V1(dbms_output_clear_line_buffer);
|
PG_FUNCTION_INFO_V1(dbms_output_enable);
|
PG_FUNCTION_INFO_V1(dbms_output_disable);
|
PG_FUNCTION_INFO_V1(dbms_output_put);
|
PG_FUNCTION_INFO_V1(dbms_output_new_line);
|
PG_FUNCTION_INFO_V1(dbms_output_put_line);
|
PG_FUNCTION_INFO_V1(dbms_output_get_line);
|
PG_FUNCTION_INFO_V1(dbms_output_get_lines);
|
|
PG_FUNCTION_INFO_V1(dbms_output_get_version);
|
|
PG_FUNCTION_INFO_V1(dbms_output_flush_line_buffer);
|
|
/// @brief Версия RUDB пакета DBMS_OUTPUT (Oracle DBMS_OUTPUT пакет)
|
#define RUDB_DBMS_OUTPUT_VERSION "1.0.0"
|
|
#define BUFSIZE_DEFAULT 20000
|
#define BUFSIZE_MIN 2000
|
#define BUFSIZE_MAX 1000000
|
#define BUFSIZE_UNLIMITED BUFSIZE_MAX
|
|
static char *main_buffer = NULL;
|
static int main_buffer_size = 0; /* allocated bytes in buffer */
|
static int main_buffer_len = 0; /* used bytes in buffer */
|
static int main_buffer_get = 0; /* retrieved bytes in buffer */
|
|
static char *line_buffer = NULL; /* временный буфер для текущей строки (PUT) */
|
static int line_buffer_size = 0; /* размер временного буфера */
|
static int line_buffer_len = 0; /* использовано во временном буфере */
|
|
static void add_str(const char *str, int len);
|
static void add_text_to_main_buffer(text *str);
|
static void clear_line_buffer_internal(void);
|
static void clear_main_buffer_internal(void);
|
|
static text *raw_datum_to_hex_text(Datum value)
|
{
|
bytea *b = DatumGetByteaPP(value);
|
const unsigned char *p = (const unsigned char *) VARDATA_ANY(b);
|
const Size n = VARSIZE_ANY_EXHDR(b);
|
|
static const char hexdigits[] = "0123456789ABCDEF";
|
char *buf = (char *) palloc(n * 2 + 1);
|
for (Size i = 0; i < n; ++i)
|
{
|
buf[i * 2] = hexdigits[(p[i] >> 4) & 0x0F];
|
buf[i * 2 + 1] = hexdigits[p[i] & 0x0F];
|
}
|
buf[n * 2] = '\0';
|
|
text *out = cstring_to_text(buf);
|
pfree(buf);
|
return out;
|
}
|
|
/*
|
* Helper: detect whether this C function is invoked via SQL helper wrapper
|
* (client-side SQL*Plus-like API) with name "..._p".
|
*
|
* We intentionally keep DBMS_OUTPUT semantics for non-_p callers (e.g. PL/SQL),
|
* and apply client-oriented buffer finalization only for *_p calls.
|
*/
|
static bool
|
called_as_sql_helper(FunctionCallInfo fcinfo, const char *expected_proname)
|
{
|
char *fname;
|
bool match = false;
|
|
if (!fcinfo || !fcinfo->flinfo)
|
return false;
|
|
fname = get_func_name(fcinfo->flinfo->fn_oid);
|
if (fname && expected_proname && strcmp(fname, expected_proname) == 0)
|
match = true;
|
if (fname)
|
pfree(fname);
|
return match;
|
}
|
|
/* Внутренняя очистка временного буфера без зависимости от вызова SQL-функции */
|
static void clear_line_buffer_internal(void)
|
{
|
if (line_buffer != NULL)
|
{
|
free(line_buffer);
|
line_buffer = NULL;
|
}
|
line_buffer_size = 0;
|
line_buffer_len = 0;
|
}
|
|
/* Внутренняя очистка основного буфера */
|
static void clear_main_buffer_internal(void)
|
{
|
if (main_buffer != NULL)
|
{
|
main_buffer_len = 0;
|
main_buffer_get = 0;
|
main_buffer[0] = '\0';
|
}
|
}
|
|
Datum dbms_output_clear_line_buffer(PG_FUNCTION_ARGS)
|
{
|
clear_line_buffer_internal();
|
PG_RETURN_VOID();
|
}
|
|
/*
|
* Aux. buffer functionality
|
*/
|
static void add_str(const char *str, int len)
|
{
|
if (main_buffer == NULL)
|
return;
|
|
/* Discard all buffers if get_line was called. */
|
if (main_buffer_get > 0)
|
{
|
main_buffer_get = 0;
|
main_buffer_len = 0;
|
}
|
|
if (main_buffer_len + len > main_buffer_size)
|
{
|
ereport(WARNING,
|
(errmsg("переполнение буфера"),
|
errdetail("Переполнение буфера, предел составляет %d байт", main_buffer_size),
|
errhint("Увеличьте размер буфера")));
|
return;
|
}
|
|
memcpy(main_buffer + main_buffer_len, str, len);
|
main_buffer_len += len;
|
main_buffer[main_buffer_len] = '\0';
|
}
|
|
/* Добавление строки в главный буфер */
|
static void add_text_to_main_buffer(text *str)
|
{
|
char *str_data = text_to_cstring(str);
|
|
if (main_buffer != NULL)
|
{
|
add_str(str_data, strlen(str_data));
|
add_str("", 1);
|
}
|
|
pfree(str_data);
|
}
|
|
/* Добавление строки во временный буфер */
|
static void add_to_line_buffer(const char *str, int len)
|
{
|
if ((main_buffer_len + line_buffer_len + len) > BUFSIZE_MAX)
|
{
|
ereport(WARNING,
|
(errmsg("переполнение буфера"),
|
errdetail("Переполнение буфера, предел составляет %d байт", main_buffer_size),
|
errhint("Увеличьте размер буфера")));
|
return;
|
}
|
|
if (line_buffer == NULL)
|
{
|
/* Инициализируем буфер */
|
line_buffer_size = len + 1;
|
line_buffer = (char*) malloc(line_buffer_size);
|
line_buffer_len = 0;
|
line_buffer[0] = '\0';
|
}
|
|
if (line_buffer_len + len >= line_buffer_size)
|
{
|
/* Увеличиваем буфер */
|
int new_size = line_buffer_len + len + 1;
|
|
char *new_buffer = (char*) realloc(line_buffer, new_size);
|
line_buffer = new_buffer;
|
line_buffer_size = new_size;
|
}
|
|
memcpy(line_buffer + line_buffer_len, str, len);
|
line_buffer_len += len;
|
line_buffer[line_buffer_len] = '\0';
|
}
|
|
static void add_text_to_line_buffer(text *str)
|
{
|
add_to_line_buffer(VARDATA_ANY(str), VARSIZE_ANY_EXHDR(str));
|
}
|
|
/* Функция для преобразования любого поддерживаемого типа Datum в текст */
|
static text *datum_to_text(Datum value, Oid type_id, bool is_null, bool *needs_free)
|
{
|
*needs_free = false;
|
|
if (is_null)
|
{
|
*needs_free = true;
|
return cstring_to_text("");
|
}
|
|
switch (type_id)
|
{
|
case 9167: /* Oracle RAW */
|
{
|
*needs_free = true;
|
return raw_datum_to_hex_text(value);
|
}
|
case TEXTOID:
|
case VARCHAROID:
|
case BPCHAROID:
|
{
|
*needs_free = false;
|
return DatumGetTextPP(value);
|
}
|
case INT4OID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(int4out, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case INT8OID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(int8out, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case NUMERICOID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(numeric_out, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case FLOAT4OID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(float4out, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case FLOAT8OID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(float8out, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case BOOLOID:
|
{
|
char *str = DatumGetCString(DirectFunctionCall1(boolout, value));
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
case DATEOID:
|
{
|
DateADT date = DatumGetDateADT(value);
|
char result[16];
|
|
int jday = date + POSTGRES_EPOCH_JDATE;
|
int year, month, day;
|
j2date(jday, &year, &month, &day);
|
|
const char *months[] = {
|
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
|
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
|
};
|
|
if (month >= 1 && month <= 12)
|
snprintf(result, sizeof(result), "%02d-%s-%02d",
|
day, months[month - 1], year % 100);
|
else
|
snprintf(result, sizeof(result), "%02d-XXX-%02d", day, year % 100);
|
|
text *final_result = cstring_to_text(result);
|
*needs_free = true;
|
return final_result;
|
}
|
case TIMESTAMPOID:
|
case TIMESTAMPTZOID:
|
{
|
Timestamp timestamp = DatumGetTimestamp(value);
|
|
/* Распаковываем timestamp */
|
struct pg_tm tm;
|
fsec_t fsec;
|
int tz;
|
const char *tzn = NULL;
|
|
if (type_id == TIMESTAMPTZOID)
|
{
|
if (timestamp2tm(timestamp, &tz, &tm, &fsec, &tzn, NULL) != 0)
|
{
|
text *result = cstring_to_text("INVALID TIMESTAMP");
|
*needs_free = true;
|
return result;
|
}
|
}
|
else
|
{
|
if (timestamp2tm(timestamp, NULL, &tm, &fsec, NULL, NULL) != 0)
|
{
|
text *result = cstring_to_text("INVALID TIMESTAMP");
|
*needs_free = true;
|
return result;
|
}
|
}
|
|
/* Форматируем в Oracle-стиле */
|
char result[64];
|
const char *months[] =
|
{
|
"JAN", "FEB", "MAR", "APR", "MAY", "JUN",
|
"JUL", "AUG", "SEP", "OCT", "NOV", "DEC"
|
};
|
|
const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
|
int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
|
|
int month_index = tm.tm_mon;
|
if (month_index >= 1 && month_index <= 12)
|
{
|
/* Если месяц 1-12, преобразуем в 0-11 */
|
month_index = month_index - 1;
|
} else if (month_index < 0 || month_index > 11)
|
month_index = 0; /* fallback */
|
|
int nanoseconds = fsec * 1000;
|
|
snprintf(result, sizeof(result), "%02d-%s-%02d %02d.%02d.%02d.%09d %s",
|
tm.tm_mday, months[month_index],
|
(tm.tm_year + 1900) % 100,
|
hour12, tm.tm_min, tm.tm_sec,
|
nanoseconds, ampm);
|
|
text *final_result = cstring_to_text(result);
|
*needs_free = true;
|
return final_result;
|
}
|
case TIMEOID:
|
case TIMETZOID:
|
{
|
struct pg_tm tm;
|
fsec_t fsec;
|
int tz = 0;
|
char result[64];
|
|
if (type_id == TIMETZOID)
|
{
|
/* Для TIMETZ разбираем структуру */
|
TimeTzADT *timetz = (TimeTzADT *) DatumGetPointer(value);
|
TimeADT time = timetz->time;
|
tz = timetz->zone; /* смещение в секундах (положительное к UTC) */
|
|
if (time2tm(time, &tm, &fsec) != 0)
|
{
|
text *error_result = cstring_to_text("INVALID TIMETZ");
|
*needs_free = true;
|
return error_result;
|
}
|
|
/* Форматируем с часовым поясом */
|
const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
|
int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
|
int nanoseconds = fsec * 1000;
|
|
int tz_total_minutes = tz / 60; /* общее смещение в минутах */
|
int tz_hour = tz_total_minutes / 60;
|
int tz_minute = abs(tz_total_minutes) % 60;
|
|
char tz_sign = (tz >= 0) ? '-' : '+';
|
|
snprintf(result, sizeof(result), "%02d.%02d.%02d.%09d %s %c%02d:%02d",
|
hour12, tm.tm_min, tm.tm_sec, nanoseconds, ampm,
|
tz_sign, abs(tz_hour), tz_minute);
|
}
|
else
|
{
|
/* Для TIME */
|
TimeADT time = DatumGetTimeADT(value);
|
|
if (time2tm(time, &tm, &fsec) != 0)
|
{
|
text *error_result = cstring_to_text("INVALID TIME");
|
*needs_free = true;
|
return error_result;
|
}
|
|
const char *ampm = (tm.tm_hour < 12) ? "AM" : "PM";
|
int hour12 = (tm.tm_hour % 12 == 0) ? 12 : tm.tm_hour % 12;
|
int nanoseconds = fsec * 1000;
|
|
snprintf(result, sizeof(result), "%02d.%02d.%02d.%09d %s",
|
hour12, tm.tm_min, tm.tm_sec, nanoseconds, ampm);
|
}
|
|
text *final_result = cstring_to_text(result);
|
*needs_free = true;
|
return final_result;
|
}
|
case INTERVALOID:
|
{
|
/* Используем встроенную функцию для форматирования interval */
|
char *interval_str = DatumGetCString(DirectFunctionCall1(interval_out, value));
|
|
/* Преобразуем PostgreSQL формат в Oracle-подобный */
|
char result[64];
|
int days = 0, hours = 0, minutes = 0, seconds = 0, microsec = 0;
|
|
if (sscanf(interval_str, "%d day %d:%d:%d.%d",
|
&days, &hours, &minutes, &seconds, µsec) == 5)
|
{
|
snprintf(result, sizeof(result), "%+03d %02d:%02d:%02d.%06d",
|
days, hours, minutes, seconds, microsec);
|
}
|
else if (sscanf(interval_str, "%d:%d:%d.%d",
|
&hours, &minutes, &seconds, µsec) == 4)
|
{
|
snprintf(result, sizeof(result), "+00 %02d:%02d:%02d.%06d",
|
hours, minutes, seconds, microsec);
|
}
|
else
|
{
|
/* Если не удалось распарсить, используем как есть */
|
strncpy(result, interval_str, sizeof(result) - 1);
|
result[sizeof(result) - 1] = '\0';
|
}
|
|
text *final_result = cstring_to_text(result);
|
pfree(interval_str);
|
*needs_free = true;
|
return final_result;
|
}
|
default:
|
{
|
Oid output_function_id;
|
bool is_varlena;
|
|
/* Получаем информацию о функции вывода для типа */
|
getTypeOutputInfo(type_id, &output_function_id, &is_varlena);
|
|
/* Проверяем, что функция вывода существует */
|
if (!OidIsValid(output_function_id))
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("неподдерживаемый тип данных"),
|
errdetail("Тип OID %u не имеет функции вывода", type_id)));
|
}
|
|
char *str = OidOutputFunctionCall(output_function_id, value);
|
text *result = cstring_to_text(str);
|
pfree(str);
|
*needs_free = true;
|
return result;
|
}
|
}
|
}
|
|
/* Основная функция для добавления всех аргументов в буфер */
|
static void add_all_arguments(FunctionCallInfo fcinfo, const char* mode)
|
{
|
/* Создаем временный буфер для агрегации всех аргументов */
|
StringInfoData aggregated;
|
initStringInfo(&aggregated);
|
|
for (int i = 0; i < PG_NARGS(); i++)
|
{
|
Oid arg_type = get_fn_expr_argtype(fcinfo->flinfo, i);
|
|
if (arg_type == InvalidOid)
|
{
|
ereport(ERROR,
|
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
|
errmsg("неизвестный тип данных"),
|
errhint("Убедитесь, что передаваемые типы данных поддерживаются")));
|
}
|
|
bool needs_free = false;
|
text *arg_text = datum_to_text(PG_GETARG_DATUM(i), arg_type, PG_ARGISNULL(i), &needs_free);
|
|
char *arg_str = text_to_cstring(arg_text);
|
appendStringInfoString(&aggregated, arg_str);
|
pfree(arg_str);
|
|
if (needs_free) pfree(arg_text);
|
}
|
|
if (aggregated.len > 0)
|
{
|
text *final_text = cstring_to_text(aggregated.data);
|
|
if (strcmp(mode, "put_line") == 0)
|
{
|
/* Для put_line объединяем накопленные данные из put с текущими аргументами */
|
if (line_buffer != NULL && line_buffer_len > 0)
|
{
|
/* Добавляем текущие аргументы к накопленным данным */
|
add_text_to_line_buffer(final_text);
|
|
/* Теперь выводим объединенную строку */
|
{
|
DirectFunctionCall0(dbms_output_flush_line_buffer);
|
}
|
}
|
else
|
{
|
/* Если нет накопленных данных, просто выводим текущие аргументы */
|
add_text_to_main_buffer(final_text);
|
}
|
}
|
else if (strcmp(mode, "put") == 0)
|
add_text_to_line_buffer(final_text);
|
|
pfree(final_text);
|
}
|
|
pfree(aggregated.data);
|
}
|
|
/*
|
* @qdb_func: dbms_output_enable(int8)
|
* @ora_func: DBMS_OUTPUT.ENABLE(NUMBER)
|
*/
|
Datum dbms_output_enable(PG_FUNCTION_ARGS)
|
{
|
int64 n_buf_size;
|
if (PG_NARGS() == 0)
|
n_buf_size = BUFSIZE_DEFAULT;
|
else if (PG_ARGISNULL(0))
|
n_buf_size = BUFSIZE_UNLIMITED;
|
else
|
{
|
n_buf_size = PG_GETARG_INT64(0);
|
|
if (n_buf_size > BUFSIZE_MAX)
|
{
|
ereport(WARNING,
|
(errmsg("указанный размер буфера превышает максимальный"),
|
errdetail("Буфер будет установлен в максимальный размер %d байт", BUFSIZE_MAX),
|
errhint("Максимальный размер буфера ограничен %d байтами", BUFSIZE_MAX)));
|
n_buf_size = BUFSIZE_MAX;
|
}
|
else if (n_buf_size < BUFSIZE_MIN)
|
{
|
ereport(WARNING,
|
(errmsg("указанный размер буфера меньше минимального"),
|
errdetail("Буфер будет установлен в минимальный размер %d байт", BUFSIZE_MIN),
|
errhint("Минимальный размер буфера составляет %d байт", BUFSIZE_MIN)));
|
n_buf_size = BUFSIZE_MIN;
|
}
|
}
|
|
/* Если буфер уже активен - перевыделяем память по новому размеру */
|
if (main_buffer != NULL)
|
{
|
int old_size = main_buffer_size;
|
|
/* Перевыделяем память */
|
char *new_buffer = (char *) realloc(main_buffer, n_buf_size);
|
main_buffer = new_buffer;
|
main_buffer_size = n_buf_size;
|
|
/* Если новый размер больше старого, инициализируем новую память */
|
if (n_buf_size > old_size)
|
{
|
memset(main_buffer + old_size, 0, n_buf_size - old_size);
|
}
|
|
/* Очищаем содержимое буфера при переинициализации */
|
clear_main_buffer_internal();
|
}
|
else
|
{
|
/* Первоначальное выделение памяти */
|
main_buffer = (char *) malloc(n_buf_size);
|
main_buffer_size = n_buf_size;
|
main_buffer_len = 0;
|
main_buffer_get = 0;
|
main_buffer[0] = '\0';
|
}
|
|
/* Очищаем временный буфер */
|
clear_line_buffer_internal();
|
|
PG_RETURN_VOID();
|
}
|
|
/*
|
* @qdb_func: dbms_output_disable()
|
* @ora_func: DBMS_OUTPUT.DISABLE()
|
*/
|
Datum dbms_output_disable(PG_FUNCTION_ARGS)
|
{
|
if (main_buffer != NULL)
|
{
|
free(main_buffer);
|
main_buffer = NULL;
|
}
|
|
main_buffer_size = 0;
|
main_buffer_len = 0;
|
main_buffer_get = 0;
|
|
clear_line_buffer_internal();
|
|
PG_RETURN_VOID();
|
}
|
|
static text *dbms_output_next(void)
|
{
|
if (main_buffer == NULL || main_buffer_len == 0 || main_buffer_get >= main_buffer_len)
|
return NULL;
|
|
/* Находим начало следующей строки */
|
char *line_start = main_buffer + main_buffer_get;
|
|
/* Находим конец строки */
|
char *line_end = line_start;
|
while (line_end < main_buffer + main_buffer_len && *line_end != '\0')
|
line_end++;
|
|
/* Если не нашли нуль символ или это конец буфера */
|
if (line_end >= main_buffer + main_buffer_len || *line_end != '\0')
|
return NULL;
|
|
/* Длина строки */
|
int line_length = line_end - line_start;
|
|
/* Создаем text объект */
|
text *result = (text *) palloc(line_length + VARHDRSZ);
|
SET_VARSIZE(result, line_length + VARHDRSZ);
|
memcpy(VARDATA(result), line_start, line_length);
|
|
/* Помечаем строку как прочитанную */
|
memset(line_start, 0, line_length + 1);
|
|
/* Обновляем позицию чтения */
|
main_buffer_get = (line_end - main_buffer) + 1;
|
|
/* Если дошли до конца буфера - сбрасываем */
|
if (main_buffer_get >= main_buffer_len)
|
clear_main_buffer_internal();
|
|
return result;
|
}
|
|
/*
|
* @qdb_func: dbms_output_get_line(text, numeric)
|
* @ora_func: DBMS_OUTPUT.GET_LINE(VARCHAR2, NUMBER)
|
*/
|
Datum dbms_output_get_line(PG_FUNCTION_ARGS)
|
{
|
TupleDesc tupdesc;
|
Datum result;
|
HeapTuple tuple;
|
Datum values[2];
|
bool nulls[2] = { false, false };
|
text *line;
|
bool is_helper = called_as_sql_helper(fcinfo, "dbms_output_get_line_p");
|
|
/* Build a tuple descriptor for our result type */
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "Тип возвращаемого значения должен быть составным типом");
|
|
if ((line = dbms_output_next()) != NULL)
|
{
|
values[0] = PointerGetDatum(line);
|
values[1] = Int32GetDatum(0); /* 0: succeeded */
|
}
|
else
|
{
|
/*
|
* QDB/SQL*Plus-like behavior: if client is fetching output via helper
|
* wrapper (dbms_output_get_line_p) and there are no complete lines,
|
* discard any pending partial line accumulated by PUT().
|
*
|
* This prevents PUT() fragments from leaking across separate SQL
|
* statements in interactive clients that fetch output after each
|
* statement.
|
*/
|
if (is_helper)
|
clear_line_buffer_internal();
|
nulls[0] = true;
|
values[1] = Int32GetDatum(1); /* 1: failed */
|
}
|
|
tuple = heap_form_tuple(tupdesc, values, nulls);
|
result = HeapTupleGetDatum(tuple);
|
|
PG_RETURN_DATUM(result);
|
}
|
|
/*
|
* @qdb_func: dbms_output_get_lines(arraytype_p, int4)
|
* @ora_func: DBMS_OUTPUT.GET_LINES(LINES PL/SQL_TABLE, NUMBER)
|
* @ora_func: DBMS_OUTPUT.GET_LINES(LINES VARRAY, NUMBER)
|
*/
|
Datum dbms_output_get_lines(PG_FUNCTION_ARGS)
|
{
|
TupleDesc tupdesc;
|
Datum result;
|
HeapTuple tuple;
|
Datum values[2];
|
bool nulls[2] = { false, false };
|
text *line;
|
bool is_helper = called_as_sql_helper(fcinfo, "dbms_output_get_lines_p");
|
bool reached_end = false;
|
|
ArrayType *lines_array = PG_GETARG_ARRAYTYPE_P(0);
|
int32 max_lines = PG_GETARG_INT32(1);
|
int32 n;
|
ArrayBuildState *astate = NULL;
|
|
/* Build a tuple descriptor for our result type */
|
if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
|
elog(ERROR, "Тип возвращаемого значения должен быть составным типом");
|
|
for (n = 0; n < max_lines; n++)
|
{
|
line = dbms_output_next();
|
if (line == NULL)
|
{
|
reached_end = true;
|
break;
|
}
|
astate = accumArrayResult(astate, PointerGetDatum(line), false,
|
TEXTOID, CurrentMemoryContext);
|
}
|
|
/*
|
* Same rationale as in dbms_output_get_line(): if helper wrapper has
|
* reached end of available complete lines, drop any pending partial line.
|
* Do not do this when we stopped because max_lines was reached.
|
*/
|
if (is_helper && reached_end)
|
clear_line_buffer_internal();
|
|
/* 0: lines as text array */
|
if (n > 0)
|
values[0] = makeArrayResult(astate, CurrentMemoryContext);
|
else
|
{
|
int16 typlen;
|
bool typbyval;
|
char typalign;
|
ArrayType *arr;
|
|
get_typlenbyvalalign(TEXTOID, &typlen, &typbyval, &typalign);
|
arr = construct_md_array(
|
NULL,
|
NULL,
|
0, NULL, NULL, TEXTOID, typlen, typbyval, typalign);
|
values[0] = PointerGetDatum(arr);
|
}
|
|
/* 1: # of lines as integer */
|
values[1] = Int32GetDatum(n);
|
|
tuple = heap_form_tuple(tupdesc, values, nulls);
|
result = HeapTupleGetDatum(tuple);
|
|
PG_RETURN_DATUM(result);
|
}
|
|
/*
|
* @qdb_func: dbms_output_put(variadic)
|
* @ora_func: DBMS_OUTPUT.PUT(VARCHAR2)
|
*/
|
Datum dbms_output_put(PG_FUNCTION_ARGS)
|
{
|
if (main_buffer != NULL)
|
if (PG_NARGS() > 0)
|
add_all_arguments(fcinfo, "put");
|
|
PG_RETURN_VOID();
|
}
|
|
/*
|
* @qdb_func: dbms_output_new_line()
|
* @ora_func: DBMS_OUTPUT.NEW_LINE()
|
*/
|
Datum dbms_output_new_line(PG_FUNCTION_ARGS)
|
{
|
if (main_buffer != NULL)
|
DirectFunctionCall0(dbms_output_flush_line_buffer);
|
|
PG_RETURN_VOID();
|
}
|
|
/*
|
* @qdb_func: dbms_output_put_line(variadic)
|
* @ora_func: DBMS_OUTPUT.PUT_LINE(VARCHAR2)
|
*/
|
Datum dbms_output_put_line(PG_FUNCTION_ARGS)
|
{
|
if (main_buffer != NULL)
|
{
|
if (PG_NARGS() > 0)
|
add_all_arguments(fcinfo, "put_line");
|
else
|
DirectFunctionCall0(dbms_output_flush_line_buffer);
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
/// @brief Возвращает версию RUDB пакета DBMS_OUTPUT (Oracle DBMS_OUTPUT пакет)
|
Datum dbms_output_get_version(PG_FUNCTION_ARGS) {
|
PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_OUTPUT_VERSION));
|
}
|
|
/* Отправка временного буфера в основной буфер */
|
Datum dbms_output_flush_line_buffer(PG_FUNCTION_ARGS)
|
{
|
if (line_buffer != NULL && line_buffer_len > 0)
|
{
|
text *message = cstring_to_text(line_buffer);
|
add_text_to_main_buffer(message);
|
pfree(message);
|
|
line_buffer_len = 0;
|
line_buffer[0] = '\0';
|
}
|
|
PG_RETURN_VOID();
|
}
|
|
} // extern "C"
|