Исходный код СУБД 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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
extern "C" {
#include "postgres.h"
#include "fmgr.h"
#include "utils/builtins.h"
#include "utils/varlena.h"
#include "catalog/pg_type.h"
}
 
#include <string>
#include <vector>
#include <algorithm>
#include <cstring>
 
PG_MODULE_MAGIC;
 
extern "C" {
PG_FUNCTION_INFO_V1(utl_encode_base64_encode);
PG_FUNCTION_INFO_V1(utl_encode_base64_decode);
PG_FUNCTION_INFO_V1(utl_encode_base64_decode_internal);
PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_encode);
PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_decode);
PG_FUNCTION_INFO_V1(utl_encode_mimeheader_encode);
PG_FUNCTION_INFO_V1(utl_encode_mimeheader_decode);
PG_FUNCTION_INFO_V1(utl_encode_text_encode);
PG_FUNCTION_INFO_V1(utl_encode_text_decode);
PG_FUNCTION_INFO_V1(utl_encode_uuencode);
PG_FUNCTION_INFO_V1(utl_encode_uudecode);
 
/* Доп. перегрузки для консоли DBEAVER-LIKE
PG_FUNCTION_INFO_V1(utl_encode_base64_decode_vc);
PG_FUNCTION_INFO_V1(utl_encode_quoted_printable_decode_vc);
PG_FUNCTION_INFO_V1(utl_encode_uudecode_vc); */
 
PG_FUNCTION_INFO_V1(utl_encode_get_version);
 
/// @brief Версия RUDB пакета UTL_ENCODE (Oracle UTL_ENCODE пакет)
#define RUDB_UTL_ENCODE_VERSION "1.0.0"
}
 
namespace {
 
/// @brief Конвертирует Datum bytea в std::string байтов через byteaout и парсинг "\\x…".
inline std::string bytea_to_bytes(Datum d)
{
    // byteaout возвращает C-строку в hex-формате: "\\xDEADBEEF"
    char* out = (char*) DirectFunctionCall1(byteaout, d); 
    if (!out) return {};
    std::string s(out);
    pfree(out);
    if (s.size() < 2 || !(s[0] == '\\' && s[1] == 'x'))
        ereport(ERROR,
            (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
             errmsg("UTL_ENCODE: unexpected byteaout format")));
    std::string bytes;
    bytes.reserve((s.size() - 2) / 2);
    auto hexv = [](char ch)->int{
        if (ch>='0'&&ch<='9') return ch-'0';
        if (ch>='A'&&ch<='F') return 10+(ch-'A');
        if (ch>='a'&&ch<='f') return 10+(ch-'a');
        return -1;
    };
    for (size_t i=2;i+1<s.size();i+=2){
        int hi=hexv(s[i]), lo=hexv(s[i+1]);
        if (hi<0||lo<0)
            ereport(ERROR,
                (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                 errmsg("UTL_ENCODE: invalid hex in byteaout")));
        bytes.push_back(char((hi<<4)|lo));
    }
    return bytes;
}
 
/// @brief Конвертирует std::string байтов в Datum bytea через формирование "\\x…" и byteain.
inline Datum bytes_to_bytea(const std::string& bytes)
{
    static const char* hexdigits="0123456789abcdef";
    std::string hex; hex.reserve(2+bytes.size()*2);
    hex.push_back('\\'); hex.push_back('x');
    for (unsigned char b: bytes){ hex.push_back(hexdigits[b>>4]); hex.push_back(hexdigits[b&0xF]); }
    char* c = pstrdup(hex.c_str());
    Datum res = DirectFunctionCall1(byteain, CStringGetDatum(c));
    return res;
}
 
/// @brief Преобразует PostgreSQL text* в std::string без перекодировки.
inline std::string text_to_std_string(text* t)
{
    char* c = text_to_cstring(t);
    std::string s(c);
    pfree(c);
    return s;
}
 
/// @brief Упаковывает std::string в PostgreSQL text* (Datum).
inline Datum std_string_to_text(const std::string& s)
{
    return PointerGetDatum(cstring_to_text_with_len(s.data(), (int)s.size()));
}
 
/// hex → nibble (0..15), или -1
inline int hex_nibble(unsigned char ch){
    if (ch>='0'&&ch<='9') return ch-'0';
    if (ch>='A'&&ch<='F') return 10+(ch-'A');
    if (ch>='a'&&ch<='f') return 10+(ch-'a');
    return -1;
}
inline bool looks_like_ascii_hex(const std::string& s){
    if (s.size()<2 || (s.size()&1)) return false;
    for (unsigned char c: s) if (hex_nibble(c)<0) return false;
    return true;
}
inline std::string coerce_hex_ascii_to_bytes(const std::string& maybe_hex){
    if (!looks_like_ascii_hex(maybe_hex)) return maybe_hex;
    std::string out; out.reserve(maybe_hex.size()/2);
    for (size_t i=0;i<maybe_hex.size();i+=2){
        int hi=hex_nibble((unsigned char)maybe_hex[i]);
        int lo=hex_nibble((unsigned char)maybe_hex[i+1]);
        out.push_back(char((hi<<4)|lo));
    }
    return out;
}
 
// ---------- Base64 ----------
static const char B64_TABLE[] =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
 
inline std::string base64_encode_bytes(const std::string& in)
{
    std::string out; out.reserve(((in.size()+2)/3)*4);
    size_t i=0; while (i+3<=in.size()){
        unsigned a=(unsigned char)in[i++], b=(unsigned char)in[i++], c=(unsigned char)in[i++];
        out.push_back(B64_TABLE[a>>2]);
        out.push_back(B64_TABLE[((a&3)<<4)|(b>>4)]);
        out.push_back(B64_TABLE[((b&0xF)<<2)|(c>>6)]);
        out.push_back(B64_TABLE[c&0x3F]);
    }
    size_t rem=in.size()-i;
    if (rem==1){
        unsigned a=(unsigned char)in[i++];
        out.push_back(B64_TABLE[a>>2]);
        out.push_back(B64_TABLE[(a&3)<<4]);
        out.push_back('='); out.push_back('=');
    } else if (rem==2){
        unsigned a=(unsigned char)in[i++], b=(unsigned char)in[i++];
        out.push_back(B64_TABLE[a>>2]);
        out.push_back(B64_TABLE[((a&3)<<4)|(b>>4)]);
        out.push_back(B64_TABLE[(b&0xF)<<2]);
        out.push_back('=');
    }
    return out;
}
 
inline std::string base64_decode_bytes(const std::string& in_raw)
{
    std::string in; in.reserve(in_raw.size());
    for (unsigned char ch: in_raw){ if (ch==' '||ch=='\t'||ch=='\r'||ch=='\n') continue; in.push_back((char)ch); }
    int8_t inv[256]; std::fill(std::begin(inv), std::end(inv), (int8_t)-1);
    for (int i=0;i<64;++i) inv[(unsigned char)B64_TABLE[i]]=(int8_t)i;
    inv[(unsigned char)'=']=-2;
    if (in.size()%4!=0)
        ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
            errmsg("UTL_ENCODE.BASE64_DECODE: input length not multiple of 4")));
    std::string out; out.reserve((in.size()/4)*3);
    for (size_t i=0;i<in.size();i+=4){
        int8_t a=inv[(unsigned char)in[i]], b=inv[(unsigned char)in[i+1]];
        int8_t c=inv[(unsigned char)in[i+2]], d=inv[(unsigned char)in[i+3]];
        if (a<0||b<0||(c==-1)||(d==-1))
            ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                errmsg("UTL_ENCODE.BASE64_DECODE: invalid character")));
        if (c==-2 && d!=-2)
            ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                errmsg("UTL_ENCODE.BASE64_DECODE: invalid padding")));
        unsigned x=((unsigned)a<<18)|((unsigned)b<<12)|((c>=0?(unsigned)c:0)<<6)|((d>=0?(unsigned)d:0));
        out.push_back((char)((x>>16)&0xFF));
        if (in[i+2]!='=') out.push_back((char)((x>>8)&0xFF));
        if (in[i+3]!='=') out.push_back((char)(x&0xFF));
        if (in[i+2]=='=' && in[i+3]!='=')
            ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                errmsg("UTL_ENCODE.BASE64_DECODE: invalid padding")));
    }
    return out;
}
 
// ---------- Quoted-Printable ----------
inline bool is_qp_printable(unsigned char c){
    if (c=='=') return false;
    if (c==9 || c==32) return true;
    if (c>=33 && c<=60) return true;
    if (c>=62 && c<=126) return true;
    return false;
}
inline char hex_up(unsigned v){ static const char* k="0123456789ABCDEF"; return k[v&0xF]; }
 
inline std::string qp_encode(const std::string& in)
{
    std::string out; out.reserve(in.size()*3);
    for (size_t i=0;i<in.size();++i){
        unsigned char c=(unsigned char)in[i];
        bool at_eol=false;
        if (c==' '||c=='\t'){
            if (i+1==in.size()) at_eol=true;
            else { unsigned char n=(unsigned char)in[i+1]; if (n=='\r'||n=='\n') at_eol=true; }
        }
        if (c=='\r'||c=='\n'){ out.push_back((char)c); }
        else if (!is_qp_printable(c) || at_eol){
            out.push_back('='); out.push_back(hex_up(c>>4)); out.push_back(hex_up(c&0xF));
        } else out.push_back((char)c);
    }
    return out;
}
inline int hex_val(unsigned char ch){
    if (ch>='0'&&ch<='9') return ch-'0';
    if (ch>='A'&&ch<='F') return 10+(ch-'A');
    if (ch>='a'&&ch<='f') return 10+(ch-'a');
    return -1;
}
inline std::string qp_decode(const std::string& in, bool header_variant=false)
{
    std::string out; out.reserve(in.size());
    for (size_t i=0;i<in.size();++i){
        unsigned char c=(unsigned char)in[i];
        if (header_variant && c=='_'){ out.push_back(' '); continue; }
        if (c!='='){ out.push_back((char)c); continue; }
        if (i+1>=in.size()){ out.push_back('='); break; }
        unsigned char c1=(unsigned char)in[i+1];
        if (c1=='\r'||c1=='\n'){ if (c1=='\r' && i+2<in.size() && in[i+2]=='\n') i+=2; else i+=1; continue; }
        if (i+2<in.size()){
            int h1=hex_val(c1), h2=hex_val((unsigned char)in[i+2]);
            if (h1>=0 && h2>=0){ out.push_back((char)((h1<<4)|h2)); i+=2; continue; }
        }
        out.push_back('=');
    }
    return out;
}
 
// ---------- RFC 2047 (MIME header) ----------
inline bool starts_with(const std::string& s,const char* pfx){ size_t n=strlen(pfx); return s.size()>=n && memcmp(s.data(),pfx,n)==0; }
 
inline std::string mimeheader_encode(const std::string& text,const std::string& charset,bool use_base64)
{
    std::string enc = use_base64 ? base64_encode_bytes(text) : qp_encode(text); // header-qp ниже
    if (!use_base64){
        // Q-variant: space->'_', '_'->=5F, CR/LF кодировать
        std::string tmp; tmp.reserve(enc.size()*2);
        for (size_t i=0;i<text.size();++i){
            unsigned char c=(unsigned char)text[i];
            if (c==' ') { tmp.push_back('_'); continue; }
            if (c=='_') { tmp.append("=5F"); continue; }
            if (c=='\r'||c=='\n'){
                tmp.append("=0D"); if (c=='\r' && i+1<text.size() && text[i+1]=='\n'){ ++i; tmp.append("=0A"); }
                else if (c=='\n') tmp.append("=0A");
                continue;
            }
            if (!is_qp_printable(c) || c=='='){ tmp.push_back('='); tmp.push_back(hex_up(c>>4)); tmp.push_back(hex_up(c&0xF)); }
            else tmp.push_back((char)c);
        }
        enc.swap(tmp);
    }
    std::string cs = charset.empty() ? "UTF-8" : charset;
    return "=?" + cs + "?" + (use_base64 ? "B" : "Q") + "?" + enc + "?=";
}
 
inline bool mimeheader_try_decode(const std::string& in, std::string& out_text)
{
    if (!starts_with(in,"=?")) return false;
    size_t p=2; size_t q1=in.find('?',p); if (q1==std::string::npos) return false;
    std::string charset=in.substr(p,q1-p);
    size_t q2=in.find('?',q1+1); if (q2==std::string::npos || q2==q1+1) return false;
    char enc=in[q1+1];
    size_t end=in.rfind("?="); if (end==std::string::npos || end<q2+1) return false;
    std::string payload=in.substr(q2+1,end-(q2+1));
    if (enc=='B'||enc=='b'){ out_text=base64_decode_bytes(payload); return true; }
    if (enc=='Q'||enc=='q'){ out_text=qp_decode(payload,true); return true; }
    return false;
}
 
// ---------- UUEncode ----------
inline unsigned char uu_enc6(unsigned v){ unsigned c=(v&0x3F)+0x20; if (c==0x20) c=0x60; return (unsigned char)c; }
inline unsigned uu_dec6(unsigned char c){ if (c=='`') return 0; if (c<0x20) return 0; return (c-0x20)&0x3F; }
 
inline std::string uuencode_bytes(const std::string& in,const std::string& filename,const std::string& perm)
{
    std::string out; out.reserve(in.size()*2);
    out.append("begin "); out.append(perm.empty()?"0":perm); out.push_back(' ');
    out.append(filename.empty()?"uuencode.txt":filename); out.push_back('\n');
    size_t i=0;
    while (i<in.size()){
        size_t n=std::min<size_t>(45, in.size()-i);
        out.push_back((char)uu_enc6((unsigned)n));
        for (size_t j=0;j<n;j+=3){
            unsigned a=(unsigned char)in[i+j];
            unsigned b=(j+1<n)?(unsigned char)in[i+j+1]:0;
            unsigned c=(j+2<n)?(unsigned char)in[i+j+2]:0;
            unsigned t1=(a>>2)&0x3F;
            unsigned t2=((a&3)<<4)|((b>>4)&0xF);
            unsigned t3=((b&0xF)<<2)|((c>>6)&3);
            unsigned t4=c&0x3F;
            out.push_back((char)uu_enc6(t1));
            out.push_back((char)uu_enc6(t2));
            out.push_back((char)uu_enc6(t3));
            out.push_back((char)uu_enc6(t4));
        }
        out.push_back('\n'); i+=n;
    }
    out.push_back((char)uu_enc6(0)); out.push_back('\n'); out.append("end\n");
    return out;
}
 
inline std::string uudecode_data_only(const std::string& in_ascii)
{
    std::string out; out.reserve(in_ascii.size());
    size_t p=0,n=in_ascii.size();
    while (p<n){
        size_t q=p; while (q<n && in_ascii[q]!='\n' && in_ascii[q]!='\r') ++q;
        if (q==p){ if (q<n && in_ascii[q]=='\r' && q+1<n && in_ascii[q+1]=='\n') q+=2; else if (q<n) ++q; p=q; continue; }
        unsigned char len_char=(unsigned char)in_ascii[p];
        unsigned len=uu_dec6(len_char);
        size_t need_groups=(len+2)/3;
        size_t r=p+1;
        if (r+need_groups*4>q)
            ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                errmsg("UTL_ENCODE.UUDECODE: truncated data line")));
        size_t produced=0;
        for (size_t g=0; g<need_groups; ++g){
            unsigned c1=uu_dec6((unsigned char)in_ascii[r++]);
            unsigned c2=uu_dec6((unsigned char)in_ascii[r++]);
            unsigned c3=uu_dec6((unsigned char)in_ascii[r++]);
            unsigned c4=uu_dec6((unsigned char)in_ascii[r++]);
            unsigned b1=(c1<<2)|(c2>>4);
            unsigned b2=((c2&0xF)<<4)|(c3>>2);
            unsigned b3=((c3&3)<<6)|c4;
            if (produced<len){ out.push_back((char)b1); ++produced; }
            if (produced<len){ out.push_back((char)b2); ++produced; }
            if (produced<len){ out.push_back((char)b3); ++produced; }
        }
        if (q<n && in_ascii[q]=='\r' && q+1<n && in_ascii[q+1]=='\n') q+=2;
        else if (q<n) ++q;
        p=q;
    }
    return out;
}
 
inline std::string uudecode_bytes(const std::string& in_raw)
{
    std::string in = coerce_hex_ascii_to_bytes(in_raw);
    size_t pos=in.find("begin ");
    if (pos==std::string::npos) return uudecode_data_only(in);
 
    size_t line_end=in.find('\n',pos);
    if (line_end==std::string::npos)
        ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
            errmsg("UTL_ENCODE.UUDECODE: truncated header")));
    size_t p=line_end+1;
 
    std::string out; out.reserve(in.size());
    while (p<in.size()){
        if (in.compare(p,3,"end")==0) break;
        if (in[p]=='\r'||in[p]=='\n'){ ++p; continue; }
        unsigned char len_char=(unsigned char)in[p++];
        unsigned len=uu_dec6(len_char);
        size_t need_groups=(len+2)/3;
        size_t q=p;
        std::vector<unsigned> sextets; sextets.reserve(need_groups*4);
        for (size_t g=0; g<need_groups; ++g){
            if (q+4>in.size())
                ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
                    errmsg("UTL_ENCODE.UUDECODE: truncated line")));
            unsigned c1=uu_dec6((unsigned char)in[q++]);
            unsigned c2=uu_dec6((unsigned char)in[q++]);
            unsigned c3=uu_dec6((unsigned char)in[q++]);
            unsigned c4=uu_dec6((unsigned char)in[q++]);
            sextets.push_back(c1); sextets.push_back(c2);
            sextets.push_back(c3); sextets.push_back(c4);
        }
        while (q<in.size() && in[q]!='\n' && in[q]!='\r') ++q;
 
        size_t produced=0;
        for (size_t i=0;i<sextets.size();i+=4){
            unsigned a=sextets[i], b=sextets[i+1], c=sextets[i+2], d=sextets[i+3];
            unsigned byte1=(a<<2)|(b>>4);
            unsigned byte2=((b&0xF)<<4)|(c>>2);
            unsigned byte3=((c&3)<<6)|d;
            if (produced<len){ out.push_back((char)byte1); ++produced; }
            if (produced<len){ out.push_back((char)byte2); ++produced; }
            if (produced<len){ out.push_back((char)byte3); ++produced; }
        }
        if (q<in.size() && in[q]=='\r' && q+1<in.size() && in[q+1]=='\n') p=q+2;
        else p=(q<in.size()? q+1 : q);
    }
 
    if (p>=in.size() || in.compare(p,3,"end")!=0)
        ereport(ERROR,(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
            errmsg("UTL_ENCODE.UUDECODE: missing 'end'")));
    return out;
}
 
// ---------- misc ----------
enum { ENC_BASE64=1, ENC_QP=2 };
inline int get_encoding_or_default(bool isnull,int32 val){
    if (isnull) return ENC_QP;
    if (val==ENC_BASE64) return ENC_BASE64;
    if (val==ENC_QP)     return ENC_QP;
    return ENC_QP;
}
 
} // namespace
 
extern "C" {
 
// --- BASE64 ---
/*
 * @qdb_func: utl_encode_base64_encode(raw)
 * @ora_func: UTL_ENCODE.BASE64_ENCODE(RAW)
 */
Datum utl_encode_base64_encode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    std::string bytes=bytea_to_bytes(d);
    bytes = coerce_hex_ascii_to_bytes(bytes);        // имитация RAW литерала
    std::string b64=base64_encode_bytes(bytes);
    PG_RETURN_DATUM(bytes_to_bytea(b64));            // RAW (ASCII в байтах)
}
 
/*
 * @qdb_func: utl_encode_base64_decode(raw)
 * @ora_func: UTL_ENCODE.BASE64_DECODE(RAW)
 */
Datum utl_encode_base64_decode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    
    LOCAL_FCINFO(local_fcinfo, 2);
    InitFunctionCallInfoData(*local_fcinfo, NULL, 2, PG_GET_COLLATION(), fcinfo->context, NULL);
    local_fcinfo->args[0].value = d;
    local_fcinfo->args[0].isnull = fcinfo->args[0].isnull;
    local_fcinfo->args[1].value = DatumGetBool(false);
    local_fcinfo->args[1].isnull = false;
    PG_RETURN_DATUM( (*utl_encode_base64_decode_internal) (local_fcinfo));
}
 
Datum utl_encode_base64_decode_internal(PG_FUNCTION_ARGS)
{
    bool onempty = false;
    if(!PG_ARGISNULL(1)){
        onempty = PG_GETARG_BOOL(1);
    }
    if (PG_ARGISNULL(0)){
        if(onempty){
            std::string res = "";
            PG_RETURN_DATUM(bytes_to_bytea(res));
        }
        else
            PG_RETURN_NULL();
    }
    Datum d=PG_GETARG_DATUM(0);
    std::string ascii_b64=bytea_to_bytes(d);
    ascii_b64 = coerce_hex_ascii_to_bytes(ascii_b64);
    std::string decoded=base64_decode_bytes(ascii_b64);
    PG_RETURN_DATUM(bytes_to_bytea(decoded));        // RAW
}
 
// --- QP ---
/*
 * @qdb_func: utl_encode_quoted_printable_encode(raw)
 * @ora_func: UTL_ENCODE.QUOTED_PRINTABLE_ENCODE(RAW)
 */
Datum utl_encode_quoted_printable_encode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    std::string bytes=bytea_to_bytes(d);
    bytes = coerce_hex_ascii_to_bytes(bytes);
    std::string enc=qp_encode(bytes);
    PG_RETURN_DATUM(bytes_to_bytea(enc));            // RAW
}
 
/*
 * @qdb_func: utl_encode_quoted_printable_decode(raw)
 * @ora_func: UTL_ENCODE.QUOTED_PRINTABLE_DECODE(RAW)
 */
Datum utl_encode_quoted_printable_decode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    std::string qp_ascii=bytea_to_bytes(d);
    qp_ascii = coerce_hex_ascii_to_bytes(qp_ascii);
    std::string dec=qp_decode(qp_ascii,false);
    PG_RETURN_DATUM(bytes_to_bytea(dec));            // RAW
}
 
// --- MIME header (varchar2) ---
/*
 * @qdb_func: utl_encode_mimeheader_encode(text, text, int4)
 * @ora_func: UTL_ENCODE.MIMEHEADER_ENCODE(VARCHAR2, VARCHAR2, BINARY_INTEGER)
 */
Datum utl_encode_mimeheader_encode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0));
    std::string charset = PG_ARGISNULL(1)? std::string() : text_to_std_string(PG_GETARG_TEXT_PP(1));
    int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2);
    bool use_b64 = (get_encoding_or_default(enc_isnull,enc_in)==ENC_BASE64);
    std::string out=mimeheader_encode(buf,charset,use_b64);
    PG_RETURN_DATUM(std_string_to_text(out));
}
 
/*
 * @qdb_func: utl_encode_mimeheader_decode(text)
 * @ora_func: UTL_ENCODE.MIMEHEADER_DECODE(VARCHAR2)
 */
Datum utl_encode_mimeheader_decode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0)), out;
    if (mimeheader_try_decode(in,out)) PG_RETURN_DATUM(std_string_to_text(out));
    PG_RETURN_DATUM(std_string_to_text(in));
}
 
// --- TEXT (varchar2) ---
/*
 * @qdb_func: utl_encode_text_encode(text, text, int4)
 * @ora_func: UTL_ENCODE.TEXT_ENCODE(VARCHAR2, VARCHAR2, BINARY_INTEGER)
 */
Datum utl_encode_text_encode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0));
    int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2);
    int enc=get_encoding_or_default(enc_isnull,enc_in);
    std::string out = (enc==ENC_BASE64) ? base64_encode_bytes(buf) : qp_encode(buf);
    PG_RETURN_DATUM(std_string_to_text(out));
}
 
/*
 * @qdb_func: utl_encode_text_decode(text, text, int4)
 * @ora_func: UTL_ENCODE.TEXT_DECODE(VARCHAR2, VARCHAR2, BINARY_INTEGER)
 */
Datum utl_encode_text_decode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string buf=text_to_std_string(PG_GETARG_TEXT_PP(0));
    int32 enc_in=0; bool enc_isnull=PG_ARGISNULL(2); if (!enc_isnull) enc_in=PG_GETARG_INT32(2);
    int enc=get_encoding_or_default(enc_isnull,enc_in);
    std::string out = (enc==ENC_BASE64) ? base64_decode_bytes(buf) : qp_decode(buf,false);
    PG_RETURN_DATUM(std_string_to_text(out));
}
 
// --- UU ---
/*
 * @qdb_func: utl_encode_uuencode(raw, int4, text, text)
 * @ora_func: UTL_ENCODE.UUENCODE(RAW, BINARY_INTEGER, VARCHAR2, VARCHAR2)
 */
Datum utl_encode_uuencode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    std::string bytes=bytea_to_bytes(d);
    bytes = coerce_hex_ascii_to_bytes(bytes);
    int32 type = (PG_NARGS()>1 && !PG_ARGISNULL(1)) ? PG_GETARG_INT32(1) : 1;
    if (type!=1)
        ereport(ERROR,(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
            errmsg("UTL_ENCODE.UUENCODE: only type=1 (complete) is supported")));
    std::string filename = (PG_NARGS()>2 && !PG_ARGISNULL(2)) ? text_to_std_string(PG_GETARG_TEXT_PP(2)) : "";
    std::string perm     = (PG_NARGS()>3 && !PG_ARGISNULL(3)) ? text_to_std_string(PG_GETARG_TEXT_PP(3)) : "";
    std::string enc=uuencode_bytes(bytes,filename,perm);
    PG_RETURN_DATUM(bytes_to_bytea(enc));            // RAW
}
 
/*
 * @qdb_func: utl_encode_uudecode(raw)
 * @ora_func: UTL_ENCODE.UUDECODE(RAW)
 */
Datum utl_encode_uudecode(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    Datum d=PG_GETARG_DATUM(0);
    std::string ascii=bytea_to_bytes(d);
    std::string dec=uudecode_bytes(ascii);
    PG_RETURN_DATUM(bytes_to_bytea(dec));            // RAW
}
 
/*
// --- Доп. перегрузки для консоли (varchar2 -> varchar2) ---
Datum utl_encode_base64_decode_vc(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0));
    in = coerce_hex_ascii_to_bytes(in);
    std::string bytes=base64_decode_bytes(in);
    PG_RETURN_DATUM(std_string_to_text(bytes));
}
 
Datum utl_encode_quoted_printable_decode_vc(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0));
    in = coerce_hex_ascii_to_bytes(in);
    std::string bytes=qp_decode(in,false);
    PG_RETURN_DATUM(std_string_to_text(bytes));
}
 
Datum utl_encode_uudecode_vc(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0)) PG_RETURN_NULL();
    std::string in=text_to_std_string(PG_GETARG_TEXT_PP(0));
    std::string bytes=uudecode_bytes(in);
    PG_RETURN_DATUM(std_string_to_text(bytes));
}
*/
 
/// @brief Возвращает версию RUDB пакета UTL_ENCODE (Oracle UTL_ENCODE пакет)
Datum utl_encode_get_version(PG_FUNCTION_ARGS) {
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_UTL_ENCODE_VERSION));
}
 
} // extern "C"