summaryrefslogtreecommitdiff
path: root/contrib/plpgsql/src/pl_funcs.c
blob: 94de9e4c9a60922dead099529a6aa5d5b2945545 (plain)
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
/**********************************************************************
 * pl_funcs.c		- Misc functins for the PL/pgSQL
 *			  procedural language
 *
 * IDENTIFICATION
 *    $Header: /cvsroot/pgsql/contrib/plpgsql/src/Attic/pl_funcs.c,v 1.1 1998/08/22 12:38:32 momjian Exp $
 *
 *    This software is copyrighted by Jan Wieck - Hamburg.
 *
 *    The author hereby grants permission  to  use,  copy,  modify,
 *    distribute,  and  license this software and its documentation
 *    for any purpose, provided that existing copyright notices are
 *    retained  in  all  copies  and  that  this notice is included
 *    verbatim in any distributions. No written agreement, license,
 *    or  royalty  fee  is required for any of the authorized uses.
 *    Modifications to this software may be  copyrighted  by  their
 *    author  and  need  not  follow  the licensing terms described
 *    here, provided that the new terms are  clearly  indicated  on
 *    the first page of each file where they apply.
 *
 *    IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY
 *    PARTY  FOR  DIRECT,   INDIRECT,   SPECIAL,   INCIDENTAL,   OR
 *    CONSEQUENTIAL   DAMAGES  ARISING  OUT  OF  THE  USE  OF  THIS
 *    SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN
 *    IF  THE  AUTHOR  HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
 *    DAMAGE.
 *
 *    THE  AUTHOR  AND  DISTRIBUTORS  SPECIFICALLY   DISCLAIM   ANY
 *    WARRANTIES,  INCLUDING,  BUT  NOT  LIMITED  TO,  THE  IMPLIED
 *    WARRANTIES  OF  MERCHANTABILITY,  FITNESS  FOR  A  PARTICULAR
 *    PURPOSE,  AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON
 *    AN "AS IS" BASIS, AND THE AUTHOR  AND  DISTRIBUTORS  HAVE  NO
 *    OBLIGATION   TO   PROVIDE   MAINTENANCE,   SUPPORT,  UPDATES,
 *    ENHANCEMENTS, OR MODIFICATIONS.
 *
 **********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <ctype.h>

#include "plpgsql.h"
#include "pl.tab.h"


/* ----------
 * Local variables for the namestack handling
 * ----------
 */
static PLpgSQL_ns		*ns_current = NULL;
static bool			ns_localmode = false;


/* ----------
 * plpgsql_dstring_init			Dynamic string initialization
 * ----------
 */
void plpgsql_dstring_init(PLpgSQL_dstring *ds)
{
    ds->value = palloc(ds->alloc = 512);
    ds->used = 0;
}


/* ----------
 * plpgsql_dstring_free			Dynamic string destruction
 * ----------
 */
void plpgsql_dstring_free(PLpgSQL_dstring *ds)
{
    pfree(ds->value);
}


/* ----------
 * plpgsql_dstring_append		Dynamic string extending
 * ----------
 */
void plpgsql_dstring_append(PLpgSQL_dstring *ds, char *str)
{
    int len = strlen(str);

    if (ds->used + len + 1 > ds->alloc) {
        ds->alloc *= 2;
	ds->value = repalloc(ds->value, ds->alloc);
    }

    strcpy(&(ds->value[ds->used]), str);
    ds->used += len;
}


/* ----------
 * plpgsql_dstring_get			Dynamic string get value
 * ----------
 */
char *plpgsql_dstring_get(PLpgSQL_dstring *ds)
{
    return ds->value;
}


/* ----------
 * plpgsql_ns_init			Initialize the namestack
 * ----------
 */
void plpgsql_ns_init(void)
{
    ns_current   = NULL;
    ns_localmode = false;
}


/* ----------
 * plpgsql_ns_setlocal			Tell plpgsql_ns_lookup to or to
 *					not look into the current level
 *					only.
 * ----------
 */
bool plpgsql_ns_setlocal(bool flag)
{
    bool oldstate;

    oldstate = ns_localmode;
    ns_localmode = flag;
    return oldstate;
}


/* ----------
 * plpgsql_ns_push			Enter a new namestack level
 * ----------
 */
void plpgsql_ns_push(char *label)
{
    PLpgSQL_ns	*new;

    new = palloc(sizeof(PLpgSQL_ns));
    memset(new, 0, sizeof(PLpgSQL_ns));
    new->upper = ns_current;
    ns_current = new;

    plpgsql_ns_additem(PLPGSQL_NSTYPE_LABEL, 0, label);
}


/* ----------
 * plpgsql_ns_pop			Return to the previous level
 * ----------
 */
void plpgsql_ns_pop()
{
    int		i;
    PLpgSQL_ns	*old;

    old = ns_current;
    ns_current = old->upper;

    for (i = 0; i < old->items_used; i++) {
        pfree(old->items[i]);
    }
    pfree(old->items);
    pfree(old);
}


/* ----------
 * plpgsql_ns_additem			Add an item to the current
 *					namestack level
 * ----------
 */
void plpgsql_ns_additem(int itemtype, int itemno, char *name)
{
    PLpgSQL_ns		*ns = ns_current;
    PLpgSQL_nsitem	*nse;

    if (name == NULL)
	    name = "";

    if (ns->items_used == ns->items_alloc) {
	if (ns->items_alloc == 0) {
	    ns->items_alloc = 32;
	    ns->items = palloc(sizeof(PLpgSQL_nsitem *) * ns->items_alloc);
	} else {
	    ns->items_alloc *= 2;
	    ns->items = repalloc(ns->items, 
	    		sizeof(PLpgSQL_nsitem *) * ns->items_alloc);
	}
    }

    nse = palloc(sizeof(PLpgSQL_nsitem) + strlen(name));
    nse->itemtype = itemtype;
    nse->itemno   = itemno;
    strcpy(nse->name, name);
    ns->items[ns->items_used++] = nse;
}


/* ----------
 * plpgsql_ns_lookup			Lookup for a word in the namestack
 * ----------
 */
PLpgSQL_nsitem *plpgsql_ns_lookup(char *name, char *label)
{
    PLpgSQL_ns	*ns;
    int		i;

    /* ----------
     * If a label is specified, lookup only in that
     * ----------
     */
    if (label != NULL) {
        for (ns = ns_current; ns != NULL; ns = ns->upper) {
	    if (!strcmp(ns->items[0]->name, label)) {
	        for (i = 1; i < ns->items_used; i++) {
		    if (!strcmp(ns->items[i]->name, name)) {
		        return ns->items[i];
		    }
		}
		return NULL;	/* name not found in specified label */
	    }
	}
	return NULL;	/* label not found */
    }

    /* ----------
     * No label given, lookup for visible labels ignoring localmode
     * ----------
     */
    for (ns = ns_current; ns != NULL; ns = ns->upper) {
	if (!strcmp(ns->items[0]->name, name)) {
	    return ns->items[0];
        }
    }

    /* ----------
     * Finally lookup name in the namestack
     * ----------
     */
    for (ns = ns_current; ns != NULL; ns = ns->upper) {
	for (i = 1; i < ns->items_used; i++) {
	    if (!strcmp(ns->items[i]->name, name))
		    return ns->items[i];
	}
	if (ns_localmode) {
	    return NULL;	/* name not found in current namespace */
	}
    }

    return NULL;
}


/* ----------
 * plpgsql_ns_rename			Rename a namespace entry
 * ----------
 */
void plpgsql_ns_rename(char *oldname, char *newname)
{
    PLpgSQL_ns		*ns;
    PLpgSQL_nsitem	*newitem;
    int			i;

    /* ----------
     * Lookup in the current namespace only
     * ----------
     */
    /* ----------
     * Lookup name in the namestack
     * ----------
     */
    for (ns = ns_current; ns != NULL; ns = ns->upper) {
	for (i = 1; i < ns->items_used; i++) {
	    if (!strcmp(ns->items[i]->name, oldname)) {
		newitem = palloc(sizeof(PLpgSQL_nsitem) + strlen(newname));
		newitem->itemtype = ns->items[i]->itemtype;
		newitem->itemno   = ns->items[i]->itemno;
		strcpy(newitem->name, newname);

		pfree(oldname);
		pfree(newname);

		pfree(ns->items[i]);
		ns->items[i] = newitem;
		return;
	    }
	}
    }

    elog(ERROR, "there is no variable '%s' in the current block", oldname);
}


/* ----------
 * plpgsql_tolower			Translate a string in place to
 *					lower case
 * ----------
 */
char *plpgsql_tolower(char *s)
{
    char *cp;

    for (cp = s; *cp; cp++) {
        if (isupper(*cp)) *cp = tolower(*cp);
    }

    return s;
}





/**********************************************************************
 * Debug functions for analyzing the compiled code
 **********************************************************************/
static int	dump_indent;

static void dump_ind();
static void dump_stmt(PLpgSQL_stmt *stmt);
static void dump_block(PLpgSQL_stmt_block *block);
static void dump_assign(PLpgSQL_stmt_assign *stmt);
static void dump_if(PLpgSQL_stmt_if *stmt);
static void dump_loop(PLpgSQL_stmt_loop *stmt);
static void dump_while(PLpgSQL_stmt_while *stmt);
static void dump_fori(PLpgSQL_stmt_fori *stmt);
static void dump_fors(PLpgSQL_stmt_fors *stmt);
static void dump_select(PLpgSQL_stmt_select *stmt);
static void dump_exit(PLpgSQL_stmt_exit *stmt);
static void dump_return(PLpgSQL_stmt_return *stmt);
static void dump_raise(PLpgSQL_stmt_raise *stmt);
static void dump_execsql(PLpgSQL_stmt_execsql *stmt);
static void dump_expr(PLpgSQL_expr *expr);


static void dump_ind()
{
    int i;
    for (i = 0; i < dump_indent; i++) {
        printf(" ");
    }
}

static void dump_stmt(PLpgSQL_stmt *stmt)
{
    printf("%3d:", stmt->lineno);
    switch (stmt->cmd_type) {
        case PLPGSQL_STMT_BLOCK:
		dump_block((PLpgSQL_stmt_block *)stmt);
		break;
        case PLPGSQL_STMT_ASSIGN:
		dump_assign((PLpgSQL_stmt_assign *)stmt);
		break;
        case PLPGSQL_STMT_IF:
		dump_if((PLpgSQL_stmt_if *)stmt);
		break;
        case PLPGSQL_STMT_LOOP:
		dump_loop((PLpgSQL_stmt_loop *)stmt);
		break;
        case PLPGSQL_STMT_WHILE:
		dump_while((PLpgSQL_stmt_while *)stmt);
		break;
        case PLPGSQL_STMT_FORI:
		dump_fori((PLpgSQL_stmt_fori *)stmt);
		break;
        case PLPGSQL_STMT_FORS:
		dump_fors((PLpgSQL_stmt_fors *)stmt);
		break;
        case PLPGSQL_STMT_SELECT:
		dump_select((PLpgSQL_stmt_select *)stmt);
		break;
        case PLPGSQL_STMT_EXIT:
		dump_exit((PLpgSQL_stmt_exit *)stmt);
		break;
        case PLPGSQL_STMT_RETURN:
		dump_return((PLpgSQL_stmt_return *)stmt);
		break;
        case PLPGSQL_STMT_RAISE:
		dump_raise((PLpgSQL_stmt_raise *)stmt);
		break;
        case PLPGSQL_STMT_EXECSQL:
		dump_execsql((PLpgSQL_stmt_execsql *)stmt);
		break;
        default:
		elog(ERROR, "plpgsql_dump: unknown cmd_type %d\n", stmt->cmd_type);
		break;
    }
}

static void dump_block(PLpgSQL_stmt_block *block)
{
    int i;
    char *name;

    if (block->label == NULL) {
        name = "*unnamed*";
    } else {
        name = block->label;
    }

    dump_ind();
    printf("BLOCK <<%s>>\n", name);

    dump_indent += 2;
    for (i = 0; i < block->body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(block->body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    END -- %s\n", name);
}

static void dump_assign(PLpgSQL_stmt_assign *stmt)
{
    dump_ind();
    printf("ASSIGN var %d := ", stmt->varno);
    dump_expr(stmt->expr);
    printf("\n");
}

static void dump_if(PLpgSQL_stmt_if *stmt)
{
    int i;

    dump_ind();
    printf("IF ");
    dump_expr(stmt->cond);
    printf(" THEN\n");

    dump_indent += 2;
    for (i = 0; i < stmt->true_body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->true_body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ELSE\n");

    dump_indent += 2;
    for (i = 0; i < stmt->false_body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->false_body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ENDIF\n");
}

static void dump_loop(PLpgSQL_stmt_loop *stmt)
{
    int i;

    dump_ind();
    printf("LOOP\n");

    dump_indent += 2;
    for (i = 0; i < stmt->body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ENDLOOP\n");
}

static void dump_while(PLpgSQL_stmt_while *stmt)
{
    int i;

    dump_ind();
    printf("WHILE ");
    dump_expr(stmt->cond);
    printf("\n");

    dump_indent += 2;
    for (i = 0; i < stmt->body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ENDWHILE\n");
}

static void dump_fori(PLpgSQL_stmt_fori *stmt)
{
    int i;

    dump_ind();
    printf("FORI %s %s\n", stmt->var->refname, (stmt->reverse) ? "REVERSE" : "NORMAL");

    dump_indent += 2;
    dump_ind();
    printf("    lower = ");
    dump_expr(stmt->lower);
    printf("\n");
    dump_ind();
    printf("    upper = ");
    dump_expr(stmt->upper);
    printf("\n");

    for (i = 0; i < stmt->body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ENDFORI\n");
}

static void dump_fors(PLpgSQL_stmt_fors *stmt)
{
    int i;

    dump_ind();
    printf("FORS %s ", (stmt->rec != NULL) ? stmt->rec->refname : stmt->row->refname);
    dump_expr(stmt->query);
    printf("\n");

    dump_indent += 2;
    for (i = 0; i < stmt->body->stmts_used; i++) {
        dump_stmt((PLpgSQL_stmt *)(stmt->body->stmts[i]));
    }
    dump_indent -= 2;

    dump_ind();
    printf("    ENDFORS\n");
}

static void dump_select(PLpgSQL_stmt_select *stmt)
{
    dump_ind();
    printf("SELECT ");
    dump_expr(stmt->query);
    printf("\n");

    dump_indent += 2;
    if (stmt->rec != NULL) {
	dump_ind();
	printf("    target = %d %s\n", stmt->rec->recno, stmt->rec->refname);
    }
    if (stmt->row != NULL) {
	dump_ind();
	printf("    target = %d %s\n", stmt->row->rowno, stmt->row->refname);
    }
    dump_indent -= 2;

}

static void dump_exit(PLpgSQL_stmt_exit *stmt)
{
    dump_ind();
    printf("EXIT lbl='%s'", stmt->label);
    if (stmt->cond != NULL) {
        printf(" WHEN ");
	dump_expr(stmt->cond);
    }
    printf("\n");
}

static void dump_return(PLpgSQL_stmt_return *stmt)
{
    dump_ind();
    printf("RETURN ");
    if (stmt->retrecno >= 0) {
        printf("record %d", stmt->retrecno);
    } else {
	if (stmt->expr == NULL) {
	    printf("NULL");
	} else {
	    dump_expr(stmt->expr);
	}
    }
    printf("\n");
}

static void dump_raise(PLpgSQL_stmt_raise *stmt)
{
    int i;

    dump_ind();
    printf("RAISE '%s'", stmt->message);
    for (i = 0; i < stmt->nparams; i++) {
        printf(" %d", stmt->params[i]);
    }
    printf("\n");
}

static void dump_execsql(PLpgSQL_stmt_execsql *stmt)
{
    dump_ind();
    printf("EXECSQL ");
    dump_expr(stmt->sqlstmt);
    printf("\n");
}

static void dump_expr(PLpgSQL_expr *expr)
{
    int i;
    printf("'%s", expr->query);
    if (expr->nparams > 0) {
	printf(" {");
	for(i = 0; i < expr->nparams; i++) {
	    if (i > 0) printf(", ");
	    printf("$%d=%d", i+1, expr->params[i]);
	}
	printf("}");
    }
    printf("'");
}

void plpgsql_dumptree(PLpgSQL_function *func)
{
    int i;
    PLpgSQL_datum *d;

    printf("\nExecution tree of successfully compiled PL/pgSQL function %s:\n",
    		func->fn_name);

    printf("\nFunctions data area:\n");
    for (i = 0; i < func->ndatums; i++) {
    	d = func->datums[i];

	printf("    entry %d: ", i);
	switch (d->dtype) {
	    case PLPGSQL_DTYPE_VAR:
		{
		    PLpgSQL_var *var = (PLpgSQL_var *)d;
		    printf("VAR %-16s type %s (typoid %d) atttypmod %d\n",
		    		var->refname, var->datatype->typname,
				var->datatype->typoid,
				var->datatype->atttypmod);
		}
	    	break;
	    case PLPGSQL_DTYPE_ROW:
	        {
		    PLpgSQL_row *row = (PLpgSQL_row *)d;
		    int i;
		    printf("ROW %-16s fields", row->refname);
		    for (i = 0; i < row->nfields; i++) {
		        printf(" %s=var %d", row->fieldnames[i],
					     row->varnos[i]);
		    }
		    printf("\n");
		}
		break;
	    case PLPGSQL_DTYPE_REC:
	    	printf("REC %s\n", ((PLpgSQL_rec *)d)->refname);
	    	break;
	    case PLPGSQL_DTYPE_RECFIELD:
	    	printf("RECFIELD %-16s of REC %d\n", ((PLpgSQL_recfield *)d)->fieldname, ((PLpgSQL_recfield *)d)->recno);
	    	break;
	    case PLPGSQL_DTYPE_TRIGARG:
	    	printf("TRIGARG ");
		dump_expr(((PLpgSQL_trigarg *)d)->argnum);
		printf("\n");
		break;
	    default:
	    	printf("??? unknown data type %d\n", d->dtype);
	}
    }
    printf("\nFunctions statements:\n");
    
    dump_indent = 0;
    printf("%3d:", func->action->lineno);
    dump_block(func->action);
    printf("\nEnd of execution tree of function %s\n\n", func->fn_name);
}