Commit Graph

497 Commits

Author SHA1 Message Date
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
Bruce Momjian e126958c2e Update copyright notices for year 2012. 2012-01-01 18:01:58 -05:00
Tom Lane 8722a1a06a Use the proper macro to convert a bool to a Datum.
The original coding was
	var->value = (Datum) state;
which is bogus, and then in commit 2f0f7b4bce
it was "corrected" to
	var->value = PointerGetDatum(state);
which is a faithful translation but still wrong.

This seems purely cosmetic, though, so no need for a back-patch.

Pavel Stehule
2011-11-27 12:57:11 -05:00
Tom Lane 051d1ba7a0 Avoid recursion while processing ELSIF lists in plpgsql.
The original implementation of ELSIF in plpgsql converted the construct
into nested simple IF statements.  This was prone to stack overflow with
long ELSIF lists, in two different ways.  First, it's difficult to generate
the parsetree without using right-recursion in the bison grammar, and
that's prone to parser stack overflow since nothing can be reduced until
the whole list has been read.  Second, we'd recurse during execution, thus
creating an unnecessary risk of execution-time stack overflow.  Rewrite
so that the ELSIF list is represented as a flat list, scanned via iteration
not recursion, and generated through left-recursion in the grammar.
Per a gripe from Håvard Kongsgård.
2011-10-27 15:21:51 -04: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 faf5cee7f0 Fix another Assert issue exposed by CLOBBER_CACHE_ALWAYS.
plpgsql's exec_stmt_execsql was Assert'ing that a CachedPlanSource was
is_valid immediately after exec_prepare_plan.  The risk factor in this case
is that after building the prepared statement, exec_prepare_plan calls
exec_simple_check_plan, which might try to generate a generic plan --- and
with CLOBBER_CACHE_ALWAYS or other unusual causes of invalidation, that
could result in an invalidation.  However, that path could only be taken
for a SELECT query, for which we need not set mod_stmt.  So in this case
I think it's best to just remove the Assert; it's okay to look at a
slightly-stale querytree for what we need here.  Per buildfarm testing.
2011-09-18 23:46:04 -04:00
Tom Lane e6ed34f70d Ensure generic plan gets used for a plpgsql expression with no parameters.
Now that a NULL ParamListInfo pointer causes significantly different
behavior in plancache.c, be sure to pass it that way when the expression
is known not to reference any plpgsql variables.  Saves a few setup
cycles anyway.
2011-09-16 12:31:23 -04:00
Tom Lane e6faf910d7 Redesign the plancache mechanism for more flexibility and efficiency.
Rewrite plancache.c so that a "cached plan" (which is rather a misnomer
at this point) can support generation of custom, parameter-value-dependent
plans, and can make an intelligent choice between using custom plans and
the traditional generic-plan approach.  The specific choice algorithm
implemented here can probably be improved in future, but this commit is
all about getting the mechanism in place, not the policy.

In addition, restructure the API to greatly reduce the amount of extraneous
data copying needed.  The main compromise needed to make that possible was
to split the initial creation of a CachedPlanSource into two steps.  It's
worth noting in particular that SPI_saveplan is now deprecated in favor of
SPI_keepplan, which accomplishes the same end result with zero data
copying, and no need to then spend even more cycles throwing away the
original SPIPlan.  The risk of long-term memory leaks while manipulating
SPIPlans has also been greatly reduced.  Most of this improvement is based
on use of the recently-added MemoryContextSetParent primitive.
2011-09-16 00:43:52 -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 1af37ec96d Replace errdetail("%s", ...) with errdetail_internal("%s", ...).
There may be some other places where we should use errdetail_internal,
but they'll have to be evaluated case-by-case.  This commit just hits
a bunch of places where invoking gettext is obviously a waste of cycles.
2011-07-16 14:22:18 -04:00
Alvaro Herrera b93f5a5673 Move Trigger and TriggerDesc structs out of rel.h into a new reltrigger.h
This lets us stop including rel.h into execnodes.h, which is a widely
used header.
2011-07-04 14:35:58 -04:00
Bruce Momjian 6560407c7d Pgindent run before 9.1 beta2. 2011-06-09 14:32:50 -04:00
Tom Lane 219dfae4e1 Make plpgsql provide the typmods for its variables to the main parser.
Historically we didn't do this, even though we had the information, because
plpgsql passed its Params via SPI APIs that only include type OIDs not
typmods.  Now that plpgsql uses parser callbacks to create Params, it's
easy to insert the right typmod.  This should generally result in lower
surprise factors, because a plpgsql variable that is declared with a typmod
will now work more like a table column with the same typmod.  In particular
it's the "right" way to fix bug #6020, in which plpgsql's attempt to return
an anonymous record type is defeated by stricter record-type matching
checks that were added in 9.0.  However, it's not impossible that this
could result in subtle behavioral changes that could break somebody's
existing plpgsql code, so I'm afraid to back-patch this change into
released branches.  In those branches we'll have to lobotomize the
record-type checks instead.
2011-05-22 15:15:07 -04:00
Peter Eisentraut bcf63a51e3 Message style improvements 2011-05-21 00:50:35 +03:00
Peter Eisentraut 5caa3479c2 Clean up most -Wunused-but-set-variable warnings from gcc 4.6
This warning is new in gcc 4.6 and part of -Wall.  This patch cleans
up most of the noise, but there are some still warnings that are
trickier to remove.
2011-04-11 22:28:45 +03:00
Bruce Momjian bf50caf105 pgindent run before PG 9.1 beta 1. 2011-04-10 11:42:00 -04:00
Tom Lane a4425e3200 Fix collation handling in plpgsql functions.
Make plpgsql treat the input collation as a polymorphism variable, so
that we cache separate plans for each input collation that's used in a
particular session, as per recent discussion.  Propagate the input
collation to all collatable input parameters.

I chose to also propagate the input collation to all declared variables of
collatable types, which is a bit more debatable but seems to be necessary
for non-astonishing behavior.  (Copying a parameter into a separate local
variable shouldn't result in a change of behavior, for example.)  There is
enough infrastructure here to support declaring a collation for each local
variable to override that default, but I thought we should wait to see what
the field demand is before adding such a feature.

In passing, remove exec_get_rec_fieldtype(), which wasn't used anywhere.

Documentation patch to follow.
2011-03-25 15:06:36 -04:00
Tom Lane b310b6e31c Revise collation derivation method and expression-tree representation.
All expression nodes now have an explicit output-collation field, unless
they are known to only return a noncollatable data type (such as boolean
or record).  Also, nodes that can invoke collation-aware functions store
a separate field that is the collation value to pass to the function.
This avoids confusion that arises when a function has collatable inputs
and noncollatable output type, or vice versa.

Also, replace the parser's on-the-fly collation assignment method with
a post-pass over the completed expression tree.  This allows us to use
a more complex (and hopefully more nearly spec-compliant) assignment
rule without paying for it in extra storage in every expression node.

Fix assorted bugs in the planner's handling of collations by making
collation one of the defining properties of an EquivalenceClass and
by converting CollateExprs into discardable RelabelType nodes during
expression preprocessing.
2011-03-19 20:30:08 -04:00
Bruce Momjian 2b8364de69 Add hint suggesting the use of EXECUTE CREATE TABLE ... AS for EXECUTE INTO. 2011-03-15 20:18:35 -04:00
Tom Lane 8acdb8bf9c Split CollateClause into separate raw and analyzed node types.
CollateClause is now used only in raw grammar output, and CollateExpr after
parse analysis.  This is for clarity and to avoid carrying collation names
in post-analysis parse trees: that's both wasteful and possibly misleading,
since the collation's name could be changed while the parsetree still
exists.

Also, clean up assorted infelicities and omissions in processing of the
node type.
2011-03-11 16:28:18 -05: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
Itagaki Takahiro 0c707aa458 Fix wrong error reports in 'number of array dimensions exceeds the
maximum allowed' messages, that have reported one-less dimensions.

Alexey Klyukin
2011-02-01 15:21:32 +09:00
Bruce Momjian 5d950e3b0c Stamp copyrights for year 2011. 2011-01-01 13:18:15 -05:00
Heikki Linnakangas f184de351d Give a more specific error message if you try to COMMIT, ROLLBACK or COPY
FROM STDIN in PL/pgSQL. We alread did this for dynamic EXECUTE statements,
ie. "EXECUTE 'COMMIT'", but not otherwise.
2010-10-29 11:44:54 +03:00
Tom Lane 37e0a01654 Save a few cycles in plpgsql simple-expression initialization.
Instead of using ExecPrepareExpr, call ExecInitExpr.  The net change here
is that we don't apply expression_planner() to the expression tree.  There
is no need to do so, because that tree is extracted from a fully planned
plancache entry, so all the needed work is already done.  This reduces
the setup costs by about a factor of 2 according to some simple tests.
Oversight noted while fooling around with the simple-expression code for
previous fix.
2010-10-28 13:29:13 -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
Tom Lane 529cb267a6 Improve handling of domains over arrays.
This patch eliminates various bizarre behaviors caused by sloppy thinking
about the difference between a domain type and its underlying array type.
In particular, the operation of updating one element of such an array
has to be considered as yielding a value of the underlying array type,
*not* a value of the domain, because there's no assurance that the
domain's CHECK constraints are still satisfied.  If we're intending to
store the result back into a domain column, we have to re-cast to the
domain type so that constraints are re-checked.

For similar reasons, such a domain can't be blindly matched to an ANYARRAY
polymorphic parameter, because the polymorphic function is likely to apply
array-ish operations that could invalidate the domain constraints.  For the
moment, we just forbid such matching.  We might later wish to insert an
automatic downcast to the underlying array type, but such a change should
also change matching of domains to ANYELEMENT for consistency.

To ensure that all such logic is rechecked, this patch removes the original
hack of setting a domain's pg_type.typelem field to match its base type;
the typelem will always be zero instead.  In those places where it's really
okay to look through the domain type with no other logic changes, use the
newly added get_base_element_type function in place of get_element_type.
catversion bumped due to change in pg_type contents.

Per bug #5717 from Richard Huxton and subsequent discussion.
2010-10-21 16:07:17 -04:00
Tom Lane 2ec993a7cb Support triggers on views.
This patch adds the SQL-standard concept of an INSTEAD OF trigger, which
is fired instead of performing a physical insert/update/delete.  The
trigger function is passed the entire old and/or new rows of the view,
and must figure out what to do to the underlying tables to implement
the update.  So this feature can be used to implement updatable views
using trigger programming style rather than rule hacking.

In passing, this patch corrects the names of some columns in the
information_schema.triggers view.  It seems the SQL committee renamed
them somewhere between SQL:99 and SQL:2003.

Dean Rasheed, reviewed by Bernd Helmle; some additional hacking by me.
2010-10-10 13:45:07 -04:00
Tom Lane caaf2e8469 Fix sloppy usage of TRIGGER_FIRED_BEFORE/TRIGGER_FIRED_AFTER.
Various places were testing TRIGGER_FIRED_BEFORE() where what they really
meant was !TRIGGER_FIRED_AFTER(), or vice versa.  This needs to be cleaned
up because there are about to be more than two possible states.

We might want to note this in the 9.1 release notes as something for
trigger authors to double-check.

For consistency's sake I also changed some places that assumed that
TRIGGER_FIRED_FOR_ROW and TRIGGER_FIRED_FOR_STATEMENT are necessarily
mutually exclusive; that's not in immediate danger of breaking, but
it's still sloppier than it should be.

Extracted from Dean Rasheed's patch for triggers on views.  I'm committing
this separately since it's an identifiable separate issue, and is the
only reason for the patch to touch most of these particular files.
2010-10-08 13:27:31 -04:00
Robert Haas 0c8ed2dafb Fix inconsistent capitalization of "PL/pgSQL".
Josh Kupershmidt
2010-09-22 21:57:37 -04:00
Magnus Hagander 9f2e211386 Remove cvs keywords from all files. 2010-09-20 22:08:53 +02:00
Tom Lane f4b4a46f01 Keep exec_simple_check_plan() from thinking "SELECT foo INTO bar" is simple.
It's not clear if this situation can occur in plpgsql other than via the
EXECUTE USING case Heikki illustrated, which I will shortly close off.
However, ignoring the intoClause if it's there is surely wrong, so let's
patch it for safety.

Backpatch to 8.3, which is as far back as this code has a PlannedStmt
to deal with.  There might be another way to make an equivalent test
before that, but since this is just preventing hypothetical bugs,
I'm not going to obsess about it.
2010-08-19 18:10:48 +00:00
Tom Lane 3869e9aecb Be a bit less cavalier with both the code and the comment for UNKNOWN fix. 2010-08-19 17:31:43 +00:00
Heikki Linnakangas ff645bf5ad Revert patch to coerce 'unknown' type parameters in the backend. As Tom
pointed out, it would need a 2nd pass after the whole query is processed to
correctly check that an unknown Param is coerced to the same target type
everywhere. Adding the 2nd pass would add a lot more code, which doesn't
seem worth the risk given that there isn't much of a use case for passing
unknown Params in the first place. The code would work without that check,
but it might be confusing and the behavior would be different from the
varparams case.

Instead, just coerce all unknown params in a PL/pgSQL USING clause to text.
That's simple, and is usually what users expect.

Revert the patch in CVS HEAD and master, and backpatch the new solution to
8.4. Unlike the previous solution, this applies easily to 8.4 too.
2010-08-19 16:54:43 +00: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
Bruce Momjian 239d769e7e pgindent run for 9.0, second run 2010-07-06 19:19:02 +00:00
Heikki Linnakangas eb81b6509f The previous fix in CVS HEAD and 8.4 for handling the case where a cursor
being used in a PL/pgSQL FOR loop is closed was inadequate, as Tom Lane
pointed out. The bug affects FOR statement variants too, because you can
close an implicitly created cursor too by guessing the "<unnamed portal X>"
name created for it.

To fix that, "pin" the portal to prevent it from being dropped while it's
being used in a PL/pgSQL FOR loop. Backpatch all the way to 7.4 which is
the oldest supported version.
2010-07-05 09:27:18 +00:00
Heikki Linnakangas 2e8a832dd6 In a PL/pgSQL "FOR cursor" statement, the statements executed in the loop
might close the cursor,  rendering the Portal pointer to it invalid.
Closing the cursor in the middle of the loop is not a very sensible thing
to do, but we must handle it gracefully and throw an error instead of
crashing.
2010-06-21 09:47:29 +00:00
Bruce Momjian 763129e04f Add error hint that PL/pgSQL "EXECUTE of SELECT ... INTO" can be
performed by "EXECUTE ... INTO".

Jaime Casanova
2010-05-31 20:02:30 +00:00
Tom Lane f7c5ff3d6d Fix plpgsql's exec_eval_expr() to ensure it returns a sane type OID
even when the expression is a query that returns no rows.

So far as I can tell, the only caller that actually fails when a garbage
OID is returned is exec_stmt_case(), which is new in 8.4 --- in all other
cases, we might make a useless trip through casting logic, but we won't
fail since the isnull flag will be set.  Hence, backpatch only to 8.4,
just in case there are apps out there that aren't expecting an error to
be thrown if the query returns more or less than one column.  (Which seems
unlikely, since the error would be thrown if the query ever did return a
row; but it's possible there's some never-exercised code out there.)

Per report from Mario Splivalo.
2010-04-14 23:52:10 +00:00
Bruce Momjian 65e806cba1 pgindent run for 9.0 2010-02-26 02:01:40 +00:00
Tom Lane 3ad7dbb1b9 Don't choke when exec_move_row assigns a synthesized null to a column
that happens to be composite itself.  Per bug #5314 from Oleg Serov.

Backpatch to 8.0 --- 7.4 has got too many other shortcomings in
composite-type support to make this worth worrying about in that branch.
2010-02-12 19:37:36 +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
Bruce Momjian 0239800893 Update copyright for the year 2010. 2010-01-02 16:58:17 +00:00
Heikki Linnakangas 84d723b6ce Previous fix for temporary file management broke returning a set from
PL/pgSQL function within an exception handler. Make sure we use the right
resource owner when we create the tuplestore to hold returned tuples.

Simplify tuplestore API so that the caller doesn't need to be in the right
memory context when calling tuplestore_put* functions. tuplestore.c
automatically switches to the memory context used when the tuplestore was
created. Tuplesort was already modified like this earlier. This patch also
removes the now useless MemoryContextSwitch calls from callers.

Report by Aleksei on pgsql-bugs on Dec 22 2009. Backpatch to 8.1, like
the previous patch that broke this.
2009-12-29 17:40: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 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 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
Alvaro Herrera 50d08346f3 Avoid including miscadmin.h into plpgsql.h; instead include it into the two
source files that need it.
2009-08-04 21:22:46 +00:00
Joe Conway 6cf9f31908 Replace PLpgSQL_dstring by StringInfo.
Replace redundant PLpgSQL_dstring functionality with StringInfo.
Patch by Pavel Stehule. Review by Joe Conway.
2009-07-22 02:31:38 +00:00
Tom Lane 011eae60ef Fix error cleanup failure caused by 8.4 changes in plpgsql to try to avoid
memory leakage in error recovery.  We were calling FreeExprContext, and
therefore invoking ExprContextCallback callbacks, in both normal and error
exits from subtransactions.  However this isn't very safe, as shown in
recent trouble report from Frank van Vugt, in which releasing a tupledesc
refcount failed.  It's also unnecessary, since the resources that callbacks
might wish to release should be cleaned up by other error recovery mechanisms
(ie the resource owners).  We only really want FreeExprContext to release
memory attached to the exprcontext in the error-exit case.  So, add a bool
parameter to FreeExprContext to tell it not to call the callbacks.

A more general solution would be to pass the isCommit bool parameter on to
the callbacks, so they could do only safe things during error exit.  But
that would make the patch significantly more invasive and possibly break
third-party code that registers ExprContextCallback callbacks.  We might want
to do that later in HEAD, but for now I'll just do what seems reasonable to
back-patch.
2009-07-18 19:15:42 +00:00
Peter Eisentraut 33d48d975f Fix typo in error message: tgargv -> tg_argv 2009-06-17 13:46:12 +00:00
Bruce Momjian d747140279 8.4 pgindent run, with new combined Linux/FreeBSD/MinGW typedef list
provided by Andrew.
2009-06-11 14:49:15 +00:00
Tom Lane 76d4abf2d9 Improve the recently-added support for properly pluralized error messages
by extending the ereport() API to cater for pluralization directly.  This
is better than the original method of calling ngettext outside the elog.c
code because (1) it avoids double translation, which wastes cycles and in
the worst case could give a wrong result; and (2) it avoids having to use
a different coding method in PL code than in the core backend.  The
client-side uses of ngettext are not touched since neither of these concerns
is very pressing in the client environment.  Per my proposal of yesterday.
2009-06-04 18:33:08 +00:00
Tom Lane c91bf01bc5 Fix plpgsql's EXIT so that an EXIT without a label only matches a loop,
never a BEGIN block.  This is required for Oracle compatibility and is
also plainly stated to be the behavior by our original documentation
(up until 8.1, in which the docs were adjusted to match the code's behavior;
but actually the old docs said the correct thing and the code was wrong).

Not back-patched because this introduces an incompatibility that could
break working applications.  Requires release note.
2009-05-02 17:27:57 +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
Tom Lane 735cb9692d Minor code beautification/consolidation. 2009-04-02 20:16:30 +00:00
Bruce Momjian 2faa8e2ac1 Have PL/pgSQL FETCH set DIAGNOSTICS ROW_COUNT.
Andrew Gierth
2009-04-02 19:20:45 +00:00
Tom Lane 24a814f441 plpgsql's exec_simple_cast_value() mistakenly supposed that it could bypass
casting effort whenever the input value was NULL.  However this prevents
application of not-null domain constraints in the cases that use this
function, as illustrated in bug #4741.  Since this function isn't meant
for use in performance-critical paths anyway, this certainly seems like
another case of "premature optimization is the root of all evil".

Back-patch as far as 8.2; older versions made no effort to enforce
domain constraints here anyway.
2009-04-02 01:16:11 +00:00
Peter Eisentraut 8032d76b5b Gettext plural support
In the backend, I changed only a handful of exemplary or important-looking
instances to make use of the plural support; there is probably more work
there.  For the rest of the source, this should cover all relevant cases.
2009-03-26 22:26:08 +00:00
Peter Eisentraut 3e96ed4c2b Add quotes to message 2009-02-23 10:03:22 +00:00
Peter Eisentraut b9a366933d Message wordsmithing 2009-02-18 11:33:04 +00:00
Peter Eisentraut 1d6b681ed3 Mark 3rd argument of validate_tupdesc_compat() for translation, instead of
marking up each instance separately.
2009-02-17 12:51:59 +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
Heikki Linnakangas 410a372ae3 Forgot to handle the new SPI_OK_REWRITTEN result code in a couple places. 2009-01-21 11:13:14 +00:00
Heikki Linnakangas 94136d5a18 Add new SPI_OK_REWRITTEN return code to SPI_execute and friends, for the
case that the command is rewritten into another type of command. The old
behavior to return the command tag of the last executed command was
pretty surprising. In PL/pgSQL, for example, it meant that if a command
was rewritten to a utility statement, FOUND wasn't set at all.
2009-01-21 11:02:40 +00:00
Heikki Linnakangas f2248478c1 Remove broken Assertions that failed if a statement executed in PL/pgSQL is
rewritten into another kind of statement, for example if an INSERT is
rewritten into an UPDATE.

Back-patch to 8.3 and 8.2. For HEAD, Tom suggested inventing a new
SPI_OK_REWRITTEN return code, but that's not a backportable solution. I'll
do that as a separate patch, this patch will do as a stopgap measure for HEAD
too in the meanwhile.
2009-01-14 09:53:51 +00:00
Tom Lane deac9488d3 Insert conditional SPI_push/SPI_pop calls into InputFunctionCall,
OutputFunctionCall, and friends.  This allows SPI-using functions to invoke
datatype I/O without concern for the possibility that a SPI-using function
will be called (which could be either the I/O function itself, or a function
used in a domain check constraint).  It's a tad ugly, but not nearly as ugly
as what'd be needed to make this work via retail insertion of push/pop
operations in all the PLs.

This reverts my patch of 2007-01-30 that inserted some retail SPI_push/pop
calls into plpgsql; that approach only fixed plpgsql, and not any other PLs.
But the other PLs have the issue too, as illustrated by a recent gripe from
Christian Schröder.

Back-patch to 8.2, which is as far back as this solution will work.  It's
also as far back as we need to worry about the domain-constraint case, since
earlier versions did not attempt to check domain constraints within datatype
input.  I'm not aware of any old I/O functions that use SPI themselves, so
this should be sufficient for a back-patch.
2009-01-07 20:38:56 +00:00
Tom Lane 1cfd9e8834 Fix executor/spi.h to follow our usual conventions for include files, ie,
not include postgres.h nor anything else it doesn't directly need.  Add
#includes to calling files as needed to compensate.  Per my proposal of
yesterday.

This should be noted as a source code change in the 8.4 release notes,
since it's likely to require changes in add-on modules.
2009-01-07 13:44:37 +00:00
Bruce Momjian 511db38ace Update copyright for 2009. 2009-01-01 17:24:05 +00:00
Magnus Hagander 6c3690d835 Don't pass strings directly to errdetail() and errhint() - use
%s to unescape them. Fixes a potential security issue (in as yet
unreleased code)
2008-11-20 15:36:22 +00:00
Tom Lane e0dc7d026f Rename several aliases for PLpgSQL_datum.dno to also be called dno.
Hopefully this will forestall future confusion about their roles.

Jonah Harris
2008-11-05 00:07:54 +00:00
Tom Lane 902d1cb35f Remove all uses of the deprecated functions heap_formtuple, heap_modifytuple,
and heap_deformtuple in favor of the newer functions heap_form_tuple et al
(which do the same things but use bool control flags instead of arbitrary
char values).  Eliminate the former duplicate coding of these functions,
reducing the deprecated functions to mere wrappers around the newer ones.
We can't get rid of them entirely because add-on modules probably still
contain many instances of the old coding style.

Kris Jurka
2008-11-02 01:45:28 +00:00
Tom Lane 05bba3d176 Be more tense about not creating tuplestores with randomAccess = true unless
backwards scan could actually happen.  In particular, pass a flag to
materialize-mode SRFs that tells them whether they need to require random
access.  In passing, also suppress unneeded backward-scan overhead for a
Portal's holdStore tuplestore.  Per my proposal about reducing I/O costs for
tuplestores.
2008-10-29 00:00:39 +00:00
Tom Lane 739c614f41 Fix unportable syntax used in recent patch. Per results from
buildfarm member 'bear'.
2008-09-24 14:40:00 +00:00
Alvaro Herrera c06629c72e Improve plpgsql's ability to report tuple incompatibility problems.
Volkan YAZICI
2008-09-09 15:14:08 +00:00
Tom Lane dd6edd5efd Fix plpgsql's exec_move_row() to supply valid type OIDs to exec_assign_value()
whenever possible, as per bug report from Oleg Serov.  While at it, reorder
the operations in the RECORD case to avoid possible palloc failure while the
variable update is only partly complete.

Back-patch as far as 8.1.  Although the code of the particular function is
similar in 8.0, 8.0's support for composite fields in rows is sufficiently
broken elsewhere that it doesn't seem worth fixing this.
2008-09-01 22:30:33 +00:00
Peter Eisentraut 7c31742a07 Remove all traces that suggest that a non-Bison yacc might be supported, and
change build system to use only Bison.  Simplify build rules, make file names
uniform.  Don't build the token table header file where it is not needed.
2008-08-29 13:02:33 +00:00
Tom Lane e5536e77a5 Move exprType(), exprTypmod(), expression_tree_walker(), and related routines
into nodes/nodeFuncs, so as to reduce wanton cross-subsystem #includes inside
the backend.  There's probably more that should be done along this line,
but this is a start anyway.
2008-08-25 22:42:34 +00:00
Tom Lane c3fc2bf744 Suppress a possibly-uninitialized-variable warning. (I'm only seeing it
on Apple's gcc and not my other machines, but still it seems worth
getting rid of.)
2008-05-16 18:34:51 +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
Alvaro Herrera 5da9da71c4 Improve snapshot manager by keeping explicit track of snapshots.
There are two ways to track a snapshot: there's the "registered" list, which
is used for arbitrary long-lived snapshots; and there's the "active stack",
which is used for the snapshot that is considered "active" at any time.
This also allows users of snapshots to stop worrying about snapshot memory
allocation and freeing, and about using PG_TRY blocks around ActiveSnapshot
assignment.  This is all done automatically now.

As a consequence, this allows us to reset MyProc->xmin when there are no
more snapshots registered in the current backend, reducing the impact that
long-running transactions have on VACUUM.
2008-05-12 20:02:02 +00:00
Alvaro Herrera f8c4d7db60 Restructure some header files a bit, in particular heapam.h, by removing some
unnecessary #include lines in it.  Also, move some tuple routine prototypes and
macros to htup.h, which allows removal of heapam.h inclusion from some .c
files.

For this to work, a new header file access/sysattr.h needed to be created,
initially containing attribute numbers of system columns, for pg_dump usage.

While at it, make contrib ltree, intarray and hstore header files more
consistent with our header style.
2008-05-12 00:00:54 +00:00
Tom Lane 47391591ba Support RETURN QUERY EXECUTE in plpgsql.
Pavel Stehule
2008-05-03 00:11:36 +00:00
Alvaro Herrera 2f0f7b4bce Clean up a few places where Datums were being treated as pointers (and vice
versa) without going through DatumGetPointer.

Gavin Sherry, with Feng Tian.
2008-04-17 21:37:28 +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 7692d8d5b7 Support statement-level ON TRUNCATE triggers. Simon Riggs 2008-03-28 00:21:56 +00:00
Alvaro Herrera 78f02ca1f5 Rename snapmgmt.c/h to snapmgr.c/h, for consistency with other files.
Per complaint from Tom Lane.
2008-03-26 18:48:59 +00:00
Alvaro Herrera d43b085d57 Separate snapshot management code from tuple visibility code, create a
snapmgmt.c file for the former.  The header files have also been reorganized
in three parts: the most basic snapshot definitions are now in a new file
snapshot.h, and the also new snapmgmt.h keeps the definitions for snapmgmt.c.
tqual.h has been reduced to the bare minimum.

This patch is just a first step towards managing live snapshots within a
transaction; there is no functionality change.

Per my proposal to pgsql-patches on 20080318191940.GB27458@alvh.no-ip.org and
subsequent discussion.
2008-03-26 16:20:48 +00:00
Tom Lane 220db7ccd8 Simplify and standardize conversions between TEXT datums and ordinary C
strings.  This patch introduces four support functions cstring_to_text,
cstring_to_text_with_len, text_to_cstring, and text_to_cstring_buffer, and
two macros CStringGetTextDatum and TextDatumGetCString.  A number of
existing macros that provided variants on these themes were removed.

Most of the places that need to make such conversions now require just one
function or macro call, in place of the multiple notational layers that used
to be needed.  There are no longer any direct calls of textout or textin,
and we got most of the places that were using handmade conversions via
memcpy (there may be a few still lurking, though).

This commit doesn't make any serious effort to eliminate transient memory
leaks caused by detoasting toasted text objects before they reach
text_to_cstring.  We changed PG_GETARG_TEXT_P to PG_GETARG_TEXT_PP in a few
places where it was easy, but much more could be done.

Brendan Jurd and Tom Lane
2008-03-25 22:42:46 +00:00
Neil Conway 1d812a98b4 Add a new tuplestore API function, tuplestore_putvalues(). This is
identical to tuplestore_puttuple(), except it operates on arrays of
Datums + nulls rather than a fully-formed HeapTuple. In several places
that use the tuplestore API, this means we can avoid creating a
HeapTuple altogether, saving a copy.
2008-03-25 19:26:54 +00:00
Bruce Momjian 9098ab9e32 Update copyrights in source tree to 2008. 2008-01-01 19:46:01 +00:00
Bruce Momjian f6e8730d11 Re-run pgindent with updated list of typedefs. (Updated README should
avoid this problem in the future.)
2007-11-15 22:25:18 +00:00
Bruce Momjian fdf5a5efb7 pgindent run for 8.3. 2007-11-15 21:14:46 +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
Tom Lane 816ff27f60 Reject zero or negative BY step in plpgsql integer FOR-loops, and behave
sanely if the loop value overflows int32 on the way to the end value.
Avoid useless computation of "SELECT 1" when BY is omitted.  Avoid some
type-punning between Datum and int4 that dates from the original coding.
2007-07-15 02:15:04 +00:00
Tom Lane 31edbadf4a Downgrade implicit casts to text to be assignment-only, except for the ones
from the other string-category types; this eliminates a lot of surprising
interpretations that the parser could formerly make when there was no directly
applicable operator.

Create a general mechanism that supports casts to and from the standard string
types (text,varchar,bpchar) for *every* datatype, by invoking the datatype's
I/O functions.  These new casts are assignment-only in the to-string direction,
explicit-only in the other, and therefore should create no surprising behavior.
Remove a bunch of thereby-obsoleted datatype-specific casting functions.

The "general mechanism" is a new expression node type CoerceViaIO that can
actually convert between *any* two datatypes if their external text
representations are compatible.  This is more general than needed for the
immediate feature, but might be useful in plpgsql or other places in future.

This commit does nothing about the issue that applying the concatenation
operator || to non-text types will now fail, often with strange error messages
due to misinterpreting the operator as array concatenation.  Since it often
(not always) worked before, we should either make it succeed or at least give
a more user-friendly error; but details are still under debate.

Peter Eisentraut and Tom Lane
2007-06-05 21:31:09 +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
Tom Lane 77a41e71a3 Fix plpgsql to avoid reference to already-freed memory when returning a
pass-by-reference data type and the RETURN statement is within an EXCEPTION
block.  Bug introduced by my fix of 2007-01-28 to use per-subtransaction
ExprContexts/EStates; since that wasn't back-patched into older branches,
only 8.2 and HEAD are affected.  Per report from Gary Winslow.
2007-04-19 16:33:24 +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 57690c6803 Support enum data types. Along the way, use macros for the values of
pg_type.typtype whereever practical.  Tom Dunstan, with some kibitzing
from Tom Lane.
2007-04-02 03:49:42 +00:00
Tom Lane bf94076348 Fix array coercion expressions to ensure that the correct volatility is
seen by code inspecting the expression.  The best way to do this seems
to be to drop the original representation as a function invocation, and
instead make a special expression node type that represents applying
the element-type coercion function to each array element.  In this way
the element function is exposed and will be checked for volatility.
Per report from Guillaume Smet.
2007-03-27 23:21:12 +00:00
Tom Lane bf8236526b Remove the prohibition on executing cursor commands through SPI_execute.
Vadim had included this restriction in the original design of the SPI code,
but I'm darned if I can see a reason for it.

I left the macro definition of SPI_ERROR_CURSOR in place, so as not to
needlessly break any SPI callers that are checking for it, but that code
will never actually be returned anymore.
2007-03-25 23:27:59 +00:00
Tom Lane 95f6d2d209 Make use of plancache module for SPI plans. In particular, since plpgsql
uses SPI plans, this finally fixes the ancient gotcha that you can't
drop and recreate a temp table used by a plpgsql function.

Along the way, clean up SPI's API a little bit by declaring SPI plan
pointers as "SPIPlanPtr" instead of "void *".  This is cosmetic but
helps to forestall simple programming mistakes.  (I have changed some
but not all of the callers to match; there are still some "void *"'s
in contrib and the PL's.  This is intentional so that we can see if
anyone's compiler complains about it.)
2007-03-15 23:12:07 +00:00
Tom Lane 9cbd0c155d Remove the Query structure from the executor's API. This allows us to stop
storing mostly-redundant Query trees in prepared statements, portals, etc.
To replace Query, a new node type called PlannedStmt is inserted by the
planner at the top of a completed plan tree; this carries just the fields of
Query that are still needed at runtime.  The statement lists kept in portals
etc. now consist of intermixed PlannedStmt and bare utility-statement nodes
--- no Query.  This incidentally allows us to remove some fields from Query
and Plan nodes that shouldn't have been there in the first place.

Still to do: simplify the execution-time range table; at the moment the
range table passed to the executor still contains Query trees for subqueries.

initdb forced due to change of stored rules.
2007-02-20 17:32:18 +00:00
Tom Lane fe796ea8ac Fix an ancient logic error in plpgsql's exec_stmt_block: it thought it could
get away with not (re)initializing a local variable if the variable is marked
"isconst" and not "isnull".  Unfortunately it makes this decision after having
already freed the old value, meaning that something like

   for i in 1..10 loop
     declare c constant text := 'hi there';

leads to subsequent accesses to freed memory, and hence probably crashes.
(In particular, this is why Asif Ali Rehman's bug leads to crash and not
just an unexpectedly-NULL value for SQLERRM: SQLERRM is marked CONSTANT
and so triggers this error.)

The whole thing seems wrong on its face anyway: CONSTANT means that you can't
change the variable inside the block, not that the initializer expression is
guaranteed not to change value across successive block entries.  Hence,
remove the "optimization" instead of trying to fix it.
2007-02-08 18:37:30 +00:00
Tom Lane 6994d0b891 Fix plpgsql so that when a local variable has no initial-value expression,
an error will be thrown correctly if the variable is of a NOT NULL domain.
Report and almost-correct fix from Sergiy Vyshnevetskiy (bug #2948).
2007-02-01 19:22:07 +00:00
Tom Lane 33d78c9e48 Add SPI_push/SPI_pop calls so that datatype input and output functions called
by plpgsql can themselves use SPI --- possibly indirectly, as in the case
of domain_in() invoking plpgsql functions in a domain check constraint.
Per bug #2945 from Sergiy Vyshnevetskiy.

Somewhat arbitrarily, I've chosen to back-patch this as far as 8.0.  Given
the lack of prior complaints, it doesn't seem critical for 7.x.
2007-01-30 18:02:22 +00:00
Tom Lane 5681cde7b1 Make some small improvements in the accuracy of plpgsql's error location
reports; inspired by the misleading CONTEXT lines shown in recent bug report
from Stefan Kaltenbrunner.  Also, allow statement-type names shown in these
messages to be translated.
2007-01-28 17:58:13 +00:00
Tom Lane a8e0b66061 Fix up plpgsql's "simple expression" evaluation mechanism so that it behaves
safely in the presence of subtransactions.  To ensure that any ExprContext
shutdown callbacks are called at the right times, we have to have a separate
EState for each level of subtransaction.  Per "TupleDesc reference leak" bug
report from Stefan Kaltenbrunner.

Although I'm convinced the code is wrong as far back as 8.0, it doesn't seem
that there are any ways for the problem to really manifest before 8.2: AFAICS,
8.0 and 8.1 only use the ExprContextCallback mechanism to handle set-returning
functions, which cannot usefully be executed in a "simple expression" anyway.
Hence, no backpatch before 8.2 --- the risk of unforeseen breakage seems
to outweigh the chance of fixing something.
2007-01-28 16:15:49 +00:00
Bruce Momjian 40f797be03 Enable another five tuple status bits by using the high bits of the
nattr field, and rename the field.

Heikki Linnakangas
2007-01-09 22:01:00 +00:00
Bruce Momjian 29dccf5fe0 Update CVS HEAD for 2007 copyright. Back branches are typically not
back-stamped for this.
2007-01-05 22:20:05 +00:00
Tom Lane c957c0bac7 Code review for XML patch. Instill a bit of sanity in the location of
the XmlExpr code in various lists, use a representation that has some hope
of reverse-listing correctly (though it's still a de-escaping function
shy of correctness), generally try to make it look more like Postgres
coding conventions.
2006-12-24 00:29:20 +00:00
Bruce Momjian f99a569a2e pgindent run for 8.2. 2006-10-04 00:30:14 +00:00
Tom Lane beca984e5f Fix bugs in plpgsql and ecpg caused by assuming that isspace() would only
return true for exactly the characters treated as whitespace by their flex
scanners.  Per report from Victor Snezhko and subsequent investigation.

Also fix a passel of unsafe usages of <ctype.h> functions, that is, ye olde
char-vs-unsigned-char issue.  I won't miss <ctype.h> when we are finally
able to stop using it.
2006-09-22 21:39:58 +00:00
Tom Lane 5983a1aaa9 Change processing of extended-Query mode so that an unnamed statement
that has parameters is always planned afresh for each Bind command,
treating the parameter values as constants in the planner.  This removes
the performance penalty formerly often paid for using out-of-line
parameters --- with this definition, the planner can do constant folding,
LIKE optimization, etc.  After a suggestion by Andrew@supernews.
2006-09-06 20:40:48 +00:00
Tom Lane ea2e263539 Add new return codes SPI_OK_INSERT_RETURNING etc to the SPI API.
Fix all the standard PLs to be able to return tuples from FOO_RETURNING
statements as well as utility statements that return tuples.  Also,
fix oversight that SPI_processed wasn't set for a utility statement
returning tuples.  Per recent discussion.
2006-08-27 23:47:58 +00:00
Tom Lane 355865c5a7 Add hooks to allow debugging and performance measurement plugins
to instrument PL/pgSQL.  Korry Douglas
2006-08-15 19:01:17 +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
Bruce Momjian a22d76d96a Allow include files to compile own their own.
Strip unused include files out unused include files, and add needed
includes to C files.

The next step is to remove unused include files in C files.
2006-07-13 16:49:20 +00:00
Tom Lane c892643a3c Code review for SELECT INTO STRICT patch: use saner choices of error
SQLSTATEs, fix some documentation problems.
2006-06-16 23:29:27 +00:00
Tom Lane 06e10abc0b Fix problems with cached tuple descriptors disappearing while still in use
by creating a reference-count mechanism, similar to what we did a long time
ago for catcache entries.  The back branches have an ugly solution involving
lots of extra copies, but this way is more efficient.  Reference counting is
only applied to tupdescs that are actually in caches --- there seems no need
to use it for tupdescs that are generated in the executor, since they'll go
away during plan shutdown by virtue of being in the per-query memory context.
Neil Conway and Tom Lane
2006-06-16 18:42:24 +00:00
Bruce Momjian a584c12426 Add STRICT to PL/pgSQL SELECT INTO, so exceptions are thrown if more or
less than one row is returned by the SELECT, for Oracle PL/SQL
compatibility.

Improve SELECT INTO documentation.

Matt Miller
2006-06-15 18:02:22 +00:00
Bruce Momjian 07c25723da Add BY clause to PL/PgSQL FOR loop, to control the iteration increment.
Jaime Casanova
2006-06-12 16:45:30 +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
Andrew Dunstan 3a9ae3d206 TG_table_name and TG_table_schema for plpgsql, plus docs and regression. 2006-05-28 03:03:17 +00:00
Tom Lane 2206b498d8 Simplify ParamListInfo data structure to support only numbered parameters,
not named ones, and replace linear searches of the list with array indexing.
The named-parameter support has been dead code for many years anyway,
and recent profiling suggests that the searching was costing a noticeable
amount of performance for complex queries.
2006-04-22 01:26:01 +00:00
Tom Lane 147d4bf3e5 Modify all callers of datatype input and receive functions so that if these
functions are not strict, they will be called (passing a NULL first parameter)
during any attempt to input a NULL value of their datatype.  Currently, all
our input functions are strict and so this commit does not change any
behavior.  However, this will make it possible to build domain input functions
that centralize checking of domain constraints, thereby closing numerous holes
in our domain support, as per previous discussion.

While at it, I took the opportunity to introduce convenience functions
InputFunctionCall, OutputFunctionCall, etc to use in code that calls I/O
functions.  This eliminates a lot of grotty-looking casts, but the main
motivation is to make it easier to grep for these places if we ever need
to touch them again.
2006-04-04 19:35:37 +00:00
Bruce Momjian 5931737571 Remove Jan Wieck's name from copyrights, and put in standard
boilerplate, with approval of author.
2006-03-09 21:29:38 +00:00
Tom Lane fa7f6ff0db Fix possible crash at transaction end when a plpgsql function is used and
then modified within the same transaction.  The code was using a linked list
of active PLpgSQL_expr structs, which was OK when it was written because
plpgsql never released any parse data structures for the life of the backend.
But since Neil fixed plpgsql's memory management, elements of the linked list
could be freed, leading to crash when the list is chased.  Per report and test
case from Kris Jurka.
2006-03-02 05:34:12 +00:00
Neil Conway 8ea91ba18e Minor code clarity improvement: AFAICS, estate.eval_econtext must be
non-NULL during the guts of plpgsql_exec_trigger() and
plpgsql_exec_function(). Therefore, we can remove the NULL check,
per discussion on -patches.
2006-01-10 18:50:43 +00:00
Tom Lane 41ec930d7c Add checks to verify that a plpgsql function returning a rowtype is actually
returning the rowtype it's supposed to return.  Per reports from David Niblett
and Michael Fuhr.
2006-01-03 22:48:10 +00:00
Tom Lane 6e07709760 Implement SQL-compliant treatment of row comparisons for < <= > >= cases
(previously we only did = and <> correctly).  Also, allow row comparisons
with any operators that are in btree opclasses, not only those with these
specific names.  This gets rid of a whole lot of indefensible assumptions
about the behavior of particular operators based on their names ... though
it's still true that IN and NOT IN expand to "= ANY".  The patch adds a
RowCompareExpr expression node type, and makes some changes in the
representation of ANY/ALL/ROWCOMPARE SubLinks so that they can share code
with RowCompareExpr.

I have not yet done anything about making RowCompareExpr an indexable
operator, but will look at that soon.

initdb forced due to changes in stored rules.
2005-12-28 01:30:02 +00:00
Bruce Momjian 436a2956d8 Re-run pgindent, fixing a problem where comment lines after a blank
comment line where output as too long, and update typedefs for /lib
directory.  Also fix case where identifiers were used as variable names
in the backend, but as typedefs in ecpg (favor the backend for
indenting).

Backpatch to 8.1.X.
2005-11-22 18:17:34 +00:00
Tom Lane 1d0d8d3c38 Mop-up for nulls-in-arrays patch: fix some places that access array
contents directly.
2005-11-18 02:38:24 +00:00
Tom Lane cecb607559 Make SQL arrays support null elements. This commit fixes the core array
functionality, but I still need to make another pass looking at places
that incidentally use arrays (such as ACL manipulation) to make sure they
are null-safe.  Contrib needs work too.
I have not changed the behaviors that are still under discussion about
array comparison and what to do with lower bounds.
2005-11-17 22:14:56 +00:00
Tom Lane 18feafcc59 Ensure that a plpgsql LOOP with an empty body still executes at least
one CHECK_FOR_INTERRUPTS() call, so that you can control-C out of the
loop.  Reported by Merlin Moncure.
2005-10-24 15:10:22 +00:00
Bruce Momjian 1dc3498251 Standard pgindent run for 8.1. 2005-10-15 02:49:52 +00:00
Tom Lane 5b0fa0c28c Fix make_tuple_from_row to support nested rowtypes, per gripe from
Roman Neuhauser.  Update some obsolete comments for exec_eval_datum, too.
2005-09-13 16:16:17 +00:00
Neil Conway 95cbfb5c7c Refactor exec_cast_value() and exec_simple_cast_value(): since they do
not ever write through the `isnull' parameter, it does not need to be
an out parameter. Therefore it can be declared a "bool" rather than a
"bool *".
2005-07-28 07:51:13 +00:00
Tom Lane 37bd2aaf28 Fix breakage introduced in plpgsql CONTINUE patch.
Per Kevin McArthur.
2005-07-28 00:26:30 +00:00
Tom Lane 943b396245 Add Oracle-compatible GREATEST and LEAST functions. Pavel Stehule 2005-06-26 22:05:42 +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
Tom Lane 638feae2c9 exec_eval_datum leaks memory when dealing with ROW or REC values.
It never leaked memory before PG 8.0, so none of the callers are
expecting this.  Cleanest fix seems to be to make it allocate the needed
memory in estate->eval_econtext, where it will be cleaned up by
the next exec_eval_cleanup.  Per report from Bill Rugolsky.
2005-06-20 22:51:29 +00:00
Tom Lane 9d7c005243 plpgsql's exec_assign_value() freed the old value of a variable before
copying/converting the new value, which meant that it failed badly on
"var := var" if var is of pass-by-reference type.  Fix this and a similar
hazard in exec_move_row(); not sure that the latter can manifest before
8.0, but patch it all the way back anyway.  Per report from Dave Chapeskie.
2005-06-20 20:44:44 +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 278bd0cc22 For some reason access/tupmacs.h has been #including utils/memutils.h,
which is neither needed by nor related to that header.  Remove the bogus
inclusion and instead include the header in those C files that actually
need it.  Also fix unnecessary inclusions and bad inclusion order in
tsearch2 files.
2005-05-06 17:24:55 +00:00
Neil Conway f478856c7f Change SPI functions to use a `long' when specifying the number of tuples
to produce when running the executor. This is consistent with the internal
executor APIs (such as ExecutorRun), which also use a long for this purpose.
It also allows FETCH_ALL to be passed -- since FETCH_ALL is defined as
LONG_MAX, this wouldn't have worked on platforms where int and long are of
different sizes. Per report from Tzahi Fadida.
2005-05-02 00:37:07 +00:00
Tom Lane 6c412f0605 Change CREATE TYPE to require datatype output and send functions to have
only one argument.  (Per recent discussion, the option to accept multiple
arguments is pretty useless for user-defined types, and would be a likely
source of security holes if it was used.)  Simplify call sites of
output/send functions to not bother passing more than one argument.
2005-05-01 18:56:19 +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
Tom Lane c90578a1d6 Make initialization of special trigger variables a little more readable.
Correct one mis-setting of freeval (which could at worst leak a few bytes
until the trigger exits, so it's no big deal).
2005-03-25 01:45:42 +00:00
Tom Lane 41994145d4 My patch this morning was overly hasty; revert code to original state. 2005-02-24 01:11:40 +00:00
Tom Lane b9a87e5219 Un-break plpgsql build by removing unwanted _() usage.
This would be a completely inappropriate place to apply localization
anyway.
2005-02-23 16:23:07 +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
Bruce Momjian 0542b1e2fe Use _() macro consistently rather than gettext(). Add translation
macros around strings that were missing them.
2005-02-22 04:43:23 +00:00
Tom Lane 2a8874841d Adjust plpgsql to allow assignment to an element of an array that is
initially NULL.  For 8.0 we changed the main executor to have this
behavior in an UPDATE of an array column, but plpgsql's equivalent case
was overlooked.  Per report from Sven Willenberger.
2005-02-01 19:35:14 +00:00
Tom Lane 2730eb9ae4 Change exec_eval_simple_expr's param list allocation call from
MemoryContextAllocZero back to MemoryContextAlloc, same as it was in 7.4.
The zeroing is unnecessary since all the meaningful fields are filled in
just below.  I had made it do that out of neatnik-ism, but some testing
with an example provided by Pavel Stehule showed that the zeroing was
accounting for about 5% of the runtime in a compute-intensive plpgsql
function.  That seems a bit high of a price for neatnik-ism...
2005-01-13 23:07:34 +00:00
Tom Lane 96b42de9a8 exec_eval_simple_expr() needs to do CommandCounterIncrement() not just
GetTransactionSnapshot() to ensure ActiveSnapshot advances properly.
Sigh.  Extend regression test so it reveals this error too.
2004-12-21 18:33:36 +00:00
Tom Lane e184663b24 plpgsql's exec_eval_simple_expr() now has to take responsibility for
advancing ActiveSnapshot when we are inside a volatile function.
Per example from Gaetano Mendola.  Add a regression test to catch
similar problems in future.
2004-12-19 20:20:27 +00:00
Tom Lane 12b1b5d837 Instead of supposing (wrongly, in the general case) that the rowtype
of an inheritance child table is binary-compatible with the rowtype of
its parent, invent an expression node type that does the conversion
correctly.  Fixes the new bug exhibited by Kris Shannon as well as a
lot of old bugs that would only show up when using multiple inheritance
or after altering the parent table.
2004-12-11 23:26:51 +00:00
Neil Conway 16c46870b7 Fix a few typos in comments. 2004-11-30 03:50:29 +00:00
Tom Lane 183e8b911c While fixing plperl and pltcl, I realized plpgsql wasn't doing
subtransactions quite right either: the ReleaseCurrentSubTransaction
call should occur inside the PG_TRY, so that the proper path is taken
if an error occurs during subtransaction commit.  This assumes that
AbortSubTransaction can cope with the state left behind if
CommitSubTransaction fails partway through, but we were already
requiring that.
2004-11-21 22:27:34 +00:00
Tom Lane 7efa8411cc Rethink plpgsql's way of handling SPI execution during an exception block.
We don't really want to start a new SPI connection, just keep using the old
one; otherwise we have memory management problems as illustrated by
John Kennedy's bug report of today.  This requires a bit of a hack to
ensure the SPI stack state is properly restored, but then again what we
were doing before was a hack too, strictly speaking.  Add a regression
test to cover this case.
2004-11-16 18:10:16 +00:00
Tom Lane 8f9f198603 Restructure subtransaction handling to reduce resource consumption,
as per recent discussions.  Invent SubTransactionIds that are managed like
CommandIds (ie, counter is reset at start of each top transaction), and
use these instead of TransactionIds to keep track of subtransaction status
in those modules that need it.  This means that a subtransaction does not
need an XID unless it actually inserts/modifies rows in the database.
Accordingly, don't assign it an XID nor take a lock on the XID until it
tries to do that.  This saves a lot of overhead for subtransactions that
are only used for error recovery (eg plpgsql exceptions).  Also, arrange
to release a subtransaction's XID lock as soon as the subtransaction
exits, in both the commit and abort cases.  This avoids holding many
unique locks after a long series of subtransactions.  The price is some
additional overhead in XactLockTableWait, but that seems acceptable.
Finally, restructure the state machine in xact.c to have a more orthogonal
set of states for subtransactions.
2004-09-16 16:58:44 +00:00
Tom Lane b2c4071299 Redesign query-snapshot timing so that volatile functions in READ COMMITTED
mode see a fresh snapshot for each command in the function, rather than
using the latest interactive command's snapshot.  Also, suppress fresh
snapshots as well as CommandCounterIncrement inside STABLE and IMMUTABLE
functions, instead using the snapshot taken for the most closely nested
regular query.  (This behavior is only sane for read-only functions, so
the patch also enforces that such functions contain only SELECT commands.)
As per my proposal of 6-Sep-2004; I note that I floated essentially the
same proposal on 19-Jun-2002, but that discussion tailed off without any
action.  Since 8.0 seems like the right place to be taking possibly
nontrivial backwards compatibility hits, let's get it done now.
2004-09-13 20:10:13 +00:00
Bruce Momjian 15d3f9f6b7 Another pgindent run with lib typedefs added. 2004-08-30 02:54:42 +00:00
Bruce Momjian b6b71b85bc Pgindent run for 8.0. 2004-08-29 05:07:03 +00:00
Tom Lane bf9d9bd2f3 Recognize plpgsql EXCEPTION condition names at function compile time
instead of runtime, for better detection of invalid condition names
(and maybe a little more speed, too).
2004-08-20 22:00:14 +00:00
Tom Lane bf08e6550b Give a more specific error message for "you can't do that" error cases
in plpgsql, particularly trying to begin/end/rollback a transaction.
2004-08-13 18:47:56 +00:00
Tom Lane 9aa30e7109 Actually, there's no need to use pg_strcasecmp for checking exception
names, because the name we got from the lexer is already downcased.
Just store the table in lower case and use strcmp ...
2004-08-02 17:03:48 +00:00
Tom Lane f622c54049 Allow DECLARE CURSOR to take parameters from the portal in which it is
executed.  Previously, the DECLARE would succeed but subsequent FETCHes
would fail since the parameter values supplied to DECLARE were not
propagated to the portal created for the cursor.
In support of this, add type Oids to ParamListInfo entries, which seems
like a good idea anyway since code that extracts a value can double-check
that it got the type of value it was expecting.
Oliver Jowett, with minor editorialization by Tom Lane.
2004-08-02 01:30:51 +00:00
Tom Lane efcaf1e868 Some mop-up work for savepoints (nested transactions). Store a small
number of active subtransaction XIDs in each backend's PGPROC entry,
and use this to avoid expensive probes into pg_subtrans during
TransactionIdIsInProgress.  Extend EOXactCallback API to allow add-on
modules to get control at subxact start/end.  (This is deliberately
not compatible with the former API, since any uses of that API probably
need manual review anyway.)  Add basic reference documentation for
SAVEPOINT and related commands.  Minor other cleanups to check off some
of the open issues for subtransactions.
Alvaro Herrera and Tom Lane.
2004-08-01 17:32:22 +00:00
Tom Lane 9c8d0850c3 Support "OR condition ..." in plpgsql EXCEPTION clauses to make the syntax
more nearly Oracle-equivalent.  Allow matching by category as well as
specific error code.  Document the set of available condition names
(or more accurately, synchronize it with the existing documentation).  In
passing, update errcodes.sgml to include codes added during 7.5 development.
2004-07-31 23:04:58 +00:00
Tom Lane ad4d2e9711 Be more consistent about reporting SPI errors in the various PLs.
Create a shared function to convert a SPI error code into a string
(replacing near-duplicate code in several PLs), and use it anywhere
that a SPI function call error is reported.
2004-07-31 20:55:45 +00:00
Tom Lane beda4814c1 plpgsql does exceptions.
There are still some things that need refinement; in particular I fear
that the recognized set of error condition names probably has little in
common with what Oracle recognizes.  But it's a start.
2004-07-31 07:39:21 +00:00
Tom Lane a393fbf937 Restructure error handling as recently discussed. It is now really
possible to trap an error inside a function rather than letting it
propagate out to PostgresMain.  You still have to use AbortCurrentTransaction
to clean up, but at least the error handling itself will cooperate.
2004-07-31 00:45:57 +00:00
Tom Lane 7e64dbc6b5 Support assignment to subfields of composite columns in UPDATE and INSERT.
As a side effect, cause subscripts in INSERT targetlists to do something
more or less sensible; previously we evaluated such subscripts and then
effectively ignored them.  Another side effect is that UPDATE-ing an
element or slice of an array value that is NULL now produces a non-null
result, namely an array containing just the assigned-to positions.
2004-06-09 19:08:20 +00:00
Tom Lane c541bb86e9 Infrastructure for I/O of composite types: arrange for the I/O routines
of a composite type to get that type's OID as their second parameter,
in place of typelem which is useless.  The actual changes are mostly
centralized in getTypeInputInfo and siblings, but I had to fix a few
places that were fetching pg_type.typelem for themselves instead of
using the lsyscache.c routines.  Also, I renamed all the related variables
from 'typelem' to 'typioparam' to discourage people from assuming that
they necessarily contain array element types.
2004-06-06 00:41:28 +00:00
Tom Lane c3a153afed Tweak palloc/repalloc to allow zero bytes to be requested, as per recent
proposal.  Eliminate several dozen now-unnecessary hacks to avoid palloc(0).
(It's likely there are more that I didn't find.)
2004-06-05 19:48:09 +00:00
Tom Lane 7eb2ff799e Support assignment to whole-row variables in plpgsql; also fix glitch
with using a trigger's NEW or OLD record as a whole-row variable in an
expression.  Fixes several long-standing complaints.
2004-06-04 02:37:06 +00:00
Tom Lane 0f059e1d13 Allow plpgsql to pass composite-type arguments (ie, whole-row variables)
into SQL expressions.  At present this only works usefully for variables
of named rowtypes, not RECORD variables, since the SQL parser can't infer
anything about datatypes from a RECORD Param.  Still, it's a step forward.
2004-06-04 00:07:52 +00:00
Neil Conway 72b6ad6313 Use the new List API function names throughout the backend, and disable the
list compatibility API by default. While doing this, I decided to keep
the llast() macro around and introduce llast_int() and llast_oid() variants.
2004-05-30 23:40:41 +00:00
Neil Conway d0b4399d81 Reimplement the linked list data structure used throughout the backend.
In the past, we used a 'Lispy' linked list implementation: a "list" was
merely a pointer to the head node of the list. The problem with that
design is that it makes lappend() and length() linear time. This patch
fixes that problem (and others) by maintaining a count of the list
length and a pointer to the tail node along with each head node pointer.
A "list" is now a pointer to a structure containing some meta-data
about the list; the head and tail pointers in that structure refer
to ListCell structures that maintain the actual linked list of nodes.

The function names of the list API have also been changed to, I hope,
be more logically consistent. By default, the old function names are
still available; they will be disabled-by-default once the rest of
the tree has been updated to use the new API names.
2004-05-26 04:41:50 +00:00
Tom Lane 2f63232d30 Promote row expressions to full-fledged citizens of the expression syntax,
rather than allowing them only in a few special cases as before.  In
particular you can now pass a ROW() construct to a function that accepts
a rowtype parameter.  Internal generation of RowExprs fixes a number of
corner cases that used to not work very well, such as referencing the
whole-row result of a JOIN or subquery.  This represents a further step in
the work I started a month or so back to make rowtype values into
first-class citizens.
2004-05-10 22:44:49 +00:00
Tom Lane 375369acd1 Replace TupleTableSlot convention for whole-row variables and function
results with tuples as ordinary varlena Datums.  This commit does not
in itself do much for us, except eliminate the horrid memory leak
associated with evaluation of whole-row variables.  However, it lays the
groundwork for allowing composite types as table columns, and perhaps
some other useful features as well.  Per my proposal of a few days ago.
2004-04-01 21:28:47 +00:00
Tom Lane 55f7c3300d Reimplement CASE val WHEN compval1 THEN ... WHEN compval2 THEN ... END
so that the 'val' is computed only once, per recent discussion.  The
speedup is not much when 'val' is just a simple variable, but could be
significant for larger expressions.  More importantly this avoids issues
with multiple evaluations of a volatile 'val', and it allows the CASE
expression to be reverse-listed in its original form by ruleutils.c.
2004-03-17 20:48:43 +00:00
Tom Lane 5ada9ef088 Teach plpgsql's lexer about dollar-quoted literals.
Andrew Dunstan, some help from Tom Lane.
2004-02-25 18:10:51 +00:00
Tom Lane 55fb172739 Don't crash when a rowtype argument to a plpgsql function is NULL.
Per report from Chris Campbell.
2004-02-24 01:44:33 +00:00
Tom Lane 391c3811a2 Rename SortMem and VacuumMem to work_mem and maintenance_work_mem.
Make btree index creation and initial validation of foreign-key constraints
use maintenance_work_mem rather than work_mem as their memory limit.
Add some code to guc.c to allow these variables to be referenced by their
old names in SHOW and SET commands, for backwards compatibility.
2004-02-03 17:34:04 +00:00
PostgreSQL Daemon 969685ad44 $Header: -> $PostgreSQL Changes ... 2003-11-29 19:52:15 +00:00
Tom Lane 04b40923d6 Add code to check that IF/WHILE/EXIT test expressions are boolean,
and try to coerce the values to boolean if not.  Per recent discussions.
2003-10-01 21:47:42 +00:00
Tom Lane 8b510838f6 Restructure plpgsql's caching of 'simple' expression evaluation trees
to be less dangerous, and often faster as well.  ExprState trees are
not kept across transaction boundaries; this eliminates problems with
resource leakage in failed transactions.  But by keeping them in a
per-transaction EState, we can safely arrange for a single ExprState
to be shared by all the expression evaluations done in a given plpgsql
function call.  (Formerly it seemed necessary to create and destroy an
ExprState for each exec_eval_simple_expr() call.)  This saves time in
any scenario where a plpgsql function executes more than one expression.
Seems to be about as fast as 7.3 for simple cases, and significantly
faster for functions that do a lot of calculations.
2003-09-28 23:37:45 +00:00
Tom Lane 2848dc5fea Make the world safe (more or less) for dropped columns in plpgsql rowtypes. 2003-09-25 23:02:12 +00:00
Bruce Momjian 089003fb46 pgindent run. 2003-08-04 00:43:34 +00:00
Tom Lane e7f3645171 Fix some localizability issues with existing errcontext() calls. 2003-07-27 18:38:26 +00:00
Tom Lane 3b04893ffc Error message editing in src/pl. The plpython module could use another
look ... I'm not real certain which errors are strictly internal and which
are likely to be provoked by users.
2003-07-25 23:37:31 +00:00
Tom Lane bee217924d Support expressions of the form 'scalar op ANY (array)' and
'scalar op ALL (array)', where the operator is applied between the
lefthand scalar and each element of the array.  The operator must
yield boolean; the result of the construct is the OR or AND of the
per-element results, respectively.

Original coding by Joe Conway, after an idea of Peter's.  Rewritten
by Tom to keep the implementation strictly separate from subqueries.
2003-06-29 00:33:44 +00:00
Tom Lane f690920a75 Infrastructure for upgraded error reporting mechanism. elog.c is
rewritten and the protocol is changed, but most elog calls are still
elog calls.  Also, we need to contemplate mechanisms for controlling
all this functionality --- eg, how much stuff should appear in the
postmaster log?  And what API should libpq expose for it?
2003-04-24 21:16:45 +00:00
Tom Lane 730840c9b6 First phase of work on array improvements. ARRAY[x,y,z] constructor
expressions, ARRAY(sub-SELECT) expressions, some array functions.
Polymorphic functions using ANYARRAY/ANYELEMENT argument and return
types.  Some regression tests in place, documentation is lacking.
Joe Conway, with some kibitzing from Tom Lane.
2003-04-08 23:20:04 +00:00
Bruce Momjian 54f7338fa1 This patch implements holdable cursors, following the proposal
(materialization into a tuple store) discussed on pgsql-hackers earlier.
I've updated the documentation and the regression tests.

Notes on the implementation:

- I needed to change the tuple store API slightly -- it assumes that it
won't be used to hold data across transaction boundaries, so the temp
files that it uses for on-disk storage are automatically reclaimed at
end-of-transaction. I added a flag to tuplestore_begin_heap() to control
this behavior. Is changing the tuple store API in this fashion OK?

- in order to store executor results in a tuple store, I added a new
CommandDest. This works well for the most part, with one exception: the
current DestFunction API doesn't provide enough information to allow the
Executor to store results into an arbitrary tuple store (where the
particular tuple store to use is chosen by the call site of
ExecutorRun). To workaround this, I've temporarily hacked up a solution
that works, but is not ideal: since the receiveTuple DestFunction is
passed the portal name, we can use that to lookup the Portal data
structure for the cursor and then use that to get at the tuple store the
Portal is using. This unnecessarily ties the Portal code with the
tupleReceiver code, but it works...

The proper fix for this is probably to change the DestFunction API --
Tom suggested passing the full QueryDesc to the receiveTuple function.
In that case, callers of ExecutorRun could "subclass" QueryDesc to add
any additional fields that their particular CommandDest needed to get
access to. This approach would work, but I'd like to think about it for
a little bit longer before deciding which route to go. In the mean time,
the code works fine, so I don't think a fix is urgent.

- (semi-related) I added a NO SCROLL keyword to DECLARE CURSOR, and
adjusted the behavior of SCROLL in accordance with the discussion on
-hackers.

- (unrelated) Cleaned up some SGML markup in sql.sgml, copy.sgml

Neil Conway
2003-03-27 16:51:29 +00:00
Tom Lane 2c19928301 plpgsql can assign to subscripted variables now, e.g.
x[42] := whatever;
The facility is pretty primitive because it doesn't do array slicing and
it has the same semantics as array update in SQL (array must already
be non-null, etc).  But it's a start.
2003-03-25 03:16:41 +00:00
Tom Lane 316c5cbfd3 Factor out duplicate code for computing values of PLpgSQL_datum items.
This is to help localize the changes needed for adding a new kind of
PLpgSQL_datum (like, say, an array element...)
2003-03-25 00:34:24 +00:00
Tom Lane aa60eecc37 Revise tuplestore and nodeMaterial so that we don't have to read the
entire contents of the subplan into the tuplestore before we can return
any tuples.  Instead, the tuplestore holds what we've already read, and
we fetch additional rows from the subplan as needed.  Random access to
the previously-read rows works with the tuplestore, and doesn't affect
the state of the partially-read subplan.  This is a step towards fixing
the problems with cursors over complex queries --- we don't want to
stick in Materialize nodes if they'll prevent quick startup for a cursor.
2003-03-09 02:19:13 +00:00
Tom Lane a1dbe521bc Repair memory leak introduced by recent change to make SPI return a
tupdesc even with zero tuples returned: some plpgsql routines assumed
they didn't need to do SPI_freetuptable() after retrieving no tuples.
2003-03-02 20:45:47 +00:00
Tom Lane 51972a9d5d COALESCE() and NULLIF() are now first-class expressions, not macros
that turn into CASE expressions.  They evaluate their arguments at most
once.  Patch by Kris Jurka, review and (very light) editorializing by me.
2003-02-16 02:30:39 +00:00
Tom Lane 3752e85bad Determine the set of constraints applied to a domain at executor
startup, not in the parser; this allows ALTER DOMAIN to work correctly
with domain constraint operations stored in rules.  Rod Taylor;
code review by Tom Lane.
2003-02-03 21:15:45 +00:00
Tom Lane a4482f4c4c Fix coredump problem in plpgsql's RETURN NEXT. When a SELECT INTO
that's selecting into a RECORD variable returns zero rows, make it
assign an all-nulls row to the RECORD; this is consistent with what
happens when the SELECT INTO target is not a RECORD.  In support of
this, tweak the SPI code so that a valid tuple descriptor is returned
even when a SPI select returns no rows.
2003-01-21 22:06:12 +00:00
Tom Lane 81ca457da8 Fix typo. 2002-12-17 15:45:01 +00:00
Tom Lane 5bab36e9f6 Revise executor APIs so that all per-query state structure is built in
a per-query memory context created by CreateExecutorState --- and destroyed
by FreeExecutorState.  This provides a final solution to the longstanding
problem of memory leaked by various ExecEndNode calls.
2002-12-15 16:17:59 +00:00
Tom Lane 3a4f7dde16 Phase 3 of read-only-plans project: ExecInitExpr now builds expression
execution state trees, and ExecEvalExpr takes an expression state tree
not an expression plan tree.  The plan tree is now read-only as far as
the executor is concerned.  Next step is to begin actually exploiting
this property.
2002-12-13 19:46:01 +00:00
Tom Lane a0bf885f9e Phase 2 of read-only-plans project: restructure expression-tree nodes
so that all executable expression nodes inherit from a common supertype
Expr.  This is somewhat of an exercise in code purity rather than any
real functional advance, but getting rid of the extra Oper or Func node
formerly used in each operator or function call should provide at least
a little space and speed improvement.
initdb forced by changes in stored-rules representation.
2002-12-12 15:49:42 +00:00
Tom Lane 1fd0c59e25 Phase 1 of read-only-plans project: cause executor state nodes to point
to plan nodes, not vice-versa.  All executor state nodes now inherit from
struct PlanState.  Copying of plan trees has been simplified by not
storing a list of SubPlans in Plan nodes (eliminating duplicate links).
The executor still needs such a list, but it can build it during
ExecutorStart since it has to scan the plan tree anyway.
No initdb forced since no stored-on-disk structures changed, but you
will need a full recompile because of node-numbering changes.
2002-12-05 15:50:39 +00:00
Tom Lane 2b7ec402c4 Code review for IS DISTINCT FROM patch. Fix incorrect constant-folding
logic, dissuade planner from thinking that 'x IS DISTINCT FROM 42' may
be optimized into 'x = 42' (!!), cause dependency on = operator to be
recorded correctly, minor other improvements.
2002-11-30 21:25:08 +00:00
Bruce Momjian 1b7f3cc02d This patch implements FOR EACH STATEMENT triggers, per my email to
-hackers a couple days ago.

Notes/caveats:

        - added regression tests for the new functionality, all
          regression tests pass on my machine

        - added pg_dump support

        - updated PL/PgSQL to support per-statement triggers; didn't
          look at the other procedural languages.

        - there's (even) more code duplication in trigger.c than there
          was previously. Any suggestions on how to refactor the
          ExecXXXTriggers() functions to reuse more code would be
          welcome -- I took a brief look at it, but couldn't see an
          easy way to do it (there are several subtly-different
          versions of the code in question)

        - updated the documentation. I also took the liberty of
          removing a big chunk of duplicated syntax documentation in
          the Programmer's Guide on triggers, and moving that
          information to the CREATE TRIGGER reference page.

        - I also included some spelling fixes and similar small
          cleanups I noticed while making the changes. If you'd like
          me to split those into a separate patch, let me know.

Neil Conway
2002-11-23 03:59:09 +00:00
Bruce Momjian 9b12ab6d5d Add new palloc0 call as merge of palloc and MemSet(0). 2002-11-13 00:39:48 +00:00
Bruce Momjian 75fee4535d Back out use of palloc0 in place if palloc/MemSet. Seems constant len
to MemSet is a performance boost.
2002-11-11 03:02:20 +00:00
Bruce Momjian 8fee9615cc Merge palloc()/MemSet(0) calls into a single palloc0() call. 2002-11-10 07:25:14 +00:00
Bruce Momjian cfd2728100 This patch makes a minor cleanup to the implementation of PERFORM in
PL/PgSQL. Previously, it had been bundled together with the assign
statement implementation, for some reason that wasn't clear to me
(they certainly don't share any code with one another). So I separated
them and made PERFORM a statement like any other. No changes in
functionality.

Along the way, I added some regression tests for PERFORM, added a
bunch more SGML tags to the PL/PgSQL docs, and removed an obsolete
comment relating to the implementation of RETURN NEXT.

Neil Conway
2002-11-10 00:35:58 +00:00
Tom Lane 4a67565b37 Fix within-function memory leaks in the various PLs' interfaces to
SPI_prepare: they all save the prepared plan into topCxt, and so the
procCxt copy that's actually returned by SPI_prepare ought to be freed.
Diagnosis and plpython fix by Nigel Andrews, followup for other PLs
by Tom Lane.
2002-10-19 22:10:58 +00:00
Tom Lane 52c9d25933 Be careful to include postgres.h *before* any system headers, to ensure
that the right flavors of largefile-related definitions are seen.
Most of these changes are probably unnecessary, but better safe than
sorry.
2002-09-05 00:43:07 +00:00
Bruce Momjian e50f52a074 pgindent run. 2002-09-04 20:31:48 +00:00
Tom Lane 470a1048ec plpgsql functions can return RECORD, per Neil Conway. 2002-09-01 16:28:06 +00:00
Tom Lane 7bacf2befa Add expected tuple descriptor to ReturnSetInfo information for table
functions, per suggestion from John Gray and Joe Conway.  Also, fix
plpgsql RETURN NEXT to verify that returned values match the expected
tupdesc.
2002-08-30 23:59:46 +00:00
Tom Lane e107f3a7e3 PL/pgSQL functions can return sets. Neil Conway's patch, modified so
that the functionality is available to anyone via ReturnSetInfo, rather
than hard-wiring it to PL/pgSQL.
2002-08-30 00:28:41 +00:00
Tom Lane 99fd5cbd41 FOUND patch was a bit over-enthusiastic: SQL commands that are not
INSERT, UPDATE, or DELETE shouldn't change FOUND.  IMHO anyway.
Also, try to make documentation a little clearer.
2002-08-29 04:12:03 +00:00
Tom Lane 976246cc7e The cstring datatype can now be copied, passed around, etc. The typlen
value '-2' is used to indicate a variable-width type whose width is
computed as strlen(datum)+1.  Everything that looks at typlen is updated
except for array support, which Joe Conway is working on; at the moment
it wouldn't work to try to create an array of cstring.
2002-08-24 15:00:47 +00:00
Bruce Momjian ebe1be1321 This patch improves the behavior of FOUND in PL/PgSQL. In Oracle,
FOUND is set whenever a SELECT INTO returns > 0 rows, *or* when an
INSERT, UPDATE, or DELETE affects > 0 rows. We implemented the first
part of this behavior, but not the second.

I also improved the documentation on the various situations in which
FOUND can be set (excluding inside FOR loops, which I still need to
think about), and added some regression tests for this behavior.

Neil Conway
2002-08-20 05:28:24 +00:00
Tom Lane 6918df16a5 plpgsql's PERFORM statement now sets FOUND depending on whether any
rows were returned by the performed query.  Per recent pgsql-general
discussion.
2002-06-24 23:12:06 +00:00
Tom Lane eb77ad55ed Re-allow CREATE AS (but not SELECT INTO) in EXECUTE. 2002-03-25 07:41:10 +00:00
Bruce Momjian 92288a1cf9 Change made to elog:
o  Change all current CVS messages of NOTICE to WARNING.  We were going
to do this just before 7.3 beta but it has to be done now, as you will
see below.

o Change current INFO messages that should be controlled by
client_min_messages to NOTICE.

o Force remaining INFO messages, like from EXPLAIN, VACUUM VERBOSE, etc.
to always go to the client.

o Remove INFO from the client_min_messages options and add NOTICE.

Seems we do need three non-ERROR elog levels to handle the various
behaviors we need for these messages.

Regression passed.
2002-03-06 06:10:59 +00:00
Tom Lane 29e3ef0fe9 Use quote-marks to try to clarify a plpgsql error message, per
gripe from Dan Langille.
2002-02-26 00:00:08 +00:00
Tom Lane 4be20187ab Fix some problems in new plpgsql cursor operations, found while trying
to reverse-engineer documentation for them.
2001-11-15 23:31:09 +00:00
Tom Lane 1c2d2dbb67 Give a more intelligible and useful error message for SELECT with no
destination in plpgsql.
2001-11-13 02:05:27 +00:00
Bruce Momjian 77e4fd889c Fix indenting for 'extern "C"' cases. 2001-11-08 20:37:52 +00:00
Tom Lane 0053cebea5 Fix coredump in plpgsql when trying to return a rowtype result.
Need to return a TupleTableSlot, not just a bare tuple.
2001-11-05 19:41:56 +00:00
Bruce Momjian b81844b173 pgindent run on all C files. Java run to follow. initdb/regression
tests pass.
2001-10-25 05:50:21 +00:00