Commit Graph

174 Commits

Author SHA1 Message Date
Tom Lane fcdfce6820 Detect mismatched CONTINUE and EXIT statements at plpgsql compile time.
With a bit of tweaking of the compile namestack data structure, we can
verify at compile time whether a CONTINUE or EXIT is legal.  This is
surely better than leaving it to runtime, both because earlier is better
and because we can issue a proper error pointer.  Also, we can get rid
of the ad-hoc old way of detecting the problem, which only took care of
CONTINUE not EXIT.

Jim Nasby, adjusted a bit by me
2015-08-21 20:17:19 -04:00
Tom Lane 2edb949115 Fix a few bogus statement type names in plpgsql error messages.
plpgsql's error location context messages ("PL/pgSQL function fn-name line
line-no at stmt-type") would misreport a CONTINUE statement as being an
EXIT, and misreport a MOVE statement as being a FETCH.  These are clear
bugs that have been there a long time, so back-patch to all supported
branches.

In addition, in 9.5 and HEAD, change the description of EXECUTE from
"EXECUTE statement" to just plain EXECUTE; there seems no good reason why
this statement type should be described differently from others that have
a well-defined head keyword.  And distinguish GET STACKED DIAGNOSTICS from
plain GET DIAGNOSTICS.  These are a bit more of a judgment call, and also
affect existing regression-test outputs, so I did not back-patch into
stable branches.

Pavel Stehule and Tom Lane
2015-08-18 19:22:37 -04:00
Tom Lane 83604cc423 Repair unsafe use of shared typecast-lookup table in plpgsql DO blocks.
DO blocks use private simple_eval_estates to avoid intra-transaction memory
leakage, cf commit c7b849a89.  I had forgotten about that while writing
commit 0fc94a5ba, but it means that expression execution trees created
within a DO block disappear immediately on exiting the DO block, and hence
can't safely be linked into plpgsql's session-wide cast hash table.
To fix, give a DO block a private cast hash table to go with its private
simple_eval_estate.  This is less efficient than one could wish, since
DO blocks can no longer share any cast lookup work with other plpgsql
execution, but it shouldn't be too bad; in any case it's no worse than
what happened in DO blocks before commit 0fc94a5ba.

Per bug #13571 from Feike Steenbergen.  Preliminary analysis by
Oleksandr Shulgin.
2015-08-15 12:00:48 -04:00
Tom Lane 0fc94a5bab Repair mishandling of cached cast-expression trees in plpgsql.
In commit 1345cc67bb, I introduced caching
of expressions representing type-cast operations into plpgsql.  However,
I supposed that I could cache both the expression trees and the evaluation
state trees derived from them for the life of the session.  This doesn't
work, because we execute the expressions in plpgsql's simple_eval_estate,
which has an ecxt_per_query_memory that is only transaction-lifespan.
Therefore we can end up putting pointers into the evaluation state tree
that point to transaction-lifespan memory; in particular this happens if
the cast expression calls a SQL-language function, as reported by Geoff
Winkless.

The minimum-risk fix seems to be to treat the state trees the same way
we do for "simple expression" trees in plpgsql, ie create them in the
simple_eval_estate's ecxt_per_query_memory, which means recreating them
once per transaction.

Since I had to introduce bookkeeping overhead for that anyway, I bought
back some of the added cost by sharing the read-only expression trees
across all functions in the session, instead of using a per-function
table as originally.  The simple-expression bookkeeping takes care of
the recursive-usage risk that I was concerned about avoiding before.

At some point we should take a harder look at how all this works,
and see if we can't reduce the amount of tree reinitialization needed.
But that won't happen for 9.5.
2015-07-17 15:53:09 -04:00
Tom Lane ae58f1430a Fix failure to cover scalar-vs-rowtype cases in exec_stmt_return().
In commit 9e3ad1aac5 I modified plpgsql
to use exec_stmt_return's simple-variables fast path in more cases.
However, I overlooked that there are really two different return
conventions in use here, depending on whether estate->retistuple is true,
and the existing fast-path code had only bothered to handle one of them.
So trying to return a scalar in a function returning composite, or vice
versa, could lead to unexpected error messages (typically "cache lookup
failed for type 0") or to a null-pointer-dereference crash.

In the DTYPE_VAR case, we can just throw error if retistuple is true,
corresponding to what happens in the general-expression code path that was
being used previously.  (Perhaps someday both of these code paths should
attempt a coercion, but today is not that day.)

In the REC and ROW cases, just hand the problem to exec_eval_datum()
when not retistuple.  Also clean up the ROW coding slightly so it looks
more like exec_eval_datum().

The previous commit also caused exec_stmt_return_next() to be used in
more cases, but that code seems to be OK as-is.

Per off-list report from Serge Rielau.  This bug is new in 9.5 so no need
to back-patch.
2015-06-12 13:44:06 -04:00
Tom Lane a4847fc3ef Add an ASSERT statement in plpgsql.
This is meant to make it easier to insert simple debugging cross-checks
in plpgsql functions.

Pavel Stehule, reviewed by Jim Nasby
2015-03-25 19:05:32 -04:00
Noah Misch f5ef00aed4 Free SQLSTATE and SQLERRM no earlier than other PL/pgSQL variables.
"RETURN SQLERRM" prompted plpgsql_exec_function() to read from freed
memory.  Back-patch to 9.0 (all supported versions).  Little code ran
between the premature free and the read, so non-assert builds are
unlikely to witness user-visible consequences.
2015-02-25 23:48:28 -05:00
Tom Lane bb1b8f694a De-reserve most statement-introducing keywords in plpgsql.
Add a bit of context sensitivity to plpgsql_yylex() so that it can
recognize when the word it is looking at is the first word of a new
statement, and if so whether it is the target of an assignment statement.
When we are at start of statement and it's not an assignment, we can
prefer recognizing unreserved keywords over recognizing variable names,
thereby allowing most statements' initial keywords to be demoted from
reserved to unreserved status.  This is rather useful already (there are
15 such words that get demoted here), and what's more to the point is
that future patches proposing to add new plpgsql statements can avoid
objections about having to add new reserved words.

The keywords BEGIN, DECLARE, FOR, FOREACH, LOOP, WHILE need to remain
reserved because they can be preceded by block labels, and the logic
added here doesn't understand about block labels.  In principle we
could probably fix that, but it would take more than one token of
lookback and the benefit doesn't seem worth extra complexity.

Also note I didn't de-reserve EXECUTE, because it is used in more places
than just statement start.  It's possible it could be de-reserved with
more work, but that would be an independent fix.

In passing, also de-reserve COLLATE and DEFAULT, which shouldn't have
been reserved in the first place since they only need to be recognized
within DECLARE sections.
2014-11-25 15:02:09 -05:00
Heikki Linnakangas c1008f0037 Check number of parameters in RAISE statement at compile time.
The number of % parameter markers in RAISE statement should match the number
of parameters given. We used to check that at execution time, but we have
all the information needed at compile time, so let's check it at compile
time instead. It's generally better to find mistakes earlier.

Marko Tiikkaja, reviewed by Fabien Coelho
2014-09-02 15:56:50 +03:00
Simon Riggs 7d8f1de1bc Extra warnings and errors for PL/pgSQL
Infrastructure to allow
 plpgsql.extra_warnings
 plpgsql.extra_errors

Initial extra checks only for shadowed_variables

Marko Tiikkaja and Petr Jelinek
Reviewed by Simon Riggs and Pavel Stěhule
2014-04-06 12:21:51 -04:00
Tom Lane c7b849a896 Prevent leakage of cached plans and execution trees in plpgsql DO blocks.
plpgsql likes to cache query plans and simple-expression execution state
trees across calls.  This is a considerable win for multiple executions
of the same function.  However, it's useless for DO blocks, since by
definition those are executed only once and discarded.  Nonetheless,
we were allowing a DO block's expression execution trees to survive
until end of transaction, resulting in a significant intra-transaction
memory leak, as reported by Yeb Havinga.  Worse, if the DO block exited
with an error, the compiled form of the block's code was leaked till
end of session --- along with subsidiary plancache entries.

To fix, make DO blocks keep their expression execution trees in a private
EState that's deleted at exit from the block, and add a PG_TRY block
to plpgsql_inline_handler to make sure that memory cleanup happens
even on error exits.  Also add a regression test covering error handling
in a DO block, because my first try at this broke that.  (The test is
not meant to prove that we don't leak memory anymore, though it could
be used for that with a much larger loop count.)

Ideally we'd back-patch this into all versions supporting DO blocks;
but the patch needs to add a field to struct PLpgSQL_execstate, and that
would break ABI compatibility for third-party plugins such as the plpgsql
debugger.  Given the small number of complaints so far, fixing this in
HEAD only seems like an acceptable choice.
2013-11-15 13:52:03 -05:00
Peter Eisentraut 001e114b8d Fix whitespace issues found by git diff --check, add gitattributes
Set per file type attributes in .gitattributes to fine-tune whitespace
checks.  With the associated cleanups, the tree is now clean for git
2013-11-10 14:48:29 -05:00
Robert Haas 689746c045 plpgsql: Add new option print_strict_params.
This option provides more detailed error messages when STRICT is used
and the number of rows returned is not one.

Marko Tiikkaja, reviewed by Ian Lawrence Barwick
2013-10-07 15:38:49 -04:00
Stephen Frost ddef1a39c6 Allow a context to be passed in for error handling
As pointed out by Tom Lane, we can allow other users of the error
handler callbacks to provide their own memory context by adding
the context to use to ErrorData and using that instead of explicitly
using ErrorContext.

This then allows GetErrorContextStack() to be called from inside
exception handlers, so modify plpgsql to take advantage of that and
add an associated regression test for it.
2013-08-01 01:07:20 -04:00
Stephen Frost 9bd0feeba8 Improvements to GetErrorContextStack()
As GetErrorContextStack() borrowed setup and tear-down code from other
places, it was less than clear that it must only be called as a
top-level entry point into the error system and can't be called by an
exception handler (unlike the rest of the error system, which is set up
to be reentrant-safe).

Being called from an exception handler is outside the charter of
GetErrorContextStack(), so add a bit more protection against it,
improve the comments addressing why we have to set up an errordata
stack for this function at all, and add a few more regression tests.

Lack of clarity pointed out by Tom Lane; all bugs are mine.
2013-07-25 09:41:55 -04:00
Stephen Frost 8312832567 Add GET DIAGNOSTICS ... PG_CONTEXT in PL/PgSQL
This adds the ability to get the call stack as a string from within a
PL/PgSQL function, which can be handy for logging to a table, or to
include in a useful message to an end-user.

Pavel Stehule, reviewed by Rushabh Lathia and rather heavily whacked
around by Stephen Frost.
2013-07-24 18:53:27 -04:00
Tom Lane 0cd787802f Rename a function to avoid naming conflict in parallel regression tests.
Commit 31a891857a added some tests in
plpgsql.sql that used a function rather unthinkingly named "foo()".
However, rangefuncs.sql has some much older tests that create a function
of that name, and since these test scripts run in parallel, there is a
chance of failures if the timing is just right.  Use another name to
avoid that.  Per buildfarm (failure seen today on "hamerkop", but
probably it's happened before and not been noticed).
2013-07-06 11:16:50 -04:00
Noah Misch 7cd9b1371d Expose object name error fields in PL/pgSQL.
Specifically, permit attaching them to the error in RAISE and retrieving
them from a caught error in GET STACKED DIAGNOSTICS.  RAISE enforces
nothing about the content of the fields; for its purposes, they are just
additional string fields.  Consequently, clarify in the protocol and
libpq documentation that the usual relationships between error fields,
like a schema name appearing wherever a table name appears, are not
universal.  This freedom has other applications; consider a FDW
propagating an error from an RDBMS having no schema support.

Back-patch to 9.3, where core support for the error fields was
introduced.  This prevents the confusion of having a release where libpq
exposes the fields and PL/pgSQL does not.

Pavel Stehule, lexical revisions by Noah Misch.
2013-07-03 07:29:56 -04:00
Tom Lane 0900ac2d0d Fix plpgsql's reporting of plan-time errors in possibly-simple expressions.
exec_simple_check_plan and exec_eval_simple_expr attempted to call
GetCachedPlan directly.  This meant that if an error was thrown during
planning, the resulting context traceback would not include the line
normally contributed by _SPI_error_callback.  This is already inconsistent,
but just to be really odd, a re-execution of the very same expression
*would* show the additional context line, because we'd already have cached
the plan and marked the expression as non-simple.

The problem is easy to demonstrate in 9.2 and HEAD because planning of a
cached plan doesn't occur at all until GetCachedPlan is done.  In earlier
versions, it could only be an issue if initial planning had succeeded, then
a replan was forced (already somewhat improbable for a simple expression),
and the replan attempt failed.  Since the issue is mainly cosmetic in older
branches anyway, it doesn't seem worth the risk of trying to fix it there.
It is worth fixing in 9.2 since the instability of the context printout can
affect the results of GET STACKED DIAGNOSTICS, as per a recent discussion
on pgsql-novice.

To fix, introduce a SPI function that wraps GetCachedPlan while installing
the correct callback function.  Use this instead of calling GetCachedPlan
directly from plpgsql.

Also introduce a wrapper function for extracting a SPI plan's
CachedPlanSource list.  This lets us stop including spi_priv.h in
pl_exec.c, which was never a very good idea from a modularity standpoint.

In passing, fix a similar inconsistency that could occur in SPI_cursor_open,
which was also calling GetCachedPlan without setting up a context callback.
2013-01-30 20:02:23 -05:00
Tom Lane 31a891857a Improve pl/pgsql to support composite-type expressions in RETURN.
For some reason lost in the mists of prehistory, RETURN was only coded to
allow a simple reference to a composite variable when the function's return
type is composite.  Allow an expression instead, while preserving the
efficiency of the original code path in the case where the expression is
indeed just a composite variable's name.  Likewise for RETURN NEXT.

As is true in various other places, the supplied expression must yield
exactly the number and data types of the required columns.  There was some
discussion of relaxing that for pl/pgsql, but no consensus yet, so this
patch doesn't address that.

Asif Rehman, reviewed by Pavel Stehule
2012-12-06 23:09:52 -05:00
Robert Haas d7c734841b Reduce messages about implicit indexes and sequences to DEBUG1.
Per recent discussion on pgsql-hackers, these messages are too
chatty for most users.
2012-07-04 20:35:29 -04:00
Peter Eisentraut 2b44306315 Assorted message style improvements 2012-07-02 21:12:46 +03:00
Tom Lane 05dbd4a773 Fix plpgsql named-cursor-parameter feature for variable name conflicts.
The parser got confused if a cursor parameter had the same name as
a plpgsql variable.  Reported and diagnosed by Yeb Havinga, though
this isn't exactly his proposed fix.

Also, some mostly-but-not-entirely-cosmetic adjustments to the original
named-cursor-parameter patch, for code readability and better error
diagnostics.
2012-04-04 21:50:31 -04:00
Tom Lane bef47331b6 Code review for plpgsql fn_signature patch.
Don't quote the output of format_procedure(); it's already quoted quite
enough.  Remove the fn_name field, which was now just dead weight.  Fix
remaining expected-output files.
2012-02-01 02:14:37 -05:00
Heikki Linnakangas 4c6cedd1b0 Print function signature, not just name, in PL/pgSQL error messages.
This makes it unambiguous which function the message is coming from, if you
have overloaded functions.

Pavel Stehule, reviewed by Abhijit Menon-Sen.
2012-01-31 10:36:20 +02:00
Heikki Linnakangas 4adead1d22 Add support for passing cursor parameters in named notation in PL/pgSQL.
Yeb Havinga, reviewed by Kevin Grittner, with small changes by me.
2011-12-14 15:55:37 +02:00
Tom Lane a4ffcc8e11 More code review for rangetypes patch.
Fix up some infelicitous coding in DefineRange, and add some missing error
checks.  Rearrange operator strategy number assignments for GiST anyrange
opclass so that they don't make such a mess of opr_sanity's table of
operator names associated with different strategy numbers.  Assign
hopefully-temporary selectivity estimators to range operators that didn't
have one --- poor as the estimates are, they're still a lot better than the
default 0.5 estimate, and they'll shut up the opr_sanity test that wants to
see selectivity estimators on all built-in operators.
2011-11-21 16:19:53 -05:00
Heikki Linnakangas 4429f6a9e3 Support range data types.
Selectivity estimation functions are missing for some range type operators,
which is a TODO.

Jeff Davis
2011-11-03 13:42:15 +02:00
Tom Lane 16762b519c Speed up array element assignment in plpgsql by caching type information.
Cache assorted data in the PLpgSQL_arrayelem struct to avoid repetitive
catalog lookups over multiple executions of the same statement.

Pavel Stehule
2011-09-26 15:38:07 -04:00
Tom Lane 3d4890c0c5 Add GET STACKED DIAGNOSTICS plpgsql command to retrieve exception info.
This is more SQL-spec-compliant, more easily extensible, and better
performing than the old method of inventing special variables.

Pavel Stehule, reviewed by Shigeru Hanada and David Wheeler
2011-07-18 14:47:18 -04:00
Tom Lane 6e02755b22 Add FOREACH IN ARRAY looping to plpgsql.
(I'm not entirely sure that we've finished bikeshedding the syntax details,
but the functionality seems OK.)

Pavel Stehule, reviewed by Stephen Frost and Tom Lane
2011-02-16 01:53:03 -05:00
Peter Eisentraut fc946c39ae Remove useless whitespace at end of lines 2010-11-23 22:34:55 +02:00
Tom Lane dd1c781903 Make get_stack_depth_rlimit() handle RLIM_INFINITY more sanely.
Rather than considering this result as meaning "unknown", report LONG_MAX.
This won't change what superusers can set max_stack_depth to, but it will
cause InitializeGUCOptions() to set the built-in default to 2MB not 100kB.
The latter seems like a fairly unreasonable interpretation of "infinity".
Per my investigation of odd buildfarm results as well as an old complaint
from Heikki.

Since this should persuade all the buildfarm animals to use a reasonable
stack depth setting during "make check", revert previous patch that dumbed
down a recursive regression test to only 5 levels.
2010-11-06 16:50:18 -04:00
Tom Lane 0abc8fdd4d Reduce recursion depth in recently-added regression test.
Some buildfarm members fail the test with the original depth of 10 levels,
apparently because they are running at the minimum max_stack_depth setting
of 100kB and using ~ 10k per recursion level.  While it might be
interesting to try to figure out why they're eating so much stack, it isn't
likely that any fix for that would be back-patchable.  So just change the
test to recurse only 5 levels.  The extra levels don't prove anything
correctness-wise anyway.
2010-11-03 13:41:46 -04:00
Tom Lane 8ce22dd4c5 Fix plpgsql's handling of "simple" expression evaluation.
In general, expression execution state trees aren't re-entrantly usable,
since functions can store private state information in them.
For efficiency reasons, plpgsql tries to cache and reuse state trees for
"simple" expressions.  It can get away with that most of the time, but it
can fail if the state tree is dirty from a previous failed execution (as
in an example from Alvaro) or is being used recursively (as noted by me).

Fix by tracking whether a state tree is in use, and falling back to the
"non-simple" code path if so.  This results in a pretty considerable speed
hit when the non-simple path is taken, but the available alternatives seem
even more unpleasant because they add overhead in the simple path.  Per
idea from Heikki.

Back-patch to all supported branches.
2010-10-28 13:02:12 -04:00
Robert Haas 0c8ed2dafb Fix inconsistent capitalization of "PL/pgSQL".
Josh Kupershmidt
2010-09-22 21:57:37 -04:00
Tom Lane 46af71ff7e Fix incorrect logic in plpgsql for cleanup after evaluation of non-simple
expressions.  We need to deal with this when handling subscripts in an array
assignment, and also when catching an exception.  In an Assert-enabled build
these omissions led to Assert failures, but I think in a normal build the
only consequence would be short-term memory leakage; which may explain why
this wasn't reported from the field long ago.

Back-patch to all supported versions.  7.4 doesn't have exceptions, but
otherwise these bugs go all the way back.

Heikki Linnakangas and Tom Lane
2010-08-09 18:50:11 +00:00
Tom Lane 2e35d4f35c Modify the handling of RAISE without parameters so that the error it throws
can be caught in the same places that could catch an ordinary RAISE ERROR
in the same location.  The previous coding insisted on throwing the error
from the block containing the active exception handler; which is arguably
more surprising, and definitely unlike Oracle's behavior.

Not back-patching, since this is a pretty obscure corner case.  The risk
of breaking somebody's code in a minor version update seems to outweigh
any possible benefit.

Piyush Newe, reviewed by David Fetter
2010-08-09 02:25:07 +00:00
Robert Haas c3a05881de Remove ancient PL/pgsql line numbering hack.
While this hack arguably has some benefit in terms of making PL/pgsql's
line numbering match the programmer's expectations, it also makes
PL/pgsql inconsistent with the remaining PLs, making it difficult for
clients to reliably determine where the error actually is.  On balance,
it seems better to be consistent.

Pavel Stehule
2010-08-02 03:46:54 +00:00
Tom Lane 399da7d882 Fix thinko in tok_is_keyword(): it was looking at the wrong union variant
of YYSTYPE, and hence returning the wrong answer for cases where a plpgsql
"unreserved keyword" really does conflict with a variable name.  Obviously
I didn't test this enough :-(.  Per bug #5524 from Peter Gagarinov.
2010-06-25 16:40:13 +00:00
Tom Lane d879697cd2 Remove the default_do_language parameter, instead making DO use a hardwired
default of "plpgsql".  This is more reasonable than it was when the DO patch
was written, because we have since decided that plpgsql should be installed
by default.  Per discussion, having a parameter for this doesn't seem useful
enough to justify the risk of application breakage if the value is changed
unexpectedly.
2010-01-26 16:33:40 +00:00
Tom Lane 309cd7cf18 Add "USING expressions" option to plpgsql's OPEN cursor FOR EXECUTE.
This is the last EXECUTE-like plpgsql statement that was missing
the capability of inserting parameter values via USING.

Pavel Stehule, reviewed by Itagaki Takahiro
2010-01-19 01:35:31 +00:00
Tom Lane 6317609986 Add control knobs for plpgsql's variable resolution behavior, and make the
default be "throw error on conflict", as per discussions.  The GUC variable
is plpgsql.variable_conflict, with values "error", "use_variable",
"use_column".  The behavior can also be specified per-function by inserting
one of
	#variable_conflict error
	#variable_conflict use_variable
	#variable_conflict use_column
at the start of the function body.

The 8.5 release notes will need to mention using "use_variable" to retain
backward-compatible behavior, although we should encourage people to migrate
to the much less mistake-prone "error" setting.

Update the plpgsql documentation to match this and other recent changes.
2009-11-13 22:43:42 +00:00
Tom Lane 2dee828cac Remove plpgsql's separate lexer (finally!), in favor of using the core lexer
directly.  This was a lot of trouble, but should be worth it in terms of
not having to keep the plpgsql lexer in step with core anymore.  In addition
the handling of keywords is significantly better-structured, allowing us to
de-reserve a number of words that plpgsql formerly treated as reserved.
2009-11-12 00:13:00 +00:00
Tom Lane 2ace38d226 Fix WHERE CURRENT OF to work as designed within plpgsql. The argument
can be the name of a plpgsql cursor variable, which formerly was converted
to $N before the core parser saw it, but that's no longer the case.
Deal with plain name references to plpgsql variables, and add a regression
test case that exposes the failure.
2009-11-09 02:36:59 +00:00
Tom Lane 39bd3fd1db Modernize plpgsql's handling of parse locations, making it look a lot more
like the core parser's code.  In particular, track locations at the character
rather than line level during parsing, allowing many more parse-time error
conditions to be reported with precise error pointers rather than just
"near line N".

Also, exploit the fact that we no longer need to substitute $N for variable
references by making extracted SQL queries and expressions be exact copies
of subranges of the function text, rather than having random whitespace
changes within them.  This makes it possible to directly map parse error
positions from the core parser onto positions in the function text, which
lets us report them without the previous kluge of showing the intermediate
internal-query form.  (Later it might be good to do that for core
parse-analysis errors too, but this patch is just touching plpgsql's
lexer/parser, not what happens at runtime.)

In passing, make plpgsql's lexer use palloc not malloc.

These changes make plpgsql's parse-time error reports noticeably nicer
(as illustrated by the regression test changes), and will also simplify
the planned removal of plpgsql's separate lexer by reducing the impedance
mismatch between what it does and what the core lexer does.
2009-11-09 00:26:55 +00:00
Tom Lane 0772f1e53d Change plpgsql from using textual substitution to insert variable references
into SQL expressions, to using the newly added parser callback hooks.

This allows us to do the substitutions in a more semantically-aware way:
a variable reference will only be recognized where it can validly go,
ie, a place where a column value or parameter would be legal, instead of
the former behavior that would replace any textual match including
table names and column aliases (leading to syntax errors later on).
A release-note-worthy fine point is that plpgsql variable names that match
fully-reserved words will now need to be quoted.

This commit preserves the former behavior that variable references take
precedence over any possible match to a column name.  The infrastructure
is in place to support the reverse precedence or throwing an error on
ambiguity, but those behaviors aren't accessible yet.

Most of the code changes here are associated with making the namespace
data structure persist so that it can be consulted at runtime, instead
of throwing it away at the end of initial function parsing.

The plpgsql scanner is still doing name lookups, but that behavior is
now irrelevant for SQL expressions.  A future commit will deal with
removing unnecessary lookups.
2009-11-06 18:37:55 +00:00
Tom Lane c29ae527e9 Remove plpgsql's RENAME declaration, which has bizarre and mostly nonfunctional
behavior, and is so little used that no one has been interested in fixing it.
To ensure that possible uses are covered, remove the ALIAS declaration's
arbitrary restriction that only $n identifiers can be aliased.

(We could alternatively make RENAME act just like ALIAS, but per discussion
having two different ways to do the same thing is probably more confusing than
helpful.)
2009-11-05 16:58:36 +00:00
Tom Lane 9bedd128d6 Add support for invoking parser callback hooks via SPI and in cached plans.
As proof of concept, modify plpgsql to use the hooks.  plpgsql is still
inserting $n symbols textually, but the "back end" of the parsing process now
goes through the ParamRef hook instead of using a fixed parameter-type array,
and then execution only fetches actually-referenced parameters, using a hook
added to ParamListInfo.

Although there's a lot left to be done in plpgsql, this already cures the
"if (TG_OP = 'INSERT' and NEW.foo ...)"  problem, as illustrated by the
changed regression test.
2009-11-04 22:26:08 +00:00
Tom Lane 960d7ff022 Allow MOVE FORWARD n, MOVE BACKWARD n, MOVE FORWARD ALL, MOVE BACKWARD ALL
in plpgsql.  Clean up a couple of corner cases in the MOVE/FETCH syntax.

Pavel Stehule
2009-09-29 20:05:29 +00:00
Tom Lane 9048b73184 Implement the DO statement to support execution of PL code without having
to create a function for it.

Procedural languages now have an additional entry point, namely a function
to execute an inline code block.  This seemed a better design than trying
to hide the transient-ness of the code from the PL.  As of this patch, only
plpgsql has an inline handler, but probably people will soon write handlers
for the other standard PLs.

In passing, remove the long-dead LANCOMPILER option of CREATE LANGUAGE.

Petr Jelinek
2009-09-22 23:43:43 +00:00
Tom Lane dcb2bda9b7 Improve plpgsql's ability to cope with rowtypes containing dropped columns,
by supporting conversions in places that used to demand exact rowtype match.

Since this issue is certain to come up elsewhere (in fact, already has,
in ExecEvalConvertRowtype), factor out the support code into new core
functions for tuple conversion.  I chose to put these in a new source
file since heaptuple.c is already overly long.

Heavily revised version of a patch by Pavel Stehule.
2009-08-06 20:44:32 +00:00
Tom Lane b680ae4bdb Improve unique-constraint-violation error messages to include the exact
values being complained of.

In passing, also remove the arbitrary length limitation in the similar
error detail message for foreign key violations.

Itagaki Takahiro
2009-08-01 19:59:41 +00:00
Tom Lane 3a624e9200 Revise plpgsql's scanner to process comments and string literals in a way
more nearly matching the core SQL scanner.  The user-visible effects are:

* Block comments (slash-star comments) now nest, as per SQL spec.

* In standard_conforming_strings mode, backslash as the last character of a
  non-E string literal is now correctly taken as an ordinary character;
  formerly it was misinterpreted as escaping the ending quote.  (Since the
  string also had to pass through the core scanner, this invariably led
  to syntax errors.)

* Formerly, backslashes in the format string of RAISE were always treated as
  quoting the next character, regardless of mode.  Now, they are ordinary
  characters with standard_conforming_strings on, while with it off, they
  introduce the same set of escapes as in the core SQL scanner.  Also,
  escape_string_warning is now effective for RAISE format strings.  These
  changes make RAISE format strings work just like any other string literal.

This is implemented by copying and pasting a lot of logic from the core
scanner.  It would be a good idea to look into getting rid of plpgsql's
scanner entirely in favor of using the core scanner.  However, that involves
more change than I can justify making during beta --- in particular, the core
scanner would have to become re-entrant.

In passing, remove the kluge that made the plpgsql scanner emit T_FUNCTION or
T_TRIGGER as a made-up first token.  That presumably had some value once upon
a time, but now it's just useless complication for both the scanner and the
grammar.
2009-04-19 18:52:58 +00:00
Tom Lane 03cd7571e8 Fix the plpgsql memory leak exhibited in bug #4677. That leak was introduced
by my patch of 2007-01-28 to use per-subtransaction ExprContexts/EStates:
since we re-prepared any expression tree when the current subtransaction ID
changed, we'd accumulate more and more leaked expression state trees in the
outermost subtransaction if the same function was executed at multiple levels
of subtransaction nesting.  To fix, go back to the previous scheme where
there was only one EState per transaction for simple plpgsql expressions.
We really only need an ExprContext per subtransaction, not a whole EState,
so it's possible to keep prepared expression state trees in the one EState
throughout the transaction.  This should be more efficient as well as not
leaking memory for cases involving lots of subtransactions.

The added regression test is the case that inspired the 2007-01-28 patch in
the first place, just to make sure we didn't go backwards.  The current
memory leak complaint is unfortunately hard to test for in the regression
test framework, though manual testing shows it's fixed.

Although this is a pre-existing bug, I'm not back-patching because I'd like to
see this method get some field testing first.  Consider back-patching if it
gets through 8.4beta unscathed.
2009-04-09 02:57:53 +00:00
Peter Eisentraut b9a366933d Message wordsmithing 2009-02-18 11:33:04 +00:00
Peter Eisentraut 71936fc5eb The Czech (cs_CZ) and Slovak (sk_SK) locales sort numbers after letters,
instead of vice versa.  Update the regression test expectations to support
that.  In the plpgsql test, adjust the test data so that this isn't an
issue.  In the char and varchar tests, add new expected files.
2009-02-12 15:11:44 +00:00
Bruce Momjian 8c78f8e65c Add PL/PgSQL FOUND and GET DIAGNOSTICS support for RETURN QUERY
statement

Pavel Stehule
2009-02-05 15:25:49 +00:00
Tom Lane 69a785b8bf Implement SQL-spec RETURNS TABLE syntax for functions.
(Unlike the original submission, this patch treats TABLE output parameters
as being entirely equivalent to OUT parameters -- tgl)

Pavel Stehule
2008-07-18 03:32:53 +00:00
Tom Lane d89737d31c Support "variadic" functions, which can accept a variable number of arguments
so long as all the trailing arguments are of the same (non-array) type.
The function receives them as a single array argument (which is why they
have to all be the same type).

It might be useful to extend this facility to aggregates, but this patch
doesn't do that.

This patch imposes a noticeable slowdown on function lookup --- a follow-on
patch will fix that by adding a redundant column to pg_proc.

Pavel Stehule
2008-07-16 01:30:23 +00:00
Tom Lane b62f246fb0 Support SQL/PSM-compatible CASE statement in plpgsql.
Pavel Stehule
2008-05-15 22:39:49 +00:00
Tom Lane 4107478d37 Improve plpgsql's RAISE command. It is now possible to attach DETAIL and
HINT fields to a user-thrown error message, and to specify the SQLSTATE
error code to use.  The syntax has also been tweaked so that the
Oracle-compatible case "RAISE exception_name" works (though you won't get a
very nice error message if you just write that much).  Lastly, support
the Oracle-compatible syntax "RAISE" with no parameters to re-throw
the current error from within an EXCEPTION block.

In passing, allow the syntax SQLSTATE 'nnnnn' within EXCEPTION lists,
so that there is a way to trap errors with custom SQLSTATE codes.

Pavel Stehule and Tom Lane
2008-05-13 22:10:30 +00:00
Tom Lane 47391591ba Support RETURN QUERY EXECUTE in plpgsql.
Pavel Stehule
2008-05-03 00:11:36 +00:00
Tom Lane 347dd6a1cf Make plpgsql support FOR over a query specified by a cursor declaration,
for improved compatibility with Oracle.

Pavel Stehule, with some fixes by me.
2008-04-06 23:43:29 +00:00
Tom Lane e2a8804330 Support EXECUTE USING in plpgsql.
Pavel Stehule, with some improvements by myself.
2008-04-01 03:51:09 +00:00
Tom Lane e67867b26c Allow AS to be omitted when specifying an output column name in SELECT
(or RETURNING), but only when the output name is not any SQL keyword.
This seems as close as we can get to the standard's syntax without a
great deal of thrashing.  Original patch by Hiroshi Saito, amended by me.
2008-02-15 22:17:06 +00:00
Neil Conway b2b9b4d59c Implement RETURN QUERY for PL/PgSQL. This provides some convenient syntax
sugar for PL/PgSQL set-returning functions that want to return the result
of evaluating a query; it should also be more efficient than repeated
RETURN NEXT statements. Based on an earlier patch from Pavel Stehule.
2007-07-25 04:19:09 +00:00
Peter Eisentraut 7abe764f17 Fix regression tests for PL/pgSQL error message changes 2007-07-20 16:38:38 +00:00
Tom Lane ae1b7e298c Allow plpgsql function parameter names to be qualified with the function's
name.  With this patch, it is always possible for the user to qualify a
plpgsql variable name if needed to avoid ambiguity.  While there is much more
work to be done in this area, this simple change removes one unnecessary
incompatibility with Oracle.  Per discussion.
2007-07-16 17:01:11 +00:00
Peter Eisentraut f4a3789b39 Clarify some error messages about duplicate things. 2007-06-03 22:16:03 +00:00
Neil Conway 8690ebc26f Support for MOVE in PL/PgSQL. Initial patch from Magnus, some improvements
by Pavel Stehule, and reviewed by Neil Conway.
2007-04-29 01:21:09 +00:00
Neil Conway f2321a3f37 Add support for IN as alternative to FROM in PL/PgSQL's FETCH statement,
for consistency with the backend's FETCH command. Patch from Pavel
Stehule, reviewed by Neil Conway.
2007-04-28 23:54:59 +00:00
Tom Lane f01b196597 Support scrollable cursors (ie, 'direction' clause in FETCH) in plpgsql.
Pavel Stehule, reworked a bit by Tom.
2007-04-16 17:21:24 +00:00
Tom Lane 3d1e01caa4 Support INSERT/UPDATE/DELETE RETURNING in plpgsql, with rowcount checking
as per yesterday's proposal.  Also make things a tad more orthogonal by
adding the recent STRICT addition to EXECUTE INTO.
Jonah Harris and Tom Lane
2006-08-14 21:14:42 +00:00
Tom Lane f1e671a0b4 Increase timeout in statement_timeout test from 1 second to 2 seconds.
We have once or twice seen failures suggesting that control didn't get
to the exception block before the timeout elapsed, which is unlikely
but not impossible in a parallel regression test (with a dozen other
backends competing for cycles).  This change doesn't completely prevent
the problem of course, but it should reduce the probability enough that
we don't see it anymore.  Per buildfarm results.
2006-06-18 16:21:23 +00:00
Bruce Momjian 4d06e86d04 Revert patch, needs more work:
---------------------------------------------------------------------------

Add dynamic record inspection to PL/PgSQL, useful for generic triggers:

  tval2 := r.(cname);

or

  columns := r.(*);

Titus von Boxberg
2006-05-30 13:40:56 +00:00
Bruce Momjian 38c7700f56 Add dynamic record inspection to PL/PgSQL, useful for generic triggers:
tval2 := r.(cname);

or

  columns := r.(*);

Titus von Boxberg
2006-05-30 12:03:13 +00:00
Bruce Momjian 88ba64d396 Back out patch, wrong previous commit message. 2006-05-30 11:58:05 +00:00
Bruce Momjian b6477c6295 Add regexp_replace() to string functions section.
Joachim Wieland
2006-05-30 11:54:51 +00:00
Tom Lane 4fb92718be Fix plpgsql to pass only one copy of any given plpgsql variable into a SQL
command or expression, rather than one copy for each textual occurrence as
it did before.  This might result in some small performance improvement,
but the compelling reason to do it is that not doing so can result in
unexpected grouping failures because the main SQL parser won't see different
parameter numbers as equivalent.  Add a regression test for the failure case.
Per report from Robert Davidson.
2006-03-23 04:22:37 +00:00
Tom Lane 20ab467d76 Improve parser so that we can show an error cursor position for errors
during parse analysis, not only errors detected in the flex/bison stages.
This is per my earlier proposal.  This commit includes all the basic
infrastructure, but locations are only tracked and reported for errors
involving column references, function calls, and operators.  More could
be done later but this seems like a good set to start with.  I've also
moved the ReportSyntaxErrorPosition logic out of psql and into libpq,
which should make it available to more people --- even within psql this
is an improvement because warnings weren't handled by ReportSyntaxErrorPosition.
2006-03-14 22:48:25 +00:00
Peter Eisentraut 7f4f42fa10 Clean up CREATE FUNCTION syntax usage in contrib and elsewhere, in
particular get rid of single quotes around language names and old WITH ()
construct.
2006-02-27 16:09:50 +00:00
Tom Lane 15c72174f3 Apply code-reviewed version of for-scalar-list patch: mostly, fixing
it to report reasonable errors in error cases.
2006-02-12 06:37:05 +00:00
Bruce Momjian 025ffe586f Allow PL/pgSQL FOR statement to return values to scalars as well as
records and row types.

Pavel Stehule
2006-02-12 06:03:38 +00:00
Tom Lane 9ea14ef56a When a function not returning RECORD has a single OUT parameter, use
the parameter's name (if any) as the default column name for SELECT FROM
the function, rather than the function name as previously.  I still think
this is a bad idea, but I lost the argument.  Force decompilation of
function RTEs to specify full aliases always, to reduce the odds of this
decision breaking dumped views.
2005-10-06 19:51:16 +00:00
Neil Conway 08dc2af91e Tweak the PL/PgSQL regression tests to catch the recently reported bug
in parsing cursor declarations.
2005-09-14 18:35:38 +00:00
Neil Conway c425dcb4ec In PL/PgSQL, allow a block's label to be optionally specified at the
end of the block:

<<label>>
begin
    ...
end label;

Similarly for loops. This is per PL/SQL. Update the documentation and
add regression tests. Patch from Pavel Stehule, code review by Neil
Conway.
2005-07-02 08:59:48 +00:00
Tom Lane 975368e267 Avoid function name conflict when plpgsql and rangefuncs regression tests
execute in parallel.  Spotted by Peter.
2005-07-01 20:29:02 +00:00
Neil Conway 738df437b2 Fix bug in CONTINUE statement for PL/pgSQL: when we continue a loop,
we need to be careful to reset rc to PLPGSQL_RC_OK, depending on how
the loop's logic is structured. If we continue a loop but it then
exits without executing the loop's body again, we want to return
PLPGSQL_RC_OK to our caller.  Enhance the regression tests to catch
this problem. Per report from Michael Fuhr.
2005-06-22 07:28:47 +00:00
Neil Conway ebcb4c931d Add a CONTINUE statement to PL/PgSQL, which can be used to begin the
next iteration of a loop. Update documentation and add regression tests.
Patch from Pavel Stehule, reviewed by Neil Conway.
2005-06-22 01:35:03 +00:00
Neil Conway d6636543c4 Allow the parameters to PL/PgSQL's RAISE statement to be expressions,
instead of just scalar variables. Add regression tests and update the
documentation. Along the way, remove some redundant error checking
code from exec_stmt_perform().

Original patch from Pavel Stehule, reworked by Neil Conway.
2005-06-14 06:43:15 +00:00
Neil Conway d46bc444ac Implement two new special variables in PL/PgSQL: SQLSTATE and SQLERRM.
These contain the SQLSTATE and error message of the current exception,
respectively. They are scope-local variables that are only defined
in exception handlers (so attempting to reference them outside an
exception handler is an error). Update the regression tests and the
documentation.

Also, do some minor related cleanup: export an unpack_sql_state()
function from the backend and use it to unpack a SQLSTATE into a
string, and add a free_var() function to pl_exec.c

Original patch from Pavel Stehule, review by Neil Conway.
2005-06-10 16:23:11 +00:00
Neil Conway c59887f916 Add support for an optional INTO clause to PL/PgSQL's EXECUTE command.
This allows the result of executing a SELECT to be assigned to a row
variable, record variable, or list of scalars. Docs and regression tests
updated. Per Pavel Stehule, improvements and cleanup by Neil Conway.
2005-06-07 02:47:23 +00:00
Bruce Momjian dabde323b2 Back out SQLSTATE and SQLERRM support. 2005-05-26 04:08:32 +00:00
Neil Conway b3195dae49 Minor cleanup for recent SQLSTATE / SQLERRM patch: spell "successful"
correctly, style fixes.
2005-05-26 03:18:53 +00:00
Bruce Momjian 38af680ad5 Add PL/pgSQL SQLSTATE and SQLERRM support which sets these values on
error.

Pavel Stehule
2005-05-26 00:16:31 +00:00
Tom Lane e00ee88761 Allow plpgsql functions to omit RETURN command when the function returns
output parameters or VOID or a set.  There seems no particular reason to
insist on a RETURN in these cases, since the function return value is
determined by other elements anyway.  Per recent discussion.
2005-04-07 14:53:04 +00:00
Tom Lane fd97cf4df0 plpgsql does OUT parameters, as per my proposal a few weeks ago. 2005-04-05 06:22:17 +00:00
Neil Conway 5a9dd0dc4f This patch changes makes some significant changes to how compilation
and parsing work in PL/PgSQL:

- memory management is now done via palloc(). The compiled representation
  of each function now has its own memory context. Therefore, the storage
  consumed by a function can be reclaimed via MemoryContextDelete().

  During compilation, the CurrentMemoryContext is the function's memory
  context. This means that a palloc() is sufficient to allocate memory
  that will have the same lifetime as the function itself. As a result,
  code invoked during compilation should be careful to pfree() temporary
  allocations to avoid leaking memory. Since a lot of the code in the
  backend is not careful about releasing palloc'ed memory, that means
  we should switch into a temporary memory context before invoking
  backend functions. A temporary context appropriate for such allocations
  is `compile_tmp_cxt'.

- The ability to use palloc() allows us to simply a lot of the code in
  the parser. Rather than representing lists of elements via ad hoc
  linked lists or arrays, we can use the List type. Rather than doing
  malloc followed by memset(0), we can just use palloc0().

- We now check that the user has supplied the right number of parameters
  to a RAISE statement. Supplying either too few or too many results in
  an error (at runtime).

- PL/PgSQL's parser needs to accept arbitrary SQL statements. Since we
  do not want to duplicate the SQL grammar in the PL/PgSQL grammar, this
  means we need to be quite lax in what the PL/PgSQL grammar considers
  a "SQL statement". This can lead to misleading behavior if there is a
  syntax error in the function definition, since we assume a malformed
  PL/PgSQL construct is a SQL statement. Furthermore, these errors were
  only detected at runtime (when we tried to execute the alleged "SQL
  statement" via SPI).

  To rectify this, the patch changes the parser to invoke the main SQL
  parser when it sees a string it believes to be a SQL expression. This
  means that synctically-invalid SQL will be rejected during the
  compilation of the PL/PgSQL function. This is only done when compiling
  for "validation" purposes (i.e. at CREATE FUNCTION time), so it should
  not impose a runtime overhead.

- Fixes for the various buffer overruns I've patched in stable branches
  in the past few weeks. I've rewritten code where I thought it was
  warranted (unlike the patches applied to older branches, which were
  minimally invasive).

- Various other minor changes and cleanups.

- Updates to the regression tests.
2005-02-22 07:18:27 +00:00
Neil Conway d600c1db7a Add some basic regression tests for refcursors in PL/PgSQL. 2005-01-19 04:32:40 +00:00