]> granicus.if.org Git - postgresql/blob - src/pl/plpgsql/src/gram.y
Add PL/pgSQL SQLSTATE and SQLERRM support which sets these values on
[postgresql] / src / pl / plpgsql / src / gram.y
1 %{
2 /**********************************************************************
3  * gram.y                               - Parser for the PL/pgSQL
4  *                                                procedural language
5  *
6  * IDENTIFICATION
7  *        $PostgreSQL: pgsql/src/pl/plpgsql/src/gram.y,v 1.70 2005/05/26 00:16:31 momjian Exp $
8  *
9  *        This software is copyrighted by Jan Wieck - Hamburg.
10  *
11  *        The author hereby grants permission  to  use,  copy,  modify,
12  *        distribute,  and      license this software and its documentation
13  *        for any purpose, provided that existing copyright notices are
14  *        retained      in      all  copies  and  that  this notice is included
15  *        verbatim in any distributions. No written agreement, license,
16  *        or  royalty  fee      is required for any of the authorized uses.
17  *        Modifications to this software may be  copyrighted  by  their
18  *        author  and  need  not  follow  the licensing terms described
19  *        here, provided that the new terms are  clearly  indicated  on
20  *        the first page of each file where they apply.
21  *
22  *        IN NO EVENT SHALL THE AUTHOR OR DISTRIBUTORS BE LIABLE TO ANY
23  *        PARTY  FOR  DIRECT,   INDIRECT,       SPECIAL,   INCIDENTAL,   OR
24  *        CONSEQUENTIAL   DAMAGES  ARISING      OUT  OF  THE  USE  OF  THIS
25  *        SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN
26  *        IF  THE  AUTHOR  HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH
27  *        DAMAGE.
28  *
29  *        THE  AUTHOR  AND      DISTRIBUTORS  SPECIFICALLY       DISCLAIM       ANY
30  *        WARRANTIES,  INCLUDING,  BUT  NOT  LIMITED  TO,  THE  IMPLIED
31  *        WARRANTIES  OF  MERCHANTABILITY,      FITNESS  FOR  A  PARTICULAR
32  *        PURPOSE,      AND NON-INFRINGEMENT.  THIS SOFTWARE IS PROVIDED ON
33  *        AN "AS IS" BASIS, AND THE AUTHOR      AND  DISTRIBUTORS  HAVE  NO
34  *        OBLIGATION   TO       PROVIDE   MAINTENANCE,   SUPPORT,  UPDATES,
35  *        ENHANCEMENTS, OR MODIFICATIONS.
36  *
37  **********************************************************************/
38
39 #include "plpgsql.h"
40
41 #include "parser/parser.h"
42
43 static PLpgSQL_expr             *read_sql_construct(int until,
44                                                                                         int until2,
45                                                                                         const char *expected,
46                                                                                         const char *sqlstart,
47                                                                                         bool isexpression,
48                                                                                         bool valid_sql,
49                                                                                         int *endtoken);
50 static  PLpgSQL_expr    *read_sql_stmt(const char *sqlstart);
51 static  PLpgSQL_type    *read_datatype(int tok);
52 static  PLpgSQL_stmt    *make_select_stmt(void);
53 static  PLpgSQL_stmt    *make_fetch_stmt(void);
54 static  void                     check_assignable(PLpgSQL_datum *datum);
55 static  PLpgSQL_row             *read_into_scalar_list(const char *initial_name,
56                                                                                            PLpgSQL_datum *initial_datum);
57 static  void                     check_sql_expr(const char *stmt);
58 static  void                     plpgsql_sql_error_callback(void *arg);
59
60 %}
61
62 %union {
63                 int32                                   ival;
64                 char                                    *str;
65                 struct
66                 {
67                         char *name;
68                         int  lineno;
69                 }                                               varname;
70                 struct
71                 {    
72                         char *name;
73                         int  lineno;
74                         PLpgSQL_rec     *rec;
75                         PLpgSQL_row     *row;
76                 }                                               forvariable;
77                 struct
78                 {
79                         char *label;
80                         int  n_initvars;
81                         int  *initvarnos;
82                 }                                               declhdr;
83                 struct 
84                 {
85                         int sqlstate_varno;
86                         int sqlerrm_varno;
87                 }                                               fict_vars;
88                 List                                    *list;
89                 PLpgSQL_type                    *dtype;
90                 PLpgSQL_datum                   *scalar;        /* a VAR, RECFIELD, or TRIGARG */
91                 PLpgSQL_variable                *variable;      /* a VAR, REC, or ROW */
92                 PLpgSQL_var                             *var;
93                 PLpgSQL_row                             *row;
94                 PLpgSQL_rec                             *rec;
95                 PLpgSQL_expr                    *expr;
96                 PLpgSQL_stmt                    *stmt;
97                 PLpgSQL_stmt_block              *program;
98                 PLpgSQL_condition               *condition;
99                 PLpgSQL_exception               *exception;
100                 PLpgSQL_nsitem                  *nsitem;
101                 PLpgSQL_diag_item               *diagitem;
102 }
103
104 %type <fict_vars> fict_vars_sect
105 %type <declhdr> decl_sect
106 %type <varname> decl_varname
107 %type <str>             decl_renname
108 %type <ival>    decl_const decl_notnull
109 %type <expr>    decl_defval decl_cursor_query
110 %type <dtype>   decl_datatype
111 %type <row>             decl_cursor_args
112 %type <list>    decl_cursor_arglist
113 %type <nsitem>  decl_aliasitem
114 %type <str>             decl_stmts decl_stmt
115
116 %type <expr>    expr_until_semi expr_until_rightbracket
117 %type <expr>    expr_until_then expr_until_loop
118 %type <expr>    opt_exitcond
119
120 %type <ival>    assign_var cursor_variable
121 %type <var>             cursor_varptr
122 %type <variable>        decl_cursor_arg
123 %type <forvariable>     for_variable
124 %type <stmt>    for_control
125
126 %type <str>             opt_lblname opt_label
127 %type <str>             opt_exitlabel
128 %type <str>             execsql_start
129
130 %type <list>    proc_sect proc_stmts stmt_else loop_body
131 %type <stmt>    proc_stmt pl_block
132 %type <stmt>    stmt_assign stmt_if stmt_loop stmt_while stmt_exit
133 %type <stmt>    stmt_return stmt_return_next stmt_raise stmt_execsql
134 %type <stmt>    stmt_for stmt_select stmt_perform
135 %type <stmt>    stmt_dynexecute stmt_getdiag
136 %type <stmt>    stmt_open stmt_fetch stmt_close stmt_null
137
138 %type <list>    exception_sect proc_exceptions
139 %type <exception>       proc_exception
140 %type <condition>       proc_conditions
141
142 %type <list>    raise_params
143 %type <ival>    raise_level raise_param
144 %type <str>             raise_msg
145
146 %type <list>    getdiag_list
147 %type <diagitem> getdiag_list_item
148 %type <ival>    getdiag_kind getdiag_target
149
150 %type <ival>    lno
151
152                 /*
153                  * Keyword tokens
154                  */
155 %token  K_ALIAS
156 %token  K_ASSIGN
157 %token  K_BEGIN
158 %token  K_CLOSE
159 %token  K_CONSTANT
160 %token  K_CURSOR
161 %token  K_DEBUG
162 %token  K_DECLARE
163 %token  K_DEFAULT
164 %token  K_DIAGNOSTICS
165 %token  K_DOTDOT
166 %token  K_ELSE
167 %token  K_ELSIF
168 %token  K_END
169 %token  K_EXCEPTION
170 %token  K_EXECUTE
171 %token  K_EXIT
172 %token  K_FOR
173 %token  K_FETCH
174 %token  K_FROM
175 %token  K_GET
176 %token  K_IF
177 %token  K_IN
178 %token  K_INFO
179 %token  K_INTO
180 %token  K_IS
181 %token  K_LOG
182 %token  K_LOOP
183 %token  K_NEXT
184 %token  K_NOT
185 %token  K_NOTICE
186 %token  K_NULL
187 %token  K_OPEN
188 %token  K_OR
189 %token  K_PERFORM
190 %token  K_ROW_COUNT
191 %token  K_RAISE
192 %token  K_RENAME
193 %token  K_RESULT_OID
194 %token  K_RETURN
195 %token  K_RETURN_NEXT
196 %token  K_REVERSE
197 %token  K_SELECT
198 %token  K_THEN
199 %token  K_TO
200 %token  K_TYPE
201 %token  K_WARNING
202 %token  K_WHEN
203 %token  K_WHILE
204
205                 /*
206                  * Other tokens
207                  */
208 %token  T_FUNCTION
209 %token  T_TRIGGER
210 %token  T_STRING
211 %token  T_NUMBER
212 %token  T_SCALAR                                /* a VAR, RECFIELD, or TRIGARG */
213 %token  T_ROW
214 %token  T_RECORD
215 %token  T_DTYPE
216 %token  T_LABEL
217 %token  T_WORD
218 %token  T_ERROR
219
220 %token  O_OPTION
221 %token  O_DUMP
222
223 %%
224
225 pl_function             : T_FUNCTION comp_optsect pl_block opt_semi
226                                         {
227                                                 yylval.program = (PLpgSQL_stmt_block *)$3;
228                                         }
229                                 | T_TRIGGER comp_optsect pl_block opt_semi
230                                         {
231                                                 yylval.program = (PLpgSQL_stmt_block *)$3;
232                                         }
233                                 ;
234
235 comp_optsect    :
236                                 | comp_options
237                                 ;
238
239 comp_options    : comp_options comp_option
240                                 | comp_option
241                                 ;
242
243 comp_option             : O_OPTION O_DUMP
244                                         {
245                                                 plpgsql_DumpExecTree = true;
246                                         }
247                                 ;
248
249 opt_semi                :
250                                 | ';'
251                                 ;
252
253 pl_block                : decl_sect fict_vars_sect K_BEGIN lno proc_sect exception_sect K_END
254                                         {
255                                                 PLpgSQL_stmt_block *new;
256
257                                                 new = palloc0(sizeof(PLpgSQL_stmt_block));
258
259                                                 new->cmd_type   = PLPGSQL_STMT_BLOCK;
260                                                 new->lineno             = $4;
261                                                 new->label              = $1.label;
262                                                 new->n_initvars = $1.n_initvars;
263                                                 new->initvarnos = $1.initvarnos;
264                                                 new->body               = $5;
265                                                 new->exceptions = $6;
266
267                                                 new->sqlstate_varno = $2.sqlstate_varno;
268                                                 new->sqlerrm_varno = $2.sqlerrm_varno;
269
270                                                 plpgsql_ns_pop();
271
272                                                 $$ = (PLpgSQL_stmt *)new;
273                                         }
274                                 ;
275
276 fict_vars_sect  :
277                                         {
278                                                 PLpgSQL_variable        *var;
279
280                                                 plpgsql_ns_setlocal(false);
281                                                 var = plpgsql_build_variable("sqlstate", 0,
282                                                                                  plpgsql_build_datatype(TEXTOID, -1), true);  
283                                                 $$.sqlstate_varno = var->dno;
284                                                 var = plpgsql_build_variable("sqlerrm", 0,
285                                                                                  plpgsql_build_datatype(TEXTOID, -1), true);  
286                                                 $$.sqlerrm_varno = var->dno;
287                                                 plpgsql_add_initdatums(NULL);
288                                         };
289
290 decl_sect               : opt_label
291                                         {
292                                                 plpgsql_ns_setlocal(false);
293                                                 $$.label          = $1;
294                                                 $$.n_initvars = 0;
295                                                 $$.initvarnos = NULL;
296                                                 plpgsql_add_initdatums(NULL);
297                                         }
298                                 | opt_label decl_start
299                                         {
300                                                 plpgsql_ns_setlocal(false);
301                                                 $$.label          = $1;
302                                                 $$.n_initvars = 0;
303                                                 $$.initvarnos = NULL;
304                                                 plpgsql_add_initdatums(NULL);
305                                         }
306                                 | opt_label decl_start decl_stmts
307                                         {
308                                                 plpgsql_ns_setlocal(false);
309                                                 if ($3 != NULL)
310                                                         $$.label = $3;
311                                                 else
312                                                         $$.label = $1;
313                                                 $$.n_initvars = plpgsql_add_initdatums(&($$.initvarnos));
314                                         }
315                                 ;
316
317 decl_start              : K_DECLARE
318                                         {
319                                                 plpgsql_ns_setlocal(true);
320                                         }
321                                 ;
322
323 decl_stmts              : decl_stmts decl_stmt
324                                         {       $$ = $2;        }
325                                 | decl_stmt
326                                         {       $$ = $1;        }
327                                 ;
328
329 decl_stmt               : '<' '<' opt_lblname '>' '>'
330                                         {       $$ = $3;        }
331                                 | K_DECLARE
332                                         {       $$ = NULL;      }
333                                 | decl_statement
334                                         {       $$ = NULL;      }
335                                 ;
336
337 decl_statement  : decl_varname decl_const decl_datatype decl_notnull decl_defval
338                                         {
339                                                 PLpgSQL_variable        *var;
340
341                                                 var = plpgsql_build_variable($1.name, $1.lineno,
342                                                                                                          $3, true);
343                                                 if ($2)
344                                                 {
345                                                         if (var->dtype == PLPGSQL_DTYPE_VAR)
346                                                                 ((PLpgSQL_var *) var)->isconst = $2;
347                                                         else
348                                                                 ereport(ERROR,
349                                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
350                                                                                  errmsg("row or record variable cannot be CONSTANT")));
351                                                 }
352                                                 if ($4)
353                                                 {
354                                                         if (var->dtype == PLPGSQL_DTYPE_VAR)
355                                                                 ((PLpgSQL_var *) var)->notnull = $4;
356                                                         else
357                                                                 ereport(ERROR,
358                                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
359                                                                                  errmsg("row or record variable cannot be NOT NULL")));
360                                                 }
361                                                 if ($5 != NULL)
362                                                 {
363                                                         if (var->dtype == PLPGSQL_DTYPE_VAR)
364                                                                 ((PLpgSQL_var *) var)->default_val = $5;
365                                                         else
366                                                                 ereport(ERROR,
367                                                                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
368                                                                                  errmsg("default value for row or record variable is not supported")));
369                                                 }
370                                         }
371                                 | decl_varname K_ALIAS K_FOR decl_aliasitem ';'
372                                         {
373                                                 plpgsql_ns_additem($4->itemtype,
374                                                                                    $4->itemno, $1.name);
375                                         }
376                                 | K_RENAME decl_renname K_TO decl_renname ';'
377                                         {
378                                                 plpgsql_ns_rename($2, $4);
379                                         }
380                                 | decl_varname K_CURSOR
381                                         { plpgsql_ns_push(NULL); }
382                                   decl_cursor_args decl_is_from decl_cursor_query
383                                         {
384                                                 PLpgSQL_var *new;
385                                                 PLpgSQL_expr *curname_def;
386                                                 char            buf[1024];
387                                                 char            *cp1;
388                                                 char            *cp2;
389
390                                                 /* pop local namespace for cursor args */
391                                                 plpgsql_ns_pop();
392
393                                                 new = (PLpgSQL_var *)
394                                                         plpgsql_build_variable($1.name, $1.lineno,
395                                                                                                    plpgsql_build_datatype(REFCURSOROID,
396                                                                                                                                                   -1),
397                                                                                                    true);
398
399                                                 curname_def = palloc0(sizeof(PLpgSQL_expr));
400
401                                                 curname_def->dtype = PLPGSQL_DTYPE_EXPR;
402                                                 strcpy(buf, "SELECT '");
403                                                 cp1 = new->refname;
404                                                 cp2 = buf + strlen(buf);
405                                                 while (*cp1 != '\0')
406                                                 {
407                                                         if (*cp1 == '\\' || *cp1 == '\'')
408                                                                 *cp2++ = '\\';
409                                                         *cp2++ = *cp1++;
410                                                 }
411                                                 strcpy(cp2, "'::refcursor");
412                                                 curname_def->query = pstrdup(buf);
413                                                 new->default_val = curname_def;
414
415                                                 new->cursor_explicit_expr = $6;
416                                                 if ($4 == NULL)
417                                                         new->cursor_explicit_argrow = -1;
418                                                 else
419                                                         new->cursor_explicit_argrow = $4->rowno;
420                                         }
421                                 ;
422
423 decl_cursor_query :
424                                         {
425                                                 PLpgSQL_expr *query;
426
427                                                 plpgsql_ns_setlocal(false);
428                                                 query = read_sql_stmt("");
429                                                 plpgsql_ns_setlocal(true);
430                                                 
431                                                 $$ = query;
432                                         }
433                                 ;
434
435 decl_cursor_args :
436                                         {
437                                                 $$ = NULL;
438                                         }
439                                 | '(' decl_cursor_arglist ')'
440                                         {
441                                                 PLpgSQL_row *new;
442                                                 int i;
443                                                 ListCell *l;
444
445                                                 new = palloc0(sizeof(PLpgSQL_row));
446                                                 new->dtype = PLPGSQL_DTYPE_ROW;
447                                                 new->lineno = plpgsql_scanner_lineno();
448                                                 new->rowtupdesc = NULL;
449                                                 new->nfields = list_length($2);
450                                                 new->fieldnames = palloc(new->nfields * sizeof(char *));
451                                                 new->varnos = palloc(new->nfields * sizeof(int));
452
453                                                 i = 0;
454                                                 foreach (l, $2)
455                                                 {
456                                                         PLpgSQL_variable *arg = (PLpgSQL_variable *) lfirst(l);
457                                                         new->fieldnames[i] = arg->refname;
458                                                         new->varnos[i] = arg->dno;
459                                                         i++;
460                                                 }
461                                                 list_free($2);
462
463                                                 plpgsql_adddatum((PLpgSQL_datum *) new);
464                                                 $$ = new;
465                                         }
466                                 ;
467
468 decl_cursor_arglist : decl_cursor_arglist decl_cursor_arg
469                                         {
470                                                 $$ = lappend($1, $2);
471                                         }
472                                 | decl_cursor_arg
473                                         {
474                                                 $$ = list_make1($1);
475                                         }
476                                 ;
477
478 decl_cursor_arg : decl_varname decl_datatype
479                                         {
480                                                 $$ = plpgsql_build_variable($1.name, $1.lineno,
481                                                                                                         $2, true);
482                                         }
483                                 ;
484
485 decl_is_from    :       K_IS |          /* Oracle */
486                                         K_FOR;          /* ANSI */
487
488 decl_aliasitem  : T_WORD
489                                         {
490                                                 char    *name;
491                                                 PLpgSQL_nsitem *nsi;
492
493                                                 plpgsql_convert_ident(yytext, &name, 1);
494                                                 if (name[0] != '$')
495                                                         yyerror("only positional parameters may be aliased");
496
497                                                 plpgsql_ns_setlocal(false);
498                                                 nsi = plpgsql_ns_lookup(name, NULL);
499                                                 if (nsi == NULL)
500                                                 {
501                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
502                                                         ereport(ERROR,
503                                                                         (errcode(ERRCODE_UNDEFINED_PARAMETER),
504                                                                          errmsg("function has no parameter \"%s\"",
505                                                                                         name)));
506                                                 }
507
508                                                 plpgsql_ns_setlocal(true);
509
510                                                 pfree(name);
511
512                                                 $$ = nsi;
513                                         }
514                                 ;
515
516 decl_varname    : T_WORD
517                                         {
518                                                 char    *name;
519
520                                                 plpgsql_convert_ident(yytext, &name, 1);
521                                                 $$.name = name;
522                                                 $$.lineno  = plpgsql_scanner_lineno();
523                                         }
524                                 ;
525
526 decl_renname    : T_WORD
527                                         {
528                                                 char    *name;
529
530                                                 plpgsql_convert_ident(yytext, &name, 1);
531                                                 /* the result must be palloc'd, see plpgsql_ns_rename */
532                                                 $$ = name;
533                                         }
534                                 ;
535
536 decl_const              :
537                                         { $$ = 0; }
538                                 | K_CONSTANT
539                                         { $$ = 1; }
540                                 ;
541
542 decl_datatype   :
543                                         {
544                                                 /*
545                                                  * If there's a lookahead token, read_datatype
546                                                  * should consume it.
547                                                  */
548                                                 $$ = read_datatype(yychar);
549                                                 yyclearin;
550                                         }
551                                 ;
552
553 decl_notnull    :
554                                         { $$ = 0; }
555                                 | K_NOT K_NULL
556                                         { $$ = 1; }
557                                 ;
558
559 decl_defval             : ';'
560                                         { $$ = NULL; }
561                                 | decl_defkey
562                                         {
563                                                 plpgsql_ns_setlocal(false);
564                                                 $$ = plpgsql_read_expression(';', ";");
565                                                 plpgsql_ns_setlocal(true);
566                                         }
567                                 ;
568
569 decl_defkey             : K_ASSIGN
570                                 | K_DEFAULT
571                                 ;
572
573 proc_sect               :
574                                         {
575                                                 $$ = NIL;
576                                         }
577                                 | proc_stmts
578                                         { $$ = $1; }
579                                 ;
580
581 proc_stmts              : proc_stmts proc_stmt
582                                                 {
583                                                         if ($2 == NULL)
584                                                                 $$ = $1;
585                                                         else
586                                                                 $$ = lappend($1, $2);
587                                                 }
588                                 | proc_stmt
589                                                 {
590                                                         if ($1 == NULL)
591                                                                 $$ = NULL;
592                                                         else
593                                                                 $$ = list_make1($1);
594                                                 }
595                                 ;
596
597 proc_stmt               : pl_block ';'
598                                                 { $$ = $1; }
599                                 | stmt_assign
600                                                 { $$ = $1; }
601                                 | stmt_if
602                                                 { $$ = $1; }
603                                 | stmt_loop
604                                                 { $$ = $1; }
605                                 | stmt_while
606                                                 { $$ = $1; }
607                                 | stmt_for
608                                                 { $$ = $1; }
609                                 | stmt_select
610                                                 { $$ = $1; }
611                                 | stmt_exit
612                                                 { $$ = $1; }
613                                 | stmt_return
614                                                 { $$ = $1; }
615                                 | stmt_return_next
616                                                 { $$ = $1; }
617                                 | stmt_raise
618                                                 { $$ = $1; }
619                                 | stmt_execsql
620                                                 { $$ = $1; }
621                                 | stmt_dynexecute
622                                                 { $$ = $1; }
623                                 | stmt_perform
624                                                 { $$ = $1; }
625                                 | stmt_getdiag
626                                                 { $$ = $1; }
627                                 | stmt_open
628                                                 { $$ = $1; }
629                                 | stmt_fetch
630                                                 { $$ = $1; }
631                                 | stmt_close
632                                                 { $$ = $1; }
633                                 | stmt_null
634                                                 { $$ = $1; }
635                                 ;
636
637 stmt_perform    : K_PERFORM lno expr_until_semi
638                                         {
639                                                 PLpgSQL_stmt_perform *new;
640
641                                                 new = palloc0(sizeof(PLpgSQL_stmt_perform));
642                                                 new->cmd_type = PLPGSQL_STMT_PERFORM;
643                                                 new->lineno   = $2;
644                                                 new->expr  = $3;
645
646                                                 $$ = (PLpgSQL_stmt *)new;
647                                         }
648                                 ;
649
650 stmt_assign             : assign_var lno K_ASSIGN expr_until_semi
651                                         {
652                                                 PLpgSQL_stmt_assign *new;
653
654                                                 new = palloc0(sizeof(PLpgSQL_stmt_assign));
655                                                 new->cmd_type = PLPGSQL_STMT_ASSIGN;
656                                                 new->lineno   = $2;
657                                                 new->varno = $1;
658                                                 new->expr  = $4;
659
660                                                 $$ = (PLpgSQL_stmt *)new;
661                                         }
662                                 ;
663
664 stmt_getdiag    : K_GET K_DIAGNOSTICS lno getdiag_list ';'
665                                         {
666                                                 PLpgSQL_stmt_getdiag     *new;
667
668                                                 new = palloc0(sizeof(PLpgSQL_stmt_getdiag));
669                                                 new->cmd_type = PLPGSQL_STMT_GETDIAG;
670                                                 new->lineno   = $3;
671                                                 new->diag_items  = $4;
672
673                                                 $$ = (PLpgSQL_stmt *)new;
674                                         }
675                                 ;
676
677 getdiag_list : getdiag_list ',' getdiag_list_item
678                                         {
679                                                 $$ = lappend($1, $3);
680                                         }
681                                 | getdiag_list_item
682                                         {
683                                                 $$ = list_make1($1);
684                                         }
685                                 ;
686
687 getdiag_list_item : getdiag_target K_ASSIGN getdiag_kind
688                                         {
689                                                 PLpgSQL_diag_item *new;
690
691                                                 new = palloc(sizeof(PLpgSQL_diag_item));
692                                                 new->target = $1;
693                                                 new->kind = $3;
694
695                                                 $$ = new;
696                                         }
697                                 ;
698
699 getdiag_kind : K_ROW_COUNT
700                                         {
701                                                 $$ = PLPGSQL_GETDIAG_ROW_COUNT;
702                                         }
703                                 | K_RESULT_OID
704                                         {
705                                                 $$ = PLPGSQL_GETDIAG_RESULT_OID;
706                                         }
707                                 ;
708
709 getdiag_target  : T_SCALAR
710                                         {
711                                                 check_assignable(yylval.scalar);
712                                                 $$ = yylval.scalar->dno;
713                                         }
714                                 ;
715
716
717 assign_var              : T_SCALAR
718                                         {
719                                                 check_assignable(yylval.scalar);
720                                                 $$ = yylval.scalar->dno;
721                                         }
722                                 | T_ROW
723                                         {
724                                                 check_assignable((PLpgSQL_datum *) yylval.row);
725                                                 $$ = yylval.row->rowno;
726                                         }
727                                 | T_RECORD
728                                         {
729                                                 check_assignable((PLpgSQL_datum *) yylval.rec);
730                                                 $$ = yylval.rec->recno;
731                                         }
732                                 | assign_var '[' expr_until_rightbracket
733                                         {
734                                                 PLpgSQL_arrayelem       *new;
735
736                                                 new = palloc0(sizeof(PLpgSQL_arrayelem));
737                                                 new->dtype              = PLPGSQL_DTYPE_ARRAYELEM;
738                                                 new->subscript  = $3;
739                                                 new->arrayparentno = $1;
740
741                                                 plpgsql_adddatum((PLpgSQL_datum *)new);
742
743                                                 $$ = new->dno;
744                                         }
745                                 ;
746
747 stmt_if                 : K_IF lno expr_until_then proc_sect stmt_else K_END K_IF ';'
748                                         {
749                                                 PLpgSQL_stmt_if *new;
750
751                                                 new = palloc0(sizeof(PLpgSQL_stmt_if));
752                                                 new->cmd_type   = PLPGSQL_STMT_IF;
753                                                 new->lineno             = $2;
754                                                 new->cond               = $3;
755                                                 new->true_body  = $4;
756                                                 new->false_body = $5;
757
758                                                 $$ = (PLpgSQL_stmt *)new;
759                                         }
760                                 ;
761
762 stmt_else               :
763                                         {
764                                                 $$ = NIL;
765                                         }
766                                 | K_ELSIF lno expr_until_then proc_sect stmt_else
767                                         {
768                                                 /*
769                                                  * Translate the structure:        into:
770                                                  *
771                                                  * IF c1 THEN                              IF c1 THEN
772                                                  *       ...                                               ...
773                                                  * ELSIF c2 THEN                           ELSE
774                                                  *                                                                 IF c2 THEN
775                                                  *       ...                                                       ...
776                                                  * ELSE                                                    ELSE
777                                                  *       ...                                                       ...
778                                                  * END IF                                                  END IF                        
779                                                  *                                                         END IF
780                                                  */
781                                                 PLpgSQL_stmt_if *new_if;
782
783                                                 /* first create a new if-statement */
784                                                 new_if = palloc0(sizeof(PLpgSQL_stmt_if));
785                                                 new_if->cmd_type        = PLPGSQL_STMT_IF;
786                                                 new_if->lineno          = $2;
787                                                 new_if->cond            = $3;
788                                                 new_if->true_body       = $4;
789                                                 new_if->false_body      = $5;
790
791                                                 /* wrap the if-statement in a "container" list */
792                                                 $$ = list_make1(new_if);
793                                         }
794
795                                 | K_ELSE proc_sect
796                                         {
797                                                 $$ = $2;                                
798                                         }
799                                 ;
800
801 stmt_loop               : opt_label K_LOOP lno loop_body
802                                         {
803                                                 PLpgSQL_stmt_loop *new;
804
805                                                 new = palloc0(sizeof(PLpgSQL_stmt_loop));
806                                                 new->cmd_type = PLPGSQL_STMT_LOOP;
807                                                 new->lineno   = $3;
808                                                 new->label        = $1;
809                                                 new->body         = $4;
810
811                                                 plpgsql_ns_pop();
812
813                                                 $$ = (PLpgSQL_stmt *)new;
814                                         }
815                                 ;
816
817 stmt_while              : opt_label K_WHILE lno expr_until_loop loop_body
818                                         {
819                                                 PLpgSQL_stmt_while *new;
820
821                                                 new = palloc0(sizeof(PLpgSQL_stmt_while));
822                                                 new->cmd_type = PLPGSQL_STMT_WHILE;
823                                                 new->lineno   = $3;
824                                                 new->label        = $1;
825                                                 new->cond         = $4;
826                                                 new->body         = $5;
827
828                                                 plpgsql_ns_pop();
829
830                                                 $$ = (PLpgSQL_stmt *)new;
831                                         }
832                                 ;
833
834 stmt_for                : opt_label K_FOR for_control loop_body
835                                         {
836                                                 /* This runs after we've scanned the loop body */
837                                                 if ($3->cmd_type == PLPGSQL_STMT_FORI)
838                                                 {
839                                                         PLpgSQL_stmt_fori               *new;
840
841                                                         new = (PLpgSQL_stmt_fori *) $3;
842                                                         new->label        = $1;
843                                                         new->body         = $4;
844                                                         $$ = (PLpgSQL_stmt *) new;
845                                                 }
846                                                 else if ($3->cmd_type == PLPGSQL_STMT_FORS)
847                                                 {
848                                                         PLpgSQL_stmt_fors               *new;
849
850                                                         new = (PLpgSQL_stmt_fors *) $3;
851                                                         new->label        = $1;
852                                                         new->body         = $4;
853                                                         $$ = (PLpgSQL_stmt *) new;
854                                                 }
855                                                 else
856                                                 {
857                                                         PLpgSQL_stmt_dynfors    *new;
858
859                                                         Assert($3->cmd_type == PLPGSQL_STMT_DYNFORS);
860                                                         new = (PLpgSQL_stmt_dynfors *) $3;
861                                                         new->label        = $1;
862                                                         new->body         = $4;
863                                                         $$ = (PLpgSQL_stmt *) new;
864                                                 }
865
866                                                 /* close namespace started in opt_label */
867                                                 plpgsql_ns_pop();
868                                         }
869                                 ;
870
871 for_control             :
872                                 lno for_variable K_IN
873                                         {
874                                                 int                     tok = yylex();
875
876                                                 /* Simple case: EXECUTE is a dynamic FOR loop */
877                                                 if (tok == K_EXECUTE)
878                                                 {
879                                                         PLpgSQL_stmt_dynfors    *new;
880                                                         PLpgSQL_expr                    *expr;
881
882                                                         expr = plpgsql_read_expression(K_LOOP, "LOOP");
883
884                                                         new = palloc0(sizeof(PLpgSQL_stmt_dynfors));
885                                                         new->cmd_type = PLPGSQL_STMT_DYNFORS;
886                                                         new->lineno   = $1;
887                                                         if ($2.rec)
888                                                                 new->rec = $2.rec;
889                                                         else if ($2.row)
890                                                                 new->row = $2.row;
891                                                         else
892                                                         {
893                                                                 plpgsql_error_lineno = $1;
894                                                                 yyerror("loop variable of loop over rows must be a record or row variable");
895                                                         }
896                                                         new->query = expr;
897
898                                                         $$ = (PLpgSQL_stmt *) new;
899                                                 }
900                                                 else
901                                                 {
902                                                         PLpgSQL_expr    *expr1;
903                                                         bool                     reverse = false;
904
905                                                         /*
906                                                          * We have to distinguish between two
907                                                          * alternatives: FOR var IN a .. b and FOR
908                                                          * var IN query. Unfortunately this is
909                                                          * tricky, since the query in the second
910                                                          * form needn't start with a SELECT
911                                                          * keyword.  We use the ugly hack of
912                                                          * looking for two periods after the first
913                                                          * token. We also check for the REVERSE
914                                                          * keyword, which means it must be an
915                                                          * integer loop.
916                                                          */
917                                                         if (tok == K_REVERSE)
918                                                                 reverse = true;
919                                                         else
920                                                                 plpgsql_push_back_token(tok);
921
922                                                         /*
923                                                          * Read tokens until we see either a ".."
924                                                          * or a LOOP. The text we read may not
925                                                          * necessarily be a well-formed SQL
926                                                          * statement, so we need to invoke
927                                                          * read_sql_construct directly.
928                                                          */
929                                                         expr1 = read_sql_construct(K_DOTDOT,
930                                                                                                            K_LOOP,
931                                                                                                            "LOOP",
932                                                                                                            "SELECT ",
933                                                                                                            true,
934                                                                                                            false,
935                                                                                                            &tok);
936
937                                                         if (tok == K_DOTDOT)
938                                                         {
939                                                                 /* Saw "..", so it must be an integer loop */
940                                                                 PLpgSQL_expr            *expr2;
941                                                                 PLpgSQL_var                     *fvar;
942                                                                 PLpgSQL_stmt_fori       *new;
943
944                                                                 /* First expression is well-formed */
945                                                                 check_sql_expr(expr1->query);
946
947                                                                 expr2 = plpgsql_read_expression(K_LOOP, "LOOP");
948
949                                                                 fvar = (PLpgSQL_var *)
950                                                                         plpgsql_build_variable($2.name,
951                                                                                                                    $2.lineno,
952                                                                                                                    plpgsql_build_datatype(INT4OID,
953                                                                                                                                                                   -1),
954                                                                                                                    true);
955
956                                                                 /* put the for-variable into the local block */
957                                                                 plpgsql_add_initdatums(NULL);
958
959                                                                 new = palloc0(sizeof(PLpgSQL_stmt_fori));
960                                                                 new->cmd_type = PLPGSQL_STMT_FORI;
961                                                                 new->lineno   = $1;
962                                                                 new->var          = fvar;
963                                                                 new->reverse  = reverse;
964                                                                 new->lower        = expr1;
965                                                                 new->upper        = expr2;
966
967                                                                 $$ = (PLpgSQL_stmt *) new;
968                                                         }
969                                                         else
970                                                         {
971                                                                 /*
972                                                                  * No "..", so it must be a query loop. We've prefixed an
973                                                                  * extra SELECT to the query text, so we need to remove that
974                                                                  * before performing syntax checking.
975                                                                  */
976                                                                 char                            *tmp_query;
977                                                                 PLpgSQL_stmt_fors       *new;
978
979                                                                 if (reverse)
980                                                                         yyerror("cannot specify REVERSE in query FOR loop");
981
982                                                                 Assert(strncmp(expr1->query, "SELECT ", 7) == 0);
983                                                                 tmp_query = pstrdup(expr1->query + 7);
984                                                                 pfree(expr1->query);
985                                                                 expr1->query = tmp_query;
986
987                                                                 check_sql_expr(expr1->query);
988
989                                                                 new = palloc0(sizeof(PLpgSQL_stmt_fors));
990                                                                 new->cmd_type = PLPGSQL_STMT_FORS;
991                                                                 new->lineno   = $1;
992                                                                 if ($2.rec)
993                                                                         new->rec = $2.rec;
994                                                                 else if ($2.row)
995                                                                         new->row = $2.row;
996                                                                 else
997                                                                 {
998                                                                         plpgsql_error_lineno = $1;
999                                                                         yyerror("loop variable of loop over rows must be record or row variable");
1000                                                                 }
1001
1002                                                                 new->query = expr1;
1003                                                                 $$ = (PLpgSQL_stmt *) new;
1004                                                         }
1005                                                 }
1006                                         }
1007                                 ;
1008
1009 for_variable    : T_SCALAR
1010                                         {
1011                                                 char            *name;
1012
1013                                                 plpgsql_convert_ident(yytext, &name, 1);
1014                                                 $$.name = name;
1015                                                 $$.lineno  = plpgsql_scanner_lineno();
1016                                                 $$.rec = NULL;
1017                                                 $$.row = NULL;
1018                                         }
1019                                 | T_WORD
1020                                         {
1021                                                 char            *name;
1022
1023                                                 plpgsql_convert_ident(yytext, &name, 1);
1024                                                 $$.name = name;
1025                                                 $$.lineno  = plpgsql_scanner_lineno();
1026                                                 $$.rec = NULL;
1027                                                 $$.row = NULL;
1028                                         }
1029                                 | T_RECORD
1030                                         {
1031                                                 char            *name;
1032
1033                                                 plpgsql_convert_ident(yytext, &name, 1);
1034                                                 $$.name = name;
1035                                                 $$.lineno  = plpgsql_scanner_lineno();
1036                                                 $$.rec = yylval.rec;
1037                                                 $$.row = NULL;
1038                                         }
1039                                 | T_ROW
1040                                         {
1041                                                 char            *name;
1042
1043                                                 plpgsql_convert_ident(yytext, &name, 1);
1044                                                 $$.name = name;
1045                                                 $$.lineno  = plpgsql_scanner_lineno();
1046                                                 $$.row = yylval.row;
1047                                                 $$.rec = NULL;
1048                                         }
1049                                 ;
1050
1051 stmt_select             : K_SELECT lno
1052                                         {
1053                                                 $$ = make_select_stmt();
1054                                                 $$->lineno = $2;
1055                                         }
1056                                 ;
1057
1058 stmt_exit               : K_EXIT lno opt_exitlabel opt_exitcond
1059                                         {
1060                                                 PLpgSQL_stmt_exit *new;
1061
1062                                                 new = palloc0(sizeof(PLpgSQL_stmt_exit));
1063                                                 new->cmd_type = PLPGSQL_STMT_EXIT;
1064                                                 new->lineno   = $2;
1065                                                 new->label        = $3;
1066                                                 new->cond         = $4;
1067
1068                                                 $$ = (PLpgSQL_stmt *)new;
1069                                         }
1070                                 ;
1071
1072 stmt_return             : K_RETURN lno
1073                                         {
1074                                                 PLpgSQL_stmt_return *new;
1075
1076                                                 new = palloc0(sizeof(PLpgSQL_stmt_return));
1077                                                 new->cmd_type = PLPGSQL_STMT_RETURN;
1078                                                 new->lineno   = $2;
1079                                                 new->expr = NULL;
1080                                                 new->retvarno   = -1;
1081
1082                                                 if (plpgsql_curr_compile->fn_retset)
1083                                                 {
1084                                                         if (yylex() != ';')
1085                                                                 yyerror("RETURN cannot have a parameter in function returning set; use RETURN NEXT");
1086                                                 }
1087                                                 else if (plpgsql_curr_compile->out_param_varno >= 0)
1088                                                 {
1089                                                         if (yylex() != ';')
1090                                                                 yyerror("RETURN cannot have a parameter in function with OUT parameters");
1091                                                         new->retvarno = plpgsql_curr_compile->out_param_varno;
1092                                                 }
1093                                                 else if (plpgsql_curr_compile->fn_rettype == VOIDOID)
1094                                                 {
1095                                                         if (yylex() != ';')
1096                                                                 yyerror("RETURN cannot have a parameter in function returning void");
1097                                                 }
1098                                                 else if (plpgsql_curr_compile->fn_retistuple)
1099                                                 {
1100                                                         switch (yylex())
1101                                                         {
1102                                                                 case K_NULL:
1103                                                                         /* we allow this to support RETURN NULL in triggers */
1104                                                                         break;
1105
1106                                                                 case T_ROW:
1107                                                                         new->retvarno = yylval.row->rowno;
1108                                                                         break;
1109
1110                                                                 case T_RECORD:
1111                                                                         new->retvarno = yylval.rec->recno;
1112                                                                         break;
1113
1114                                                                 default:
1115                                                                         yyerror("RETURN must specify a record or row variable in function returning tuple");
1116                                                                         break;
1117                                                         }
1118                                                         if (yylex() != ';')
1119                                                                 yyerror("RETURN must specify a record or row variable in function returning tuple");
1120                                                 }
1121                                                 else
1122                                                 {
1123                                                         /*
1124                                                          * Note that a well-formed expression is
1125                                                          * _required_ here; anything else is a
1126                                                          * compile-time error.
1127                                                          */
1128                                                         new->expr = plpgsql_read_expression(';', ";");
1129                                                 }
1130
1131                                                 $$ = (PLpgSQL_stmt *)new;
1132                                         }
1133                                 ;
1134
1135 stmt_return_next: K_RETURN_NEXT lno
1136                                         {
1137                                                 PLpgSQL_stmt_return_next *new;
1138
1139                                                 if (!plpgsql_curr_compile->fn_retset)
1140                                                         yyerror("cannot use RETURN NEXT in a non-SETOF function");
1141
1142                                                 new = palloc0(sizeof(PLpgSQL_stmt_return_next));
1143                                                 new->cmd_type   = PLPGSQL_STMT_RETURN_NEXT;
1144                                                 new->lineno             = $2;
1145                                                 new->expr = NULL;
1146                                                 new->retvarno   = -1;
1147
1148                                                 if (plpgsql_curr_compile->out_param_varno >= 0)
1149                                                 {
1150                                                         if (yylex() != ';')
1151                                                                 yyerror("RETURN NEXT cannot have a parameter in function with OUT parameters");
1152                                                         new->retvarno = plpgsql_curr_compile->out_param_varno;
1153                                                 }
1154                                                 else if (plpgsql_curr_compile->fn_retistuple)
1155                                                 {
1156                                                         switch (yylex())
1157                                                         {
1158                                                                 case T_ROW:
1159                                                                         new->retvarno = yylval.row->rowno;
1160                                                                         break;
1161
1162                                                                 case T_RECORD:
1163                                                                         new->retvarno = yylval.rec->recno;
1164                                                                         break;
1165
1166                                                                 default:
1167                                                                         yyerror("RETURN NEXT must specify a record or row variable in function returning tuple");
1168                                                                         break;
1169                                                         }
1170                                                         if (yylex() != ';')
1171                                                                 yyerror("RETURN NEXT must specify a record or row variable in function returning tuple");
1172                                                 }
1173                                                 else
1174                                                         new->expr = plpgsql_read_expression(';', ";");
1175
1176                                                 $$ = (PLpgSQL_stmt *)new;
1177                                         }
1178                                 ;
1179
1180 stmt_raise              : K_RAISE lno raise_level raise_msg raise_params ';'
1181                                         {
1182                                                 PLpgSQL_stmt_raise              *new;
1183
1184                                                 new = palloc(sizeof(PLpgSQL_stmt_raise));
1185
1186                                                 new->cmd_type   = PLPGSQL_STMT_RAISE;
1187                                                 new->lineno             = $2;
1188                                                 new->elog_level = $3;
1189                                                 new->message    = $4;
1190                                                 new->params             = $5;
1191
1192                                                 $$ = (PLpgSQL_stmt *)new;
1193                                         }
1194                                 | K_RAISE lno raise_level raise_msg ';'
1195                                         {
1196                                                 PLpgSQL_stmt_raise              *new;
1197
1198                                                 new = palloc(sizeof(PLpgSQL_stmt_raise));
1199
1200                                                 new->cmd_type   = PLPGSQL_STMT_RAISE;
1201                                                 new->lineno             = $2;
1202                                                 new->elog_level = $3;
1203                                                 new->message    = $4;
1204                                                 new->params             = NIL;
1205
1206                                                 $$ = (PLpgSQL_stmt *)new;
1207                                         }
1208                                 ;
1209
1210 raise_msg               : T_STRING
1211                                         {
1212                                                 $$ = plpgsql_get_string_value();
1213                                         }
1214                                 ;
1215
1216 raise_level             : K_EXCEPTION
1217                                         {
1218                                                 $$ = ERROR;
1219                                         }
1220                                 | K_WARNING
1221                                         {
1222                                                 $$ = WARNING;
1223                                         }
1224                                 | K_NOTICE
1225                                         {
1226                                                 $$ = NOTICE;
1227                                         }
1228                                 | K_INFO
1229                                         {
1230                                                 $$ = INFO;
1231                                         }
1232                                 | K_LOG
1233                                         {
1234                                                 $$ = LOG;
1235                                         }
1236                                 | K_DEBUG
1237                                         {
1238                                                 $$ = DEBUG1;
1239                                         }
1240                                 ;
1241
1242 raise_params    : raise_params raise_param
1243                                         {
1244                                                 $$ = lappend_int($1, $2);
1245                                         }
1246                                 | raise_param
1247                                         {
1248                                                 $$ = list_make1_int($1);
1249                                         }
1250                                 ;
1251
1252 raise_param             : ',' T_SCALAR
1253                                         {
1254                                                 $$ = yylval.scalar->dno;
1255                                         }
1256                                 ;
1257
1258 loop_body               : proc_sect K_END K_LOOP ';'
1259                                         { $$ = $1; }
1260                                 ;
1261
1262 stmt_execsql    : execsql_start lno
1263                                         {
1264                                                 PLpgSQL_stmt_execsql    *new;
1265
1266                                                 new = palloc(sizeof(PLpgSQL_stmt_execsql));
1267                                                 new->cmd_type = PLPGSQL_STMT_EXECSQL;
1268                                                 new->lineno   = $2;
1269                                                 new->sqlstmt  = read_sql_stmt($1);
1270
1271                                                 $$ = (PLpgSQL_stmt *)new;
1272                                         }
1273                                 ;
1274
1275 stmt_dynexecute : K_EXECUTE lno expr_until_semi
1276                                         {
1277                                                 PLpgSQL_stmt_dynexecute *new;
1278
1279                                                 new = palloc(sizeof(PLpgSQL_stmt_dynexecute));
1280                                                 new->cmd_type = PLPGSQL_STMT_DYNEXECUTE;
1281                                                 new->lineno   = $2;
1282                                                 new->query        = $3;
1283
1284                                                 $$ = (PLpgSQL_stmt *)new;
1285                                         }
1286                                 ;
1287
1288 stmt_open               : K_OPEN lno cursor_varptr
1289                                         {
1290                                                 PLpgSQL_stmt_open *new;
1291                                                 int                               tok;
1292
1293                                                 new = palloc0(sizeof(PLpgSQL_stmt_open));
1294                                                 new->cmd_type = PLPGSQL_STMT_OPEN;
1295                                                 new->lineno = $2;
1296                                                 new->curvar = $3->varno;
1297
1298                                                 if ($3->cursor_explicit_expr == NULL)
1299                                                 {
1300                                                     tok = yylex();
1301                                                         if (tok != K_FOR)
1302                                                         {
1303                                                                 plpgsql_error_lineno = $2;
1304                                                                 ereport(ERROR,
1305                                                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1306                                                                                  errmsg("syntax error at \"%s\"",
1307                                                                                                 yytext),
1308                                                                                  errdetail("Expected FOR to open a reference cursor.")));
1309                                                         }
1310
1311                                                         tok = yylex();
1312                                                         if (tok == K_EXECUTE)
1313                                                         {
1314                                                                 new->dynquery = read_sql_stmt("SELECT ");
1315                                                         }
1316                                                         else
1317                                                         {
1318                                                                 plpgsql_push_back_token(tok);
1319                                                                 new->query = read_sql_stmt("");
1320                                                         }
1321                                                 }
1322                                                 else
1323                                                 {
1324                                                         if ($3->cursor_explicit_argrow >= 0)
1325                                                         {
1326                                                                 char   *cp;
1327
1328                                                                 tok = yylex();
1329                                                                 if (tok != '(')
1330                                                                 {
1331                                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1332                                                                         ereport(ERROR,
1333                                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1334                                                                                          errmsg("cursor \"%s\" has arguments",
1335                                                                                                         $3->refname)));
1336                                                                 }
1337
1338                                                                 /*
1339                                                                  * Push back the '(', else read_sql_stmt
1340                                                                  * will complain about unbalanced parens.
1341                                                                  */
1342                                                                 plpgsql_push_back_token(tok);
1343
1344                                                                 new->argquery = read_sql_stmt("SELECT ");
1345
1346                                                                 /*
1347                                                                  * Now remove the leading and trailing parens,
1348                                                                  * because we want "select 1, 2", not
1349                                                                  * "select (1, 2)".
1350                                                                  */
1351                                                                 cp = new->argquery->query;
1352
1353                                                                 if (strncmp(cp, "SELECT", 6) != 0)
1354                                                                 {
1355                                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1356                                                                         /* internal error */
1357                                                                         elog(ERROR, "expected \"SELECT (\", got \"%s\"",
1358                                                                                  new->argquery->query);
1359                                                                 }
1360                                                                 cp += 6;
1361                                                                 while (*cp == ' ') /* could be more than 1 space here */
1362                                                                         cp++;
1363                                                                 if (*cp != '(')
1364                                                                 {
1365                                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1366                                                                         /* internal error */
1367                                                                         elog(ERROR, "expected \"SELECT (\", got \"%s\"",
1368                                                                                  new->argquery->query);
1369                                                                 }
1370                                                                 *cp = ' ';
1371
1372                                                                 cp += strlen(cp) - 1;
1373
1374                                                                 if (*cp != ')')
1375                                                                         yyerror("expected \")\"");
1376                                                                 *cp = '\0';
1377                                                         }
1378                                                         else
1379                                                         {
1380                                                                 tok = yylex();
1381                                                                 if (tok == '(')
1382                                                                 {
1383                                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1384                                                                         ereport(ERROR,
1385                                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1386                                                                                          errmsg("cursor \"%s\" has no arguments",
1387                                                                                                         $3->refname)));
1388                                                                 }
1389                                                                 
1390                                                                 if (tok != ';')
1391                                                                 {
1392                                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1393                                                                         ereport(ERROR,
1394                                                                                         (errcode(ERRCODE_SYNTAX_ERROR),
1395                                                                                          errmsg("syntax error at \"%s\"",
1396                                                                                                         yytext)));
1397                                                                 }
1398                                                         }
1399                                                 }
1400
1401                                                 $$ = (PLpgSQL_stmt *)new;
1402                                         }
1403                                 ;
1404
1405 stmt_fetch              : K_FETCH lno cursor_variable K_INTO
1406                                         {
1407                                                 PLpgSQL_stmt_fetch *new;
1408
1409                                                 new = (PLpgSQL_stmt_fetch *)make_fetch_stmt();
1410                                                 new->curvar = $3;
1411
1412                                                 $$ = (PLpgSQL_stmt *)new;
1413                                                 $$->lineno = $2;
1414                                         }
1415                                 ;
1416
1417 stmt_close              : K_CLOSE lno cursor_variable ';'
1418                                         {
1419                                                 PLpgSQL_stmt_close *new;
1420
1421                                                 new = palloc(sizeof(PLpgSQL_stmt_close));
1422                                                 new->cmd_type = PLPGSQL_STMT_CLOSE;
1423                                                 new->lineno = $2;
1424                                                 new->curvar = $3;
1425
1426                                                 $$ = (PLpgSQL_stmt *)new;
1427                                         }
1428                                 ;
1429
1430 stmt_null               : K_NULL ';'
1431                                         {
1432                                                 /* We do not bother building a node for NULL */
1433                                                 $$ = NULL;
1434                                         }
1435                                 ;
1436
1437 cursor_varptr   : T_SCALAR
1438                                         {
1439                                                 if (yylval.scalar->dtype != PLPGSQL_DTYPE_VAR)
1440                                                         yyerror("cursor variable must be a simple variable");
1441
1442                                                 if (((PLpgSQL_var *) yylval.scalar)->datatype->typoid != REFCURSOROID)
1443                                                 {
1444                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1445                                                         ereport(ERROR,
1446                                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1447                                                                          errmsg("\"%s\" must be of type cursor or refcursor",
1448                                                                                         ((PLpgSQL_var *) yylval.scalar)->refname)));
1449                                                 }
1450                                                 $$ = (PLpgSQL_var *) yylval.scalar;
1451                                         }
1452                                 ;
1453
1454 cursor_variable : T_SCALAR
1455                                         {
1456                                                 if (yylval.scalar->dtype != PLPGSQL_DTYPE_VAR)
1457                                                         yyerror("cursor variable must be a simple variable");
1458
1459                                                 if (((PLpgSQL_var *) yylval.scalar)->datatype->typoid != REFCURSOROID)
1460                                                 {
1461                                                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1462                                                         ereport(ERROR,
1463                                                                         (errcode(ERRCODE_DATATYPE_MISMATCH),
1464                                                                          errmsg("\"%s\" must be of type refcursor",
1465                                                                                         ((PLpgSQL_var *) yylval.scalar)->refname)));
1466                                                 }
1467                                                 $$ = yylval.scalar->dno;
1468                                         }
1469                                 ;
1470
1471 execsql_start   : T_WORD
1472                                         { $$ = pstrdup(yytext); }
1473                                 | T_ERROR
1474                                         { $$ = pstrdup(yytext); }
1475                                 ;
1476
1477 exception_sect  :
1478                                         { $$ = NIL; }
1479                                 | K_EXCEPTION proc_exceptions
1480                                         { $$ = $2; }
1481                                 ;
1482
1483 proc_exceptions : proc_exceptions proc_exception
1484                                                 {
1485                                                         $$ = lappend($1, $2);
1486                                                 }
1487                                 | proc_exception
1488                                                 {
1489                                                         $$ = list_make1($1);
1490                                                 }
1491                                 ;
1492
1493 proc_exception  : K_WHEN lno proc_conditions K_THEN proc_sect
1494                                         {
1495                                                 PLpgSQL_exception *new;
1496
1497                                                 new = palloc0(sizeof(PLpgSQL_exception));
1498                                                 new->lineno     = $2;
1499                                                 new->conditions = $3;
1500                                                 new->action         = $5;
1501
1502                                                 $$ = new;
1503                                         }
1504                                 ;
1505
1506 proc_conditions : proc_conditions K_OR opt_lblname
1507                                                 {
1508                                                         PLpgSQL_condition       *old;
1509
1510                                                         for (old = $1; old->next != NULL; old = old->next)
1511                                                                 /* skip */ ;
1512                                                         old->next = plpgsql_parse_err_condition($3);
1513
1514                                                         $$ = $1;
1515                                                 }
1516                                 | opt_lblname
1517                                                 {
1518                                                         $$ = plpgsql_parse_err_condition($1);
1519                                                 }
1520                                 ;
1521
1522 expr_until_semi :
1523                                         { $$ = plpgsql_read_expression(';', ";"); }
1524                                 ;
1525
1526 expr_until_rightbracket :
1527                                         { $$ = plpgsql_read_expression(']', "]"); }
1528                                 ;
1529
1530 expr_until_then :
1531                                         { $$ = plpgsql_read_expression(K_THEN, "THEN"); }
1532                                 ;
1533
1534 expr_until_loop :
1535                                         { $$ = plpgsql_read_expression(K_LOOP, "LOOP"); }
1536                                 ;
1537
1538 opt_label               :
1539                                         {
1540                                                 plpgsql_ns_push(NULL);
1541                                                 $$ = NULL;
1542                                         }
1543                                 | '<' '<' opt_lblname '>' '>'
1544                                         {
1545                                                 plpgsql_ns_push($3);
1546                                                 $$ = $3;
1547                                         }
1548                                 ;
1549
1550 opt_exitlabel   :
1551                                         { $$ = NULL; }
1552                                 | T_LABEL
1553                                         {
1554                                                 char    *name;
1555
1556                                                 plpgsql_convert_ident(yytext, &name, 1);
1557                                                 $$ = name;
1558                                         }
1559                                 | T_WORD
1560                                         {
1561                                                 /* just to give a better error than "syntax error" */
1562                                                 yyerror("no such label");
1563                                         }
1564                                 ;
1565
1566 opt_exitcond    : ';'
1567                                         { $$ = NULL; }
1568                                 | K_WHEN expr_until_semi
1569                                         { $$ = $2; }
1570                                 ;
1571
1572 opt_lblname             : T_WORD
1573                                         {
1574                                                 char    *name;
1575
1576                                                 plpgsql_convert_ident(yytext, &name, 1);
1577                                                 $$ = name;
1578                                         }
1579                                 ;
1580
1581 lno                             :
1582                                         {
1583                                                 $$ = plpgsql_error_lineno = plpgsql_scanner_lineno();
1584                                         }
1585                                 ;
1586
1587 %%
1588
1589
1590 PLpgSQL_expr *
1591 plpgsql_read_expression(int until, const char *expected)
1592 {
1593         return read_sql_construct(until, 0, expected, "SELECT ", true, true, NULL);
1594 }
1595
1596 static PLpgSQL_expr *
1597 read_sql_stmt(const char *sqlstart)
1598 {
1599         return read_sql_construct(';', 0, ";", sqlstart, false, true, NULL);
1600 }
1601
1602 /*
1603  * Read a SQL construct and build a PLpgSQL_expr for it.
1604  *
1605  * until:               token code for expected terminator
1606  * until2:              token code for alternate terminator (pass 0 if none)
1607  * expected:    text to use in complaining that terminator was not found
1608  * sqlstart:    text to prefix to the accumulated SQL text
1609  * isexpression: whether to say we're reading an "expression" or a "statement"
1610  * valid_sql:   whether to check the syntax of the expression (plus sqlstart)
1611  * endtoken:    if not NULL, ending token is stored at *endtoken
1612  *                              (this is only interesting if until2 isn't zero)
1613  */
1614 static PLpgSQL_expr *
1615 read_sql_construct(int until,
1616                                    int until2,
1617                                    const char *expected,
1618                                    const char *sqlstart,
1619                                    bool isexpression,
1620                                    bool valid_sql,
1621                                    int *endtoken)
1622 {
1623         int                                     tok;
1624         int                                     lno;
1625         PLpgSQL_dstring         ds;
1626         int                                     parenlevel = 0;
1627         int                                     nparams = 0;
1628         int                                     params[1024];
1629         char                            buf[32];
1630         PLpgSQL_expr            *expr;
1631
1632         lno = plpgsql_scanner_lineno();
1633         plpgsql_dstring_init(&ds);
1634         plpgsql_dstring_append(&ds, sqlstart);
1635
1636         for (;;)
1637         {
1638                 tok = yylex();
1639                 if (tok == until && parenlevel == 0)
1640                         break;
1641                 if (tok == until2 && parenlevel == 0)
1642                         break;
1643                 if (tok == '(' || tok == '[')
1644                         parenlevel++;
1645                 else if (tok == ')' || tok == ']')
1646                 {
1647                         parenlevel--;
1648                         if (parenlevel < 0)
1649                                 ereport(ERROR,
1650                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1651                                                  errmsg("mismatched parentheses")));
1652                 }
1653                 /*
1654                  * End of function definition is an error, and we don't expect to
1655                  * hit a semicolon either (unless it's the until symbol, in which
1656                  * case we should have fallen out above).
1657                  */
1658                 if (tok == 0 || tok == ';')
1659                 {
1660                         plpgsql_error_lineno = lno;
1661                         if (parenlevel != 0)
1662                                 ereport(ERROR,
1663                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1664                                                  errmsg("mismatched parentheses")));
1665                         if (isexpression)
1666                                 ereport(ERROR,
1667                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1668                                                  errmsg("missing \"%s\" at end of SQL expression",
1669                                                                 expected)));
1670                         else
1671                                 ereport(ERROR,
1672                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1673                                                  errmsg("missing \"%s\" at end of SQL statement",
1674                                                                 expected)));
1675                 }
1676
1677                 if (plpgsql_SpaceScanned)
1678                         plpgsql_dstring_append(&ds, " ");
1679
1680                 /* Check for array overflow */
1681                 if (nparams >= 1024)
1682                 {
1683                         plpgsql_error_lineno = lno;
1684                         ereport(ERROR,
1685                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1686                                          errmsg("too many variables specified in SQL statement")));
1687                 }
1688
1689                 switch (tok)
1690                 {
1691                         case T_SCALAR:
1692                                 params[nparams] = yylval.scalar->dno;
1693                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1694                                 plpgsql_dstring_append(&ds, buf);
1695                                 break;
1696
1697                         case T_ROW:
1698                                 params[nparams] = yylval.row->rowno;
1699                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1700                                 plpgsql_dstring_append(&ds, buf);
1701                                 break;
1702
1703                         case T_RECORD:
1704                                 params[nparams] = yylval.rec->recno;
1705                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1706                                 plpgsql_dstring_append(&ds, buf);
1707                                 break;
1708
1709                         default:
1710                                 plpgsql_dstring_append(&ds, yytext);
1711                                 break;
1712                 }
1713         }
1714
1715         if (endtoken)
1716                 *endtoken = tok;
1717
1718         expr = palloc(sizeof(PLpgSQL_expr) + sizeof(int) * nparams - sizeof(int));
1719         expr->dtype                     = PLPGSQL_DTYPE_EXPR;
1720         expr->query                     = pstrdup(plpgsql_dstring_get(&ds));
1721         expr->plan                      = NULL;
1722         expr->nparams           = nparams;
1723         while(nparams-- > 0)
1724                 expr->params[nparams] = params[nparams];
1725         plpgsql_dstring_free(&ds);
1726
1727         if (valid_sql)
1728                 check_sql_expr(expr->query);
1729
1730         return expr;
1731 }
1732
1733 static PLpgSQL_type *
1734 read_datatype(int tok)
1735 {
1736         int                                     lno;
1737         PLpgSQL_dstring         ds;
1738         PLpgSQL_type            *result;
1739         bool                            needspace = false;
1740         int                                     parenlevel = 0;
1741
1742         lno = plpgsql_scanner_lineno();
1743
1744         /* Often there will be a lookahead token, but if not, get one */
1745         if (tok == YYEMPTY)
1746                 tok = yylex();
1747
1748         if (tok == T_DTYPE)
1749         {
1750                 /* lexer found word%TYPE and did its thing already */
1751                 return yylval.dtype;
1752         }
1753
1754         plpgsql_dstring_init(&ds);
1755
1756         while (tok != ';')
1757         {
1758                 if (tok == 0)
1759                 {
1760                         plpgsql_error_lineno = lno;
1761                         if (parenlevel != 0)
1762                                 ereport(ERROR,
1763                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1764                                                  errmsg("mismatched parentheses")));
1765                         ereport(ERROR,
1766                                         (errcode(ERRCODE_SYNTAX_ERROR),
1767                                          errmsg("incomplete datatype declaration")));
1768                 }
1769                 /* Possible followers for datatype in a declaration */
1770                 if (tok == K_NOT || tok == K_ASSIGN || tok == K_DEFAULT)
1771                         break;
1772                 /* Possible followers for datatype in a cursor_arg list */
1773                 if ((tok == ',' || tok == ')') && parenlevel == 0)
1774                         break;
1775                 if (tok == '(')
1776                         parenlevel++;
1777                 else if (tok == ')')
1778                         parenlevel--;
1779                 if (needspace)
1780                         plpgsql_dstring_append(&ds, " ");
1781                 needspace = true;
1782                 plpgsql_dstring_append(&ds, yytext);
1783
1784                 tok = yylex();
1785         }
1786
1787         plpgsql_push_back_token(tok);
1788
1789         plpgsql_error_lineno = lno;     /* in case of error in parse_datatype */
1790
1791         result = plpgsql_parse_datatype(plpgsql_dstring_get(&ds));
1792
1793         plpgsql_dstring_free(&ds);
1794
1795         return result;
1796 }
1797
1798 static PLpgSQL_stmt *
1799 make_select_stmt(void)
1800 {
1801         PLpgSQL_dstring         ds;
1802         int                                     nparams = 0;
1803         int                                     params[1024];
1804         char                            buf[32];
1805         PLpgSQL_expr            *expr;
1806         PLpgSQL_row                     *row = NULL;
1807         PLpgSQL_rec                     *rec = NULL;
1808         int                                     tok;
1809         bool                            have_into = false;
1810
1811         plpgsql_dstring_init(&ds);
1812         plpgsql_dstring_append(&ds, "SELECT ");
1813
1814         while (1)
1815         {
1816                 tok = yylex();
1817
1818                 if (tok == ';')
1819                         break;
1820                 if (tok == 0)
1821                 {
1822                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1823                         ereport(ERROR,
1824                                         (errcode(ERRCODE_SYNTAX_ERROR),
1825                                          errmsg("unexpected end of function definition")));
1826                 }
1827                 if (tok == K_INTO)
1828                 {
1829                         if (have_into)
1830                         {
1831                                 plpgsql_error_lineno = plpgsql_scanner_lineno();
1832                                 ereport(ERROR,
1833                                                 (errcode(ERRCODE_SYNTAX_ERROR),
1834                                                  errmsg("INTO specified more than once")));
1835                         }
1836                         tok = yylex();
1837                         switch (tok)
1838                         {
1839                                 case T_ROW:
1840                                         row = yylval.row;
1841                                         have_into = true;
1842                                         break;
1843
1844                                 case T_RECORD:
1845                                         rec = yylval.rec;
1846                                         have_into = true;
1847                                         break;
1848
1849                                 case T_SCALAR:
1850                                         row = read_into_scalar_list(yytext, yylval.scalar);
1851                                         have_into = true;
1852                                         break;
1853
1854                                 default:
1855                                         /* Treat the INTO as non-special */
1856                                         plpgsql_dstring_append(&ds, " INTO ");
1857                                         plpgsql_push_back_token(tok);
1858                                         break;
1859                         }
1860                         continue;
1861                 }
1862
1863                 if (plpgsql_SpaceScanned)
1864                         plpgsql_dstring_append(&ds, " ");
1865
1866                 /* Check for array overflow */
1867                 if (nparams >= 1024)
1868                 {
1869                         plpgsql_error_lineno = plpgsql_scanner_lineno();
1870                         ereport(ERROR,
1871                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1872                                          errmsg("too many parameters specified in SQL statement")));
1873                 }
1874
1875                 switch (tok)
1876                 {
1877                         case T_SCALAR:
1878                                 params[nparams] = yylval.scalar->dno;
1879                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1880                                 plpgsql_dstring_append(&ds, buf);
1881                                 break;
1882
1883                         case T_ROW:
1884                                 params[nparams] = yylval.row->rowno;
1885                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1886                                 plpgsql_dstring_append(&ds, buf);
1887                                 break;
1888
1889                         case T_RECORD:
1890                                 params[nparams] = yylval.rec->recno;
1891                                 snprintf(buf, sizeof(buf), " $%d ", ++nparams);
1892                                 plpgsql_dstring_append(&ds, buf);
1893                                 break;
1894
1895                         default:
1896                                 plpgsql_dstring_append(&ds, yytext);
1897                                 break;
1898                 }
1899         }
1900
1901         expr = palloc(sizeof(PLpgSQL_expr) + sizeof(int) * nparams - sizeof(int));
1902         expr->dtype                     = PLPGSQL_DTYPE_EXPR;
1903         expr->query                     = pstrdup(plpgsql_dstring_get(&ds));
1904         expr->plan                      = NULL;
1905         expr->nparams           = nparams;
1906         while(nparams-- > 0)
1907                 expr->params[nparams] = params[nparams];
1908         plpgsql_dstring_free(&ds);
1909
1910         if (have_into)
1911         {
1912                 PLpgSQL_stmt_select *select;
1913
1914                 select = palloc0(sizeof(PLpgSQL_stmt_select));
1915                 select->cmd_type = PLPGSQL_STMT_SELECT;
1916                 select->rec              = rec;
1917                 select->row              = row;
1918                 select->query    = expr;
1919
1920                 return (PLpgSQL_stmt *)select;
1921         }
1922         else
1923         {
1924                 PLpgSQL_stmt_execsql *execsql;
1925
1926                 execsql = palloc(sizeof(PLpgSQL_stmt_execsql));
1927                 execsql->cmd_type = PLPGSQL_STMT_EXECSQL;
1928                 execsql->sqlstmt  = expr;
1929
1930                 return (PLpgSQL_stmt *)execsql;
1931         }
1932 }
1933
1934
1935 static PLpgSQL_stmt *
1936 make_fetch_stmt(void)
1937 {
1938         int                                     tok;
1939         PLpgSQL_row                *row = NULL;
1940         PLpgSQL_rec                *rec = NULL;
1941         PLpgSQL_stmt_fetch *fetch;
1942
1943         /* We have already parsed everything through the INTO keyword */
1944
1945         tok = yylex();
1946         switch (tok)
1947         {
1948                 case T_ROW:
1949                         row = yylval.row;
1950                         break;
1951
1952                 case T_RECORD:
1953                         rec = yylval.rec;
1954                         break;
1955
1956                 case T_SCALAR:
1957                         row = read_into_scalar_list(yytext, yylval.scalar);
1958                         break;
1959
1960                 default:
1961                         yyerror("syntax error");
1962         }
1963
1964         tok = yylex();
1965         if (tok != ';')
1966                 yyerror("syntax error");
1967
1968         fetch = palloc0(sizeof(PLpgSQL_stmt_select));
1969         fetch->cmd_type = PLPGSQL_STMT_FETCH;
1970         fetch->rec               = rec;
1971         fetch->row               = row;
1972
1973         return (PLpgSQL_stmt *)fetch;
1974 }
1975
1976
1977 static void
1978 check_assignable(PLpgSQL_datum *datum)
1979 {
1980         switch (datum->dtype)
1981         {
1982                 case PLPGSQL_DTYPE_VAR:
1983                         if (((PLpgSQL_var *) datum)->isconst)
1984                         {
1985                                 plpgsql_error_lineno = plpgsql_scanner_lineno();
1986                                 ereport(ERROR,
1987                                                 (errcode(ERRCODE_ERROR_IN_ASSIGNMENT),
1988                                                  errmsg("\"%s\" is declared CONSTANT",
1989                                                                 ((PLpgSQL_var *) datum)->refname)));
1990                         }
1991                         break;
1992                 case PLPGSQL_DTYPE_ROW:
1993                         /* always assignable? */
1994                         break;
1995                 case PLPGSQL_DTYPE_REC:
1996                         /* always assignable?  What about NEW/OLD? */
1997                         break;
1998                 case PLPGSQL_DTYPE_RECFIELD:
1999                         /* always assignable? */
2000                         break;
2001                 case PLPGSQL_DTYPE_ARRAYELEM:
2002                         /* always assignable? */
2003                         break;
2004                 case PLPGSQL_DTYPE_TRIGARG:
2005                         yyerror("cannot assign to tg_argv");
2006                         break;
2007                 default:
2008                         elog(ERROR, "unrecognized dtype: %d", datum->dtype);
2009                         break;
2010         }
2011 }
2012
2013 /*
2014  * Given the first datum and name in the INTO list, continue to read
2015  * comma-separated scalar variables until we run out. Then construct
2016  * and return a fake "row" variable that represents the list of
2017  * scalars.
2018  */
2019 static PLpgSQL_row *
2020 read_into_scalar_list(const char *initial_name,
2021                                           PLpgSQL_datum *initial_datum)
2022 {
2023         int                              nfields;
2024         char                    *fieldnames[1024];
2025         int                              varnos[1024];
2026         PLpgSQL_row             *row;
2027         int                              tok;
2028
2029         check_assignable(initial_datum);
2030         fieldnames[0] = pstrdup(initial_name);
2031         varnos[0]         = initial_datum->dno;
2032         nfields           = 1;
2033
2034         while ((tok = yylex()) == ',')
2035         {
2036                 /* Check for array overflow */
2037                 if (nfields >= 1024)
2038                 {
2039                         plpgsql_error_lineno = plpgsql_scanner_lineno();
2040                         ereport(ERROR,
2041                                         (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2042                                          errmsg("too many INTO variables specified")));
2043                 }
2044
2045                 tok = yylex();
2046                 switch(tok)
2047                 {
2048                         case T_SCALAR:
2049                                 check_assignable(yylval.scalar);
2050                                 fieldnames[nfields] = pstrdup(yytext);
2051                                 varnos[nfields++]       = yylval.scalar->dno;
2052                                 break;
2053
2054                         default:
2055                                 plpgsql_error_lineno = plpgsql_scanner_lineno();
2056                                 ereport(ERROR,
2057                                                 (errcode(ERRCODE_SYNTAX_ERROR),
2058                                                  errmsg("\"%s\" is not a variable",
2059                                                                 yytext)));
2060                 }
2061         }
2062
2063         /*
2064          * We read an extra, non-comma character from yylex(), so push it
2065          * back onto the input stream
2066          */
2067         plpgsql_push_back_token(tok);
2068
2069         row = palloc(sizeof(PLpgSQL_row));
2070         row->dtype = PLPGSQL_DTYPE_ROW;
2071         row->refname = pstrdup("*internal*");
2072         row->lineno = plpgsql_scanner_lineno();
2073         row->rowtupdesc = NULL;
2074         row->nfields = nfields;
2075         row->fieldnames = palloc(sizeof(char *) * nfields);
2076         row->varnos = palloc(sizeof(int) * nfields);
2077         while (--nfields >= 0)
2078         {
2079                 row->fieldnames[nfields] = fieldnames[nfields];
2080                 row->varnos[nfields] = varnos[nfields];
2081         }
2082
2083         plpgsql_adddatum((PLpgSQL_datum *)row);
2084
2085         return row;
2086 }
2087
2088 /*
2089  * When the PL/PgSQL parser expects to see a SQL statement, it is very
2090  * liberal in what it accepts; for example, we often assume an
2091  * unrecognized keyword is the beginning of a SQL statement. This
2092  * avoids the need to duplicate parts of the SQL grammar in the
2093  * PL/PgSQL grammar, but it means we can accept wildly malformed
2094  * input. To try and catch some of the more obviously invalid input,
2095  * we run the strings we expect to be SQL statements through the main
2096  * SQL parser.
2097  *
2098  * We only invoke the raw parser (not the analyzer); this doesn't do
2099  * any database access and does not check any semantic rules, it just
2100  * checks for basic syntactic correctness. We do this here, rather
2101  * than after parsing has finished, because a malformed SQL statement
2102  * may cause the PL/PgSQL parser to become confused about statement
2103  * borders. So it is best to bail out as early as we can.
2104  */
2105 static void
2106 check_sql_expr(const char *stmt)
2107 {
2108         ErrorContextCallback  syntax_errcontext;
2109         ErrorContextCallback *previous_errcontext;
2110         MemoryContext oldCxt;
2111
2112         if (!plpgsql_check_syntax)
2113                 return;
2114
2115         /*
2116          * Setup error traceback support for ereport(). The previous
2117          * ereport callback is installed by pl_comp.c, but we don't want
2118          * that to be invoked (since it will try to transpose the syntax
2119          * error to be relative to the CREATE FUNCTION), so temporarily
2120          * remove it from the list of callbacks.
2121          */
2122         Assert(error_context_stack->callback == plpgsql_compile_error_callback);
2123
2124         previous_errcontext = error_context_stack;
2125         syntax_errcontext.callback = plpgsql_sql_error_callback;
2126         syntax_errcontext.arg = (char *) stmt;
2127         syntax_errcontext.previous = error_context_stack->previous;
2128         error_context_stack = &syntax_errcontext;
2129
2130         oldCxt = MemoryContextSwitchTo(compile_tmp_cxt);
2131         (void) raw_parser(stmt);
2132         MemoryContextSwitchTo(oldCxt);
2133
2134         /* Restore former ereport callback */
2135         error_context_stack = previous_errcontext;
2136 }
2137
2138 static void
2139 plpgsql_sql_error_callback(void *arg)
2140 {
2141         char *sql_stmt = (char *) arg;
2142
2143         Assert(plpgsql_error_funcname);
2144
2145         errcontext("SQL statement in PL/PgSQL function \"%s\" near line %d",
2146                            plpgsql_error_funcname, plpgsql_error_lineno);
2147         internalerrquery(sql_stmt);
2148         internalerrposition(geterrposition());
2149         errposition(0);
2150 }
2151
2152 #include "pl_scan.c"