1 /*-------------------------------------------------------------------------
3 * pl_funcs.c - Misc functions for the PL/pgSQL
6 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/pl/plpgsql/src/pl_funcs.c,v 1.52 2006/05/30 13:40:55 momjian Exp $
13 *-------------------------------------------------------------------------
21 #include "parser/scansup.h"
25 * Local variables for the namestack handling
28 static PLpgSQL_ns *ns_current = NULL;
29 static bool ns_localmode = false;
33 * plpgsql_dstring_init Dynamic string initialization
37 plpgsql_dstring_init(PLpgSQL_dstring *ds)
39 ds->value = palloc(ds->alloc = 512);
46 * plpgsql_dstring_free Dynamic string destruction
50 plpgsql_dstring_free(PLpgSQL_dstring *ds)
56 plpgsql_dstring_expand(PLpgSQL_dstring *ds, int needed)
58 /* Don't allow truncating the string */
59 Assert(needed > ds->alloc);
60 Assert(ds->used <= ds->alloc);
62 /* Might have to double more than once, if needed is large */
66 } while (needed > ds->alloc);
67 ds->value = repalloc(ds->value, ds->alloc);
71 * plpgsql_dstring_append Dynamic string extending
75 plpgsql_dstring_append(PLpgSQL_dstring *ds, const char *str)
77 int len = strlen(str);
78 int needed = ds->used + len;
80 if (needed > ds->alloc)
81 plpgsql_dstring_expand(ds, needed);
83 memcpy(&(ds->value[ds->used - 1]), str, len);
85 ds->value[ds->used - 1] = '\0';
89 * plpgsql_dstring_append_char Append a single character
94 plpgsql_dstring_append_char(PLpgSQL_dstring *ds, char c)
96 if (ds->used == ds->alloc)
97 plpgsql_dstring_expand(ds, ds->used + 1);
99 ds->value[ds->used - 1] = c;
100 ds->value[ds->used] = '\0';
106 * plpgsql_dstring_get Dynamic string get value
110 plpgsql_dstring_get(PLpgSQL_dstring *ds)
117 * plpgsql_ns_init Initialize the namestack
121 plpgsql_ns_init(void)
124 ns_localmode = false;
129 * plpgsql_ns_setlocal Tell plpgsql_ns_lookup to or to
130 * not look into the current level
135 plpgsql_ns_setlocal(bool flag)
139 oldstate = ns_localmode;
146 * plpgsql_ns_push Enter a new namestack level
150 plpgsql_ns_push(char *label)
157 new = palloc(sizeof(PLpgSQL_ns));
158 memset(new, 0, sizeof(PLpgSQL_ns));
159 new->upper = ns_current;
162 plpgsql_ns_additem(PLPGSQL_NSTYPE_LABEL, 0, label);
167 * plpgsql_ns_pop Return to the previous level
177 ns_current = old->upper;
179 for (i = 0; i < old->items_used; i++)
180 pfree(old->items[i]);
187 * plpgsql_ns_additem Add an item to the current
192 plpgsql_ns_additem(int itemtype, int itemno, const char *name)
194 PLpgSQL_ns *ns = ns_current;
197 Assert(name != NULL);
199 if (ns->items_used == ns->items_alloc)
201 if (ns->items_alloc == 0)
203 ns->items_alloc = 32;
204 ns->items = palloc(sizeof(PLpgSQL_nsitem *) * ns->items_alloc);
208 ns->items_alloc *= 2;
209 ns->items = repalloc(ns->items,
210 sizeof(PLpgSQL_nsitem *) * ns->items_alloc);
214 nse = palloc(sizeof(PLpgSQL_nsitem) + strlen(name));
215 nse->itemtype = itemtype;
216 nse->itemno = itemno;
217 strcpy(nse->name, name);
218 ns->items[ns->items_used++] = nse;
223 * plpgsql_ns_lookup Lookup for a word in the namestack
227 plpgsql_ns_lookup(char *name, char *label)
233 * If a label is specified, lookup only in that
237 for (ns = ns_current; ns != NULL; ns = ns->upper)
239 if (!strcmp(ns->items[0]->name, label))
241 for (i = 1; i < ns->items_used; i++)
243 if (!strcmp(ns->items[i]->name, name))
246 return NULL; /* name not found in specified label */
249 return NULL; /* label not found */
253 * No label given, lookup for visible labels ignoring localmode
255 for (ns = ns_current; ns != NULL; ns = ns->upper)
257 if (!strcmp(ns->items[0]->name, name))
262 * Finally lookup name in the namestack
264 for (ns = ns_current; ns != NULL; ns = ns->upper)
266 for (i = 1; i < ns->items_used; i++)
268 if (!strcmp(ns->items[i]->name, name))
272 return NULL; /* name not found in current namespace */
280 * plpgsql_ns_rename Rename a namespace entry
284 plpgsql_ns_rename(char *oldname, char *newname)
287 PLpgSQL_nsitem *newitem;
291 * Lookup name in the namestack; do the lookup in the current namespace
294 for (ns = ns_current; ns != NULL; ns = ns->upper)
296 for (i = 1; i < ns->items_used; i++)
298 if (!strcmp(ns->items[i]->name, oldname))
300 newitem = palloc(sizeof(PLpgSQL_nsitem) + strlen(newname));
301 newitem->itemtype = ns->items[i]->itemtype;
302 newitem->itemno = ns->items[i]->itemno;
303 strcpy(newitem->name, newname);
309 ns->items[i] = newitem;
316 (errcode(ERRCODE_UNDEFINED_OBJECT),
317 errmsg("there is no variable \"%s\" in the current block",
323 * plpgsql_convert_ident
325 * Convert a possibly-qualified identifier to internal form: handle
326 * double quotes, translate to lower case where not inside quotes,
327 * truncate to NAMEDATALEN.
329 * There may be several identifiers separated by dots and optional
330 * whitespace. Each one is converted to a separate palloc'd string.
331 * The caller passes the expected number of identifiers, as well as
332 * a char* array to hold them. It is an error if we find the wrong
333 * number of identifiers (cf grammar processing of fori_varname).
335 * NOTE: the input string has already been accepted by the flex lexer,
336 * so we don't need a heckuva lot of error checking here.
340 plpgsql_convert_ident(const char *s, char **output, int numidents)
342 const char *sstart = s;
345 /* Outer loop over identifiers */
351 /* Process current identifier */
355 /* Quoted identifier: copy, collapsing out doubled quotes */
357 curident = palloc(strlen(s) + 1); /* surely enough room */
370 if (*s != '"') /* should not happen if lexer checked */
372 (errcode(ERRCODE_SYNTAX_ERROR),
373 errmsg("unterminated \" in name: %s", sstart)));
376 /* Truncate to NAMEDATALEN */
377 truncate_identifier(curident, cp - curident, false);
381 /* Normal identifier: extends till dot or whitespace */
382 const char *thisstart = s;
384 while (*s && *s != '.' && !isspace((unsigned char) *s))
386 /* Downcase and truncate to NAMEDATALEN */
387 curident = downcase_truncate_identifier(thisstart, s - thisstart,
391 /* Pass ident to caller */
392 if (identctr < numidents)
393 output[identctr++] = curident;
396 (errcode(ERRCODE_SYNTAX_ERROR),
397 errmsg("qualified identifier cannot be used here: %s",
400 /* If not done, skip whitespace, dot, whitespace */
403 while (*s && isspace((unsigned char) *s))
406 elog(ERROR, "expected dot between identifiers: %s", sstart);
407 while (*s && isspace((unsigned char) *s))
410 elog(ERROR, "expected another identifier: %s", sstart);
414 if (identctr != numidents)
415 elog(ERROR, "improperly qualified identifier: %s",
421 * Statement type as a string, for use in error messages etc.
424 plpgsql_stmt_typename(PLpgSQL_stmt *stmt)
426 switch (stmt->cmd_type)
428 case PLPGSQL_STMT_BLOCK:
429 return "block variables initialization";
430 case PLPGSQL_STMT_ASSIGN:
432 case PLPGSQL_STMT_IF:
434 case PLPGSQL_STMT_LOOP:
436 case PLPGSQL_STMT_WHILE:
438 case PLPGSQL_STMT_FORI:
439 return "for with integer loopvar";
440 case PLPGSQL_STMT_FORS:
441 return "for over select rows";
442 case PLPGSQL_STMT_SELECT:
443 return "select into variables";
444 case PLPGSQL_STMT_EXIT:
446 case PLPGSQL_STMT_RETURN:
448 case PLPGSQL_STMT_RETURN_NEXT:
449 return "return next";
450 case PLPGSQL_STMT_RAISE:
452 case PLPGSQL_STMT_EXECSQL:
453 return "SQL statement";
454 case PLPGSQL_STMT_DYNEXECUTE:
455 return "execute statement";
456 case PLPGSQL_STMT_DYNFORS:
457 return "for over execute statement";
458 case PLPGSQL_STMT_GETDIAG:
459 return "get diagnostics";
460 case PLPGSQL_STMT_OPEN:
462 case PLPGSQL_STMT_FETCH:
464 case PLPGSQL_STMT_CLOSE:
466 case PLPGSQL_STMT_PERFORM:
474 /**********************************************************************
475 * Debug functions for analyzing the compiled code
476 **********************************************************************/
477 static int dump_indent;
479 static void dump_ind();
480 static void dump_stmt(PLpgSQL_stmt *stmt);
481 static void dump_block(PLpgSQL_stmt_block *block);
482 static void dump_assign(PLpgSQL_stmt_assign *stmt);
483 static void dump_if(PLpgSQL_stmt_if *stmt);
484 static void dump_loop(PLpgSQL_stmt_loop *stmt);
485 static void dump_while(PLpgSQL_stmt_while *stmt);
486 static void dump_fori(PLpgSQL_stmt_fori *stmt);
487 static void dump_fors(PLpgSQL_stmt_fors *stmt);
488 static void dump_select(PLpgSQL_stmt_select *stmt);
489 static void dump_exit(PLpgSQL_stmt_exit *stmt);
490 static void dump_return(PLpgSQL_stmt_return *stmt);
491 static void dump_return_next(PLpgSQL_stmt_return_next *stmt);
492 static void dump_raise(PLpgSQL_stmt_raise *stmt);
493 static void dump_execsql(PLpgSQL_stmt_execsql *stmt);
494 static void dump_dynexecute(PLpgSQL_stmt_dynexecute *stmt);
495 static void dump_dynfors(PLpgSQL_stmt_dynfors *stmt);
496 static void dump_getdiag(PLpgSQL_stmt_getdiag *stmt);
497 static void dump_open(PLpgSQL_stmt_open *stmt);
498 static void dump_fetch(PLpgSQL_stmt_fetch *stmt);
499 static void dump_close(PLpgSQL_stmt_close *stmt);
500 static void dump_perform(PLpgSQL_stmt_perform *stmt);
501 static void dump_expr(PLpgSQL_expr *expr);
509 for (i = 0; i < dump_indent; i++)
514 dump_stmt(PLpgSQL_stmt *stmt)
516 printf("%3d:", stmt->lineno);
517 switch (stmt->cmd_type)
519 case PLPGSQL_STMT_BLOCK:
520 dump_block((PLpgSQL_stmt_block *) stmt);
522 case PLPGSQL_STMT_ASSIGN:
523 dump_assign((PLpgSQL_stmt_assign *) stmt);
525 case PLPGSQL_STMT_IF:
526 dump_if((PLpgSQL_stmt_if *) stmt);
528 case PLPGSQL_STMT_LOOP:
529 dump_loop((PLpgSQL_stmt_loop *) stmt);
531 case PLPGSQL_STMT_WHILE:
532 dump_while((PLpgSQL_stmt_while *) stmt);
534 case PLPGSQL_STMT_FORI:
535 dump_fori((PLpgSQL_stmt_fori *) stmt);
537 case PLPGSQL_STMT_FORS:
538 dump_fors((PLpgSQL_stmt_fors *) stmt);
540 case PLPGSQL_STMT_SELECT:
541 dump_select((PLpgSQL_stmt_select *) stmt);
543 case PLPGSQL_STMT_EXIT:
544 dump_exit((PLpgSQL_stmt_exit *) stmt);
546 case PLPGSQL_STMT_RETURN:
547 dump_return((PLpgSQL_stmt_return *) stmt);
549 case PLPGSQL_STMT_RETURN_NEXT:
550 dump_return_next((PLpgSQL_stmt_return_next *) stmt);
552 case PLPGSQL_STMT_RAISE:
553 dump_raise((PLpgSQL_stmt_raise *) stmt);
555 case PLPGSQL_STMT_EXECSQL:
556 dump_execsql((PLpgSQL_stmt_execsql *) stmt);
558 case PLPGSQL_STMT_DYNEXECUTE:
559 dump_dynexecute((PLpgSQL_stmt_dynexecute *) stmt);
561 case PLPGSQL_STMT_DYNFORS:
562 dump_dynfors((PLpgSQL_stmt_dynfors *) stmt);
564 case PLPGSQL_STMT_GETDIAG:
565 dump_getdiag((PLpgSQL_stmt_getdiag *) stmt);
567 case PLPGSQL_STMT_OPEN:
568 dump_open((PLpgSQL_stmt_open *) stmt);
570 case PLPGSQL_STMT_FETCH:
571 dump_fetch((PLpgSQL_stmt_fetch *) stmt);
573 case PLPGSQL_STMT_CLOSE:
574 dump_close((PLpgSQL_stmt_close *) stmt);
576 case PLPGSQL_STMT_PERFORM:
577 dump_perform((PLpgSQL_stmt_perform *) stmt);
580 elog(ERROR, "unrecognized cmd_type: %d", stmt->cmd_type);
586 dump_stmts(List *stmts)
592 dump_stmt((PLpgSQL_stmt *) lfirst(s));
597 dump_block(PLpgSQL_stmt_block *block)
601 if (block->label == NULL)
607 printf("BLOCK <<%s>>\n", name);
609 dump_stmts(block->body);
611 if (block->exceptions)
615 foreach(e, block->exceptions->exc_list)
617 PLpgSQL_exception *exc = (PLpgSQL_exception *) lfirst(e);
618 PLpgSQL_condition *cond;
621 printf(" EXCEPTION WHEN ");
622 for (cond = exc->conditions; cond; cond = cond->next)
624 if (cond != exc->conditions)
626 printf("%s", cond->condname);
629 dump_stmts(exc->action);
634 printf(" END -- %s\n", name);
638 dump_assign(PLpgSQL_stmt_assign *stmt)
641 printf("ASSIGN var %d := ", stmt->varno);
642 dump_expr(stmt->expr);
647 dump_if(PLpgSQL_stmt_if *stmt)
651 dump_expr(stmt->cond);
654 dump_stmts(stmt->true_body);
656 if (stmt->false_body != NIL)
660 dump_stmts(stmt->false_body);
668 dump_loop(PLpgSQL_stmt_loop *stmt)
673 dump_stmts(stmt->body);
676 printf(" ENDLOOP\n");
680 dump_while(PLpgSQL_stmt_while *stmt)
684 dump_expr(stmt->cond);
687 dump_stmts(stmt->body);
690 printf(" ENDWHILE\n");
694 dump_fori(PLpgSQL_stmt_fori *stmt)
697 printf("FORI %s %s\n", stmt->var->refname, (stmt->reverse) ? "REVERSE" : "NORMAL");
702 dump_expr(stmt->lower);
706 dump_expr(stmt->upper);
710 dump_stmts(stmt->body);
713 printf(" ENDFORI\n");
717 dump_fors(PLpgSQL_stmt_fors *stmt)
720 printf("FORS %s ", (stmt->rec != NULL) ? stmt->rec->refname : stmt->row->refname);
721 dump_expr(stmt->query);
724 dump_stmts(stmt->body);
727 printf(" ENDFORS\n");
731 dump_select(PLpgSQL_stmt_select *stmt)
735 dump_expr(stmt->query);
739 if (stmt->rec != NULL)
742 printf(" target = %d %s\n", stmt->rec->recno, stmt->rec->refname);
744 if (stmt->row != NULL)
747 printf(" target = %d %s\n", stmt->row->rowno, stmt->row->refname);
754 dump_open(PLpgSQL_stmt_open *stmt)
757 printf("OPEN curvar=%d\n", stmt->curvar);
760 if (stmt->argquery != NULL)
763 printf(" arguments = '");
764 dump_expr(stmt->argquery);
767 if (stmt->query != NULL)
770 printf(" query = '");
771 dump_expr(stmt->query);
774 if (stmt->dynquery != NULL)
777 printf(" execute = '");
778 dump_expr(stmt->dynquery);
786 dump_fetch(PLpgSQL_stmt_fetch *stmt)
789 printf("FETCH curvar=%d\n", stmt->curvar);
792 if (stmt->rec != NULL)
795 printf(" target = %d %s\n", stmt->rec->recno, stmt->rec->refname);
797 if (stmt->row != NULL)
800 printf(" target = %d %s\n", stmt->row->rowno, stmt->row->refname);
807 dump_close(PLpgSQL_stmt_close *stmt)
810 printf("CLOSE curvar=%d\n", stmt->curvar);
814 dump_perform(PLpgSQL_stmt_perform *stmt)
817 printf("PERFORM expr = ");
818 dump_expr(stmt->expr);
823 dump_exit(PLpgSQL_stmt_exit *stmt)
826 printf("%s label='%s'",
827 stmt->is_exit ? "EXIT" : "CONTINUE", stmt->label);
828 if (stmt->cond != NULL)
831 dump_expr(stmt->cond);
837 dump_return(PLpgSQL_stmt_return *stmt)
841 if (stmt->retvarno >= 0)
842 printf("variable %d", stmt->retvarno);
843 else if (stmt->expr != NULL)
844 dump_expr(stmt->expr);
851 dump_return_next(PLpgSQL_stmt_return_next *stmt)
854 printf("RETURN NEXT ");
855 if (stmt->retvarno >= 0)
856 printf("variable %d", stmt->retvarno);
857 else if (stmt->expr != NULL)
858 dump_expr(stmt->expr);
865 dump_raise(PLpgSQL_stmt_raise *stmt)
871 printf("RAISE '%s'\n", stmt->message);
873 foreach(lc, stmt->params)
876 printf(" parameter %d: ", i++);
877 dump_expr((PLpgSQL_expr *) lfirst(lc));
884 dump_execsql(PLpgSQL_stmt_execsql *stmt)
888 dump_expr(stmt->sqlstmt);
893 dump_dynexecute(PLpgSQL_stmt_dynexecute *stmt)
897 dump_expr(stmt->query);
901 if (stmt->rec != NULL)
904 printf(" target = %d %s\n", stmt->rec->recno, stmt->rec->refname);
906 else if (stmt->row != NULL)
909 printf(" target = %d %s\n", stmt->row->rowno, stmt->row->refname);
915 dump_dynfors(PLpgSQL_stmt_dynfors *stmt)
918 printf("FORS %s EXECUTE ", (stmt->rec != NULL) ? stmt->rec->refname : stmt->row->refname);
919 dump_expr(stmt->query);
922 dump_stmts(stmt->body);
925 printf(" ENDFORS\n");
929 dump_getdiag(PLpgSQL_stmt_getdiag *stmt)
934 printf("GET DIAGNOSTICS ");
935 foreach(lc, stmt->diag_items)
937 PLpgSQL_diag_item *diag_item = (PLpgSQL_diag_item *) lfirst(lc);
939 if (lc != list_head(stmt->diag_items))
942 printf("{var %d} = ", diag_item->target);
944 switch (diag_item->kind)
946 case PLPGSQL_GETDIAG_ROW_COUNT:
950 case PLPGSQL_GETDIAG_RESULT_OID:
951 printf("RESULT_OID");
963 dump_expr(PLpgSQL_expr *expr)
967 printf("'%s", expr->query);
968 if (expr->nparams > 0)
971 for (i = 0; i < expr->nparams; i++)
975 printf("$%d=%d", i + 1, expr->params[i]);
983 plpgsql_dumptree(PLpgSQL_function *func)
988 printf("\nExecution tree of successfully compiled PL/pgSQL function %s:\n",
991 printf("\nFunction's data area:\n");
992 for (i = 0; i < func->ndatums; i++)
996 printf(" entry %d: ", i);
999 case PLPGSQL_DTYPE_VAR:
1001 PLpgSQL_var *var = (PLpgSQL_var *) d;
1003 printf("VAR %-16s type %s (typoid %u) atttypmod %d\n",
1004 var->refname, var->datatype->typname,
1005 var->datatype->typoid,
1006 var->datatype->atttypmod);
1008 printf(" CONSTANT\n");
1010 printf(" NOT NULL\n");
1011 if (var->default_val != NULL)
1013 printf(" DEFAULT ");
1014 dump_expr(var->default_val);
1017 if (var->cursor_explicit_expr != NULL)
1019 if (var->cursor_explicit_argrow >= 0)
1020 printf(" CURSOR argument row %d\n", var->cursor_explicit_argrow);
1022 printf(" CURSOR IS ");
1023 dump_expr(var->cursor_explicit_expr);
1028 case PLPGSQL_DTYPE_ROW:
1030 PLpgSQL_row *row = (PLpgSQL_row *) d;
1033 printf("ROW %-16s fields", row->refname);
1034 for (i = 0; i < row->nfields; i++)
1036 if (row->fieldnames[i])
1037 printf(" %s=var %d", row->fieldnames[i],
1043 case PLPGSQL_DTYPE_REC:
1044 printf("REC %s\n", ((PLpgSQL_rec *) d)->refname);
1046 case PLPGSQL_DTYPE_RECFIELD:
1047 printf("RECFIELD %-16s of REC %d\n",
1048 ((PLpgSQL_recfield *) d)->fieldname,
1049 ((PLpgSQL_recfield *) d)->recparentno);
1051 case PLPGSQL_DTYPE_ARRAYELEM:
1052 printf("ARRAYELEM of VAR %d subscript ",
1053 ((PLpgSQL_arrayelem *) d)->arrayparentno);
1054 dump_expr(((PLpgSQL_arrayelem *) d)->subscript);
1057 case PLPGSQL_DTYPE_TRIGARG:
1059 dump_expr(((PLpgSQL_trigarg *) d)->argnum);
1063 printf("??? unknown data type %d\n", d->dtype);
1066 printf("\nFunction's statements:\n");
1069 printf("%3d:", func->action->lineno);
1070 dump_block(func->action);
1071 printf("\nEnd of execution tree of function %s\n\n", func->fn_name);