-
-
Extending SQL: Functions
-
- As it turns out, part of defining a new type is the
- definition of functions that describe its behavior.
- Consequently, while it is possible to define a new
- function without defining a new type, the reverse is
- not true. We therefore describe how to add new functions
- to
Postgres before describing
- how to add new types.
- provides two types of functions: query language functions
- (functions written in
SQL and programming
- language functions (functions written in a compiled
- programming language such as
C.) Either kind
- of function can take a base type, a composite type or
- some combination as arguments (parameters). In addition,
- both kinds of functions can return a base type or
- a composite type. It's easier to define
SQL
- functions, so we'll start with those. Examples in this section
- can also be found in funcs.sql
- and funcs.c.
-
-
-
-
Query Language (SQL) Functions
-
-
-
SQL Functions on Base Types
-
- The simplest possible
SQL function has no arguments and
- simply returns a base type, such as
int4:
+
+
Extending SQL: Functions
+
+ As it turns out, part of defining a new type is the
+ definition of functions that describe its behavior.
+ Consequently, while it is possible to define a new
+ function without defining a new type, the reverse is
+ not true. We therefore describe how to add new functions
+ to
Postgres before describing
+ how to add new types.
+
+
+ provides three types of functions:
+
+
+
+ query language functions
+ (functions written in
SQL)
+
+
+
+ procedural language
+ functions (functions written in, for example, PLTCL or PLSQL)
+
+
+
+ programming
+ language functions (functions written in a compiled
+ programming language such as
C)
+
+
+
+
+ Every kind
+ of function can take a base type, a composite type or
+ some combination as arguments (parameters). In addition,
+ every kind of function can return a base type or
+ a composite type. It's easiest to define
SQL
+ functions, so we'll start with those. Examples in this section
+ can also be found in funcs.sql
+ and funcs.c.
+
+
+
+
Query Language (SQL) Functions
+
+ SQL functions execute an arbitrary list of SQL queries, returning
+ the results of the last query in the list. SQL functions in general
+ return sets. If their returntype is not specified as a
+ setof,
+ then an arbitrary element of the last query's result will be returned.
+
+
+ The body of a SQL function following AS
+ should be a list of queries separated by whitespace characters and
+ bracketed within quotation marks. Note that quotation marks used in
+ the queries must be escaped, by preceding them with two
+ backslashes.
+
+
+ Arguments to the SQL function may be referenced in the queries using
+ a $n syntax: $1 refers to the first argument, $2 to the second, and so
+ on. If an argument is complex, then a dot
+ notation (e.g. "$1.emp") may be
+ used to access attributes of the argument or
+ to invoke functions.
+
+
+
+
Examples
+
+ To illustrate a simple SQL function, consider the following,
+ which might be used to debit a bank account:
+
+create function TP1 (int4, float8) returns int4
+ as 'update BANK set balance = BANK.balance - $2
+ where BANK.acctountno = $1
+ select(x = 1)'
+ language 'sql';
+
+
+ A user could execute this function to debit account 17 by $100.00 as
+ follows:
+
+select (x = TP1( 17,100.0));
+
+
+
+ The following more interesting example takes a single argument of type
+ EMP, and retrieves multiple results:
+
+select function hobbies (EMP) returns set of HOBBIES
+ as 'select (HOBBIES.all) from HOBBIES
+ where $1.name = HOBBIES.person'
+ language 'sql';
+
+
+
+
+
+
SQL Functions on Base Types
+
+ The simplest possible
SQL function has no arguments and
+ simply returns a base type, such as
int4:
CREATE FUNCTION one() RETURNS int4
AS 'SELECT 1 as RESULT' LANGUAGE 'sql';
+-------+
|1 |
+-------+
-
-
-
+
+
Notice that we defined a target list for the function
(with the name RESULT), but the target list of the
query that invoked the function overrode the function's
target list. Hence, the result is labelled answer
instead of one.
-ara>
- It's almost as easy to define <Acronym>SQLcronym> functions
+ ara>
+ It's almost as easy to define <acronym>SQLcronym> functions
that take base types as arguments. In the example below, notice
how we refer to the arguments within the function as $1
- and $2.
-
+ and $2:
+
CREATE FUNCTION add_em(int4, int4) RETURNS int4
AS 'SELECT $1 + $2;' LANGUAGE 'sql';
+-------+
|3 |
+-------+
-isting>
-ara>
-
+ isting>
+ ara>
+
-ect2>
-
SQL Functions on Composite Typesitle>
+ ect2>
+
SQL Functions on Composite Typesitle>
When specifying functions with arguments of composite
types (such as EMP), we must not only specify which
argument we want (as we did above with $1 and $2) but
also the attributes of that argument. For example,
take the function double_salary that computes what your
- salary would be if it were doubled.
-
+ salary would be if it were doubled:
+
CREATE FUNCTION double_salary(EMP) RETURNS int4
AS 'SELECT $1.salary * 2 AS salary;' LANGUAGE 'sql';
+-----+-------+
|Sam | 2400 |
+-----+-------+
-isting>
-
+ isting>
+
Notice the use of the syntax $1.salary.
Before launching into the subject of functions that
return composite types, we must first introduce the
function notation for projecting attributes. The simple way
to explain this is that we can usually use the
- notation attribute(class) and class.attribute interchangably.
-
+ notation attribute(class) and class.attribute interchangably:
+
--
-- this is the same as:
-- SELECT EMP.name AS youngster FROM EMP WHERE EMP.age < 30
+----------+
|Sam |
+----------+
-isting>
-
+ isting>
+
As we shall see, however, this is not always the case.
This function notation is important when we want to use
a function that returns a single instance. We do this
by assembling the entire instance within the function,
attribute by attribute. This is an example of a function
that returns a single EMP instance:
-
+
CREATE FUNCTION new_emp() RETURNS EMP
AS 'SELECT \'None\'::text AS name,
1000 AS salary,
25 AS age,
\'(2,2)\'::point AS cubicle'
LANGUAGE 'sql';
-
-
-
+
+
In this case we have specified each of the attributes
with a constant value, but any computation or expression
could have been substituted for these constants.
Defining a function like this can be tricky. Some of
the more important caveats are as follows:
-
-
-
-
- The target list order must be exactly the same as
- that in which the attributes appear in the CREATE
- TABLE statement (or when you execute a .* query).
-
-
-
-You must typecast the expressions (using ::) very carefully
-or you will see the following error:
-
- WARN::function declared to return type EMP does not retrieve (EMP.*)
-
-
-
-
-When calling a function that returns an instance, we
+
+
+
+ The target list order must be exactly the same as
+ that in which the attributes appear in the CREATE
+ TABLE statement (or when you execute a .* query).
+
+
+
+ You must typecast the expressions (using ::) very carefully
+ or you will see the following error:
+
+
+WARN::function declared to return type EMP does not retrieve (EMP.*)
+
+
+
+
+
+ When calling a function that returns an instance, we
cannot retrieve the entire instance. We must either
project an attribute out of the instance or pass the
entire instance into another function.
+
SELECT name(new_emp()) AS nobody;
+-------+
+-------+
|None |
+-------+
-isting>
-ara>
- ListItem>
-tem>
-The reason why, in general, we must use the function
+ isting>
+ ara>
+ listitem>
+ tem>
+ The reason why, in general, we must use the function
syntax for projecting attributes of function return
values is that the parser just doesn't understand
the other (dot) syntax for projection when combined
with function calls.
-
+
SELECT new_emp().name AS nobody;
WARN:parser: syntax error at or near "."
-isting>
-ara>
- ListItem>
-ist>
-
- Any collection of commands in the <Acronym>SQLcronym> query
+ isting>
+ ara>
+ listitem>
+ ist>
+
+ Any collection of commands in the <acronym>SQLcronym> query
language can be packaged together and defined as a function.
- The commands can include updates (i.e., <Acronym>insertcronym>,
- <
Acronym>update and deletecronym>) as well
- as <Acronym>selectcronym> queries. However, the final command
- must be a <Acronym>selectcronym> that returns whatever is
+ The commands can include updates (i.e., <acronym>insertcronym>,
+ <
acronym>update and deletecronym>) as well
+ as <acronym>selectcronym> queries. However, the final command
+ must be a <acronym>selectcronym> that returns whatever is
specified as the function's returntype.
-
+
CREATE FUNCTION clean_EMP () RETURNS int4
AS 'DELETE FROM EMP WHERE EMP.salary <= 0;
SELECT 1 AS ignore_this'
|1 |
+--+
-
-
-
-
+
+
+
+
+
+
+
Procedural Language Functions
+
+ Procedural languages aren't built into Postgres. They are offered
+ by loadable modules. Please refer to the documentation for the
+ PL in question for details about the syntax and how the AS
+ clause is interpreted by the PL handler.
+
-
-
Programming Language Functions
+ There are two procedural languages available with the standard
+
Postgres distribution (PLTCL and PLSQL), and other
+ languages can be defined.
+ Refer to for
+ more information.
+
+
->
-Programming Language Functions on Base Typesitle>
+ >
+ Internal Functionsitle>
- Internally,
Postgres regards a
+ Internal functions are functions written in C which have been statically
+ linked into the
Postgres backend
+ process. The AS
+ clause gives the C-language name of the function, which need not be the
+ same as the name being declared for SQL use.
+ (For reasons of backwards compatibility, an empty AS
+ string is accepted as meaning that the C-language function name is the
+ same as the SQL name.) Normally, all internal functions present in the
+ backend are declared as SQL functions during database initialization,
+ but a user could use CREATE FUNCTION
+ to create additional alias names for an internal function.
+
+
+
+
+
Compiled (C) Language Functions
+
+ Functions written in C can be defined to Postgres, which will dynamically
+ load them into its address space. The AS
+ clause gives the full path name of the object file that contains the
+ function. This file is loaded either using
+ load(l)
+ or automatically the first time the function is necessary for
+ execution. Repeated execution of a function will cause negligible
+ additional overhead, as the function will remain in a main memory
+ cache.
+
+
+ The string which specifies the object file (the string in the AS clause)
+ should be the full path
+ of the object code file for the function, bracketed by quotation
+ marks. (
Postgres will not compile a
+ function automatically; it must
+ be compiled before it is used in a CREATE FUNCTION
+ command. See below for additional information.)
+
+
+
+
C Language Functions on Base Types
+
+ The following table gives the C type required for parameters in the C
+ functions that will be loaded into Postgres. The "Defined In"
+ column gives the actual header file (in the
+ .../src/backend/
+ directory) that the equivalent C type is defined. However, if you
+ include utils/builtins.h,
+ these files will automatically be
+ included.
+
+
+
Equivalent C Types
+ for Built-In
Postgres Types
+ Equivalent C Types
+
+
+ |
+
+ Built-In Type
+
+
+ C Type
+
+
+ Defined In
+
+
+
+
+ |
+ abstime
+ AbsoluteTime
+ utils/nabstime.h
+
+ |
+ bool
+ bool
+ include/c.h
+
+ |
+ box
+ (BOX *)
+ utils/geo-decls.h
+
+ |
+ bytea
+ (bytea *)
+ include/postgres.h
+
+ |
+ char
+ char
+ N/A
+
+ |
+ cid
+ CID
+ include/postgres.h
+
+ |
+ datetime
+ (DateTime *)
+ include/c.h or include/postgres.h
+
+ |
+ int2
+ int2
+ include/postgres.h
+
+ |
+ int28
+ (int28 *)
+ include/postgres.h
+
+ |
+ int4
+ int4
+ include/postgres.h
+
+ |
+ float4
+ float32 or (float4 *)
+ include/c.h or include/postgres.h
+
+ |
+ float8
+ float64 or (float8 *)
+ include/c.h or include/postgres.h
+
+ |
+ lseg
+ (LSEG *)
+ include/geo-decls.h
+
+ |
+ name
+ (Name)
+ include/postgres.h
+
+ |
+ oid
+ oid
+ include/postgres.h
+
+ |
+ oid8
+ (oid8 *)
+ include/postgres.h
+
+ |
+ path
+ (PATH *)
+ utils/geo-decls.h
+
+ |
+ point
+ (POINT *)
+ utils/geo-decls.h
+
+ |
+ regproc
+ regproc or REGPROC
+ include/postgres.h
+
+ |
+ reltime
+ RelativeTime
+ utils/nabstime.h
+
+ |
+ text
+ (text *)
+ include/postgres.h
+
+ |
+ tid
+ ItemPointer
+ storage/itemptr.h
+
+ |
+ timespan
+ (TimeSpan *)
+ include/c.h or include/postgres.h
+
+ |
+ tinterval
+ TimeInterval
+ utils/nabstime.h
+
+ |
+ uint2
+ uint16
+ include/c.h
+
+ |
+ uint4
+ uint32
+ include/c.h
+
+ |
+ xid
+ (XID *)
+ include/postgres.h
+
+
+
+
+
+
+ Internally,
Postgres regards a
base type as a "blob of memory." The user-defined
functions that you define over a type in turn define the
- way that <ProductName>Postgresame> can operate
- on it. That is, <ProductName>Postgresame> will
+ way that <productname>Postgresame> can operate
+ on it. That is, <productname>Postgresame> will
only store and retrieve the data from disk and use your
user-defined functions to input, process, and output the data.
Base types can have one of three internal formats:
-
-
pass by value, fixed-length
-
-
pass by reference, fixed-length
-
-
pass by reference, variable-length
-
-
-
-
+
+
+
+ pass by value, fixed-length
+
+
+
+ pass by reference, fixed-length
+
+
+
+ pass by reference, variable-length
+
+
+
+
+
By-value types can only be 1, 2 or 4 bytes in length
(even if your computer supports by-value types of other
- sizes). <ProductName>Postgresame> itself
+ sizes). <productname>Postgresame> itself
only passes integer types by value. You should be careful
to define your types such that they will be the same
size (in bytes) on all architectures. For example, the
- <Acronym>longcronym> type is dangerous because it
+ <acronym>longcronym> type is dangerous because it
is 4 bytes on some machines and 8 bytes on others, whereas
- <Acronym>intcronym> type is 4 bytes on most
- <Acronym>UNIXcronym> machines (though not on most
+ <acronym>intcronym> type is 4 bytes on most
+ <acronym>UNIXcronym> machines (though not on most
personal computers). A reasonable implementation of
- the <
Acronym>int4 type on UNIXcronym>
+ the <
acronym>int4 type on UNIXcronym>
machines might be:
- /* 4-byte integer, passed by value */
- typedef int int4;
-isting>
-ara>
+/* 4-byte integer, passed by value */
+typedef int int4;
+ isting>
+ ara>
On the other hand, fixed-length types of any size may
be passed by-reference. For example, here is a sample
- implementation of a <ProductName>Postgresame> type:
+ implementation of a <productname>Postgresame> type:
- /* 16-byte structure, passed by reference */
- typedef struct
- {
- double x, y;
- } Point;
-isting>
-ara>
-
+/* 16-byte structure, passed by reference */
+typedef struct
+{
+ double x, y;
+} Point;
+ isting>
+ ara>
+
Only pointers to such types can be used when passing
- them in and out of <ProductName>Postgresame> functions.
+ them in and out of <productname>Postgresame> functions.
Finally, all variable-length types must also be passed
by reference. All variable-length types must begin
with a length field of exactly 4 bytes, and all data to
length field is the total length of the structure
(i.e., it includes the size of the length field
itself). We can define the text type as follows:
-
-
- typedef struct {
- int4 length;
- char data[1];
- } text;
-
-
-
+
+typedef struct {
+ int4 length;
+ char data[1];
+} text;
+
+
+
Obviously, the data field is not long enough to hold
- all possible strings -- it's impossible to declare such
- a structure in <Acronym>Ccronym>. When manipulating
+ all possible strings; it's impossible to declare such
+ a structure in <acronym>Ccronym>. When manipulating
variable-length types, we must be careful to allocate
the correct amount of memory and initialize the length field.
For example, if we wanted to store 40 bytes in a text
structure, we might use a code fragment like this:
- #include "postgres.h"
- ...
- char buffer[40]; /* our source data */
- ...
- text *destination = (text *) palloc(VARHDRSZ + 40);
- destination->length = VARHDRSZ + 40;
- memmove(destination->data, buffer, 40);
- ...
-
-
+#include "postgres.h"
+...
+char buffer[40]; /* our source data */
+...
+text *destination = (text *) palloc(VARHDRSZ + 40);
+destination->length = VARHDRSZ + 40;
+memmove(destination->data, buffer, 40);
+...
+
+
+
Now that we've gone over all of the possible structures
for base types, we can show some examples of real functions.
- Suppose funcs.c look like:
+ Suppose funcs.c look like:
+
#include <string.h>
#include "postgres.h"
strncat(VARDATA(new_text), VARDATA(arg2), VARSIZE(arg2)-VARHDRSZ);
return (new_text);
}
-isting>
-ara>
+ isting>
+ ara>
- On <Acronym>OSF/1cronym> we would type:
+ On <acronym>OSF/1cronym> we would type:
CREATE FUNCTION add_one(int4) RETURNS int4
- AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
+ AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
CREATE FUNCTION makepoint(point, point) RETURNS point
- AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
+ AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
CREATE FUNCTION concat_text(text, text) RETURNS text
- AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
+ AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
CREATE FUNCTION copytext(text) RETURNS text
- AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
-isting>
-ara>
+ AS 'PGROOT/tutorial/funcs.so' LANGUAGE 'c';
+ isting>
+ ara>
On other systems, we might have to make the filename
end in .sl (to indicate that it's a shared library).
-ara>
-ect2>
+ ara>
+ ect2>
-ect2>
-Programming Language Functions on Composite Typesitle>
+ ect2>
+ C Language Functions on Composite Typesitle>
Composite types do not have a fixed layout like C
structures. Instances of a composite type may contain
null fields. In addition, composite types that are
part of an inheritance hierarchy may have different
fields than other members of the same inheritance hierarchy.
- Therefore, <ProductName>Postgresame> provides
+ Therefore, <productname>Postgresame> provides
a procedural interface for accessing fields of composite types
- from C. As <ProductName>Postgresame> processes
+ from C. As <productname>Postgresame> processes
a set of instances, each instance will be passed into your
- function as an opaque structure of type <Acronym>TUPLEcronym>.
+ function as an opaque structure of type <acronym>TUPLEcronym>.
Suppose we want to write a function to answer the query
+
* SELECT name, c_overpaid(EMP, 1500) AS overpaid
FROM EMP
WHERE name = 'Bill' or name = 'Sam';
-
+
+
In the query above, we can define c_overpaid as:
#include "postgres.h"
#include "executor/executor.h" /* for GetAttributeByName() */
return (false);
return(salary > limit);
}
-isting>
-ara>
+ isting>
+ ara>
- <Acronym>GetAttributeByNamecronym> is the
- <ProductName>Postgresame> system function that
+ <acronym>GetAttributeByNamecronym> is the
+ <productname>Postgresame> system function that
returns attributes out of the current instance. It has
three arguments: the argument of type TUPLE passed into
the function, the name of the desired attribute, and a
return parameter that describes whether the attribute
- is null. <Acronym>GetAttributeByNamecronym> will
+ is null. <acronym>GetAttributeByNamecronym> will
align data properly so you can cast its return value to
the desired type. For example, if you have an attribute
- name which is of the type name, the <Acronym>GetAttributeByNamecronym>
+ name which is of the type name, the <acronym>GetAttributeByNamecronym>
call would look like:
+
char *str;
...
str = (char *) GetAttributeByName(t, "name", &isnull)
-isting>
-ara>
+ isting>
+ ara>
- The following query lets <ProductName>Postgresame>
+ The following query lets <productname>Postgresame>
know about the c_overpaid function:
+
* CREATE FUNCTION c_overpaid(EMP, int4) RETURNS bool
- AS 'PGROOT/tutorial/obj/funcs.so' LANGUAGE 'c';
-isting>
-ara>
+ AS 'PGROOT/tutorial/obj/funcs.so' LANGUAGE 'c';
+ isting>
+ ara>
While there are ways to construct new instances or modify
existing instances from within a C function, these
are far too complex to discuss in this manual.
-ara>
-ect2>
+ ara>
+ ect2>
-ect2>
-Caveatsitle>
+ ect2>
+ Writing Codeitle>
We now turn to the more difficult task of writing
programming language functions. Be warned: this section
of the manual will not make you a programmer. You must
- have a good understanding of <Acronym>Ccronym>
+ have a good understanding of <acronym>Ccronym>
(including the use of pointers and the malloc memory manager)
- before trying to write <Acronym>Ccronym> functions for
- use with <ProductName>Postgresame>. While it may
+ before trying to write <acronym>Ccronym> functions for
+ use with <productname>Postgresame>. While it may
be possible to load functions written in languages other
- than <
Acronym>C into Postgresame>,
+ than <
acronym>C into Postgresame>,
this is often difficult (when it is possible at all)
- because other languages, such as
FORTRAN
- and
Pascal often do not follow the same
- "calling convention" as
C. That is, other
+ because other languages, such as
FORTRAN
+ and
Pascal often do not follow the same
+ calling convention
languages do not pass argument and return values
between functions in the same way. For this reason, we
will assume that your programming language functions
- The basic rules for building
C functions
+
+
+ C functions with base type arguments can be written in a
+ straightforward fashion. The C equivalents of built-in Postgres types
+ are accessible in a C file if
+ PGROOT/src/backend/utils/builtins.h
+ is included as a header file. This can be achieved by having
+
+#include <utils/builtins.h>
+
+
+ at the top of the C source file.
+
+
+ The basic rules for building
C functions
are as follows:
-
-
- Most of the header (include) files for
- should already be installed in
- PGROOT/include (see Figure 2).
- You should always include
-
- -I$PGROOT/include
-
- on your cc command lines. Sometimes, you may
- find that you require header files that are in
- the server source itself (i.e., you need a file
- we neglected to install in include). In those
- cases you may need to add one or more of
- -I$PGROOT/src/backend
- -I$PGROOT/src/backend/include
- -I$PGROOT/src/backend/port/<PORTNAME>
- -I$PGROOT/src/backend/obj
-
- (where <PORTNAME> is the name of the port, e.g.,
- alpha or sparc).
-
-
-
-
When allocating memory, use the
- routines palloc and pfree instead of the
- corresponding
C library routines
- malloc and free.
- The memory allocated by palloc will be freed
- automatically at the end of each transaction,
- preventing memory leaks.
-
-
-
-
Always zero the bytes of your structures using
- memset or bzero. Several routines (such as the
- hash access method, hash join and the sort algorithm)
- compute functions of the raw bits contained in
- your structure. Even if you initialize all fields
- of your structure, there may be
- several bytes of alignment padding (holes in the
- structure) that may contain garbage values.
-
-
-
-
Most of the internal Postgres
- types are declared in postgres.h, so it's a good
- idea to always include that file as well. Including
- postgres.h will also include elog.h and palloc.h for you.
-
-
-
-
Compiling and loading your object code so that
- it can be dynamically loaded into
- always requires special flags. See Appendix A
- for a detailed explanation of how to do it for
- your particular operating system.
-
-
-
-
-
-
-
+
+
+ Most of the header (include) files for
+ should already be installed in
+ PGROOT/include (see Figure 2).
+ You should always include
+
+-I$PGROOT/include
+
+
+ on your cc command lines. Sometimes, you may
+ find that you require header files that are in
+ the server source itself (i.e., you need a file
+ we neglected to install in include). In those
+ cases you may need to add one or more of
+
+-I$PGROOT/src/backend
+-I$PGROOT/src/backend/include
+-I$PGROOT/src/backend/port/<PORTNAME>
+-I$PGROOT/src/backend/obj
+
+
+ (where <PORTNAME> is the name of the port, e.g.,
+ alpha or sparc).
+
+
+
+ When allocating memory, use the
+ routines palloc and pfree instead of the
+ corresponding
C library routines
+ malloc and free.
+ The memory allocated by palloc will be freed
+ automatically at the end of each transaction,
+ preventing memory leaks.
+
+
+
+ Always zero the bytes of your structures using
+ memset or bzero. Several routines (such as the
+ hash access method, hash join and the sort algorithm)
+ compute functions of the raw bits contained in
+ your structure. Even if you initialize all fields
+ of your structure, there may be
+ several bytes of alignment padding (holes in the
+ structure) that may contain garbage values.
+
+
+
+ Most of the internal
Postgres
+ types are declared in postgres.h,
+ so it's a good
+ idea to always include that file as well. Including
+ postgres.h will also include elog.h and palloc.h for you.
+
+
+
+ Compiling and loading your object code so that
+ it can be dynamically loaded into
+ always requires special flags.
+ See
+ for a detailed explanation of how to do it for
+ your particular operating system.
+
+
+
+
+
+
+
+
+
Function Overloading
+
+ More than one function may be defined with the same name, as long as
+ the arguments they take are different. In other words, function names
+ can be overloaded.
+ A function may also have the same name as an attribute. In the case
+ that there is an ambiguity between a function on a complex type and
+ an attribute of the complex type, the attribute will always be used.
+
+
+
+
Name Space Conflicts
+
+ CREATE FUNCTION can decouple a C language
+ function name from the name of the entry point. This is now the
+ preferred technique to accomplish function overloading.
+
+
+
+
Pre-v6.5
+
+ For functions written in C, the SQL name declared in
+ CREATE FUNCTION
+ must be exactly the same as the actual name of the function in the
+ C code (hence it must be a legal C function name).
+
+
+ There is a subtle implication of this restriction: while the
+ dynamic loading routines in most operating systems are more than
+ happy to allow you to load any number of shared libraries that
+ contain conflicting (identically-named) function names, they may
+ in fact botch the load in interesting ways. For example, if you
+ define a dynamically-loaded function that happens to have the
+ same name as a function built into Postgres, the DEC OSF/1 dynamic
+ loader causes Postgres to call the function within itself rather than
+ allowing Postgres to call your function. Hence, if you want your
+ function to be used on different architectures, we recommend that
+ you do not overload C function names.
+
+
+ There is a clever trick to get around the problem just described.
+ Since there is no problem overloading SQL functions, you can
+ define a set of C functions with different names and then define
+ a set of identically-named SQL function wrappers that take the
+ appropriate argument types and call the matching C function.
+
+
+ Another solution is not to use dynamic loading, but to link your
+ functions into the backend statically and declare them as INTERNAL
+ functions. Then, the functions must all have distinct C names but
+ they can be declared with the same SQL names (as long as their
+ argument types differ, of course). This way avoids the overhead of
+ an SQL wrapper function, at the cost of more effort to prepare a
+ custom backend executable.
+
+
+
+
+
+
-d="xplang">
-Procedural Languagesitle>
+ d="xplang">
+ Procedural Languagesitle>
-<Para>
+<para>
Beginning with the release of version 6.3,
- <ProductName>Postgresame> supports
+ <productname>Postgresame> supports
the definition of procedural languages.
In the case of a function or trigger
procedure defined in a procedural language, the database has
handler itself is a special programming language function
compiled into a shared object
and loaded on demand.
-Para>
+para>
-<Sect1>
-<Title>Installing Procedural Languagesitle>
+<sect1>
+<title>Installing Procedural Languagesitle>
-<Procedure>
- <Title>
+<procedure>
+ <title>
Procedural Language Installation
- Title>
+ title>
A procedural language is installed in the database in three steps.
- <Step Performance="Required">
- <Para>
+ <step performance="Required">
+ <para>
The shared object for the language handler
must be compiled and installed. By default the
handler for PL/pgSQL is built and installed into the
database library directory. If Tcl/Tk support is
configured in, the handler for PL/Tcl is also built
and installed in the same location.
- Para>
- <Para>
+ para>
+ <para>
Writing a handler for a new procedural language (PL)
is outside the scope of this manual.
- Para>
- Step>
- <Step Performance="Required">
- <Para>
+ para>
+ step>
+ <step performance="Required">
+ <para>
The handler must be declared with the command
- <ProgramListing>
- CREATE FUNCTION <Replaceable>handler_function_nameeplaceable> () RETURNS OPAQUE AS
- '<Filename>path-to-shared-objectilename>' LANGUAGE 'C';
- ProgramListing>
- The special return type of <Acronym>OPAQUEcronym> tells
+ <programlisting>
+ CREATE FUNCTION <replaceable>handler_function_nameeplaceable> () RETURNS OPAQUE AS
+ '<filename>path-to-shared-objectilename>' LANGUAGE 'C';
+ programlisting>
+ The special return type of <acronym>OPAQUEcronym> tells
the database, that this function does not return one of
the defined base- or composite types and is not directly usable
- in <Acronym>SQLcronym> statements.
- Para>
- Step>
- <Step Performance="Required">
- <Para>
+ in <acronym>SQLcronym> statements.
+ para>
+ step>
+ <step performance="Required">
+ <para>
The PL must be declared with the command
- <ProgramListing>
- CREATE [ TRUSTED ] PROCEDURAL LANGUAGE '<Replaceable>language-nameeplaceable>'
- HANDLER <Replaceable>handler_function_nameeplaceable>
- LANCOMPILER '<Replaceable>descriptioneplaceable>';
- ProgramListing>
- The optional keyword <Acronym>TRUSTEDcronym> tells
+ <programlisting>
+ CREATE [ TRUSTED ] PROCEDURAL LANGUAGE '<replaceable>language-nameeplaceable>'
+ HANDLER <replaceable>handler_function_nameeplaceable>
+ LANCOMPILER '<replaceable>descriptioneplaceable>';
+ programlisting>
+ The optional keyword <acronym>TRUSTEDcronym> tells
if ordinary database users that have no superuser
privileges can use this language to create functions
and trigger procedures. Since PL functions are
languages that don't gain access to database backends
internals or the filesystem. The languages PL/pgSQL and
PL/Tcl are known to be trusted.
- Para>
- Step>
-Procedure>
-
-<Procedure>
- <Title>Exampleitle>
- <Step Performance="Required">
- <Para>
+ para>
+ step>
+procedure>
+
+<procedure>
+ <title>Exampleitle>
+ <step performance="Required">
+ <para>
The following command tells the database where to find the
shared object for the PL/pgSQL languages call handler function.
- Para>
- <ProgramListing>
+ para>
+ <programlisting>
CREATE FUNCTION plpgsql_call_handler () RETURNS OPAQUE AS
'/usr/local/pgsql/lib/plpgsql.so' LANGUAGE 'C';
- ProgramListing>
- Step>
+ programlisting>
+ step>
- <Step Performance="Required">
- <Para>
+ <step performance="Required">
+ <para>
The command
- Para>
- <ProgramListing>
+ para>
+ <programlisting>
CREATE TRUSTED PROCEDURAL LANGUAGE 'plpgsql'
HANDLER plpgsql_call_handler
LANCOMPILER 'PL/pgSQL';
- ProgramListing>
- <Para>
+ programlisting>
+ <para>
then defines that the previously declared call handler
function should be invoked for functions and trigger procedures
where the language attribute is 'plpgsql'.
- Para>
- <Para>
+ para>
+ <para>
PL handler functions have a special call interface that is
different from regular C language functions. One of the arguments
- given to the handler is the object ID in the <FileName>pg_procame>
+ given to the handler is the object ID in the <filename>pg_procame>
tables entry for the function that should be executed.
The handler examines various system catalogs to analyze the
functions call arguments and it's return data type. The source
text of the functions body is found in the prosrc attribute of
- <FileName>pg_procame>.
+ <filename>pg_procame>.
Due to this, in contrast to C language functions, PL functions
can be overloaded like SQL language functions. There can be
multiple different PL functions having the same function name,
as long as the call arguments differ.
- Para>
- <Para>
- Procedural languages defined in the <FileName>template1ame>
+ para>
+ <para>
+ Procedural languages defined in the <filename>template1ame>
database are automatically defined in all subsequently created
databases. So the database administrator can decide which
languages are available by default.
- Para>
- Step>
-Procedure>
-Sect1>
+ para>
+ step>
+procedure>
+sect1>
-<Sect1>
-<Title>PL/pgSQLitle>
+<sect1>
+<title>PL/pgSQLitle>
-<Para>
+<para>
PL/pgSQL is a loadable procedural language for the
- <ProductName>Postgresame> database system.
-Para>
+ <productname>Postgresame> database system.
+para>
-<Para>
+<para>
This package was originally written by Jan Wieck.
-Para>
+para>
-<Sect2>
-<Title>Overviewitle>
+<sect2>
+<title>Overviewitle>
-<Para>
+<para>
The design goals of PL/pgSQL were to create a loadable procedural
language that
- <ItemizedList>
- <ListItem>
- <Para>
+ <itemizedlist>
+ <listitem>
+ <para>
can be used to create functions and trigger procedures,
- Para>
- ListItem>
- <ListItem>
- <Para>
- adds control structures to the <Acronym>SQLcronym> language,
- Para>
- ListItem>
- <ListItem>
- <Para>
+ para>
+ listitem>
+ <listitem>
+ <para>
+ adds control structures to the <acronym>SQLcronym> language,
+ para>
+ listitem>
+ <listitem>
+ <para>
can perform complex computations,
- Para>
- ListItem>
- <ListItem>
- <Para>
+ para>
+ listitem>
+ <listitem>
+ <para>
inherits all user defined types, functions and operators,
- Para>
- ListItem>
- <ListItem>
- <Para>
+ para>
+ listitem>
+ <listitem>
+ <para>
can be defined to be trusted by the server,
- Para>
- ListItem>
- <ListItem>
- <Para>
+ para>
+ listitem>
+ <listitem>
+ <para>
is easy to use.
- Para>
- ListItem>
- ItemizedList>
-Para>
-<Para>
+ para>
+ listitem>
+ itemizedlist>
+para>
+<para>
The PL/pgSQL call handler parses the functions source text and
produces an internal binary instruction tree on the first time, the
function is called by a backend. The produced bytecode is identified
in the call handler by the object ID of the function. This ensures,
that changing a function by a DROP/CREATE sequence will take effect
without establishing a new database connection.
-Para>
-<Para>
- For all expressions and <Acronym>SQLcronym> statements used in
+para>
+<para>
+ For all expressions and <acronym>SQLcronym> statements used in
the function, the PL/pgSQL bytecode interpreter creates a
prepared execution plan using the SPI managers SPI_prepare() and
SPI_saveplan() functions. This is done the first time, the individual
plans would be required, will only prepare and save those plans
that are really used during the entire lifetime of the database
connection.
-Para>
-<Para>
+para>
+<para>
Except for input-/output-conversion and calculation functions
for user defined types, anything that can be defined in C language
functions can also be done with PL/pgSQL. It is possible to
create complex conditional computation functions and later use
them to define operators or use them in functional indices.
-Para>
-Sect2>
+para>
+sect2>
-<Sect2>
-<Title>Descriptionitle>
+<sect2>
+<title>Descriptionitle>
-<Sect3>
-<Title>Structure of PL/pgSQLitle>
+<sect3>
+<title>Structure of PL/pgSQLitle>
-<Para>
+<para>
The PL/pgSQL language is case insensitive. All keywords and
identifiers can be used in mixed upper- and lowercase.
-Para>
-<Para>
+para>
+<para>
PL/pgSQL is a block oriented language. A block is defined as
-<ProgramListing>
+<programlisting>
[<<label>>]
[DECLARE
declarations]
BEGIN
statements
END;
-ProgramListing>
+programlisting>
There can be any number of subblocks in the statement section
of a block. Subblocks can be used to hide variables from outside a
declared in the declarations section preceding a block are
initialized to their default values every time the block is entered,
not only once per function call.
-Para>
+para>
-<Para>
+<para>
It is important not to misunderstand the meaning of BEGIN/END for
grouping statements in PL/pgSQL and the database commands for
transaction control. Functions and trigger procedures cannot
- start or commit transactions and <ProductName>Postgresame>
+ start or commit transactions and <productname>Postgresame>
does not have nested transactions.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Commentsitle>
+<sect3>
+<title>Commentsitle>
-<Para>
+<para>
There are two types of comments in PL/pgSQL. A double dash '--'
starts a comment that extends to the end of the line. A '/*'
starts a block comment that extends to the next occurence of '*/'.
Block comments cannot be nested, but double dash comments can be
enclosed into a block comment and a double dash can hide
the block comment delimiters '/*' and '*/'.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Declarationsitle>
+<sect3>
+<title>Declarationsitle>
-<Para>
+<para>
All variables, rows and records used in a block or it's
subblocks must be declared in the declarations section of a block
except for the loop variable of a FOR loop iterating over a range
of integer values. Parameters given to a PL/pgSQL function are
automatically declared with the usual identifiers $n.
The declarations have the following syntax:
-
-
-
-
-
-name [ CONSTANT ] type [ NOT NULL ] [ DEFAULT | := value ];
-
-
+
+
+
+
+
+name [ CONSTANT ]
+>typ> [ NOT NULL ] [ DEFAULT | :=
+ value ];
+
+
Declares a variable of the specified base type. If the variable
is declared as CONSTANT, the value cannot be changed. If NOT NULL
is specified, an assignment of a NULL value results in a runtime
error. Since the default value of all variables is the
- <Acronym>SQLcronym> NULL value, all variables declared as NOT NULL
+ <acronym>SQLcronym> NULL value, all variables declared as NOT NULL
must also have a default value specified.
-Para>
-<Para>
+para>
+<para>
The default value is evaluated ever time the function is called. So
- assigning '<Replaceable>noweplaceable>' to a variable of type
- <Replaceable>datetimeeplaceable> causes the variable to have the
+ assigning '<replaceable>noweplaceable>' to a variable of type
+ <replaceable>datetimeeplaceable> causes the variable to have the
time of the actual function call, not when the function was
precompiled into it's bytecode.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-<Replaceable>name classeplaceable>%ROWTYPE;
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+<replaceable>name classeplaceable>%ROWTYPE;
+term>
+<listitem>
+<para>
Declares a row with the structure of the given class. Class must be
an existing table- or viewname of the database. The fields of the row
are accessed in the dot notation. Parameters to a function can
attributes of a table row are accessible in the row, no Oid or other
system attributes (hence the row could be from a view and view rows
don't have useful system attributes).
-Para>
-<Para>
+para>
+<para>
The fields of the rowtype inherit the tables fieldsizes
or precision for char() etc. data types.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-<Replaceable>nameeplaceable> RECORD;
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+<replaceable>nameeplaceable> RECORD;
+term>
+<listitem>
+<para>
Records are similar to rowtypes, but they have no predefined structure.
They are used in selections and FOR loops to hold one actual
database row from a SELECT operation. One and the same record can be
used in different selections. Accessing a record or an attempt to assign
a value to a record field when there is no actual row in it results
in a runtime error.
-Para>
-<Para>
+para>
+<para>
The NEW and OLD rows in a trigger are given to the procedure as
- records. This is necessary because in <ProductName>Postgresame>
+ records. This is necessary because in <productname>Postgresame>
one and the same trigger procedure can handle trigger events for
different tables.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-<Replaceable>nameeplaceable> ALIAS FOR $n;
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+<replaceable>nameeplaceable> ALIAS FOR $n;
+term>
+<listitem>
+<para>
For better readability of the code it is possible to define an alias
for a positional parameter to a function.
-Para>
-<Para>
+para>
+<para>
This aliasing is required for composite types given as arguments to
a function. The dot notation $1.salary as in SQL functions is not
allowed in PL/pgSQL.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-RENAME <Replaceable>oldname TO newnameeplaceable>;
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+RENAME <replaceable>oldname TO newnameeplaceable>;
+term>
+<listitem>
+<para>
Change the name of a variable, record or row. This is useful
if NEW or OLD should be referenced by another name inside a
trigger procedure.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-VariableList>
-Sect3>
+variablelist>
+sect3>
-<Sect3>
-<Title>Data Typesitle>
+<sect3>
+<title>Data Typesitle>
-<Para>
+<para>
The type of a varible can be any of the existing basetypes of
- the database. <Replaceable>typeeplaceable> in the declarations
+ the database. <replaceable>typeeplaceable> in the declarations
section above is defined as:
-Para>
-<Para>
- <ItemizedList>
- <ListItem>
- <Para>
- <ProductName>Postgresame>-basetype
- Para>
- ListItem>
- <ListItem>
- <Para>
- <Replaceable>variableeplaceable>%TYPE
- Para>
- ListItem>
- <ListItem>
- <Para>
- <Replaceable>class.fieldeplaceable>%TYPE
- Para>
- ListItem>
- ItemizedList>
-Para>
-<Para>
- <Replaceable>variableeplaceable> is the name of a variable,
+para>
+<para>
+ <itemizedlist>
+ <listitem>
+ <para>
+ <productname>Postgresame>-basetype
+ para>
+ listitem>
+ <listitem>
+ <para>
+ <replaceable>variableeplaceable>%TYPE
+ para>
+ listitem>
+ <listitem>
+ <para>
+ <replaceable>class.fieldeplaceable>%TYPE
+ para>
+ listitem>
+ itemizedlist>
+para>
+<para>
+ <replaceable>variableeplaceable> is the name of a variable,
previously declared in the
same function, that is visible at this point.
-Para>
-<Para>
- <Replaceable>classeplaceable> is the name of an existing table
- or view where <Replaceable>fieldeplaceable> is the name of
+para>
+<para>
+ <replaceable>classeplaceable> is the name of an existing table
+ or view where <replaceable>fieldeplaceable> is the name of
an attribute.
-Para>
-<Para>
- Using the <Replaceable>class.fieldeplaceable>%TYPE
+para>
+<para>
+ Using the <replaceable>class.fieldeplaceable>%TYPE
causes PL/pgSQL to lookup the attributes definitions at the
first call to the funciton during the lifetime of a backend.
Have a table with a char(20) attribute and some PL/pgSQL functions
char(40) and restores the data. Ha - he forgot about the
funcitons. The computations inside them will truncate the values
to 20 characters. But if they are defined using the
- <Replaceable>class.fieldeplaceable>%TYPE
+ <replaceable>class.fieldeplaceable>%TYPE
declarations, they will automagically handle the size change or
if the new table schema defines the attribute as text type.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Expressionsitle>
+<sect3>
+<title>Expressionsitle>
-<Para>
+<para>
All expressions used in PL/pgSQL statements are processed using
the backends executor. Expressions which appear to contain
constants may in fact require run-time evaluation (e.g. 'now' for the
it is impossible for the PL/pgSQL parser
to identify real constant values other than the NULL keyword. All
expressions are evaluated internally by executing a query
- <ProgramListing>
- SELECT <Replaceable>expressioneplaceable>
- ProgramListing>
+ <programlisting>
+ SELECT <replaceable>expressioneplaceable>
+ programlisting>
using the SPI manager. In the expression, occurences of variable
identifiers are substituted by parameters and the actual values from
the variables are passed to the executor in the parameter array. All
expressions used in a PL/pgSQL function are only prepared and
saved once.
-Para>
-<Para>
+para>
+<para>
The type checking done by the
Postgres
main parser has some side
effects to the interpretation of constant values. In detail there
is a difference between what the two functions
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION logfunc1 (text) RETURNS datetime AS '
DECLARE
logtxt ALIAS FOR $1;
RETURN ''now'';
END;
' LANGUAGE 'plpgsql';
- ProgramListing>
+ programlisting>
and
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION logfunc2 (text) RETURNS datetime AS '
DECLARE
logtxt ALIAS FOR $1;
RETURN curtime;
END;
' LANGUAGE 'plpgsql';
- ProgramListing>
+ programlisting>
- do. In the case of logfunc1(), the <ProductName>Postgresame>
+ do. In the case of logfunc1(), the <productname>Postgresame>
main parser
knows when preparing the plan for the INSERT, that the string 'now'
should be interpreted as datetime because the target field of logtable
and this constant value is then used in all invocations of logfunc1()
during the lifetime of the backend. Needless to say that this isn't what the
programmer wanted.
-Para>
-<Para>
- In the case of logfunc2(), the <ProductName>Postgresame>
+para>
+<para>
+ In the case of logfunc2(), the <productname>Postgresame>
main parser does not know
what type 'now' should become and therefor it returns a datatype of
text containing the string 'now'. During the assignment
to the local variable curtime, the PL/pgSQL interpreter casts this
string to the datetime type by calling the text_out() and datetime_in()
functions for the conversion.
-Para>
-<Para>
- This type checking done by the <ProductName>Postgresame> main
+para>
+<para>
+ This type checking done by the <productname>Postgresame> main
parser got implemented after PL/pgSQL was nearly done.
It is a difference between 6.3 and 6.4 and affects all functions
using the prepared plan feature of the SPI manager.
Using a local
variable in the above manner is currently the only way in PL/pgSQL to get
those values interpreted correctly.
-Para>
-<Para>
+para>
+<para>
If record fields are used in expressions or statements, the data types of
fields should not change between calls of one and the same expression.
Keep this in mind when writing trigger procedures that handle events
for more than one table.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Statementsitle>
+<sect3>
+<title>Statementsitle>
-<Para>
+<para>
Anything not understood by the PL/pgSQL parser as specified below
will be put into a query and sent down to the database engine
to execute. The resulting query should not return any data.
-Para>
+para>
-<VariableList>
+<variablelist>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Assignment
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
An assignment of a value to a variable or row/record field is
written as
- <ProgramListing>
- <Replaceable>identifier := expressioneplaceable>;
- ProgramListing>
+ <programlisting>
+ <replaceable>identifier := expressioneplaceable>;
+ programlisting>
If the expressions result data type doesn't match the variables
data type, or the variable has a size/precision that is known
(as for char(20)), the result value will be implicitly casted by
the PL/pgSQL bytecode interpreter using the result types output- and
the variables type input-functions. Note that this could potentially
result in runtime errors generated by the types input functions.
-Para>
-<Para>
+para>
+<para>
An assignment of a complete selection into a record or row can
be done by
- <ProgramListing>
- SELECT <Replaceable>expressions INTO targeteplaceable> FROM ...;
- ProgramListing>
- <Replaceable>targeteplaceable> can be a record, a row variable or a
+ <programlisting>
+ SELECT <replaceable>expressions INTO targeteplaceable> FROM ...;
+ programlisting>
+ <replaceable>targeteplaceable> can be a record, a row variable or a
comma separated list of variables and record-/row-fields.
-Para>
-<Para>
+para>
+<para>
if a row or a variable list is used as target, the selected values
must exactly match the structure of the target(s) or a runtime error
occurs. The FROM keyword can be followed by any valid qualification,
grouping, sorting etc. that can be given for a SELECT statement.
-Para>
-<Para>
+para>
+<para>
There is a special variable named FOUND of type bool that can be used
immediately after a SELECT INTO to check if an assignment had success.
- <ProgramListing>
+ <programlisting>
SELECT * INTO myrec FROM EMP WHERE empname = myname;
IF NOT FOUND THEN
RAISE EXCEPTION ''employee % not found'', myname;
END IF;
- ProgramListing>
+ programlisting>
If the selection returns multiple rows, only the first is moved
into the target fields. All others are silently discarded.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Calling another function
-Term>
-<ListItem>
-<Para>
- All functions defined in a <ProductName>Prostgresame>
+term>
+<listitem>
+<para>
+ All functions defined in a <productname>Prostgresame>
database return a value. Thus, the normal way to call a function
is to execute a SELECT query or doing an assignment (resulting
in a PL/pgSQL internal SELECT). But there are cases where someone
isn't interested int the functions result.
- <ProgramListing>
- PERFORM <Replaceable>queryeplaceable>
- ProgramListing>
- executes a 'SELECT <Replaceable>queryeplaceable>' over the
+ <programlisting>
+ PERFORM <replaceable>queryeplaceable>
+ programlisting>
+ executes a 'SELECT <replaceable>queryeplaceable>' over the
SPI manager and discards the result. Identifiers like local
variables are still substituted into parameters.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Returning from the function
-Term>
-<ListItem>
-<Para>
- <ProgramListing>
- RETURN <Replaceable>expressioneplaceable>
- ProgramListing>
- The function terminates and the value of <Replaceable>expressioneplaceable>
+term>
+<listitem>
+<para>
+ <programlisting>
+ RETURN <replaceable>expressioneplaceable>
+ programlisting>
+ The function terminates and the value of <replaceable>expressioneplaceable>
will be returned to the upper executor. The return value of a function
cannot be undefined. If control reaches the end of the toplevel block
of the function without hitting a RETURN statement, a runtime error
will occur.
-Para>
-<Para>
+para>
+<para>
The expressions result will be automatically casted into the
functions return type as described for assignments.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Aborting and messages
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
As indicated in the above examples there is a RAISE statement that
- can throw messages into the <ProductName>Postgresame>
+ can throw messages into the <productname>Postgresame>
elog mechanism.
- RAISE level ''format'' [, identifier [...]];
-
+ RAISE level
+ r">forle>'' [,
+ identifier [...]];
+
Inside the format, %
is used as a placeholder for the
subsequent comma-separated identifiers. Possible levels are
DEBUG (silently suppressed in production running databases), NOTICE
(written into the database log and forwarded to the client application)
and EXCEPTION (written into the database log and aborting the transaction).
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Conditionals
-Term>
-<ListItem>
-<Para>
- <ProgramListing>
- IF <Replaceable>expressioneplaceable> THEN
+term>
+<listitem>
+<para>
+ <programlisting>
+ IF <replaceable>expressioneplaceable> THEN
statements
[ELSE
statements]
END IF;
- ProgramListing>
- The <Replaceable>expressioneplaceable> must return a value that
+ programlisting>
+ The <replaceable>expressioneplaceable> must return a value that
at least can be casted into a boolean type.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Loops
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
There are multiple types of loops.
- <ProgramListing>
+ <programlisting>
[<<label>>]
LOOP
statements
END LOOP;
- ProgramListing>
+ programlisting>
An unconditional loop that must be terminated explicitly
by an EXIT statement. The optional label can be used by
EXIT statements of nested loops to specify which level of
nesting should be terminated.
- <ProgramListing>
+ <programlisting>
[<<label>>]
- WHILE <Replaceable>expressioneplaceable> LOOP
+ WHILE <replaceable>expressioneplaceable> LOOP
statements
END LOOP;
- ProgramListing>
+ programlisting>
A conditional loop that is executed as long as the evaluation
- of <Replaceable>expressioneplaceable> is true.
- <ProgramListing>
+ of <replaceable>expressioneplaceable> is true.
+ <programlisting>
[<<label>>]
- FOR name IN [ REVERSE ] expression .. expression LOOP
+ FOR name IN [ REVERSE ]
+le>expressle> .. expression LOOP
statements
END LOOP;
- ProgramListing>
+ programlisting>
A loop that iterates over a range of integer values. The variable
- <Replaceable>nameeplaceable> is automatically created as type
+ <replaceable>nameeplaceable> is automatically created as type
integer and exists only inside the loop. The two expressions giving
the lower and upper bound of the range are evaluated only when entering
the loop. The iteration step is always 1.
- <ProgramListing>
+ <programlisting>
[<<label>>]
- FOR <Replaceable>record | row IN select_clauseeplaceable> LOOP
+ FOR <replaceable>record | row IN select_clauseeplaceable> LOOP
statements
END LOOP;
- ProgramListing>
+ programlisting>
The record or row is assigned all the rows resulting from the select
clause and the statements executed for each. If the loop is terminated
with an EXIT statement, the last assigned row is still accessible
after the loop.
- <ProgramListing>
- EXIT [ <Replaceable>label ] [ WHEN expressioneplaceable> ];
- ProgramListing>
- If no <Replaceable>labeleplaceable> given,
+ <programlisting>
+ EXIT [ <replaceable>label ] [ WHEN expressioneplaceable> ];
+ programlisting>
+ If no <replaceable>labeleplaceable> given,
the innermost loop is terminated and the
statement following END LOOP is executed next.
- If <Replaceable>labeleplaceable> is given, it
+ If <replaceable>labeleplaceable> is given, it
must be the label of the current or an upper level of nested loop
blocks. Then the named loop or block is terminated and control
continues with the statement after the loops/blocks corresponding
END.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-VariableList>
+variablelist>
-Sect3>
+sect3>
-<Sect3>
-<Title>Trigger Proceduresitle>
+<sect3>
+<title>Trigger Proceduresitle>
-<Para>
+<para>
PL/pgSQL can be used to define trigger procedures. They are created
with the usual CREATE FUNCTION command as a function with no
arguments and a return type of OPAQUE.
-Para>
-<Para>
- There are some <ProductName>Postgresame> specific details
+para>
+<para>
+ There are some <productname>Postgresame> specific details
in functions used as trigger procedures.
-Para>
-<Para>
+para>
+<para>
First they have some special variables created automatically in the
toplevel blocks declaration section. They are
-Para>
+para>
-<VariableList>
+<variablelist>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
NEW
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype RECORD; variable holding the new database row on INSERT/UPDATE
operations on ROW level triggers.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
OLD
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype RECORD; variable holding the old database row on UPDATE/DELETE
operations on ROW level triggers.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_NAME
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype name; variable that contains the name of the trigger actually
fired.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_WHEN
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype text; a string of either 'BEFORE' or 'AFTER' depending on the
triggers definition.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_LEVEL
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype text; a string of either 'ROW' or 'STATEMENT' depending on the
triggers definition.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_OP
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype text; a string of 'INSERT', 'UPDATE' or 'DELETE' telling
for which operation the trigger is actually fired.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_RELID
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype oid; the object ID of the table that caused the
trigger invocation.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_RELNAME
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype name; the name of the table that caused the trigger
invocation.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_NARGS
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype integer; the number of arguments given to the trigger
procedure in the CREATE TRIGGER statement.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
TG_ARGV[]
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
Datatype array of text; the arguments from the CREATE TRIGGER statement.
The index counts from 0 and can be given as an expression. Invalid
indices (< 0 or >= tg_nargs) result in a NULL value.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-VariableList>
+variablelist>
-<Para>
+<para>
Second they must return either NULL or a record/row containing
exactly the structure of the table the trigger was fired for.
Triggers fired AFTER might always return a NULL value with no
row in the operation. It is possible to replace single values directly
in NEW and return that or to build a complete new record/row to
return.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Exceptionsitle>
+<sect3>
+<title>Exceptionsitle>
-<Para>
- <ProductName>Postgresame> does not have a very smart
+<para>
+ <productname>Postgresame> does not have a very smart
exception handling model. Whenever the parser, planner/optimizer
or executor decide that a statement cannot be processed any longer,
the whole transaction gets aborted and the system jumps back
into the mainloop to get the next query from the client application.
-Para>
-<Para>
+para>
+<para>
It is possible to hook into the error mechanism to notice that this
happens. But currently it's impossible to tell what really
caused the abort (input/output conversion error, floating point
And even if, at this point the information, that the transaction
is aborted, is already sent to the client application, so resuming
operation does not make any sense.
-Para>
-<Para>
+para>
+<para>
Thus, the only thing PL/pgSQL currently does when it encounters
an abort during execution of a function or trigger
procedure is to write some additional DEBUG level log messages
telling in which function and where (line number and type of
statement) this happened.
-Para>
-Sect3>
-Sect2>
+para>
+sect3>
+sect2>
-<Sect2>
-<Title>Examplesitle>
+<sect2>
+<title>Examplesitle>
-<Para>
+<para>
Here are only a few functions to demonstrate how easy PL/pgSQL
functions can be written. For more complex examples the programmer
might look at the regression test for PL/pgSQL.
-Para>
+para>
-<Para>
+<para>
One painful detail of writing functions in PL/pgSQL is the handling
of single quotes. The functions source text on CREATE FUNCTION must
be a literal string. Single quotes inside of literal strings must be
either doubled or quoted with a backslash. We are still looking for
an elegant alternative. In the meantime, doubling the single qoutes
as in the examples below should be used. Any solution for this
-in future versions of <ProductName>Postgresame> will be
+in future versions of <productname>Postgresame> will be
upward compatible.
-Para>
+para>
-<Sect3>
-<Title>Some Simple PL/pgSQL Functionsitle>
+<sect3>
+<title>Some Simple PL/pgSQL Functionsitle>
-<Para>
+<para>
The following two PL/pgSQL functions are identical to their
counterparts from the C language function discussion.
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION add_one (int4) RETURNS int4 AS '
BEGIN
RETURN $1 + 1;
END;
' LANGUAGE 'plpgsql';
- ProgramListing>
+ programlisting>
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION concat_text (text, text) RETURNS text AS '
BEGIN
RETURN $1 || $2;
END;
' LANGUAGE 'plpgsql';
- ProgramListing>
-Para>
+ programlisting>
+para>
-Sect3>
+sect3>
-<Sect3>
-<Title>PL/pgSQL Function on Composite Typeitle>
+<sect3>
+<title>PL/pgSQL Function on Composite Typeitle>
-<Para>
+<para>
Again it is the PL/pgSQL equivalent to the example from
The C functions.
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION c_overpaid (EMP, int4) RETURNS bool AS '
DECLARE
emprec ALIAS FOR $1;
RETURN emprec.salary > sallim;
END;
' LANGUAGE 'plpgsql';
- ProgramListing>
-Para>
+ programlisting>
+para>
-Sect3>
+sect3>
-<Sect3>
-<Title>PL/pgSQL Trigger Procedureitle>
+<sect3>
+<title>PL/pgSQL Trigger Procedureitle>
-<Para>
+<para>
This trigger ensures, that any time a row is inserted or updated
in the table, the current username and time are stamped into the
row. And it ensures that an employees name is given and that the
salary is a positive value.
- <ProgramListing>
+ <programlisting>
CREATE TABLE emp (
empname text,
salary int4,
CREATE TRIGGER emp_stamp BEFORE INSERT OR UPDATE ON emp
FOR EACH ROW EXECUTE PROCEDURE emp_stamp();
- ProgramListing>
-Para>
+ programlisting>
+para>
-Sect3>
+sect3>
-Sect2>
+sect2>
-Sect1>
+sect1>
-<Sect1>
-<Title>PL/Tclitle>
+<sect1>
+<title>PL/Tclitle>
-<Para>
+<para>
PL/Tcl is a loadable procedural language for the
- <ProductName>Postgresame> database system
+ <productname>Postgresame> database system
that enables the Tcl language to be used to create functions and
trigger-procedures.
-Para>
+para>
-<Para>
+<para>
This package was originally written by Jan Wieck.
-Para>
+para>
-<Sect2>
-<Title>Overviewitle>
+<sect2>
+<title>Overviewitle>
-<Para>
+<para>
PL/Tcl offers most of the capabilities a function
writer has in the C language, except for some restrictions.
-Para>
-<Para>
+para>
+<para>
The good restriction is, that everything is executed in a safe
Tcl-interpreter. In addition to the limited command set of safe Tcl, only
a few commands are available to access the database over SPI and to raise
messages via elog(). There is no way to access internals of the
database backend or gaining OS-level access under the permissions of the
- <ProductName>Postgresame> user ID like in C.
+ <productname>Postgresame> user ID like in C.
Thus, any unprivileged database user may be
permitted to use this language.
-Para>
-<Para>
+para>
+<para>
The other, internal given, restriction is, that Tcl procedures cannot
be used to create input-/output-functions for new data types.
-Para>
-<Para>
+para>
+<para>
The shared object for the PL/Tcl call handler is automatically built
- and installed in the <ProductName>Postgresame>
+ and installed in the <productname>Postgresame>
library directory if the Tcl/Tk support is specified
in the configuration step of the installation procedure.
-Para>
-Sect2>
+para>
+sect2>
-<Sect2>
-<Title>Descriptionitle>
+<sect2>
+<title>Descriptionitle>
-<Sect3>
-<
Title>Postgres Functions and Tcl Procedure Namesitle>
+<sect3>
+<
title>Postgres Functions and Tcl Procedure Namesitle>
-<Para>
- In <ProductName>Postgresame>, one and the
+<para>
+ In <productname>Postgresame>, one and the
same function name can be used for
different functions as long as the number of arguments or their types
differ. This would collide with Tcl procedure names. To offer the same
flexibility in PL/Tcl, the internal Tcl procedure names contain the object
ID of the procedures pg_proc row as part of their name. Thus, different
- argtype versions of the same <ProductName>Postgresame>
+ argtype versions of the same <productname>Postgresame>
function are different for Tcl too.
-Para>
+para>
-Sect3>
+sect3>
-<Sect3>
-<Title>Defining Functions in PL/Tclitle>
+<sect3>
+<title>Defining Functions in PL/Tclitle>
-<Para>
+<para>
To create a function in the PL/Tcl language, use the known syntax
- CREATE FUNCTION funcname (argument-types) RETURNS returntype AS '
+ CREATE FUNCTION funcname
+ ceable>argumenceable>) RETURNS
+ returntype AS '
# PL/Tcl function body
' LANGUAGE 'pltcl';
- ProgramListing>
+ programlisting>
When calling this function in a query, the arguments are given as
variables $1 ... $n to the Tcl procedure body. So a little max function
returning the higher of two int4 values would be created as:
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION tcl_max (int4, int4) RETURNS int4 AS '
if {$1 > $2} {return $1}
return $2
' LANGUAGE 'pltcl';
- ProgramListing>
+ programlisting>
Composite type arguments are given to the procedure as Tcl arrays.
The element names
type. If an attribute in the actual row
has the NULL value, it will not appear in the array! Here is
an example that defines the overpaid_2 function (as found in the
- older <ProductName>Postgresame> documentation) in PL/Tcl
+ older <productname>Postgresame> documentation) in PL/Tcl
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION overpaid_2 (EMP) RETURNS bool AS '
if {200000.0 < $1(salary)} {
return "t"
}
return "f"
' LANGUAGE 'pltcl';
- ProgramListing>
-Para>
+ programlisting>
+para>
-Sect3>
+sect3>
-<Sect3>
-<Title>Global Data in PL/Tclitle>
+<sect3>
+<title>Global Data in PL/Tclitle>
-<Para>
+<para>
Sometimes (especially when using the SPI functions described later) it
is useful to have some global status data that is held between two
calls to a procedure.
an array is made available to each procedure via the upvar
command. The global name of this variable is the procedures internal
name and the local name is GD.
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Trigger Procedures in PL/Tclitle>
+<sect3>
+<title>Trigger Procedures in PL/Tclitle>
-<Para>
- Trigger procedures are defined in <ProductName>Postgresame>
+<para>
+ Trigger procedures are defined in <productname>Postgresame>
as functions without
arguments and a return type of opaque. And so are they in the PL/Tcl
language.
-Para>
-<Para>
+para>
+<para>
The informations from the trigger manager are given to the procedure body
in the following variables:
-Para>
-<VariableList>
+para>
+<variablelist>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_name
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The name of the trigger from the CREATE TRIGGER statement.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_relid
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The object ID of the table that caused the trigger procedure
to be invoked.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_relatts
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
A Tcl list of the tables field names prefixed with an empty list element.
So looking up an element name in the list with the lsearch Tcl command
returns the same positive number starting from 1 as the fields are numbered
in the pg_attribute system catalog.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_when
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The string BEFORE or AFTER depending on the event of the trigger call.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_level
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The string ROW or STATEMENT depending on the event of the trigger call.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$TG_op
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The string INSERT, UPDATE or DELETE depending on the event of the
trigger call.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$NEW
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
An array containing the values of the new table row on INSERT/UPDATE
actions, or empty on DELETE.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$OLD
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
An array containing the values of the old table row on UPDATE/DELETE
actions, or empty on INSERT.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$GD
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
The global status data array as described above.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>eplaceable class="Parameter">
+<varlistentry>
+<term>eplaceable class="Parameter">
$args
-Replaceable>erm>
-<ListItem>
-<Para>
+replaceable>erm>
+<listitem>
+<para>
A Tcl list of the arguments to the procedure as given in the
CREATE TRIGGER statement. The arguments are also accessible as $1 ... $n
in the procedure body.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-VariableList>
+variablelist>
-<Para>
+<para>
The return value from a trigger procedure is one of the strings OK or SKIP,
or a list as returned by the 'array get' Tcl command. If the return value
is OK, the normal operation (INSERT/UPDATE/DELETE) that fired this trigger
to return a modified row to the trigger manager that will be inserted instead
of the one given in $NEW (INSERT/UPDATE only). Needless to say that all
this is only meaningful when the trigger is BEFORE and FOR EACH ROW.
-Para>
-<Para>
+para>
+<para>
Here's a little example trigger procedure that forces an integer value
in a table to keep track of the # of updates that are performed on the
row. For new row's inserted, the value is initialized to 0 and then
incremented on every update operation:
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION trigfunc_modcount() RETURNS OPAQUE AS '
switch $TG_op {
INSERT {
CREATE TRIGGER trig_mytab_modcount BEFORE INSERT OR UPDATE ON mytab
FOR EACH ROW EXECUTE PROCEDURE trigfunc_modcount('modcnt');
- ProgramListing>
+ programlisting>
-Para>
-Sect3>
+para>
+sect3>
-<Sect3>
-<Title>Database Access from PL/Tclitle>
+<sect3>
+<title>Database Access from PL/Tclitle>
-<Para>
+<para>
The following commands are available to access the database from
the body of a PL/Tcl procedure:
-Para>
+para>
-<VariableList>
+<variablelist>
-<VarListEntry>
-<Term>
-elog <Replaceable>level msgeplaceable>
-Term>
-<ListItem>
-<Para>
+<varlistentry>
+<term>
+elog <replaceable>level msgeplaceable>
+term>
+<listitem>
+<para>
Fire a log message. Possible levels are NOTICE, WARN, ERROR,
FATAL, DEBUG and NOIND
like for the elog() C function.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-quote <Replaceable>stringeplaceable>
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+quote <replaceable>stringeplaceable>
+term>
+<listitem>
+<para>
Duplicates all occurences of single quote and backslash characters.
It should be used when variables are used in the query string given
to spi_exec or spi_prepare (not for the value list on spi_execp).
Think about a query string like
- <ProgramListing>
+ <programlisting>
"SELECT '$val' AS ret"
- ProgramListing>
+ programlisting>
where the Tcl variable val actually contains "doesn't". This would result
in the final query string
- <ProgramListing>
+ <programlisting>
"SELECT 'doesn't' AS ret"
- ProgramListing>
+ programlisting>
what would cause a parse error during spi_exec or spi_prepare.
It should contain
- <ProgramListing>
+ <programlisting>
"SELECT 'doesn''t' AS ret"
- ProgramListing>
+ programlisting>
and has to be written as
- <ProgramListing>
+ <programlisting>
"SELECT '[ quote $val ]' AS ret"
-
-
-
-
-
-
-
-spi_exec ?-count n? ?-array name? query ?loop-body?
-
-
+
+
+
+
+
+
+
+spi_exec ?-count n? ?-array
+>nam>?e>quee> ?loop-body?
+
+
Call parser/planner/optimizer/executor for query.
The optional -count value tells spi_exec the maximum number of rows
to be processed by the query.
-Para>
-<Para>
+para>
+<para>
If the query is
a SELECT statement and the optional loop-body (a body of Tcl commands
like in a foreach statement) is given, it is evaluated for each
row selected and behaves like expected on continue/break. The values
of selected fields are put into variables named as the column names. So a
- <ProgramListing>
+ <programlisting>
spi_exec "SELECT count(*) AS cnt FROM pg_proc"
- ProgramListing>
+ programlisting>
will set the variable $cnt to the number of rows in the pg_proc system
catalog. If the option -array is given, the column values are stored
in the associative array named 'name' indexed by the column name
instead of individual variables.
- <ProgramListing>
+ <programlisting>
spi_exec -array C "SELECT * FROM pg_class" {
elog DEBUG "have table $C(relname)"
}
- ProgramListing>
+ programlisting>
will print a DEBUG log message for every row of pg_class. The return value
of spi_exec is the number of rows affected by query as found in
the global variable SPI_processed.
-Para>
-ListItem>
-VarListEntry>
-
-<VarListEntry>
-<Term>
-spi_prepare <Replaceable>query typelisteplaceable>
-Term>
-<ListItem>
-<Para>
+para>
+listitem>
+varlistentry>
+
+<varlistentry>
+<term>
+spi_prepare <replaceable>query typelisteplaceable>
+term>
+<listitem>
+<para>
Prepares AND SAVES a query plan for later execution. It is a bit different
from the C level SPI_prepare in that the plan is automatically copied to the
toplevel memory context. Thus, there is currently no way of preparing a
plan without saving it.
-Para>
-<Para>
+para>
+<para>
If the query references arguments, the type names must be given as a Tcl
list. The return value from spi_prepare is a query ID to be used in
subsequent calls to spi_execp. See spi_execp for a sample.
-
-
-
-
-
-
-spi_exec ?-count n? ?-array name? ?-nulls str? query ?valuelist? ?loop-body?
-
-
+
+
+
+
+
+
+spi_exec ?-count n? ?-array
+>nam>? ?-nullse>se>le>quleble>valueble>? ?loop-body?
+
+
Execute a prepared plan from spi_prepare with variable substitution.
The optional -count value tells spi_execp the maximum number of rows
to be processed by the query.
-Para>
-<Para>
+para>
+<para>
The optional value for -nulls is a string of spaces and 'n' characters
telling spi_execp which of the values are NULL's. If given, it must
have exactly the length of the number of values.
-Para>
-<Para>
+para>
+<para>
The queryid is the ID returned by the spi_prepare call.
-Para>
-<Para>
+para>
+<para>
If there was a typelist given to spi_prepare, a Tcl list of values of
exactly the same length must be given to spi_execp after the query. If
the type list on spi_prepare was empty, this argument must be omitted.
-Para>
-<Para>
+para>
+<para>
If the query is a SELECT statement, the same as described for spi_exec
happens for the loop-body and the variables for the fields selected.
-Para>
-<Para>
+para>
+<para>
Here's an example for a PL/Tcl function using a prepared plan:
- <ProgramListing>
+ <programlisting>
CREATE FUNCTION t1_count(int4, int4) RETURNS int4 AS '
if {![ info exists GD(plan) ]} {
# prepare the saved plan on the first call
spi_execp -count 1 $GD(plan) [ list $1 $2 ]
return $cnt
' LANGUAGE 'pltcl';
- ProgramListing>
+ programlisting>
Note that each backslash that Tcl should see must be doubled in
the query creating the function, since the main parser processes
Inside the query string given to spi_prepare should
really be dollar signs to mark the parameter positions and to not let
$1 be substituted by the value given in the first function call.
-Para>
-ListItem>
-VarListEntry>
+para>
+listitem>
+varlistentry>
-<VarListEntry>
-<Term>
+<varlistentry>
+<term>
Modules and the unknown command
-Term>
-<ListItem>
-<Para>
+term>
+<listitem>
+<para>
PL/Tcl has a special support for things often used. It recognizes two
magic tables, pltcl_modules and pltcl_modfuncs.
If these exist, the module 'unknown' is loaded into the interpreter
of the modules. If this is true, the module is loaded on demand.
To enable this behavior, the PL/Tcl call handler must be compiled
with -DPLTCL_UNKNOWN_SUPPORT set.
-Para>
-<Para>
+para>
+<para>
There are support scripts to maintain these tables in the modules
subdirectory of the PL/Tcl source including the source for the
unknown module that must get installed initially.
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+