Исходный код СУБД 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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
// QDB_DBMS_GEN_MANAGED_SKELETON
// Generated implementation scaffold. Business logic must be implemented manually.
 
#include "dbms_vector_chain.hpp"
#include "dbms_vector_chain_common.hpp"
 
#include <libxml/HTMLparser.h>
#include <libxml/parser.h>
#include <libxml/xpath.h>
#include <libxml/xpathInternals.h>
 
extern "C"
{
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <errno.h>
#include <poll.h>
#include "miscadmin.h"
#include "storage/fd.h"
#include "utils/wait_event.h"
#include "utils/builtins.h"
#include "utils/jsonb.h"
#include "utils/numeric.h"
#include "catalog/pg_type.h"
#include "utils/palloc.h"
#include "utils/elog.h"
} // extern "C"
 
namespace
{
constexpr const char* kDbmsVectorChainPreferenceProfileValue = "PROFILE";
constexpr const char* kDbmsVectorChainPreferenceChunkerValue = "CHUNKER";
constexpr const char* kDbmsVectorChainPreferenceEmbedderValue = "EMBEDDER";
constexpr const char* kDbmsVectorChainPreferenceIndexValue = "INDEX";
constexpr int32 kDbmsVectorChainExcpCredNotExistValue = -20001;
constexpr int32 kDbmsVectorChainExcpProviderErrValue = -20002;
constexpr int32 kDbmsVectorChainExcpGuErrValue = -20003;
} // namespace
 
extern "C"
{
PG_FUNCTION_INFO_V1(dbms_vector_chain_hybrid_search);
PG_FUNCTION_INFO_V1(dbms_vector_chain_similar);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_chunks_0);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_chunks_1);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embedding);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embeddings_0);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_embeddings_1);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_generate_text);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_summary);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_text_0);
PG_FUNCTION_INFO_V1(dbms_vector_chain_utl_to_text_1);
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_profile);
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_chunker);
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_embedder);
PG_FUNCTION_INFO_V1(dbms_vector_chain_preference_index);
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_cred_not_exist);
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_provider_err);
PG_FUNCTION_INFO_V1(dbms_vector_chain_excp_gu_err);
PG_FUNCTION_INFO_V1(dbms_vector_chain_get_version);
PG_FUNCTION_INFO_V1(dbms_vector_chain_mock);
PG_FUNCTION_INFO_V1(dbms_vector_chain_add_credential);
PG_FUNCTION_INFO_V1(dbms_vector_chain_create_lang_data);
PG_FUNCTION_INFO_V1(dbms_vector_chain_create_preference);
PG_FUNCTION_INFO_V1(dbms_vector_chain_add_vocabulary);
PG_FUNCTION_INFO_V1(dbms_vector_chain_del_credential);
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_lang_data);
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_preference);
PG_FUNCTION_INFO_V1(dbms_vector_chain_drop_vocabulary);
} // extern "C"
 
#define RUDB_DBMS_VECTOR_CHAIN_VERSION "1.0.0"
 
static void
dbms_vector_chain_raise_stub_error(const char* message)
{
    ereport(ERROR, (errmsg("%s", message)));
}
 
Datum dbms_vector_chain_hybrid_search(PG_FUNCTION_ARGS)
{
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const int32 query_spec = PG_GETARG_INT32(0);
    // (void) query_spec;
    //
    // RESULT return_value (json): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.HYBRID_SEARCH не реализована.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_similar(PG_FUNCTION_ARGS)
{
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* index_name = PG_GETARG_TEXT_PP(0);
    // (void) index_name;
    //
    // const text* vector_query = PG_GETARG_TEXT_PP(1);
    // (void) vector_query;
    //
    // const int32 num_results = PG_GETARG_INT32(2);
    // (void) num_results;
    //
    // const bool has_text_query = PG_NARGS() > 3 && !PG_ARGISNULL(3);
    // const text* text_query_default = nullptr;
    // if (!has_text_query) {
    //     /* default literal nullptr для text_query: NULL (source CSV) */
    //     (void) text_query_default;
    // } else {
    //     (void) PG_GETARG_TEXT_PP(3);
    // }
    //
    // const text* result_mode = PG_GETARG_TEXT_PP(4);
    // (void) result_mode;
    //
    // const text* score_function = PG_GETARG_TEXT_PP(5);
    // (void) score_function;
    //
    // RESULT return_value (json): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.SIMILAR не реализована.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_chunks_0(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    text *data = PG_GETARG_TEXT_PP(0);
    text *parameters = PG_ARGISNULL(1) ? NULL : PG_GETARG_TEXT_PP(1);
    dbms_vector_chain::ChunkParams *param = dbms_vector_chain::initChunkParams(parameters);
    //dbms_vector_chain::printChunkParams(param);
    if(param->by == dbms_vector_chain::CHUNK_BY_CHARACTERS){
        ArrayType   *result = dbms_vector_chain::chunk_for_chars(data, param);
        PG_RETURN_ARRAYTYPE_P(result);
    }
    if(param->by == dbms_vector_chain::CHUNK_BY_WORDS){
        ArrayType   *result = dbms_vector_chain::chunk_for_words(data, param);
        PG_RETURN_ARRAYTYPE_P(result);
    }
    if(param->by == dbms_vector_chain::CHUNK_BY_VOCABULARY){
        ArrayType   *result = dbms_vector_chain::chunk_for_vocabulary(data, param);
        PG_RETURN_ARRAYTYPE_P(result);
    }
 
    
    ereport(ERROR, (errmsg("Некорректный параметр by")));
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_chunks_1(PG_FUNCTION_ARGS)
{
    /*
     * ERROR: неподдерживаемый элемент сохранён как заглушка.
     * ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
     */
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* data = PG_GETARG_TEXT_PP(0);
    // (void) data;
    //
    // const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
    // const int32 params_default = 0;
    // if (!has_params) {
    //     /* default literal 0 для params: NULL (source CSV) */
    //     (void) params_default;
    // } else {
    //     (void) PG_GETARG_INT32(1);
    // }
    //
    // RESULT return_value (text): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_CHUNKS не поддерживается: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_embedding(PG_FUNCTION_ARGS)
{
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* data = PG_GETARG_TEXT_PP(0);
    // (void) data;
    //
    // const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
    // const int32 params_default = 0;
    // if (!has_params) {
    //     /* default literal 0 для params: NULL (source CSV) */
    //     (void) params_default;
    // } else {
    //     (void) PG_GETARG_INT32(1);
    // }
    //
    // RESULT return_value (vector): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDING не реализована.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_embeddings_0(PG_FUNCTION_ARGS)
{
    /*
     * ERROR: неподдерживаемый элемент сохранён как заглушка.
     * ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
     */
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* data = PG_GETARG_TEXT_PP(0);
    // (void) data;
    //
    // const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
    // const int32 params_default = 0;
    // if (!has_params) {
    //     /* default literal 0 для params: NULL (source CSV) */
    //     (void) params_default;
    // } else {
    //     (void) PG_GETARG_INT32(1);
    // }
    //
    // RESULT return_value (text): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDINGS не поддерживается: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_embeddings_1(PG_FUNCTION_ARGS)
{
    /*
     * ERROR: неподдерживаемый элемент сохранён как заглушка.
     * ERROR: тип TABLE не поддерживается текущим каталогом rudb.
     * ERROR: Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация.
     */
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* data = PG_GETARG_TEXT_PP(0);
    // (void) data;
    //
    // const int32 params = PG_GETARG_INT32(1);
    // (void) params;
    //
    // RESULT return_value (text): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_EMBEDDINGS не поддерживается: тип TABLE не поддерживается текущим каталогом rudb.; Неподдерживаемый возвращаемый тип TABLE; функция сгенерирована как заглушка с catalog return type text. Требуется ручная проверка/реализация. Проверьте соответствующую запись в pg_proc.dat.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_utl_to_generate_text(PG_FUNCTION_ARGS)
{
    /*
     * DBMS_VECTOR_CHAIN.UTL_TO_GENERATE_TEXT(data clob, params json).
     *
     * Логика живёт в dbms_vector_chain::utl_to_generate_text()
     * (dbms_vector_chain_common.cpp): credential читается из собственной
     * таблицы пакета pg_catalog.dbms_vector_chain_credential_table, а не из
     * "SYS".vector_credentials пакета DBMS_VECTOR.
     */
    if (PG_ARGISNULL(0))
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("data must be specified"),
                 errdetail("Oracle error: ORA-20003 (EXCP_GU_ERR).")));
 
    text *data = PG_GETARG_TEXT_PP(0);
 
    Jsonb *params = NULL;
 
    if (PG_NARGS() > 1 && !PG_ARGISNULL(1))
    {
        /* SQL-тип params — json; приводим к jsonb через jsonb_in. */
        text *params_text = PG_GETARG_TEXT_PP(1);
 
        params = DatumGetJsonbP(DirectFunctionCall1(
            jsonb_in, CStringGetDatum(text_to_cstring(params_text))));
    }
 
    char *result = dbms_vector_chain::utl_to_generate_text(
        VARDATA_ANY(data), VARSIZE_ANY_EXHDR(data), params);
 
    PG_RETURN_TEXT_P(cstring_to_text(result));
}
 
Datum dbms_vector_chain_utl_to_summary(PG_FUNCTION_ARGS)
{
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // const text* data = PG_GETARG_TEXT_PP(0);
    // (void) data;
    //
    // const bool has_params = PG_NARGS() > 1 && !PG_ARGISNULL(1);
    // const int32 params_default = 0;
    // if (!has_params) {
    //     /* default literal 0 для params: NULL (source CSV) */
    //     (void) params_default;
    // } else {
    //     (void) PG_GETARG_INT32(1);
    // }
    //
    // RESULT return_value (clob): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("функция DBMS_VECTOR_CHAIN.UTL_TO_SUMMARY не реализована.");
    PG_RETURN_NULL();
}
 
 
char *extract_text_from_html(const char *html, int size_html)
{
    if (html == NULL || size_html <= 0)
        return NULL;
 
    /* 1. Парсим HTML из памяти */
    htmlDocPtr doc = htmlReadMemory(html,
                                    size_html,
                                    nullptr,   /* URL */
                                    nullptr,   /* encoding: пусть определит сам */
                                    HTML_PARSE_NOERROR |
                                    HTML_PARSE_NOWARNING |
                                    HTML_PARSE_RECOVER);
    if (doc == NULL)
        return NULL;
 
    /* 2. XPath-контекст */
    xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
    if (xpathCtx == NULL)
    {
        xmlFreeDoc(doc);
        return NULL;
    }
 
    /* 3. Выбираем все текстовые узлы внутри body.
     *    Если body нет (фрагмент), попробуем взять весь документ. */
    xmlXPathObjectPtr result = xmlXPathEvalExpression(
        BAD_CAST "//body//text()", xpathCtx);
 
    if (result == NULL || result->nodesetval == NULL ||
        result->nodesetval->nodeNr == 0)
    {
        if (result) xmlXPathFreeObject(result);
        result = xmlXPathEvalExpression(
            BAD_CAST "//text()", xpathCtx);
    }
 
    /* 4. Собираем текст в StringInfo */
    StringInfoData buffer;
    initStringInfo(&buffer);
 
    if (result != NULL && result->nodesetval != NULL)
    {
        for (int i = 0; i < result->nodesetval->nodeNr; ++i)
        {
            xmlNodePtr node = result->nodesetval->nodeTab[i];
            if (node == NULL)
                continue;
 
            /* Пропускаем содержимое <script> и <style> */
            if (node->parent != NULL &&
                node->parent->type == XML_ELEMENT_NODE)
            {
                const xmlChar *parentName = node->parent->name;
                if (parentName != NULL &&
                    (xmlStrcasecmp(parentName, BAD_CAST "script") == 0 ||
                     xmlStrcasecmp(parentName, BAD_CAST "style")  == 0))
                {
                    continue;
                }
            }
 
            xmlChar *content = xmlNodeGetContent(node);
            if (content != NULL)
            {
                appendStringInfoString(&buffer,
                                       reinterpret_cast<const char *>(content));
                xmlFree(content);
            }
        }
    }
 
    /* 5. Освобождаем ресурсы libxml2 */
    if (result) xmlXPathFreeObject(result);
    xmlXPathFreeContext(xpathCtx);
    xmlFreeDoc(doc);
 
    return buffer.data;
}
 
char *extract_text_from_xml(const char *xml, int size_xml)
{
    if (xml == NULL || size_xml <= 0)
        return NULL;
 
    /* 1. Парсим XML из памяти */
    xmlDocPtr doc = xmlReadMemory(xml,
                                  size_xml,
                                  nullptr,   /* URL */
                                  nullptr,   /* encoding: пусть определит сам */
                                  XML_PARSE_NOERROR |
                                  XML_PARSE_NOWARNING |
                                  XML_PARSE_RECOVER);
    if (doc == NULL)
        return NULL;
 
    /* 2. XPath-контекст */
    xmlXPathContextPtr xpathCtx = xmlXPathNewContext(doc);
    if (xpathCtx == NULL)
    {
        xmlFreeDoc(doc);
        return NULL;
    }
 
    /* 3. Выбираем все текстовые узлы документа.
     *    Извлекаются только текстовые поля (значения элементов и атрибутов
     *    не включаются). */
    xmlXPathObjectPtr result = xmlXPathEvalExpression(
        BAD_CAST "//text()", xpathCtx);
 
    /* 4. Собираем текст в StringInfo */
    StringInfoData buffer;
    initStringInfo(&buffer);
 
    if (result != NULL && result->nodesetval != NULL)
    {
        for (int i = 0; i < result->nodesetval->nodeNr; ++i)
        {
            xmlNodePtr node = result->nodesetval->nodeTab[i];
            if (node == NULL)
                continue;
 
            /* Пропускаем содержимое комментариев, CDATA и PI */
            if (node->type != XML_TEXT_NODE)
                continue;
 
            xmlChar *content = xmlNodeGetContent(node);
            if (content != NULL)
            {
                appendStringInfoString(&buffer,
                                       reinterpret_cast<const char *>(content));
                xmlFree(content);
            }
        }
    }
 
    /* 5. Освобождаем ресурсы libxml2 */
    if (result) xmlXPathFreeObject(result);
    xmlXPathFreeContext(xpathCtx);
    xmlFreeDoc(doc);
 
    return buffer.data;
}
 
// text
char *extract_text_from_pdf(const char *buffer, Size buffer_len)
{
    int         in_fd[2]  = {-1, -1};
    int         out_fd[2] = {-1, -1};
    int         err_fd[2] = {-1, -1};
    pid_t       pid       = -1;
    StringInfoData result;
 
    initStringInfo(&result);
 
    PG_TRY();
    {
        if (pipe(in_fd) < 0 || pipe(out_fd) < 0 || pipe(err_fd) < 0)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("could not create pipes for pdftotext: %m")));
 
        pid = fork();
        if (pid < 0)
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("could not fork for pdftotext: %m")));
 
        if (pid == 0)
        {
            struct sigaction sa;
            memset(&sa, 0, sizeof(sa));
            sa.sa_handler = SIG_DFL;
            sigemptyset(&sa.sa_mask);
            sigaction(SIGPIPE, &sa, NULL);
            sigaction(SIGINT,  &sa, NULL);
            sigaction(SIGQUIT, &sa, NULL);
            sigaction(SIGTERM, &sa, NULL);
            sigaction(SIGHUP,  &sa, NULL);
 
            if (dup2(in_fd[0],  STDIN_FILENO)  < 0 ||
                dup2(out_fd[1], STDOUT_FILENO) < 0 ||
                dup2(err_fd[1], STDERR_FILENO) < 0)
                _exit(127);
 
            close(in_fd[0]);  close(in_fd[1]);
            close(out_fd[0]); close(out_fd[1]);
            close(err_fd[0]); close(err_fd[1]);
 
            execlp("pdftotext", "pdftotext", "-nopgbrk", "-enc", "UTF-8", "-", "-", (char *) NULL);
 
            {
                static const char msg[] = "failed to exec pdftotext\n";
                (void) write(STDERR_FILENO, msg, sizeof(msg) - 1);
            }
            _exit(127);
        }
 
        close(in_fd[0]);  in_fd[0]  = -1;
        close(out_fd[1]); out_fd[1] = -1;
        close(err_fd[1]); err_fd[1] = -1;
 
        StringInfoData errbuf;
        initStringInfo(&errbuf);
 
        Size written  = 0;
        bool in_open  = true;
        bool out_open = true;
        bool err_open = true;
 
        if (buffer_len == 0)
        {
            close(in_fd[1]); in_fd[1] = -1; in_open = false;
        }
 
        while (in_open || out_open || err_open)
        {
            struct pollfd pfds[3];
            int idx_in = -1, idx_out = -1, idx_err = -1, nfds = 0;
 
            if (in_open)  { pfds[nfds].fd = in_fd[1];
                            pfds[nfds].events = POLLOUT;
                            pfds[nfds].revents = 0;
                            idx_in = nfds++; }
            if (out_open) { pfds[nfds].fd = out_fd[0];
                            pfds[nfds].events = POLLIN;
                            pfds[nfds].revents = 0;
                            idx_out = nfds++; }
            if (err_open) { pfds[nfds].fd = err_fd[0];
                            pfds[nfds].events = POLLIN;
                            pfds[nfds].revents = 0;
                            idx_err = nfds++; }
 
            int prc = poll(pfds, nfds, -1);
            if (prc < 0)
            {
                if (errno == EINTR)
                {
                    CHECK_FOR_INTERRUPTS();
                    continue;
                }
                ereport(ERROR,
                        (errcode_for_file_access(),
                         errmsg("poll() failed while running pdftotext: %m")));
            }
 
            if (idx_in >= 0 && pfds[idx_in].revents)
            {
                if (pfds[idx_in].revents & (POLLERR | POLLHUP))
                {
                    close(in_fd[1]); in_fd[1] = -1; in_open = false;
                }
                else if (pfds[idx_in].revents & POLLOUT)
                {
                    ssize_t n = write(in_fd[1], buffer + written,
                                      buffer_len - written);
                    if (n < 0)
                    {
                        if (errno == EINTR)
                            CHECK_FOR_INTERRUPTS();
                        else if (errno == EPIPE)
                        {
                            close(in_fd[1]); in_fd[1] = -1; in_open = false;
                        }
                        else
                            ereport(ERROR,
                                    (errcode_for_file_access(),
                                     errmsg("write to pdftotext failed: %m")));
                    }
                    else
                    {
                        written += (Size) n;
                        if (written >= buffer_len)
                        {
                            close(in_fd[1]); in_fd[1] = -1; in_open = false;
                        }
                    }
                }
            }
 
            if (idx_out >= 0 &&
                (pfds[idx_out].revents & (POLLIN | POLLHUP | POLLERR)))
            {
                char buf[8192];
                ssize_t n = read(out_fd[0], buf, sizeof(buf));
                if (n < 0)
                {
                    if (errno == EINTR)
                        CHECK_FOR_INTERRUPTS();
                    else
                        ereport(ERROR,
                                (errcode_for_file_access(),
                                 errmsg("read from pdftotext failed: %m")));
                }
                else if (n == 0)
                {
                    close(out_fd[0]); out_fd[0] = -1; out_open = false;
                }
                else
                    appendBinaryStringInfo(&result, buf, n);
            }
 
            if (idx_err >= 0 &&
                (pfds[idx_err].revents & (POLLIN | POLLHUP | POLLERR)))
            {
                char buf[1024];
                ssize_t n = read(err_fd[0], buf, sizeof(buf));
                if (n < 0)
                {
                    if (errno == EINTR)
                        CHECK_FOR_INTERRUPTS();
                    else
                        ereport(ERROR,
                                (errcode_for_file_access(),
                                 errmsg("read from pdftotext stderr failed: %m")));
                }
                else if (n == 0)
                {
                    close(err_fd[0]); err_fd[0] = -1; err_open = false;
                }
                else if (errbuf.len < 16 * 1024)
                    appendBinaryStringInfo(&errbuf, buf, n);
            }
        }
 
        int status = 0;
        while (waitpid(pid, &status, 0) < 0)
        {
            if (errno == EINTR) { CHECK_FOR_INTERRUPTS(); continue; }
            ereport(ERROR,
                    (errcode_for_file_access(),
                     errmsg("waitpid() for pdftotext failed: %m")));
        }
        pid = -1;
 
        if (WIFSIGNALED(status))
            ereport(ERROR,
                    (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                     errmsg("pdftotext was terminated by signal %d",
                            WTERMSIG(status))));
 
        if (!WIFEXITED(status))
            ereport(ERROR,
                    (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                     errmsg("pdftotext did not exit normally")));
 
        int exitcode = WEXITSTATUS(status);
        if (exitcode != 0)
        {
            if (exitcode == 127)
                ereport(ERROR,
                        (errcode(ERRCODE_UNDEFINED_FILE),
                         errmsg("could not execute pdftotext: command not found or "
                                "not executable in PATH")));
            else
                ereport(ERROR,
                        (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                         errmsg("pdftotext exited with code %d: %s",
                                exitcode,
                                errbuf.len > 0 ? errbuf.data : "no stderr output")));
        }
 
        return result.data;
    }
    PG_CATCH();
    {
        if (pid > 0)
        {
            (void) kill(pid, SIGKILL);
            {
                int st;
                while (waitpid(pid, &st, 0) < 0 && errno == EINTR) {}
            }
        }
        if (in_fd[0]  >= 0) close(in_fd[0]);
        if (in_fd[1]  >= 0) close(in_fd[1]);
        if (out_fd[0] >= 0) close(out_fd[0]);
        if (out_fd[1] >= 0) close(out_fd[1]);
        if (err_fd[0] >= 0) close(err_fd[0]);
        if (err_fd[1] >= 0) close(err_fd[1]);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    return NULL;
}
 
char *extract_html_from_pdf(const char *buffer, Size buffer_len)
{
    File            temp_file;
    char           *temp_filename;
    FILE           *pipe;
    StringInfoData  result;
    char            read_buf[4096];
    size_t          nread;
    char            command[MAXPGPATH];
    int             n;
 
    /* 1. Создаём временный файл, который будет автоматически удалён
     *    при закрытии или при завершении транзакции. */
    temp_file = OpenTemporaryFile(false);
    if (temp_file < 0)
        ereport(ERROR,
                (errcode(ERRCODE_IO_ERROR),
                 errmsg("could not create temporary file: %m")));
 
    /* 2. Получаем имя временного файла, чтобы передать его pdftohtml. */
    temp_filename = FilePathName(temp_file);
    if (temp_filename == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_IO_ERROR),
                 errmsg("could not get temporary file name")));
 
    ereport(NOTICE,
        (errmsg("extract_html_from_pdf: buffer_len = %zu", buffer_len)));
    /* 3. Записываем PDF-буфер во временный файл. */
    if (FileWrite(temp_file, buffer, (int) buffer_len, (pgoff_t) 0,
                  WAIT_EVENT_BUFFILE_WRITE) != (int) buffer_len)
        ereport(ERROR,
                (errcode(ERRCODE_IO_ERROR),
                 errmsg("could not write to temporary file: %m")));
 
    /* 4. Формируем команду для pdftohtml. */
    n = snprintf(command, sizeof(command),
                 "pdftohtml -enc UTF-8 -stdout -s -i -noframes -q \"%s\"",
                 temp_filename);
    if (n < 0 || n >= (int) sizeof(command))
        ereport(ERROR,
                (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
                 errmsg("pdftohtml command too long")));
 
    /* 5. Запускаем pdftohtml и открываем pipe для чтения его stdout. */
    pipe = OpenPipeStream(command, "r");
    if (pipe == NULL)
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("could not execute pdftohtml: %m")));
 
    /* 6. Читаем вывод pdftohtml в StringInfo. */
    initStringInfo(&result);
    while ((nread = fread(read_buf, 1, sizeof(read_buf), pipe)) > 0)
        appendBinaryStringInfo(&result, read_buf, nread);
 
    if (ferror(pipe))
    {
        ClosePipeStream(pipe);
        ereport(ERROR,
                (errcode(ERRCODE_IO_ERROR),
                 errmsg("error reading from pdftohtml: %m")));
    }
 
    /* 7. Закрываем pipe. ClosePipeStream возвращает -1 при ошибке. */
    if (ClosePipeStream(pipe) != 0)
        ereport(ERROR,
                (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
                 errmsg("could not close pipe to pdftohtml: %m")));
 
    /* 8. Закрываем временный файл – он будет автоматически удалён. */
    FileClose(temp_file);
 
    /* 9. Возвращаем извлечённый текст (HTML-вывод pdftohtml). */
    return result.data;
}
 
bool hasHtml(const char *str)
{
    const char *p;
    const char *tag = "<html>";
 
    if (str == NULL)
        return false;
 
    /* Пропускаем ведущие пробельные символы */
    p = str;
    while (*p != '\0' && isspace((unsigned char) *p))
        p++;
 
    /* Сравниваем с "<html>" без учёта регистра */
    if(pg_strncasecmp(p, tag, 6)==0)
        return true;
 
    return false;
}
 
bool hasXml(const char *str)
{
    if (str == NULL)
        return false;
 
    /* Пытаемся распарсить строку как XML.
     * Если парсинг удался — считаем, что это XML. */
    xmlDocPtr doc = xmlReadMemory(str,
                                  strlen(str),
                                  nullptr,   /* URL */
                                  nullptr,   /* encoding: пусть определит сам */
                                  XML_PARSE_NOERROR |
                                  XML_PARSE_NOWARNING);
    if (doc == NULL)
        return false;
 
    xmlFreeDoc(doc);
    return true;
}
 
/*
 * hasPdf
 *   Проверяет, является ли буфер PDF-документом по сигнатуре.
 *
 *   Согласно спецификации PDF (ISO 32000-1, раздел 7.5.2), заголовок
 *   "%PDF-" должен находиться в первых 1024 байтах файла — перед ним
 *   допускается "мусор" (например, BOM или артефакты генератора).
 *
 *   Параметры:
 *     buffer - указатель на данные (может быть NULL)
 *     len    - длина буфера в байтах
 *
 *   Возвращает true, если сигнатура "%PDF-" найдена в первых 1024 байтах.
 */
bool hasPdf(const char *buffer, Size len)
{
    static const char magic[] = "%PDF-";
    const Size magic_len = sizeof(magic) - 1;   /* 5, без '\0' */
    Size       limit;
    const char  *p;
    const char  *end;
 
    if (buffer == NULL || len < magic_len)
        return false;
 
    /* По спеке заголовок должен быть в первых 1024 байтах */
    limit = Min(len, (Size) 1024);
    end = buffer + limit;
 
    for (p = buffer; p + magic_len <= end; p++)
    {
        if (memcmp(p, magic, magic_len) == 0)
            return true;
    }
 
    return false;
}
 
Datum dbms_vector_chain_utl_to_text_0(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        PG_RETURN_NULL();
 
    text *data = PG_GETARG_TEXT_PP(0);
    text *parameters = PG_ARGISNULL(1) ? NULL : PG_GETARG_TEXT_PP(1);
    bool plaintext = true; // значение по умолчанию
    char *charset = NULL;
    Size buffer_len = VARSIZE_ANY_EXHDR(data);
    char *buffer = VARDATA_ANY(data);
 
    if (parameters != NULL)
    {
        Datum options;
        Jsonb *jb;
 
        /* json хранится как text — превращаем в jsonb для удобного доступа */
        options = DirectFunctionCall1(jsonb_in,
                                     CStringGetDatum(text_to_cstring(parameters)));
        jb = DatumGetJsonbP(options);
 
        plaintext = dbms_vector_chain::jsonGetBoolParam("plaintext", jb, true);
        charset = dbms_vector_chain::jsonGetStringParam("charset", jb);
    }
 
    //elog(NOTICE, "plaintext: %s", plaintext ? "true" : "false");
    //elog(NOTICE, "charset: %s", charset ? charset : "NULL");
    
    // если charset задан, пропускается только UTF8
    if(charset){
        if(pg_strcasecmp(charset, "UTF8")!=0){
            ereport(ERROR, (errmsg("недопустимое значение %s для charset", charset)));
            PG_RETURN_NULL();
        }
    }
    char *data_str = text_to_cstring(data);
    if(hasHtml(data_str) && plaintext){
        char *html_text = extract_text_from_html(data_str, strlen(data_str));
        text *txt_result;
        if(html_text){
            txt_result = cstring_to_text(html_text);
            pfree(html_text);
        }
        else{
            // пустая строка
            const char *empty_str = "";
            txt_result = cstring_to_text(empty_str);
        }
        PG_RETURN_TEXT_P(txt_result);
    }
    else if(hasXml(data_str) && plaintext){
        char *xml_text = extract_text_from_xml(data_str, strlen(data_str));
        text *txt_result;
        if(xml_text){
            txt_result = cstring_to_text(xml_text);
            pfree(xml_text);
        }
        else{
            // пустая строка
            const char *empty_str = "";
            txt_result = cstring_to_text(empty_str);
        }
        PG_RETURN_TEXT_P(txt_result);
    }
    else if(hasPdf(buffer, buffer_len)){
        text *txt_result;
        char *pdf_text = plaintext ? extract_text_from_pdf(buffer, buffer_len) :
                                     extract_html_from_pdf(buffer, buffer_len);
 
            
        if(pdf_text){
            /* pdftotext всегда отдаёт UTF-8 (мы указали -enc UTF-8).
            * Приводим к кодировке базы, если это необходимо. */
            char *converted = pg_any_to_server(pdf_text,
                                            strlen(pdf_text),
                                            PG_UTF8);
 
            txt_result = cstring_to_text(converted);
 
            /* pg_any_to_server может вернуть либо исходный указатель,
            * либо новый (palloc'ed). Освобождаем оба корректно. */
            if (converted != pdf_text)
                pfree(converted);
            pfree(pdf_text);
        }
        else{
            // пустая строка
            const char *empty_str = "";
            txt_result = cstring_to_text(empty_str);
        }
        PG_RETURN_TEXT_P(txt_result);
    }
    
    PG_RETURN_TEXT_P(data);
}
 
Datum dbms_vector_chain_utl_to_text_1(PG_FUNCTION_ARGS)
{
    Datum             result;
    Size              sz;
    FunctionCallInfo  fcinfo_data;
 
    /* Под args[] — flexible array member, поэтому выделяем память
     * под структуру + место под 2 аргумента. */
    sz = SizeForFunctionCallInfo(2);
    fcinfo_data = (FunctionCallInfo) palloc0(sz);
 
    InitFunctionCallInfoData(*fcinfo_data, NULL, 2,
                             InvalidOid, NULL, NULL);
 
    fcinfo_data->args[0].value  = (Datum) 0;
    fcinfo_data->args[0].isnull = true;
    fcinfo_data->args[1].value  = (Datum) 0;
    fcinfo_data->args[1].isnull = true;
 
    /* Первый аргумент: blob (bytea) -> clob (text).
     * Так как clob — это домен над text, а bytea и text структурно
     * идентичны (оба varlena), достаточно переинтерпретировать указатель. */
    if (!PG_ARGISNULL(0))
    {
        fcinfo_data->args[0].value =
            PointerGetDatum((text *) PG_GETARG_BYTEA_PP(0));
        fcinfo_data->args[0].isnull = false;
    }
 
    /* Второй аргумент: json (хранится как text). */
    if (!PG_ARGISNULL(1))
    {
        fcinfo_data->args[1].value  = PG_GETARG_DATUM(1);
        fcinfo_data->args[1].isnull = false;
    }
 
 
    /* Вызываем целевую функцию. Она получит корректные argnull-флаги
     * и сможет через PG_ARGISNULL отличить NULL от валидного значения. */
    result = dbms_vector_chain_utl_to_text_0(fcinfo_data);
 
    if (fcinfo_data->isnull)
    {
        pfree(fcinfo_data);
        PG_RETURN_NULL();
    }
 
    pfree(fcinfo_data);
    PG_RETURN_DATUM(result);
}
 
Datum dbms_vector_chain_preference_profile(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceProfileValue));
}
 
Datum dbms_vector_chain_preference_chunker(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceChunkerValue));
}
 
Datum dbms_vector_chain_preference_embedder(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceEmbedderValue));
}
 
Datum dbms_vector_chain_preference_index(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(kDbmsVectorChainPreferenceIndexValue));
}
 
Datum dbms_vector_chain_excp_cred_not_exist(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsVectorChainExcpCredNotExistValue);
}
 
Datum dbms_vector_chain_excp_provider_err(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsVectorChainExcpProviderErrValue);
}
 
Datum dbms_vector_chain_excp_gu_err(PG_FUNCTION_ARGS)
{
    PG_RETURN_INT32(kDbmsVectorChainExcpGuErrValue);
}
 
Datum dbms_vector_chain_get_version(PG_FUNCTION_ARGS)
{
    PG_RETURN_TEXT_P(cstring_to_text(RUDB_DBMS_VECTOR_CHAIN_VERSION));
}
 
Datum dbms_vector_chain_mock(PG_FUNCTION_ARGS)
{
    /*
     * ERROR: generated package mock stub.
     * ERROR: Эта функция является checkpoint-заглушкой и требует ручной реализации.
     * ERROR: Generated package mock stub: функция DBMS_VECTOR_CHAIN.MOCK является заглушкой и требует ручной реализации.
     */
    /*
     * TODO: функция пока не реализована; чтение аргументов оставлено
     * ниже как подсказка для разработчика. Раскомментируйте и
     * адаптируйте эти строки при ручной реализации.
     */
    // RESULT return_value (text): вернуть как scalar result функции.
 
    dbms_vector_chain_raise_stub_error("Сгенерированная функция DBMS_VECTOR_CHAIN.MOCK является mock stub; требуется ручная реализация.");
    PG_RETURN_NULL();
}
 
Datum dbms_vector_chain_add_credential(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        ereport(ERROR, (errmsg("credential_name not defined")));
    if(PG_ARGISNULL(0))
        ereport(ERROR, (errmsg("credential_name not defined")));
    text *credential_name = PG_GETARG_TEXT_PP(0);
    text *params = PG_GETARG_TEXT_PP(1);
    dbms_vector_chain::create_credential(credential_name, params);
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_create_lang_data(PG_FUNCTION_ARGS)
{
    text *params = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
 
    dbms_vector_chain::create_lang_data(params);
 
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_create_preference(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        ereport(ERROR, (errmsg("pref_name not defined")));
    if (PG_ARGISNULL(1))
        ereport(ERROR, (errmsg("pref_type not defined")));
 
    char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
    char *pref_type = text_to_cstring(PG_GETARG_TEXT_PP(1));
    text *params    = PG_ARGISNULL(2) ? NULL : PG_GETARG_TEXT_PP(2);
 
    dbms_vector_chain::create_preference(pref_name, pref_type, params);
 
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_add_vocabulary(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
    
    text *parameters = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
    dbms_vector_chain::VocabularyParams *param = dbms_vector_chain::initVocabularyParams(parameters);
    dbms_vector_chain::create_vocabulary(param);
 
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_del_credential(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
    text *credential_name = PG_GETARG_TEXT_PP(0);
    dbms_vector_chain::drop_credential(credential_name);
    
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_drop_lang_data(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        ereport(ERROR,
                (errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
                 errmsg("language name must not be null")));
 
    char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
 
    dbms_vector_chain::drop_lang_data(pref_name);
 
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_drop_preference(PG_FUNCTION_ARGS)
{
    if (PG_ARGISNULL(0))
        ereport(ERROR, (errmsg("pref_name not defined")));
 
    char *pref_name = text_to_cstring(PG_GETARG_TEXT_PP(0));
 
    dbms_vector_chain::drop_preference(pref_name);
 
    PG_RETURN_VOID();
}
 
Datum dbms_vector_chain_del_vocabulary(PG_FUNCTION_ARGS)
{
    if(PG_ARGISNULL(0))
        dbms_vector_chain_raise_stub_error("недопустимый идентификатор");
    text *vocabulary_name = PG_ARGISNULL(0) ? NULL : PG_GETARG_TEXT_PP(0);
    dbms_vector_chain::drop_vocabulary(vocabulary_name);
    PG_RETURN_VOID();
}