Исходный код СУБД 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
/*
 * Python procedure manipulation for plpython
 *
 * src/pl/plpython/plpy_procedure.c
 */
 
#include "postgres.h"
 
#include "catalog/pg_proc.h"
#include "catalog/pg_type.h"
#include "commands/event_trigger.h"
#include "commands/trigger.h"
#include "funcapi.h"
#include "plpy_elog.h"
#include "plpy_exec.h"
#include "plpy_main.h"
#include "plpy_procedure.h"
#include "plpy_util.h"
#include "utils/builtins.h"
#include "utils/funccache.h"
#include "utils/hsearch.h"
#include "utils/syscache.h"
 
/*
 * SD dictionaries, one per function (and per relation, for DML triggers).
 * funccache.c may build several PLyProcedures for one function, for example
 * one per input collation, and they must all see the same SD.
 */
typedef struct PLyStaticsKey
{
    Oid         fn_oid;         /* function OID */
    Oid         fn_rel;         /* triggered-on relation or InvalidOid */
} PLyStaticsKey;
 
typedef struct PLyStaticsEntry
{
    PLyStaticsKey key;          /* hash key, must be first */
    PyObject   *statics;        /* the SD dictionary */
} PLyStaticsEntry;
 
static HTAB *PLy_statics_hash = NULL;
 
static void PLy_procedure_create(PLyProcedure *proc,
                                 HeapTuple procTup,
                                 Oid fn_oid,
                                 Oid fn_rel,
                                 PLyTrigType is_trigger);
static PyObject *PLy_procedure_get_statics(Oid fn_oid, Oid fn_rel);
static char *PLy_procedure_munge_source(const char *name, const char *src);
static void PLy_compile_callback(FunctionCallInfo fcinfo,
                                 HeapTuple procTup,
                                 const CachedFunctionHashKey *hashkey,
                                 CachedFunction *cfunc,
                                 bool forValidator);
static void PLy_delete_callback(CachedFunction *cfunc);
static void RemovePLyProcedureCache(void *arg);
 
 
/*
 * PLy_procedure_name: get the name of the specified procedure.
 *
 * NB: this returns the SQL name, not the internal Python procedure name
 */
char *
PLy_procedure_name(PLyProcedure *proc)
{
    if (proc == NULL)
        return "<unknown procedure>";
    return proc->proname;
}
 
/*
 * PLy_procedure_get: returns a PLyProcedureCache struct for the function,
 * making it valid if necessary.
 *
 * The PLyProcedureCache contains a pointer to the long-lived PLyProcedure
 * (managed by funccache.c) and execution-specific state like SRF state.
 *
 * For SRFs, if we are resuming execution (srfstate->iter != NULL), we skip
 * revalidation and continue using the same PLyProcedure to ensure consistent
 * behavior throughout the SRF execution.
 */
PLyProcedureCache *
PLy_procedure_get(FunctionCallInfo fcinfo, bool forValidator)
{
    FmgrInfo   *finfo = fcinfo->flinfo;
    PLyProcedureCache *pcache;
    PLyProcedure *proc;
 
    /*
     * If this is the first execution for this FmgrInfo, set up a cache struct
     * (initially containing null pointers).  The cache must live as long as
     * the FmgrInfo, so it goes in fn_mcxt.  Also set up a memory context
     * callback that will be invoked when fn_mcxt is reset/deleted.
     */
    pcache = finfo->fn_extra;
    if (pcache == NULL)
    {
        pcache = (PLyProcedureCache *)
            MemoryContextAllocZero(finfo->fn_mcxt, sizeof(PLyProcedureCache));
 
        pcache->fcontext = finfo->fn_mcxt;
        pcache->mcb.func = RemovePLyProcedureCache;
        pcache->mcb.arg = pcache;
 
        MemoryContextRegisterResetCallback(finfo->fn_mcxt, &pcache->mcb);
 
        finfo->fn_extra = pcache;
    }
 
    /*
     * If we are resuming execution of a set-returning function, just keep
     * using the same cache.  We do not ask funccache.c to re-validate the
     * PLyProcedure: we want to run to completion using the function's initial
     * definition.
     *
     * A live iterator (srfstate->iter != NULL) reliably means a genuine
     * resume: when an iteration ends for any reason, srfstate->iter is reset
     * to NULL (see comments for PLy_function_cleanup_srfstate).
     */
    if (pcache->srfstate != NULL && pcache->srfstate->iter != NULL)
    {
        Assert(pcache->proc != NULL);
        return pcache;
    }
 
    /*
     * Look up, or re-validate, the long-lived hash entry.  Like SQL-language
     * functions, make the hash key depend on the result of
     * get_call_result_type() when that's composite, so that we can safely
     * assume that we'll build a new hash entry if the composite rowtype
     * changes.
     */
    proc = (PLyProcedure *)
        cached_function_compile(fcinfo,
                                (CachedFunction *) pcache->proc,
                                PLy_compile_callback,
                                PLy_delete_callback,
                                sizeof(PLyProcedure),
                                true,
                                forValidator);
 
    /*
     * Install the hash pointer in the PLyProcedureCache, and increment its
     * use count to reflect that.  If cached_function_compile gave us back a
     * different hash entry than we were using before, we must decrement that
     * one's use count.
     */
    if (proc != pcache->proc)
    {
        if (pcache->proc != NULL)
        {
            Assert(pcache->proc->cfunc.use_count > 0);
            pcache->proc->cfunc.use_count--;
        }
        pcache->proc = proc;
        proc->cfunc.use_count++;
    }
 
    return pcache;
}
 
/*
 * Create (well, fill in) a new PLyProcedure structure
 */
static void
PLy_procedure_create(PLyProcedure *proc,
                     HeapTuple procTup,
                     Oid fn_oid,
                     Oid fn_rel,
                     PLyTrigType is_trigger)
{
    char        procName[NAMEDATALEN + 256];
    Form_pg_proc procStruct;
    MemoryContext cxt;
    MemoryContext oldcxt;
    int         rv;
    char       *ptr;
 
    procStruct = (Form_pg_proc) GETSTRUCT(procTup);
    rv = snprintf(procName, sizeof(procName),
                  "__plpython_procedure_%s_%u",
                  NameStr(procStruct->proname),
                  fn_oid);
    if (rv >= sizeof(procName) || rv < 0)
        elog(ERROR, "procedure name would overrun buffer");
 
    /* Replace any not-legal-in-Python-names characters with '_' */
    for (ptr = procName; *ptr; ptr++)
    {
        if (!((*ptr >= 'A' && *ptr <= 'Z') ||
              (*ptr >= 'a' && *ptr <= 'z') ||
              (*ptr >= '0' && *ptr <= '9')))
            *ptr = '_';
    }
 
    /* Create long-lived context that all procedure info will live in */
    cxt = AllocSetContextCreate(TopMemoryContext,
                                "PL/Python function",
                                ALLOCSET_DEFAULT_SIZES);
 
    oldcxt = MemoryContextSwitchTo(cxt);
 
    proc->mcxt = cxt;
 
    PG_TRY();
    {
        Datum       protrftypes_datum;
        Datum       prosrcdatum;
        bool        isnull;
        char       *procSource;
        int         i;
 
        proc->proname = pstrdup(NameStr(procStruct->proname));
        MemoryContextSetIdentifier(cxt, proc->proname);
        proc->pyname = pstrdup(procName);
        proc->fn_readonly = (procStruct->provolatile != PROVOLATILE_VOLATILE);
        proc->is_setof = procStruct->proretset;
        proc->is_procedure = (procStruct->prokind == PROKIND_PROCEDURE);
        proc->is_trigger = is_trigger;
        proc->src = NULL;
        proc->argnames = NULL;
        proc->args = NULL;
        proc->nargs = 0;
        proc->langid = procStruct->prolang;
        protrftypes_datum = SysCacheGetAttr(PROCOID, procTup,
                                            Anum_pg_proc_protrftypes,
                                            &isnull);
        proc->trftypes = isnull ? NIL : oid_array_to_list(protrftypes_datum);
        proc->code = NULL;
        proc->statics = NULL;
        proc->globals = NULL;
        proc->calldepth = 0;
        proc->argstack = NULL;
 
        /*
         * get information required for output conversion of the return value,
         * but only if this isn't a trigger.
         */
        if (is_trigger == PLPY_NOT_TRIGGER)
        {
            Oid         rettype = procStruct->prorettype;
            HeapTuple   rvTypeTup;
            Form_pg_type rvTypeStruct;
 
            rvTypeTup = SearchSysCache1(TYPEOID, ObjectIdGetDatum(rettype));
            if (!HeapTupleIsValid(rvTypeTup))
                elog(ERROR, "cache lookup failed for type %u", rettype);
            rvTypeStruct = (Form_pg_type) GETSTRUCT(rvTypeTup);
 
            /* Disallow pseudotype result, except for void or record */
            if (rvTypeStruct->typtype == TYPTYPE_PSEUDO)
            {
                if (rettype == VOIDOID ||
                    rettype == RECORDOID)
                     /* okay */ ;
                else if (rettype == TRIGGEROID || rettype == EVENT_TRIGGEROID)
                    ereport(ERROR,
                            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                             errmsg("trigger functions can only be called as triggers")));
                else
                    ereport(ERROR,
                            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                             errmsg("PL/Python functions cannot return type %s",
                                    format_type_be(rettype))));
            }
 
            /* set up output function for procedure result */
            PLy_output_setup_func(&proc->result, proc->mcxt,
                                  rettype, -1, proc);
 
            ReleaseSysCache(rvTypeTup);
        }
        else
        {
            /*
             * In a trigger function, we use proc->result and proc->result_in
             * for converting tuples, but we don't yet have enough info to set
             * them up.  PLy_exec_trigger will deal with it.
             */
            proc->result.typoid = InvalidOid;
            proc->result_in.typoid = InvalidOid;
        }
 
        /*
         * Now get information required for input conversion of the
         * procedure's arguments.  Note that we ignore output arguments here.
         * If the function returns record, those I/O functions will be set up
         * when the function is first called.
         */
        if (procStruct->pronargs)
        {
            Oid        *types;
            char      **names,
                       *modes;
            int         pos,
                        total;
 
            /* extract argument type info from the pg_proc tuple */
            total = get_func_arg_info(procTup, &types, &names, &modes);
 
            /* count number of in+inout args into proc->nargs */
            if (modes == NULL)
                proc->nargs = total;
            else
            {
                /* proc->nargs was initialized to 0 above */
                for (i = 0; i < total; i++)
                {
                    if (modes[i] != PROARGMODE_OUT &&
                        modes[i] != PROARGMODE_TABLE)
                        (proc->nargs)++;
                }
            }
 
            /* Allocate arrays for per-input-argument data */
            proc->argnames = (char **) palloc0_array(char *, proc->nargs);
            proc->args = (PLyDatumToOb *) palloc0_array(PLyDatumToOb, proc->nargs);
 
            for (i = pos = 0; i < total; i++)
            {
                HeapTuple   argTypeTup;
                Form_pg_type argTypeStruct;
 
                if (modes &&
                    (modes[i] == PROARGMODE_OUT ||
                     modes[i] == PROARGMODE_TABLE))
                    continue;   /* skip OUT arguments */
 
                Assert(types[i] == procStruct->proargtypes.values[pos]);
 
                argTypeTup = SearchSysCache1(TYPEOID,
                                             ObjectIdGetDatum(types[i]));
                if (!HeapTupleIsValid(argTypeTup))
                    elog(ERROR, "cache lookup failed for type %u", types[i]);
                argTypeStruct = (Form_pg_type) GETSTRUCT(argTypeTup);
 
                /* disallow pseudotype arguments */
                if (argTypeStruct->typtype == TYPTYPE_PSEUDO)
                    ereport(ERROR,
                            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                             errmsg("PL/Python functions cannot accept type %s",
                                    format_type_be(types[i]))));
 
                /* set up I/O function info */
                PLy_input_setup_func(&proc->args[pos], proc->mcxt,
                                     types[i], -1,  /* typmod not known */
                                     proc);
 
                /* get argument name */
                proc->argnames[pos] =
                    (names && names[i][0] != '\0') ? pstrdup(names[i]) : NULL;
 
                ReleaseSysCache(argTypeTup);
 
                pos++;
            }
        }
 
        /*
         * get the text of the function.
         */
        prosrcdatum = SysCacheGetAttrNotNull(PROCOID, procTup,
                                             Anum_pg_proc_prosrc);
        procSource = TextDatumGetCString(prosrcdatum);
 
        /* SD is shared with other PLyProcedures of the function */
        proc->statics = PLy_procedure_get_statics(fn_oid, fn_rel);
 
        PLy_procedure_compile(proc, procSource);
 
        pfree(procSource);
    }
    PG_CATCH();
    {
        MemoryContextSwitchTo(oldcxt);
        PLy_procedure_delete(proc);
        PG_RE_THROW();
    }
    PG_END_TRY();
 
    MemoryContextSwitchTo(oldcxt);
}
 
/*
 * Insert the procedure into the Python interpreter
 */
void
PLy_procedure_compile(PLyProcedure *proc, const char *src)
{
    PyObject   *crv = NULL;
    char       *msrc;
    PyObject   *code0;
 
    proc->globals = PyDict_Copy(PLy_interp_globals);
 
    /*
     * SD is private preserved data between calls. GD is global data shared by
     * all functions.  The caller supplies SD.
     */
    Assert(proc->statics != NULL);
    PyDict_SetItemString(proc->globals, "SD", proc->statics);
 
    /*
     * insert the function code into the interpreter
     */
    msrc = PLy_procedure_munge_source(proc->pyname, src);
    /* Save the mangled source for later inclusion in tracebacks */
    proc->src = MemoryContextStrdup(proc->mcxt, msrc);
    code0 = Py_CompileString(msrc, "<string>", Py_file_input);
    if (code0)
        crv = PyEval_EvalCode(code0, proc->globals, NULL);
    pfree(msrc);
 
    if (crv != NULL)
    {
        int         clen;
        char        call[NAMEDATALEN + 256];
 
        Py_DECREF(crv);
 
        /*
         * compile a call to the function
         */
        clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
        if (clen < 0 || clen >= sizeof(call))
            elog(ERROR, "string would overflow buffer");
        proc->code = Py_CompileString(call, "<string>", Py_eval_input);
        if (proc->code != NULL)
            return;
    }
 
    if (proc->proname)
        PLy_elog(ERROR, "could not compile PL/Python function \"%s\"",
                 proc->proname);
    else
        PLy_elog(ERROR, "could not compile anonymous PL/Python code block");
}
 
void
PLy_procedure_delete(PLyProcedure *proc)
{
    Py_XDECREF(proc->code);
    Py_XDECREF(proc->statics);
    Py_XDECREF(proc->globals);
    MemoryContextDelete(proc->mcxt);
}
 
static char *
PLy_procedure_munge_source(const char *name, const char *src)
{
    char       *mrc,
               *mp;
    const char *sp;
    size_t      mlen;
    int         plen;
 
    /*
     * room for function source and the def statement
     */
    mlen = (strlen(src) * 2) + strlen(name) + 16;
 
    mrc = palloc(mlen);
    plen = snprintf(mrc, mlen, "def %s():\n\t", name);
    Assert(plen >= 0 && plen < mlen);
 
    sp = src;
    mp = mrc + plen;
 
    while (*sp != '\0')
    {
        if (*sp == '\r' && *(sp + 1) == '\n')
            sp++;
 
        if (*sp == '\n' || *sp == '\r')
        {
            *mp++ = '\n';
            *mp++ = '\t';
            sp++;
        }
        else
            *mp++ = *sp++;
    }
    *mp++ = '\n';
    *mp++ = '\n';
    *mp = '\0';
 
    if (mp > (mrc + mlen))
        elog(FATAL, "buffer overrun in PLy_procedure_munge_source");
 
    return mrc;
}
 
/*
 * Compile callback for funccache.c.
 *
 * cached_function_compile() calls this when it needs to (re)compile the
 * long-lived PLyProcedure for a function.  The CachedFunction handed to us is
 * pre-zeroed workspace of size sizeof(PLyProcedure); we just have to fill in
 * the PL/Python-specific fields.
 */
static void
PLy_compile_callback(FunctionCallInfo fcinfo,
                     HeapTuple procTup,
                     const CachedFunctionHashKey *hashkey,
                     CachedFunction *cfunc,
                     bool forValidator)
{
    PLyProcedure *proc = (PLyProcedure *) cfunc;
    Oid         fn_oid = fcinfo->flinfo->fn_oid;
    Oid         fn_rel = InvalidOid;
    PLyTrigType is_trigger;
 
    /*
     * Derive the trigger type from the call context, matching what
     * plpython3_call_handler dispatches on.  DML triggers get one SD per
     * relation.  The validator has no relation.
     */
    if (CALLED_AS_TRIGGER(fcinfo))
    {
        is_trigger = PLPY_TRIGGER;
        if (!forValidator)
            fn_rel = RelationGetRelid(((TriggerData *) fcinfo->context)->tg_relation);
    }
    else if (CALLED_AS_EVENT_TRIGGER(fcinfo))
        is_trigger = PLPY_EVENT_TRIGGER;
    else
        is_trigger = PLPY_NOT_TRIGGER;
 
    PLy_procedure_create(proc, procTup, fn_oid, fn_rel, is_trigger);
}
 
/*
 * Get the SD dictionary of a function, as a new reference.
 */
static PyObject *
PLy_procedure_get_statics(Oid fn_oid, Oid fn_rel)
{
    PLyStaticsKey key;
    PLyStaticsEntry *entry;
    bool        found;
 
    if (PLy_statics_hash == NULL)
    {
        HASHCTL     ctl;
 
        ctl.keysize = sizeof(PLyStaticsKey);
        ctl.entrysize = sizeof(PLyStaticsEntry);
        PLy_statics_hash = hash_create("PL/Python SD dictionaries", 32,
                                       &ctl, HASH_ELEM | HASH_BLOBS);
    }
 
    key.fn_oid = fn_oid;
    key.fn_rel = fn_rel;
    entry = hash_search(PLy_statics_hash, &key, HASH_ENTER, &found);
    if (!found)
        entry->statics = NULL;
 
    /* A failed PyDict_New leaves the entry empty, so retry it here */
    if (entry->statics == NULL)
    {
        entry->statics = PyDict_New();
        if (entry->statics == NULL)
            PLy_elog(ERROR, NULL);
    }
 
    Py_INCREF(entry->statics);
    return entry->statics;
}
 
/*
 * Deletion callback for funccache.c.
 *
 * cached_function_compile() calls this when it discards a cache entry, which
 * only happens once the entry's use count has dropped to zero.  We must free
 * the subsidiary data but not the CachedFunction struct itself.
 */
static void
PLy_delete_callback(CachedFunction *cfunc)
{
    PLyProcedure *proc = (PLyProcedure *) cfunc;
 
    Assert(proc->cfunc.use_count == 0);
    Assert(proc->calldepth == 0);
 
    PLy_procedure_delete(proc);
}
 
/*
 * MemoryContext callback function
 *
 * We register this in the memory context that contains a PLyProcedureCache
 * struct (that is, the FmgrInfo's fn_mcxt).  When the memory context is reset
 * or deleted, we release the reference count (if any) that the cache holds on
 * the long-lived hash entry.  Note that this will happen even during error
 * aborts.
 *
 * This is also our opportunity to release the Python references held by an
 * interrupted set-returning function.  ShutdownPLyFunction() handles that for
 * routine in-query cancellation cases, but it does not run during an error
 * abort; this callback does, so it is the backstop that prevents leaking the
 * SRF's iterator and saved arguments when a query errors out mid-iteration.
 */
static void
RemovePLyProcedureCache(void *arg)
{
    PLyProcedureCache *pcache = (PLyProcedureCache *) arg;
 
    /* Release any Python state left behind by an interrupted SRF */
    PLy_function_cleanup_srfstate(pcache);
 
    /* Release reference count on PLyProcedure */
    if (pcache->proc != NULL)
    {
        Assert(pcache->proc->cfunc.use_count > 0);
        pcache->proc->cfunc.use_count--;
        pcache->proc = NULL;
    }
 
    /* We needn't free the pcache object itself, context cleanup does that */
}