Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
#include "dbms_pipe_buffer.hpp"
 
extern "C"
{
#include "utils/elog.h"
#include "utils/memutils.h"
#include "varatt.h"
}
 
static constexpr Size DBMS_PIPE_LOCAL_BUFFER_LIMIT = 32766;
static constexpr Size DBMS_PIPE_GENERIC_ITEM_OVERHEAD = 3;
static constexpr Size DBMS_PIPE_VARCHAR2_ITEM_OVERHEAD = 6;
 
struct DbmsPipeBufferItem
{
    DbmsPipeBufferItem *next;
    int32 type_code;
    Size data_bytes;
    bool is_null;
    char data[FLEXIBLE_ARRAY_MEMBER];
};
 
struct DbmsPipeOutgoingBuffer
{
    MemoryContext context;
    DbmsPipeBufferItem *head;
    DbmsPipeBufferItem *tail;
    Size accounted_bytes;
};
 
enum class DbmsPipeReadState
{
    FRESH,
    NO_RECEIVED_MESSAGE,
    RECEIVED_MESSAGE,
    INVALID
};
 
struct DbmsPipeIncomingBuffer
{
    MemoryContext context;
    DbmsPipeBufferItem *head;
    DbmsPipeBufferItem *tail;
    DbmsPipeBufferItem *cursor;
    bool has_retained_message;
    DbmsPipeReadState state;
};
 
/* Внутренний формат передачи typed items между backend-ами RuDB. */
struct DbmsPipeSerializedItemHeader
{
    int32 type_code;
    uint32 data_bytes;
    uint8 is_null;
    uint8 reserved[3];
};
 
static DbmsPipeOutgoingBuffer dbms_pipe_outgoing_buffer = {};
static DbmsPipeIncomingBuffer dbms_pipe_incoming_buffer = {
    nullptr,
    nullptr,
    nullptr,
    nullptr,
    false,
    DbmsPipeReadState::FRESH
};
 
static void
dbms_pipe_buffer_ensure_outgoing_context()
{
    if (dbms_pipe_outgoing_buffer.context == nullptr)
        dbms_pipe_outgoing_buffer.context =
            AllocSetContextCreate(TopMemoryContext,
                                  "DBMS_PIPE outgoing buffer",
                                  ALLOCSET_SMALL_SIZES);
}
 
static void
dbms_pipe_buffer_check_capacity(Size item_bytes)
{
    if (item_bytes > DBMS_PIPE_LOCAL_BUFFER_LIMIT ||
        dbms_pipe_outgoing_buffer.accounted_bytes >
            DBMS_PIPE_LOCAL_BUFFER_LIMIT - item_bytes)
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("ORA-06558: buffer in dbms_pipe package is full.  "
                        "No more items allowed")));
}
 
static DbmsPipeBufferItem *
dbms_pipe_buffer_allocate_item(MemoryContext context, DbmsPipeItemType type_code,
                               const void *data, Size data_bytes, bool is_null)
{
    const Size allocation_size = offsetof(DbmsPipeBufferItem, data) + data_bytes;
    auto *const item = static_cast<DbmsPipeBufferItem *>(
        MemoryContextAlloc(context, allocation_size));
 
    item->next = nullptr;
    item->type_code = type_code;
    item->data_bytes = data_bytes;
    item->is_null = is_null;
 
    if (!is_null && data_bytes > 0)
        memcpy(item->data, data, data_bytes);
 
    return item;
}
 
static void
dbms_pipe_buffer_append(DbmsPipeItemType type_code, const void *data,
                        Size data_bytes, bool is_null, Size accounted_bytes)
{
    dbms_pipe_buffer_check_capacity(accounted_bytes);
    dbms_pipe_buffer_ensure_outgoing_context();
 
    DbmsPipeBufferItem *const packed =
        dbms_pipe_buffer_allocate_item(dbms_pipe_outgoing_buffer.context,
                                      type_code, data, data_bytes, is_null);
 
    if (dbms_pipe_outgoing_buffer.tail == nullptr)
        dbms_pipe_outgoing_buffer.head = packed;
    else
        dbms_pipe_outgoing_buffer.tail->next = packed;
 
    dbms_pipe_outgoing_buffer.tail = packed;
    dbms_pipe_outgoing_buffer.accounted_bytes += accounted_bytes;
 
    if (dbms_pipe_incoming_buffer.state != DbmsPipeReadState::RECEIVED_MESSAGE)
        dbms_pipe_incoming_buffer.state =
            DbmsPipeReadState::NO_RECEIVED_MESSAGE;
}
 
static void
dbms_pipe_buffer_pack_varlena(DbmsPipeItemType type_code,
                              const varlena *item, bool is_null,
                              Size item_overhead)
{
    const Size logical_bytes = is_null ? 0 : VARSIZE_ANY_EXHDR(item);
    const Size stored_bytes = is_null ? 0 : VARSIZE_ANY(item);
 
    dbms_pipe_buffer_append(type_code, item, stored_bytes, is_null,
                            logical_bytes + item_overhead);
}
 
static void
dbms_pipe_buffer_clear_outgoing()
{
    if (dbms_pipe_outgoing_buffer.context != nullptr)
        MemoryContextReset(dbms_pipe_outgoing_buffer.context);
 
    dbms_pipe_outgoing_buffer.head = nullptr;
    dbms_pipe_outgoing_buffer.tail = nullptr;
    dbms_pipe_outgoing_buffer.accounted_bytes = 0;
}
 
static void
dbms_pipe_buffer_clear_incoming()
{
    if (dbms_pipe_incoming_buffer.context != nullptr)
        MemoryContextReset(dbms_pipe_incoming_buffer.context);
 
    dbms_pipe_incoming_buffer.head = nullptr;
    dbms_pipe_incoming_buffer.tail = nullptr;
    dbms_pipe_incoming_buffer.cursor = nullptr;
}
 
static void
dbms_pipe_buffer_raise_empty()
{
    ereport(ERROR,
            (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
             errmsg("ORA-06556: the pipe is empty, cannot fulfill the "
                    "unpack_message request")));
}
 
void
dbms_pipe_buffer_pack_varchar2(const text *item, bool is_null)
{
    dbms_pipe_buffer_pack_varlena(DBMS_PIPE_ITEM_VARCHAR2, item, is_null,
                                 DBMS_PIPE_VARCHAR2_ITEM_OVERHEAD);
}
 
void
dbms_pipe_buffer_pack_number(Numeric item, bool is_null)
{
    dbms_pipe_buffer_pack_varlena(DBMS_PIPE_ITEM_NUMBER,
                                 reinterpret_cast<const varlena *>(item),
                                 is_null,
                                 DBMS_PIPE_GENERIC_ITEM_OVERHEAD);
}
 
void
dbms_pipe_buffer_pack_date(Timestamp item, bool is_null)
{
    dbms_pipe_buffer_append(DBMS_PIPE_ITEM_DATE,
                            is_null ? nullptr : &item,
                            is_null ? 0 : sizeof(item),
                            is_null,
                            (is_null ? 0 : sizeof(item)) +
                                DBMS_PIPE_GENERIC_ITEM_OVERHEAD);
}
 
void
dbms_pipe_buffer_pack_raw(const bytea *item, bool is_null)
{
    dbms_pipe_buffer_pack_varlena(DBMS_PIPE_ITEM_RAW, item, is_null,
                                 DBMS_PIPE_GENERIC_ITEM_OVERHEAD);
}
 
void
dbms_pipe_buffer_pack_rowid(const text *item, bool is_null)
{
    dbms_pipe_buffer_pack_varlena(DBMS_PIPE_ITEM_ROWID, item, is_null,
                                 DBMS_PIPE_GENERIC_ITEM_OVERHEAD);
}
 
DbmsPipeSerializedMessage
dbms_pipe_buffer_serialize_outgoing()
{
    DbmsPipeSerializedMessage message = {
        nullptr,
        0,
        dbms_pipe_outgoing_buffer.accounted_bytes
    };
 
    for (DbmsPipeBufferItem *item = dbms_pipe_outgoing_buffer.head;
         item != nullptr;
         item = item->next)
    {
        const Size item_bytes = sizeof(DbmsPipeSerializedItemHeader) +
            item->data_bytes;
 
        if (message.data_bytes > MaxAllocSize - item_bytes)
            ereport(ERROR,
                    (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                     errmsg("DBMS_PIPE serialized message is too large")));
 
        message.data_bytes += item_bytes;
    }
 
    if (message.data_bytes == 0)
        return message;
 
    message.data = static_cast<char *>(palloc(message.data_bytes));
    Size offset = 0;
 
    for (DbmsPipeBufferItem *item = dbms_pipe_outgoing_buffer.head;
         item != nullptr;
         item = item->next)
    {
        DbmsPipeSerializedItemHeader header = {};
        header.type_code = item->type_code;
        header.data_bytes = static_cast<uint32>(item->data_bytes);
        header.is_null = item->is_null ? 1 : 0;
 
        memcpy(message.data + offset, &header, sizeof(header));
        offset += sizeof(header);
 
        if (item->data_bytes > 0)
        {
            memcpy(message.data + offset, item->data, item->data_bytes);
            offset += item->data_bytes;
        }
    }
 
    Assert(offset == message.data_bytes);
    return message;
}
 
void
dbms_pipe_buffer_send_succeeded()
{
    dbms_pipe_buffer_clear_outgoing();
 
    if (dbms_pipe_incoming_buffer.state != DbmsPipeReadState::RECEIVED_MESSAGE)
        dbms_pipe_incoming_buffer.state =
            DbmsPipeReadState::NO_RECEIVED_MESSAGE;
}
 
void
dbms_pipe_buffer_receive_succeeded(const char *data, Size data_bytes)
{
    /*
     * Сначала полностью разбираем сообщение в новом контексте.
     * Ошибка не должна разрушать сохранённое принятое сообщение.
     */
    MemoryContext new_context = AllocSetContextCreate(TopMemoryContext,
                                "DBMS_PIPE incoming buffer",
                                ALLOCSET_SMALL_SIZES);
    DbmsPipeBufferItem *head = nullptr;
    DbmsPipeBufferItem *tail = nullptr;
 
    PG_TRY();
    {
        Size offset = 0;
 
        while (offset < data_bytes)
        {
            if (data_bytes - offset < sizeof(DbmsPipeSerializedItemHeader))
                ereport(ERROR,
                        (errcode(ERRCODE_DATA_CORRUPTED),
                         errmsg("corrupt DBMS_PIPE message header")));
 
            DbmsPipeSerializedItemHeader header;
            memcpy(&header, data + offset, sizeof(header));
            offset += sizeof(header);
 
            if (header.data_bytes > data_bytes - offset)
                ereport(ERROR,
                        (errcode(ERRCODE_DATA_CORRUPTED),
                         errmsg("corrupt DBMS_PIPE message payload")));
 
            const auto type_code = static_cast<DbmsPipeItemType>(header.type_code);
            DbmsPipeBufferItem *const item =
                dbms_pipe_buffer_allocate_item(new_context,
                                                type_code,
                                                data + offset,
                                                header.data_bytes,
                                                header.is_null != 0);
 
            if (tail == nullptr)
                head = item;
            else
                tail->next = item;
 
            tail = item;
            offset += header.data_bytes;
        }
    }
    PG_CATCH();
    {
        MemoryContextDelete(new_context);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    if (dbms_pipe_incoming_buffer.context != nullptr)
        MemoryContextDelete(dbms_pipe_incoming_buffer.context);
 
    dbms_pipe_incoming_buffer.context = new_context;
    dbms_pipe_incoming_buffer.head = head;
    dbms_pipe_incoming_buffer.tail = tail;
    dbms_pipe_incoming_buffer.cursor = head;
    dbms_pipe_incoming_buffer.has_retained_message = true;
    dbms_pipe_incoming_buffer.state = DbmsPipeReadState::RECEIVED_MESSAGE;
}
 
void
dbms_pipe_buffer_receive_failed()
{
    dbms_pipe_incoming_buffer.state = DbmsPipeReadState::INVALID;
}
 
void
dbms_pipe_buffer_purge_read_state()
{
    /*
     * PURGE не затрагивает исходящий packed payload, но делает прежнее
     * received message недоступным для NEXT_ITEM_TYPE/UNPACK/RESET replay.
     */
    dbms_pipe_buffer_clear_incoming();
    dbms_pipe_incoming_buffer.has_retained_message = false;
    dbms_pipe_incoming_buffer.state = DbmsPipeReadState::INVALID;
}
 
int32
dbms_pipe_buffer_next_item_type()
{
    switch (dbms_pipe_incoming_buffer.state)
    {
        case DbmsPipeReadState::RECEIVED_MESSAGE:
            if (dbms_pipe_incoming_buffer.cursor == nullptr)
                return DBMS_PIPE_ITEM_END;
            return dbms_pipe_incoming_buffer.cursor->type_code;
 
        case DbmsPipeReadState::NO_RECEIVED_MESSAGE:
            return DBMS_PIPE_ITEM_NO_RECEIVED_MESSAGE;
 
        case DbmsPipeReadState::FRESH:
        case DbmsPipeReadState::INVALID:
            dbms_pipe_buffer_raise_empty();
    }
 
    pg_unreachable();
}
 
DbmsPipeUnpackedItem
dbms_pipe_buffer_unpack(DbmsPipeItemType expected_type)
{
    if (dbms_pipe_incoming_buffer.state != DbmsPipeReadState::RECEIVED_MESSAGE ||
        dbms_pipe_incoming_buffer.cursor == nullptr)
        dbms_pipe_buffer_raise_empty();
 
    DbmsPipeBufferItem *const item = dbms_pipe_incoming_buffer.cursor;
    if (item->type_code != expected_type)
        ereport(ERROR,
                (errcode(ERRCODE_DATATYPE_MISMATCH),
                 errmsg("ORA-06559: wrong datatype requested, %d, "
                        "actual datatype is %d",
                        static_cast<int>(expected_type), item->type_code)));
 
    dbms_pipe_incoming_buffer.cursor = item->next;
 
    return {
        item->is_null ? nullptr : item->data,
        item->data_bytes,
        item->is_null
    };
}
 
void
dbms_pipe_buffer_reset()
{
    dbms_pipe_buffer_clear_outgoing();
 
    if (dbms_pipe_incoming_buffer.has_retained_message)
    {
        dbms_pipe_incoming_buffer.cursor = dbms_pipe_incoming_buffer.head;
        dbms_pipe_incoming_buffer.state = DbmsPipeReadState::RECEIVED_MESSAGE;
    }
    else
        dbms_pipe_incoming_buffer.state =
            DbmsPipeReadState::NO_RECEIVED_MESSAGE;
}