Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
#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);
}