+ outer transaction. For more
about that see
linkend="plpgsql-error-trapping">.
The default value is evaluated every time the block is entered. So,
- for example, assigning 'now' to a variable of type
+ for example, assigning now() to a variable of type
timestamp causes the variable to have the
time of the current function call, not the time when the function was
precompiled.
$n
parameter names for increased readability. Either the alias or the
numeric identifier can then be used to refer to the parameter value.
+
+
There are two ways to create an alias. The preferred way is to give a
name to the parameter in the CREATE FUNCTION command,
for example:
All expressions used in
PL/pgSQL
statements are processed using the server's regular
-
SQL executor. Expressions that appear to
- contain constants may in fact require run-time evaluation
- (e.g., 'now' for the timestamp
- type) so it is impossible for the
-
PL/pgSQL parser to identify real
- constant values other than the key word NULL>. All expressions are
- evaluated internally by executing a query
+
SQL executor. In effect, a query like
SELECT expression
-
using the SPI manager. For evaluation,
+
is executed using the SPI manager. Before evaluation,
occurrences of
PL/pgSQL variable
identifiers are replaced by parameters, and the actual values from
the variables are passed to the executor in the parameter array.
and can use its full power.
+ The INTO> clause can appear almost anywhere in the
+ SELECT statement. Customarily it is written
+ either just after SELECT> as shown above, or
+ just before FROM> — that is, either just before
+ or just after the list of select_expressions.
+
+
If the query returns zero rows, null values are assigned to the
target(s). If the query returns multiple rows, the first
- The INTO> clause can appear almost anywhere in the SELECT
- statement.
-
-
- You can use FOUND immediately after a SELECT
- INTO statement to determine whether the assignment was successful
- (that is, at least one row was was returned by the query). For example:
+ You can check the special FOUND variable (see
+ ) after a
+ SELECT INTO statement to determine whether the
+ assignment was successful, that is, at least one row was was returned by
+ the query. For example:
SELECT INTO myrec * FROM emp WHERE empname = myname;
be inserted in the command string as it is constructed.
- When working with dynamic commands you will often have to handle escaping
- of single quotes. The recommended method for quoting fixed text in your
- function body is dollar quoting. If you have legacy code that does
- not use dollar quoting, please refer to the
- overview in , which can save you
- some effort when translating said code to a more reasonable scheme.
-
-
Unlike all other commands in
PL/pgSQL>, a command
run by an EXECUTE statement is not prepared
and saved just once during the life of the session. Instead, the
command is prepared each time the statement is run. The command
string can be dynamically created within the function to perform
- actions on variable tables and columns.
+ actions on different tables and columns.
+ When working with dynamic commands you will often have to handle escaping
+ of single quotes. The recommended method for quoting fixed text in your
+ function body is dollar quoting. (If you have legacy code that does
+ not use dollar quoting, please refer to the
+ overview in , which can save you
+ some effort when translating said code to a more reasonable scheme.)
+
+
+ Dynamic values that are to be inserted into the constructed
+ query require special handling since they might themselves contain
+ quote characters.
An example (this assumes that you are using dollar quoting for the
function as a whole, so the quote marks need not be doubled):
all three variants of the FOR> statement (integer
FOR> loops, record-set FOR> loops, and
dynamic record-set FOR>
- loops). FOUND is only set when the
- FOR> loop exits: inside the execution of the loop,
+ loops). FOUND is set this way when the
+ FOR> loop exits; inside the execution of the loop,
FOUND is not modified by the
FOR> statement, although it may be changed by the
execution of other statements within the loop body.
- FOUND is a local variable; any changes
- to it affect only the current
PL/pgSQL
- function.
+
+ FOUND is a local variable within each
+
PL/pgSQL function; so any changes
+ to it affect only the current function.
SELECT * FROM some_func();
- That is, the function is used as a table source in a FROM
- clause.
+ That is, the function must be used as a table source in a
+ FROM clause.
RETURN NEXT does not actually return from the
- function; it simply saves away the value of the expression (or
- record or row variable, as appropriate for the data type being
- returned). Execution then continues with the next statement in
+ function; it simply saves away the value of the expression.
+ Execution then continues with the next statement in
the
PL/pgSQL> function. As successive
RETURN NEXT commands are executed, the result
set is built up. A final RETURN, which should
BEGIN
-- some computations
IF stocks > 100000 THEN
- EXIT; -- invalid; cannot use EXIT outside of LOOP
+ EXIT; -- causes exit from the BEGIN block
END IF;
END;
END LOOP;
The record or row variable is successively assigned each row
- resulting from the query (which must be a SELECT
- command) and the loop body is executed for each row. Here is an example:
+ resulting from the query (which must be a
+ SELECT command) and the loop body is executed for each
+ row. Here is an example:
CREATE FUNCTION cs_refresh_mviews() RETURNS integer AS $$
DECLARE
IN> and LOOP>. If ..> is not seen then
the loop is presumed to be a loop over rows. Mistyping the ..>
is thus likely to lead to a complaint along the lines of
- loop variable of loop over rows must be a record or row>,
+ loop variable of loop over rows must be a record or row variable>,
rather than the simple syntax error one might expect to get.
handler_statements
WHEN condition OR condition ... THEN
handler_statements
- ...
+ ...
END;
OPEN FOR SELECT
-OPEN unbound-cursor FOR SELECT ...;
+OPEN unbound_cursor FOR SELECT ...;
OPEN FOR EXECUTE
-OPEN unbound-cursor FOR EXECUTE query-string;
+OPEN unbound_cursor FOR EXECUTE query_string;
Opening a Bound Cursor
-OPEN bound-cursor ( argument_values ) ;
+OPEN bound_cursor ( argument_values ) ;
priority levels.
Whether messages of a particular priority are reported to the client,
written to the server log, or both is controlled by the
- <varname>log_min_messages> and
- <varname>client_min_messages> configuration
+ <xref linkend="guc-log-min-messages"> and
+ <xref linkend="guc-client-min-messages"> configuration
variables. See for more
information.
Another way to log changes to a table involves creating a new table that
- holds a row for each insert, update, delete that occurs. This approach can
- be thought of as auditing changes to a table.
-
-
+ holds a row for each insert, update, or delete that occurs. This approach
+ can be thought of as auditing changes to a table.
shows an example of an
audit trigger procedure in
PL/pgSQL.
salary integer
);
-CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
+CREATE OR REPLACE FUNCTION process_emp_audit() RETURNS TRIGGER AS $emp_audit$
BEGIN
--
-- Create a row in emp_audit to reflect the operation performed on emp,
INSERT INTO emp_audit SELECT 'I', now(), user, NEW.*;
RETURN NEW;
END IF;
+ RETURN NULL; -- result is ignored since this is an AFTER trigger
END;
$emp_audit$ language plpgsql;
-
CREATE TRIGGER emp_audit
AFTER INSERT OR UPDATE OR DELETE ON emp
- FOR EACH ROW EXECUTE PROCEDURE process_emp_audit()
-;
+ FOR EACH ROW EXECUTE PROCEDURE process_emp_audit();
PL/Tcl is a loadable procedural language for the
PostgreSQL database system
- that enables the Tcl language to be used to write functions and
+ language to be used to write functions and
trigger procedures.
The shared object for the
PL/Tcl> and PL/TclU> call handlers is
automatically built and installed in the
- library directory if Tcl/Tk support is specified
+ library directory if Tcl support is specified
in the configuration step of the installation procedure. To install
PL/Tcl> and/or PL/TclU> in a particular database, use the
createlang program, for example
To create a function in the
PL/Tcl> language, use the standard syntax:
-CREATE FUNCTION funcname
-(argument-types) RETURNS return-type AS $$
+CREATE FUNCTION funcname (argument-types) RETURNS return-type AS $$
# PL/Tcl function body
$$ LANGUAGE pltcl;
There is currently no support for returning a composite-type
- result value.
+ result value, nor for returning sets.
+
+
+
PL/Tcl> does not currently have full support for
+ domain types: it treats a domain the same as the underlying scalar
+ type. This means that constraints associated with the domain will
+ not be enforced. This is not an issue for function arguments, but
+ it is a hazard if you declare a
PL/Tcl> function
+ as returning a domain type.
The argument values supplied to a PL/Tcl function's code are simply
the input arguments converted to text form (just as if they had been
- displayed by a SELECT> statement). Conversely, the return>
+ displayed by a SELECT> statement). Conversely, the
+ return>
command will accept any string that is acceptable input format for
- the function's declared return type. So, the PL/Tcl programmer can
- manipulate data values as if they were just text.
+ the function's declared return type. So, within the PL/Tcl function,
+ all values are just text strings.
command. The global name of this variable is the function's internal
name, and the local name is GD>. It is recommended that
GD> be used
- for private data of a function. Use regular Tcl global variables
- only for values that you specifically intend to be shared among multiple
- functions.
+ for persistent private data of a function. Use regular Tcl global
+ variables only for values that you specifically intend to be shared among
+ multiple functions.
spi_exec -count n -array name command loop-body
- Executes an SQL command given as a string. An error in the command
- causes an error to be raised. Otherwise, the return value of spi_exec
- is the number of rows processed (selected, inserted, updated, or
- deleted) by the command, or zero if the command is a utility
- statement. In addition, if the command is a SELECT> statement, the
- values of the selected columns are placed in Tcl variables as
- described below.
+ Executes an SQL command given as a string. An error in the command
+ causes an error to be raised. Otherwise, the return value of spi_exec
+ is the number of rows processed (selected, inserted, updated, or
+ deleted) by the command, or zero if the command is a utility
+ statement. In addition, if the command is a SELECT> statement, the
+ values of the selected columns are placed in Tcl variables as
+ described below.
- The optional -count> value tells
- spi_exec the maximum number of rows
- to process in the command. The effect of this is comparable to
- setting up a query as a cursor and then saying FETCH n>>.
+ The optional -count> value tells
+ spi_exec the maximum number of rows
+ to process in the command. The effect of this is comparable to
+ setting up a query as a cursor and then saying FETCH n>>.
- If the command is a SELECT> statement, the values of the
- result columns are placed into Tcl variables named after the columns.
+ If the command is a SELECT> statement, the values of the
+ result columns are placed into Tcl variables named after the columns.
If the -array> option is given, the column values are
- instead stored into the named associative array, with the
- column names used as array indexes.
+ instead stored into the named associative array, with the
+ column names used as array indexes.
If the command is a SELECT> statement and no loop-body>
- script is given, then only the first row of results are stored into
- Tcl variables; remaining rows, if any, are ignored. No storing occurs
- if the
- query returns no rows. (This case can be detected by checking the
- result of spi_exec.) For example,
+ script is given, then only the first row of results are stored into
+ Tcl variables; remaining rows, if any, are ignored. No storing occurs
+ if the
+ query returns no rows. (This case can be detected by checking the
+ result of spi_exec.) For example,
spi_exec "SELECT count(*) AS cnt FROM pg_proc"
- will set the Tcl variable $cnt> to the number of rows in
- the pg_proc> system catalog.
+ will set the Tcl variable $cnt> to the number of rows in
+ the pg_proc> system catalog.
If the optional loop-body> argument is given, it is
- a piece of Tcl script that is executed once for each row in the
- query result. (loop-body> is ignored if the given
- command is not a SELECT>.) The values of the current row's columns
- are stored into Tcl variables before each iteration. For example,
+ a piece of Tcl script that is executed once for each row in the
+ query result. (loop-body> is ignored if the given
+ command is not a SELECT>.) The values of the current row's columns
+ are stored into Tcl variables before each iteration. For example,
spi_exec -array C "SELECT * FROM pg_class" {
}
- will print a log message for every row of pg_class>. This
- feature works similarly to other Tcl looping constructs; in
- particular continue> and break> work in the
- usual way inside the loop body.
+ will print a log message for every row of pg_class>. This
+ feature works similarly to other Tcl looping constructs; in
+ particular continue> and break> work in the
+ usual way inside the loop body.
If a column of a query result is null, the target
- variable for it is unset> rather than being set.
+ variable for it is unset> rather than being set.
spi_prepare query typelist
- Prepares and saves a query plan for later execution. The
- saved plan will be retained for the life of the current
- session.
preparing a query>in
- PL/Tcl>>
+ Prepares and saves a query plan for later execution. The
+ saved plan will be retained for the life of the current
+
session.
preparing a query>in
+ PL/Tcl>>
The query may use parameters, that is, placeholders for
- values to be supplied whenever the plan is actually executed.
- In the query string, refer to parameters
- by the symbols $1 ... $n.
- If the query uses parameters, the names of the parameter types
- must be given as a Tcl list. (Write an empty list for
- typelist if no parameters are used.)
- Presently, the parameter types must be identified by the internal
- type names shown in the system table pg_type>; for example int4> not
- integer>.
+ values to be supplied whenever the plan is actually executed.
+ In the query string, refer to parameters
+ by the symbols $1 ... $n.
+ If the query uses parameters, the names of the parameter types
+ must be given as a Tcl list. (Write an empty list for
+ typelist if no parameters are used.)
+ Presently, the parameter types must be identified by the internal
+ type names shown in the system table pg_type>; for example int4> not
+ integer>.
The return value from spi_prepare is a query ID
- to be used in subsequent calls to spi_execp. See
- spi_execp for an example.
+ to be used in subsequent calls to spi_execp. See
+ spi_execp for an example.
spi_execp> -count n -array name -nulls string queryid value-list loop-body
- Executes a query previously prepared with spi_prepare>.
- queryid is the ID returned by
- spi_prepare>. If the query references parameters,
- a value-list must be supplied. This
- is a Tcl list of actual values for the parameters. The list must be
- the same length as the parameter type list previously given to
- spi_prepare>. Omit value-list
- if the query has no parameters.
+ Executes a query previously prepared with spi_prepare>.
+ queryid is the ID returned by
+ spi_prepare>. If the query references parameters,
+ a value-list must be supplied. This
+ is a Tcl list of actual values for the parameters. The list must be
+ the same length as the parameter type list previously given to
+ spi_prepare>. Omit value-list
+ if the query has no parameters.
- The optional value for -nulls> is a string of spaces and
- 'n'> characters telling spi_execp
- which of the parameters are null values. If given, it must have exactly the
- same length as the value-list. If it
- is not given, all the parameter values are nonnull.
+ The optional value for -nulls> is a string of spaces and
+ 'n'> characters telling spi_execp
+ which of the parameters are null values. If given, it must have exactly the
+ same length as the value-list. If it
+ is not given, all the parameter values are nonnull.
Except for the way in which the query and its parameters are specified,
- spi_execp> works just like spi_exec>.
+ spi_execp> works just like spi_exec>.
The -count>, -array>, and
- loop-body options are the same,
- and so is the result value.
+ loop-body options are the same,
+ and so is the result value.
- Here's an example of a PL/Tcl function using a prepared plan:
+ Here's an example of a PL/Tcl function using a prepared plan:
CREATE FUNCTION t1_count(integer, integer) RETURNS integer AS $$
spi_lastoid>
- Returns the OID of the row inserted by the last
- spi_exec> or spi_execp>,
- if the command was a single-row INSERT>. (If not, you get zero.)
+ Returns the OID of the row inserted by the last
+ spi_exec> or spi_execp>,
+ if the command was a single-row INSERT>. (If not, you get zero.)
quote> string
- Doubles all occurrences of single quote and backslash characters
- in the given string. This may be used to safely quote strings
- that are to be inserted into SQL commands given
- to spi_exec or
- spi_prepare.
- For example, think about an SQL command string like
+ Doubles all occurrences of single quote and backslash characters
+ in the given string. This may be used to safely quote strings
+ that are to be inserted into SQL commands given
+ to spi_exec or
+ spi_prepare.
+ For example, think about an SQL command string like
"SELECT '$val' AS ret"
- where the Tcl variable val> actually contains
- doesn't. This would result
- in the final command string
+ where the Tcl variable val> actually contains
+ doesn't. This would result
+ in the final command string
SELECT 'doesn't' AS ret
- which would cause a parse error during
- spi_exec or
- spi_prepare.
- To work properly, the submitted command should contain
+ which would cause a parse error during
+ spi_exec or
+ spi_prepare.
+ To work properly, the submitted command should contain
SELECT 'doesn''t' AS ret
- which can be formed in PL/Tcl using
+ which can be formed in PL/Tcl using
"SELECT '[ quote $val ]' AS ret"
One advantage of spi_execp is that you don't
- have to quote parameter values like this, since the parameters are never
- parsed as part of an SQL command string.
+ have to quote parameter values like this, since the parameters are never
+ parsed as part of an SQL command string.
Emits a log or error message. Possible levels are
DEBUG>, LOG>, INFO>,
NOTICE>, WARNING>, ERROR>, and
- FATAL>. Most simply emit the given message just like
- the elog> C function. ERROR>
+ FATAL>. ERROR>
raises an error condition; if this is not trapped by the surrounding
Tcl code, the error propagates out to the calling query, causing
the current transaction or subtransaction to be aborted. This
FATAL> aborts the transaction and causes the current
session to shut down. (There is probably no good reason to use
this error level in PL/Tcl functions, but it's provided for
- completeness.)
+ completeness.) The other levels only generate messages of different
+ priority levels.
+ Whether messages of a particular priority are reported to the client,
+ written to the server log, or both is controlled by the
+ and
+ configuration
+ variables. See for more
+ information.
$TG_name
- The name of the trigger from the CREATE TRIGGER statement.
-
+ The name of the trigger from the CREATE TRIGGER statement.
+
$TG_relid
- The object ID of the table that caused the trigger procedure
- to be invoked.
-
+ The object ID of the table that caused the trigger procedure
+ to be invoked.
+
$TG_relatts
- A Tcl list of the table column names, prefixed with an empty list
+ A Tcl list of the table column names, prefixed with an empty list
element. So looking up a column name in the list with
Tcl>'s
lsearch> command returns the element's number starting
- with 1 for the first column, the same way the columns are customarily
- numbered in
PostgreSQL. (Empty list
- elements also appear in the positions of columns that have been
- dropped, so that the attribute numbering is correct for columns
- to their right.)
-
+ with 1 for the first column, the same way the columns are customarily
+
numbered in
PostgreSQL. (Empty list
+ elements also appear in the positions of columns that have been
+ dropped, so that the attribute numbering is correct for columns
+ to their right.)
+
$TG_when
- The string BEFORE> or AFTER> depending on the
- type of trigger call.
-
+ The string BEFORE> or AFTER> depending on the
+ type of trigger call.
+
$TG_level
- The string ROW> or STATEMENT> depending on the
- type of trigger call.
-
+ The string ROW> or STATEMENT> depending on the
+ type of trigger call.
+
$TG_op
- The string INSERT>, UPDATE>, or
- DELETE> depending on the type of trigger call.
-
+ The string INSERT>, UPDATE>, or
+ DELETE> depending on the type of trigger call.
+
$NEW
- An associative array containing the values of the new table
- row for INSERT> or UPDATE> actions, or
- empty for DELETE>. The array is indexed by column
- name. Columns that are null will not appear in the array.
-
+ An associative array containing the values of the new table
+ row for INSERT> or UPDATE> actions, or
+ empty for DELETE>. The array is indexed by column
+ name. Columns that are null will not appear in the array.
+
$OLD
- An associative array containing the values of the old table
- row for UPDATE> or DELETE> actions, or
- empty for INSERT>. The array is indexed by column
- name. Columns that are null will not appear in the array.
-
+ An associative array containing the values of the old table
+ row for UPDATE> or DELETE> actions, or
+ empty for INSERT>. The array is indexed by column
+ name. Columns that are null will not appear in the array.
+
$args
- A Tcl list of the arguments to the procedure as given in the
- CREATE TRIGGER statement. These arguments are also accessible as
- $1 ... $n in the procedure body.
-
+ A Tcl list of the arguments to the procedure as given in the
+ CREATE TRIGGER statement. These arguments are also accessible as
+ $1 ... $n in the procedure body.
+
Modules and the unknown> command
- PL/Tcl has support for autoloading Tcl code when used.
- It recognizes a special table, pltcl_modules>, which
- is presumed to contain modules of Tcl code. If this table
- exists, the module unknown> is fetched from the table
- and loaded into the Tcl interpreter immediately after creating
- the interpreter.
+ PL/Tcl has support for autoloading Tcl code when used.
+ It recognizes a special table, pltcl_modules>, which
+ is presumed to contain modules of Tcl code. If this table
+ exists, the module unknown> is fetched from the table
+ and loaded into the Tcl interpreter immediately after creating
+ the interpreter.
While the unknown> module could actually contain any
- initialization script you need, it normally defines a Tcl
- unknown> procedure that is invoked whenever Tcl does
- not recognize an invoked procedure name.
PL/Tcl>'s standard version
- of this procedure tries to find a module in pltcl_modules>
- that will define the required procedure. If one is found, it is
- loaded into the interpreter, and then execution is allowed to
- proceed with the originally attempted procedure call. A
- secondary table pltcl_modfuncs> provides an index of
- which functions are defined by which modules, so that the lookup
- is reasonably quick.
+ initialization script you need, it normally defines a Tcl
+ unknown> procedure that is invoked whenever Tcl does
+
not recognize an invoked procedure name.
PL/Tcl>'s standard version
+ of this procedure tries to find a module in pltcl_modules>
+ that will define the required procedure. If one is found, it is
+ loaded into the interpreter, and then execution is allowed to
+ proceed with the originally attempted procedure call. A
+ secondary table pltcl_modfuncs> provides an index of
+ which functions are defined by which modules, so that the lookup
+ is reasonably quick.
The
PostgreSQL distribution includes
- support scripts to maintain these tables:
- pltcl_loadmod>, pltcl_listmod>,
- pltcl_delmod>, as well as source for the standard
- unknown> module in share/unknown.pltcl>. This module
- must be loaded
- into each database initially to support the autoloading mechanism.
+ support scripts to maintain these tables:
+ pltcl_loadmod>, pltcl_listmod>,
+ pltcl_delmod>, as well as source for the standard
+ unknown> module in share/unknown.pltcl>. This module
+ must be loaded
+ into each database initially to support the autoloading mechanism.
The tables pltcl_modules> and pltcl_modfuncs>
- must be readable by all, but it is wise to make them owned and
- writable only by the database administrator.
+ must be readable by all, but it is wise to make them owned and
+ writable only by the database administrator.
The available procedural languages provide various means to
- execute SQL commands from procedures. Some of these are based on or
- modelled after SPI, so this documentation might be of use for users
+ execute SQL commands from procedures. Most of these facilities are
+ based on SPI, so this documentation might be of use for users
of those languages as well.
- Note that if during the execution of a procedure the transaction is
- aborted because of an error in a command, then control will not be
- returned to your procedure. Rather, all work will be rolled back
- and the server will wait for the next command from the client. A
- related restriction is the inability to execute
- BEGIN, COMMIT, and
- ROLLBACK (transaction control statements) inside
- a procedure. Both of these restrictions will probably be changed in
- the future.
+ Note that if a command invoked via SPI fails, then control will not be
+ returned to your procedure. Rather, the
+ transaction or subtransaction in which your procedure executes will be
+ rolled back. (This may seem surprising given that the SPI functions mostly
+ have documented error-return conventions. Those conventions only apply
+ for errors detected within the SPI functions themselves, however.)
+ It is possible to recover control after an error by establishing your own
+ subtransaction surrounding SPI calls that might fail. This is not currently
+ documented because the mechanisms required are still in flux.
SPI, directly nested calls to
SPI_connect and
SPI_finish are forbidden.
+ (But see SPI_push and SPI_pop.)
SPI_push
- pushes SPI stack to allow recursive SPI usage
+ push SPI stack to allow recursive SPI usage
SPI_pop
- pops SPI stack to return from recursive SPI usage
+ pop SPI stack to return from recursive SPI usage
- You may pass multiple commands in one string, and the commands may
- be rewritten by rules. SPI_execute returns the
+ You may pass multiple commands in one string.
+ SPI_execute returns the
result for the command executed last. The
count
limit applies to each command separately, but it is not applied to
hidden commands generated by rules.
The plan returned by SPI_prepare can be used
- only in the current invocation of the procedure since
+ only in the current invocation of the procedure, since
SPI_finish frees memory allocated for a plan.
But a plan can be saved for longer using the function
SPI_saveplan.
SPI_getargcount
- returns the number of arguments needed by a plan
+ return the number of arguments needed by a plan
prepared by SPI_prepare
SPI_getargtypeid
-
returns the expected typeid for the specified argument of
+ return the data type OID for an argument of
a plan prepared by SPI_prepare
SPI_is_cursor_plan
- returns true if a plan
+ return true if a plan
prepared by SPI_prepare can be used with
SPI_cursor_open
SPI_execute_plan
- executes a plan prepared by SPI_prepare
+ execute a plan prepared by SPI_prepare
SPI_execp
- executes a plan in read/write mode
+ execute a plan in read/write mode
Description
- SPI_fname returns the column name of the
+ SPI_fname returns a copy of the column name of the
specified column. (You can use pfree to
release the copy of the name when you don't need it anymore.)
Description
- SPI_gettype returns the data type name of the
+ SPI_gettype returns a copy of the data type name of the
specified column. (You can use pfree to
release the copy of the name when you don't need it anymore.)
Description
- SPI_getrelname returns the name of the
+ SPI_getrelname returns a copy of the name of the
specified relation. (You can use pfree to
release the copy of the name when you don't need it anymore.)
object. SPI_palloc allocates memory in the
upper executor context
, that is, the memory context
that was current when SPI_connect was called,
- which is precisely the right context for return a value from your
+ which is precisely the right context for a value returned from your
procedure.
array of the numbers of the columns that are to be changed
- (count starts at 1)
+ (column numbers start at 1)
SPI_freetuple
- frees a row allocated in the upper executor context
+ free a row allocated in the upper executor context
Visibility of Data Changes
- The following two rules govern the visibility of data changes in
+ The following rules govern the visibility of data changes in
functions that use SPI (or any other C function):
During the execution of an SQL command, any data changes made by
- the command (or by function called by the command, including
- trigger functions) are invisible to the command. For
- example, in command
+ the command are invisible to the command itself. For
+ example, in
INSERT INTO a SELECT * FROM a;
(during the execution of C) or after C is done.
+
+
+ Commands executed via SPI inside a function called by an SQL command
+ (either an ordinary function or a trigger) follow one or the
+ other of the above rules depending on the read/write flag passed
+ to SPI. Commands executed in read-only mode follow the first
+ rule: they can't see changes of the calling command. Commands executed
+ in read-write mode follow the second rule: they can see all changes made
+ so far.
+
+
+
+
+ All standard procedural languages set the SPI read-write mode
+ depending on the volatility attribute of the function. Commands of
+ STABLE> and IMMUTABLE> functions are done in
+ read-only mode, while commands of VOLATILE> functions are
+ done in read-write mode. While authors of C functions are able to
+ violate this convention, it's unlikely to be a good idea to do so.
+
+
(This function uses call convention version 0, to make the example
- easier to understand. In real applications you should user the new
+ easier to understand. In real applications you should use the new
version 1 interface.)