0301 Postgresql Functions by Example
0301 Postgresql Functions by Example
Function Basics
By Example
Joe Conway
[email protected]
credativ Group
Functions
Operators
Data types
Index methods
Casts
Triggers
Aggregates
SQL Functions
Behavior
Executes an arbitrary list of SQL statements separated by
semicolons
Last statement may be INSERT, UPDATE, or DELETE with
RETURNING clause
Arguments
Referenced by function body using $n: $1 is first arg, etc. . .
If composite type, then dot notation $1.name used to access
Only used as data values, not as identifiers
Return
If singleton, first row of last query result returned, NULL on no
result
If SETOF, all rows of last query result returned, empty set on
no result
http://www.postgresql.org/docs/9.1/interactive/xfunc-sql.html
Joe Conway SCALE10X-PGDay
Introduction
Overview
Uses
Function Basics
Varieties
By Example
Languages
Procedural Languages
User-defined functions
Written in languages besides SQL and C
Task is passed to a special handler that knows the details of
the language
Handler could be self-contained (e.g. PL/pgSQL)
Handler could be dynamically loaded (e.g. PL/Perl)
http://www.postgresql.org/docs/9.1/interactive/xplang.html
Internal Functions
http://www.postgresql.org/docs/9.1/interactive/xfunc-internal.html
C Language Functions
Language Availability
PL/pgSQL
Perl
Python
Tcl
Other languages available:
http://pgfoundry.org/softwaremap/trove_list.php?form_cat=311
Java
PHP
Ruby
R
Shell
others . . .
Joe Conway SCALE10X-PGDay
Overview
Creation
Function Basics
Attributes
By Example
http://www.postgresql.org/docs/9.1/interactive/sql-createfunction.html
Dollar Quoting
http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING
Function Overloading
IN argument signature used
Avoid ambiguities:
Type (e.g. REAL vs. DOUBLE PRECISION)
Function name same as IN composite field name
VARIADIC vs same type scalar
CREATE OR REPLACE FUNCTION foo (text) RETURNS text AS $$
SELECT $1
$$ LANGUAGE sql;
CREATE OR REPLACE FUNCTION foo (int) RETURNS text AS $$
SELECT ($1 + 1)::text
$$ LANGUAGE sql;
http://www.postgresql.org/docs/9.1/interactive/xfunc-overload.html
Joe Conway SCALE10X-PGDay
Overview
Creation
Function Basics
Attributes
By Example
Volatility
VOLATILE (default)
Each call can return a different result
Example: random() or timeofday()
Functions modifying table contents must be declared volatile
STABLE
Returns same result for same arguments within single query
Example: now()
Consider configuration settings that affect output
IMMUTABLE
Always returns the same result for the same arguments
Example: lower(’ABC’)
Unaffected by configuration settings
Not dependent on table contents
select lower(’ABC’), now(), timeofday() from generate_series(1,3);
Security Attributes
SECURITY INVOKER (default)
Function executed with the rights of the current user
SECURITY DEFINER
Executed with rights of creator, like ”setuid”
CREATE TABLE foo (f1 int);
REVOKE ALL ON foo FROM public;
CREATE FUNCTION see_foo() RETURNS SETOF foo AS $$
SELECT * FROM foo
$$ LANGUAGE SQL SECURITY DEFINER;
\c - guest
You are now connected to database "postgres" as user "guest".
SELECT * FROM foo;
ERROR: permission denied for relation foo
SELECT * FROM see_foo();
f1
----
(0 rows)
Simple
Custom Operator
CREATE OPERATOR + (
procedure = sum,
leftarg = text,
rightarg = text
);
Custom Aggregate
INSERT RETURNING
Composite Argument
SELECT name,
double_salary(ROW(name, salary*1.1, age, cubicle)) AS dream
FROM emp;
Polymorphic
SELECT (new_emp()).name;
name
------
None
VARIADIC
DEFAULT Arguments
PL/pgSQL
http://www.postgresql.org/docs/9.1/interactive/plpgsql.html
Simple
Parameter ALIAS
Named Parameters
SELECT factorial(42::numeric);
factorial
------------------------------------------------------
1405006117752879898543142606244511569936384000000000
(1 row)
Recursive
SELECT factorial(42::numeric);
factorial
------------------------------------------------------
1405006117752879898543142606244511569936384000000000
(1 row)
Record types
select format();
format
--------------
a = 2; b = 4
(1 row)
PERFORM
SELECT dummy();
SELECT * FROM foo;
f1
----
41
42
(2 rows)
Dynamic SQL
Cursors
SELECT totalbalance();
totalbalance
--------------
83.00
(1 row)
Error Handling
http://www.postgresql.org/docs/9.1/interactive/errcodes-appendix.html
Thank You
Questions?