#include "dbms_lob_bfile.hpp"
|
#include <sys/stat.h>
|
#include <unistd.h>
|
#include <fcntl.h>
|
#include <errno.h>
|
#include <cstring>
|
#include <vector>
|
#include <cstdlib>
|
#include <limits.h> // для PATH_MAX
|
|
extern "C" {
|
#include "postgres.h"
|
#include "fmgr.h"
|
#include "utils/builtins.h"
|
#include "executor/spi.h"
|
#include "funcapi.h"
|
#include "utils/numeric.h"
|
#include "access/htup_details.h"
|
#include "catalog/pg_type.h"
|
}
|
|
// Реализация BFileManager
|
std::unordered_map<std::string, BFileInfo> BFileManager::open_files;
|
MemoryContext BFileManager::bfile_context = NULL;
|
|
static bool
|
bfile_filename_is_safe(const char *filename)
|
{
|
const char *part;
|
|
if (filename == nullptr || filename[0] == '\0' || filename[0] == '/')
|
return false;
|
|
part = filename;
|
while (*part != '\0')
|
{
|
const char *slash = strchr(part, '/');
|
size_t len = slash ? static_cast<size_t>(slash - part) : strlen(part);
|
|
if (len == 2 && part[0] == '.' && part[1] == '.')
|
return false;
|
|
if (!slash)
|
break;
|
part = slash + 1;
|
}
|
|
return true;
|
}
|
|
void BFileManager::Initialize() {
|
if (bfile_context == NULL) {
|
bfile_context = AllocSetContextCreate(TopMemoryContext,
|
"DBMS_LOB BFILE Context",
|
ALLOCSET_DEFAULT_SIZES);
|
}
|
}
|
|
void BFileManager::Cleanup() {
|
CloseAllFiles();
|
if (bfile_context != NULL) {
|
MemoryContextDelete(bfile_context);
|
bfile_context = NULL;
|
}
|
}
|
|
BFileInfo* BFileManager::GetBFileInfo(text* bfile) {
|
std::string key = GetBFileKey(bfile);
|
auto it = open_files.find(key);
|
if (it != open_files.end()) {
|
return &(it->second);
|
}
|
return nullptr;
|
}
|
|
void BFileManager::RegisterBFile(text* bfile, const char* dir_alias, const char* filename) {
|
std::string key = MakeKey(dir_alias, filename);
|
BFileInfo info;
|
info.directory_alias = dir_alias;
|
info.filename = filename;
|
info.full_path = GetFullPath(dir_alias, filename);
|
open_files[key] = info;
|
}
|
|
void BFileManager::UnregisterBFile(text* bfile) {
|
std::string key = GetBFileKey(bfile);
|
auto it = open_files.find(key);
|
if (it != open_files.end()) {
|
if (it->second.is_open && it->second.fd >= 0) {
|
close(it->second.fd);
|
}
|
open_files.erase(it);
|
}
|
}
|
|
void BFileManager::CloseAllFiles() {
|
for (auto& pair : open_files) {
|
if (pair.second.is_open && pair.second.fd >= 0) {
|
close(pair.second.fd);
|
pair.second.fd = -1;
|
pair.second.is_open = false;
|
}
|
}
|
}
|
|
bool BFileManager::IsOpen(text* bfile) {
|
BFileInfo* info = GetBFileInfo(bfile);
|
return info && info->is_open;
|
}
|
|
int BFileManager::OpenFile(text* bfile) {
|
BFileInfo* info = GetBFileInfo(bfile);
|
if (!info) {
|
return -1;
|
}
|
|
if (info->is_open) {
|
return info->fd; // Already open
|
}
|
|
info->fd = open(info->full_path.c_str(), O_RDONLY);
|
if (info->fd >= 0) {
|
info->is_open = true;
|
}
|
return info->fd;
|
}
|
|
void BFileManager::CloseFile(text* bfile) {
|
BFileInfo* info = GetBFileInfo(bfile);
|
if (info && info->is_open && info->fd >= 0) {
|
close(info->fd);
|
info->fd = -1;
|
info->is_open = false;
|
}
|
}
|
|
int64 BFileManager::GetLength(text* bfile) {
|
char *dir_alias = nullptr;
|
char *filename = nullptr;
|
struct stat st;
|
|
parse_bfile(bfile, &dir_alias, &filename);
|
std::string full_path = GetFullPath(dir_alias, filename);
|
pfree(dir_alias);
|
pfree(filename);
|
|
if (stat(full_path.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("non-existent directory or file"),
|
errdetail("ORA-22285: non-existent directory or file for GETLENGTH operation")));
|
}
|
|
return static_cast<int64>(st.st_size);
|
}
|
|
bytea* BFileManager::ReadFile(text* bfile, int64 offset, int32 amount) {
|
BFileInfo *info;
|
int fd;
|
bool close_fd = false;
|
ssize_t bytes_read;
|
bytea *result;
|
|
if (offset < 0 || amount < 0) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid BFILE read range")));
|
}
|
|
info = GetBFileInfo(bfile);
|
if (info && info->is_open && info->fd >= 0) {
|
fd = info->fd;
|
} else {
|
char *dir_alias = nullptr;
|
char *filename = nullptr;
|
|
parse_bfile(bfile, &dir_alias, &filename);
|
std::string full_path = GetFullPath(dir_alias, filename);
|
pfree(dir_alias);
|
pfree(filename);
|
|
fd = open(full_path.c_str(), O_RDONLY);
|
if (fd < 0) {
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("could not open BFILE \"%s\": %m", full_path.c_str())));
|
}
|
close_fd = true;
|
}
|
|
result = (bytea *) palloc(VARHDRSZ + amount);
|
bytes_read = pread(fd, VARDATA(result), amount, static_cast<off_t>(offset));
|
if (bytes_read < 0) {
|
if (close_fd)
|
close(fd);
|
pfree(result);
|
ereport(ERROR,
|
(errcode_for_file_access(),
|
errmsg("could not read BFILE: %m")));
|
}
|
|
if (close_fd)
|
close(fd);
|
|
SET_VARSIZE(result, VARHDRSZ + bytes_read);
|
return result;
|
}
|
|
std::string BFileManager::GetFullPath(const char* dir_alias, const char* filename) {
|
if (!bfile_filename_is_safe(filename)) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid BFILE filename"),
|
errdetail("BFILE filename must remain within the configured directory")));
|
}
|
|
// Универсальная реализация с поддержкой переменных окружения
|
// В реальной реализации нужно брать из системного каталога
|
|
if (strcmp(dir_alias, "TEMP_DIR") == 0) {
|
// Список путей для поиска файлов (в порядке приоритета)
|
std::vector<std::string> search_paths;
|
|
// 1. Проверяем переменную окружения QDB_TEMP_DIR_PATH
|
const char* env_temp_dir = getenv("QDB_TEMP_DIR_PATH");
|
if (env_temp_dir && strlen(env_temp_dir) > 0) {
|
search_paths.push_back(std::string(env_temp_dir) + "/");
|
}
|
|
// 2. Проверяем переменную окружения QDB_TEST_DATA_PATH (для тестов)
|
const char* env_test_data = getenv("QDB_TEST_DATA_PATH");
|
if (env_test_data && strlen(env_test_data) > 0) {
|
search_paths.push_back(std::string(env_test_data) + "/");
|
}
|
|
// 3. Определяем базовый путь для относительного пути tests/test_data/python/
|
// Поиск базового пути в порядке приоритета:
|
std::vector<std::string> base_paths;
|
|
// 3a. Используем переменную QDATABASE_HOME если установлена
|
const char* qdb_home = getenv("QDATABASE_HOME");
|
if (qdb_home && strlen(qdb_home) > 0) {
|
base_paths.push_back(std::string(qdb_home) + "/");
|
}
|
|
// 3b. Путь к исходникам PostgreSQL из переменной окружения
|
const char* pg_src = getenv("PG_SRC");
|
if (pg_src && strlen(pg_src) > 0) {
|
base_paths.push_back(std::string(pg_src) + "/");
|
}
|
|
// 3c. Определяем путь относительно исполняемого файла postgres
|
char exe_path[PATH_MAX];
|
ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
|
if (len != -1) {
|
exe_path[len] = '\0';
|
char* dir_end = strrchr(exe_path, '/');
|
if (dir_end) {
|
*dir_end = '\0'; // Удаляем имя исполняемого файла
|
// Поднимаемся до корня установки (обычно ../.. от bin/)
|
char* parent_dir = strrchr(exe_path, '/');
|
if (parent_dir) {
|
*parent_dir = '\0';
|
base_paths.push_back(std::string(exe_path) + "/");
|
}
|
}
|
}
|
|
// 3d. Проверяем текущую рабочую директорию и ее родительские директории
|
char cwd[PATH_MAX];
|
if (getcwd(cwd, sizeof(cwd)) != NULL) {
|
std::string current_dir = std::string(cwd);
|
while (!current_dir.empty() && current_dir != "/") {
|
base_paths.push_back(current_dir + "/");
|
|
// Поднимаемся на уровень выше
|
size_t last_slash = current_dir.find_last_of('/');
|
if (last_slash != std::string::npos && last_slash > 0) {
|
current_dir = current_dir.substr(0, last_slash);
|
} else {
|
break;
|
}
|
}
|
}
|
|
// Добавляем относительные пути с найденными базовыми путями
|
for (const auto& base_path : base_paths) {
|
search_paths.push_back(base_path + "tests/test_data/python/");
|
}
|
|
// 4. Стандартный путь /tmp как fallback
|
search_paths.push_back("/tmp/");
|
|
// Ищем файл в указанных путях
|
struct stat st;
|
for (const auto& base_path : search_paths) {
|
std::string full_path = base_path + filename;
|
if (stat(full_path.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
|
return full_path;
|
}
|
}
|
|
// Если файл не найден нигде, возвращаем /tmp/ как надежный fallback
|
// (это позволит создать файл в стандартном месте или выдать корректную ошибку)
|
return "/tmp/" + std::string(filename);
|
}
|
|
// Для других директорий возвращаем ошибку
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("non-existent directory or file"),
|
errdetail("ORA-22285: non-existent directory or file for %s operation", "FILEOPEN")));
|
|
// Недостижимый код, но нужен для компилятора
|
return "";
|
}
|
|
// Утилиты для работы с BFILE
|
extern "C" {
|
|
void parse_bfile(text* bfile, char** dir_alias, char** filename) {
|
if (!bfile) {
|
*dir_alias = NULL;
|
*filename = NULL;
|
return;
|
}
|
|
char* bfile_str = text_to_cstring(bfile);
|
char* separator = strchr(bfile_str, BFILE_SEPARATOR);
|
|
if (!separator) {
|
ereport(ERROR,
|
(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
|
errmsg("invalid BFILE format"),
|
errdetail("BFILE must be in format 'directory:filename'")));
|
}
|
|
*separator = '\0';
|
*dir_alias = pstrdup(bfile_str);
|
*filename = pstrdup(separator + 1);
|
|
pfree(bfile_str);
|
}
|
|
text* make_bfile(const char* dir_alias, const char* filename) {
|
if (!dir_alias || !filename) {
|
return NULL;
|
}
|
|
size_t len = strlen(dir_alias) + strlen(filename) + 2; // +1 for separator, +1 for \0
|
char* bfile_str = (char*)palloc(len);
|
snprintf(bfile_str, len, "%s%c%s", dir_alias, BFILE_SEPARATOR, filename);
|
|
text* result = cstring_to_text(bfile_str);
|
pfree(bfile_str);
|
return result;
|
}
|
|
bool bfile_exists(const char* dir_alias, const char* filename) {
|
std::string full_path = BFileManager::GetFullPath(dir_alias, filename);
|
struct stat st;
|
return (stat(full_path.c_str(), &st) == 0 && S_ISREG(st.st_mode));
|
}
|
|
} // extern "C"
|
|
// Новые методы для работы с ключами
|
std::string BFileManager::GetBFileKey(text* bfile) {
|
char *dir_alias, *filename;
|
parse_bfile(bfile, &dir_alias, &filename);
|
std::string key = MakeKey(dir_alias, filename);
|
pfree(dir_alias);
|
pfree(filename);
|
return key;
|
}
|
|
std::string BFileManager::MakeKey(const char* dir_alias, const char* filename) {
|
return std::string(dir_alias) + ":" + std::string(filename);
|
}
|