PostgreSQL Functions By Example



Similar documents
Advanced PostgreSQL SQL Injection and Filter Bypass Techniques

Chapter 39. PL/pgSQL - SQL Procedural Language

Programming Database lectures for mathema

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

Database Management System Choices. Introduction To Database Systems CSE 373 Spring 2013

Oracle Database: SQL and PL/SQL Fundamentals

Database Programming with PL/SQL: Learning Objectives

Moving from CS 61A Scheme to CS 61B Java

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

Oracle Database: SQL and PL/SQL Fundamentals NEW

Programming in postgresql with PL/pgSQL. Procedural Language extension to postgresql

Programming the SQL Way with Common Table Expressions

Instant SQL Programming

The C Programming Language course syllabus associate level

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Oracle Database: SQL and PL/SQL Fundamentals

Maintaining Stored Procedures in Database Application

Java EE Web Development Course Program

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Web development... the server side (of the force)

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

SQL Databases Course. by Applied Technology Research Center. This course provides training for MySQL, Oracle, SQL Server and PostgreSQL databases.

DIPLOMA IN WEBDEVELOPMENT

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

14 Triggers / Embedded SQL

A Brief Introduction to MySQL

How To Use Postgresql With Foreign Data In A Foreign Server In A Multi Threaded Database (Postgres)

MOC 20461C: Querying Microsoft SQL Server. Course Overview

PL/SQL Programming Workbook

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Querying Microsoft SQL Server

Lecture 5: Java Fundamentals III

Darshan Institute of Engineering & Technology PL_SQL

Real SQL Programming 1

Facebook Twitter YouTube Google Plus Website

Getting Started with the Internet Communications Engine

J a v a Quiz (Unit 3, Test 0 Practice)

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Web Development using PHP (WD_PHP) Duration 1.5 months

Example of a Java program

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

Intro to Embedded SQL Programming for ILE RPG Developers

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

Static vs. Dynamic. Lecture 10: Static Semantics Overview 1. Typical Semantic Errors: Java, C++ Typical Tasks of the Semantic Analyzer

Oracle 11g PL/SQL training

AP Computer Science Java Subset

dictionary find definition word definition book index find relevant pages term list of page numbers

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Course ID#: W 35 Hrs. Course Content

Querying Microsoft SQL Server 20461C; 5 days

Automation of Library (Codes) Development for Content Management System (CMS)

Chapter 5 Names, Bindings, Type Checking, and Scopes

Stored Routines in Transactional Context

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

Introducing Microsoft SQL Server 2012 Getting Started with SQL Server Management Studio

SQL Server Database Coding Standards and Guidelines

Extending HP Vertica. HP Vertica Analytic Database. Software Version: 7.1.x

sqlite driver manual

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!

Specialized Programme on Web Application Development using Open Source Tools

Data Tool Platform SQL Development Tools

Webapps Vulnerability Report

An Incomplete C++ Primer. University of Wyoming MA 5310

Course Number: IAC-SOFT-WDAD Web Design and Application Development

T-SQL STANDARD ELEMENTS

How To Create A Table In Sql (Ahem)

Getting started with PostgreSQL

Course 20461C: Querying Microsoft SQL Server Duration: 35 hours

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Oracle Database 10g: Program with PL/SQL

Querying Microsoft SQL Server 2012

CSC230 Getting Starting in C. Tyler Bletsch

MOC QUERYING MICROSOFT SQL SERVER

Guide to SQL Programming: SQL:1999 and Oracle Rdb V7.1

The software shall provide the necessary tools to allow a user to create a Dashboard based on the queries created.

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Oracle Database: SQL and PL/SQL Fundamentals NEW

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

Introduction to Java

Course 10774A: Querying Microsoft SQL Server 2012

Database SQL messages and codes

Course 10774A: Querying Microsoft SQL Server 2012 Length: 5 Days Published: May 25, 2012 Language(s): English Audience(s): IT Professionals

not at all a manual simply a quick how-to-do guide

"SQL Database Professional " module PRINTED MANUAL

Japan Communication India Skill Development Center

Embedded SQL programming

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Java Application Developer Certificate Program Competencies

Transcription:

Postgre joe.conway@credativ.com credativ Group January 20, 2012

What are Functions? Introduction Uses Varieties Languages Full fledged SQL objects Many other database objects are implemented with them Fundamental part of PostgreSQL s system architecture Created with CREATE FUNCTION Executed through normal SQL target-list: SELECT myfunc(f1) FROM foo; FROM clause: SELECT * FROM myfunc(); WHERE clause: SELECT * FROM foo WHERE myfunc(f1) = 42;

How are they Used? Introduction Uses Varieties Languages Functions Operators Data types Index methods Casts Triggers Aggregates

What Forms Can They Take? Introduction Uses Varieties Languages PostgreSQL provides four kinds of functions: SQL Procedural Languages Internal C-language Arguments Base, composite, or combinations Scalar or array Pseudo or polymorphic VARIADIC IN/OUT/INOUT Return Singleton or set (SETOF) Base or composite type Pseudo or polymorphic http://www.postgresql.org/docs/9.1/interactive/sql-createfunction.html

Introduction Uses Varieties Languages 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

Procedural Languages Introduction Uses Varieties 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 Introduction Uses Varieties Languages Statically linked C functions Could use CREATE FUNCTION to create additional alias names for an internal function Most internal functions expect to be declared STRICT CREATE FUNCTION square_root(double precision) RETURNS double precision AS dsqrt LANGUAGE internal STRICT; http://www.postgresql.org/docs/9.1/interactive/xfunc-internal.html

C Language Functions Introduction Uses Varieties Languages User-defined functions written in C Compiled into dynamically loadable objects (also called shared libraries) Loaded by the server on demand contrib is good source of examples Same as internal function coding conventions Require PG MODULE MAGIC call Needs separate topic http://www.postgresql.org/docs/9.1/interactive/xfunc-c.html

Language Availability Introduction Uses Varieties Languages PostgreSQL includes the following server-side procedural languages: http://www.postgresql.org/docs/9.1/interactive/xplang.html PL/pgSQL Perl Python Tcl Other languages available: http://pgfoundry.org/softwaremap/trove_list.php?form_cat=311 Java PHP Ruby R Shell others...

Creating New Functions Creation Attributes CREATE [ OR REPLACE ] FUNCTION name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT = } defexpr ] [,...] [ RETURNS rettype RETURNS TABLE ( colname coltype [,...] ) ] { LANGUAGE langname WINDOW IMMUTABLE STABLE VOLATILE CALLED ON NULL INPUT RETURNS NULL ON NULL INPUT STRICT [ EXTERNAL ] SECURITY INVOKER [ EXTERNAL ] SECURITY DEFINER COST execution_cost ROWS result_rows SET configuration_parameter { TO value = value FROM CURRENT } AS definition AS obj_file, link_symbol }... [ WITH ( attribute [,...] ) ] http://www.postgresql.org/docs/9.1/interactive/sql-createfunction.html

Dollar Quoting Creation Attributes Works for all character strings Particularly useful for function bodies CREATE OR REPLACE FUNCTION dummy () RETURNS text AS $Q$ DECLARE result text; BEGIN PERFORM SELECT 1+1 ; RETURN ok ; END; $Q$ LANGUAGE plpgsql; http://www.postgresql.org/docs/9.1/static/sql-syntax-lexical.html#sql-syntax-dollar-quoting

Function Overloading Creation Attributes 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; SELECT foo( 42 ), foo(41); foo foo -----+----- 42 42 http://www.postgresql.org/docs/9.1/interactive/xfunc-overload.html

Changing Existing Functions Creation Attributes Once created, dependent objects may be created Must do DROP FUNCTION... CASCADE to recreate Or use OR REPLACE to avoid dropping dependent objects Very useful for large dependency tree Can t be used in some circumstances (must drop/recreate instead). You cannot: change function name or argument types change return type change types of any OUT parameters CREATE OR REPLACE FUNCTION...;

Volatility Creation Attributes 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);

Behavior with Null Input Values Creation Attributes CALLED ON NULL INPUT (default) Function called normally with the null input values RETURNS NULL ON NULL INPUT Function not called when null input values are present Instead, null is returned automatically CREATE FUNCTION sum1 (int, int) RETURNS int AS $$ SELECT $1 + $2 $$ LANGUAGE SQL RETURNS NULL ON NULL INPUT; CREATE FUNCTION sum2 (int, int) RETURNS int AS $$ SELECT COALESCE($1, 0) + COALESCE($2, 0) $$ LANGUAGE SQL CALLED ON NULL INPUT; SELECT sum1(9, NULL) IS NULL AS "true", sum2(9, NULL); true sum2 ------+------ t 9

Security Attributes Creation 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 PL/pg CREATE FUNCTION sum (text, text) RETURNS text AS $$ SELECT $1 $2 $$ LANGUAGE SQL; SELECT sum( hello, world ); sum ------------- hello world

Custom Operator PL/pg CREATE OPERATOR + ( procedure = sum, leftarg = text, rightarg = text ); SELECT hello + world ;?column? ------------- hello world

Custom Aggregate PL/pg CREATE OR REPLACE FUNCTION concat_ws_comma(text, ANYELEMENT) RETURNS text AS $$ SELECT concat_ws(,, $1, $2) $$ LANGUAGE sql; CREATE AGGREGATE str_agg (ANYELEMENT) ( sfunc = concat_ws_comma, stype = text); SELECT str_agg(f1) FROM foo; str_agg --------- 41,42

SETOF with OUT Arguments PL/pg CREATE OR REPLACE FUNCTION sql_with_rows(out a int, OUT b text) RETURNS SETOF RECORD AS $$ values (1, a ),(2, b ) $$ LANGUAGE SQL; select * from sql_with_rows(); a b ---+--- 1 a 2 b (2 rows)

INSERT RETURNING PL/pg CREATE TABLE foo (f0 serial, f1 int, f2 text); CREATE OR REPLACE FUNCTION sql_insert_returning(inout f1 int, INOUT f2 text, OUT id int) AS $$ INSERT INTO foo(f1, f2) VALUES ($1,$2) RETURNING f1, f2, f0 $$ LANGUAGE SQL; SELECT * FROM sql_insert_returning(1, a ); f1 f2 id ----+----+---- 1 a 1

Composite Argument PL/pg CREATE TABLE emp (name salary age cubicle text, numeric, integer, point); CREATE FUNCTION double_salary(emp) RETURNS numeric AS $$ SELECT $1.salary * 2 AS salary; $$ LANGUAGE SQL; SELECT name, double_salary(emp.*) AS dream FROM emp WHERE emp.cubicle ~= point (2,1) ; SELECT name, double_salary(row(name, salary*1.1, age, cubicle)) AS dream FROM emp;

Polymorphic PL/pg CREATE FUNCTION myappend(anyarray, anyelement) RETURNS anyarray AS $$ SELECT $1 $2; $$ LANGUAGE SQL; SELECT myappend(array[42,6], 21), myappend(array[ abc, def ], xyz ); myappend myappend -----------+--------------- {42,6,21} {abc,def,xyz}

Target List versus FROM Clause PL/pg CREATE FUNCTION new_emp() RETURNS emp AS $$ SELECT ROW( None, 1000.0, 25, (2,2) )::emp; $$ LANGUAGE SQL; SELECT new_emp(); new_emp -------------------------- (None,1000.0,25,"(2,2)") SELECT * FROM new_emp(); name salary age cubicle ------+--------+-----+--------- None 1000.0 25 (2,2) SELECT (new_emp()).name; name ------ None

VARIADIC PL/pg CREATE FUNCTION mleast(variadic numeric[]) RETURNS numeric AS $$ SELECT min($1[i]) FROM generate_subscripts($1, 1) g(i); $$ LANGUAGE SQL; SELECT mleast(10, -1, 5, 4.4); mleast -------- -1 SELECT mleast(42, 6, 42.42); mleast -------- 6

DEFAULT Arguments PL/pg CREATE FUNCTION foo(a int, b int DEFAULT 2, c int DEFAULT 3) RETURNS int LANGUAGE SQL AS $$SELECT $1 + $2 + $3$$; SELECT foo(10, 20, 30); foo ----- 60 SELECT foo(10, 20); foo ----- 33

PL/pgSQL PL/pg PL/pgSQL is SQL plus procedural elements variables if/then/else loops cursors error checking Loading the language handler into a database: createlang plpgsql dbname http://www.postgresql.org/docs/9.1/interactive/plpgsql.html

Simple PL/pg CREATE OR REPLACE FUNCTION sum (text, text) RETURNS text AS $$ BEGIN RETURN $1 $2; END; $$ LANGUAGE plpgsql; SELECT sum( hello, world ); sum ------------- hello world

Parameter ALIAS PL/pg CREATE OR REPLACE FUNCTION sum (int, int) RETURNS int AS $$ DECLARE i ALIAS FOR $1; j ALIAS FOR $2; sum int; BEGIN sum := i + j; RETURN sum; END; $$ LANGUAGE plpgsql; SELECT sum(41, 1); sum ----- 42

Named Parameters PL/pg CREATE OR REPLACE FUNCTION sum (i int, j int) RETURNS int AS $$ DECLARE sum int; BEGIN sum := i + j; RETURN sum; END; $$ LANGUAGE plpgsql; SELECT sum(41, 1); sum ----- 42

Control Structures: IF... PL/pg CREATE OR REPLACE FUNCTION even (i int) RETURNS boolean AS $$ DECLARE tmp int; BEGIN tmp := i % 2; IF tmp = 0 THEN RETURN true; ELSE RETURN false; END IF; END; $$ LANGUAGE plpgsql; SELECT even(3), even(42); even even ------+------ f t

Control Structures: FOR... LOOP PL/pg CREATE OR REPLACE FUNCTION factorial (i numeric) RETURNS numeric AS $$ DECLARE tmp numeric; result numeric; BEGIN result := 1; FOR tmp IN 1.. i LOOP result := result * tmp; END LOOP; RETURN result; END; $$ LANGUAGE plpgsql; SELECT factorial(42::numeric); factorial ------------------------------------------------------ 1405006117752879898543142606244511569936384000000000

PL/pg Control Structures: WHILE... LOOP CREATE OR REPLACE FUNCTION factorial (i numeric) RETURNS numeric AS $$ DECLARE tmp numeric; result numeric; BEGIN result := 1; tmp := 1; WHILE tmp <= i LOOP result := result * tmp; tmp := tmp + 1; END LOOP; RETURN result; END; $$ LANGUAGE plpgsql; SELECT factorial(42::numeric); factorial ------------------------------------------------------ 1405006117752879898543142606244511569936384000000000

Recursive PL/pg CREATE OR REPLACE FUNCTION factorial (i numeric) RETURNS numeric AS $$ BEGIN IF i = 0 THEN RETURN 1; ELSIF i = 1 THEN RETURN 1; ELSE RETURN i * factorial(i - 1); END IF; END; $$ LANGUAGE plpgsql; SELECT factorial(42::numeric); factorial ------------------------------------------------------ 1405006117752879898543142606244511569936384000000000

Record types PL/pg CREATE OR REPLACE FUNCTION format () RETURNS text AS $$ DECLARE tmp RECORD; BEGIN SELECT INTO tmp 1 + 1 AS a, 2 + 2 AS b; RETURN a = tmp.a ; b = tmp.b; END; $$ LANGUAGE plpgsql; select format(); format -------------- a = 2; b = 4

PERFORM PL/pg CREATE OR REPLACE FUNCTION func_w_side_fx() RETURNS void AS $$ INSERT INTO foo VALUES (41),(42) $$ LANGUAGE sql; CREATE OR REPLACE FUNCTION dummy () RETURNS text AS $$ BEGIN PERFORM func_w_side_fx(); RETURN OK ; END; $$ LANGUAGE plpgsql; SELECT dummy(); SELECT * FROM foo; f1 ---- 41 42 (2 rows)

Dynamic SQL PL/pg CREATE OR REPLACE FUNCTION get_foo(i int) RETURNS foo AS $$ DECLARE rec RECORD; BEGIN EXECUTE SELECT * FROM foo WHERE f1 = i INTO rec; RETURN rec; END; $$ LANGUAGE plpgsql; SELECT * FROM get_foo(42); f1 ---- 42

Cursors PL/pg CREATE OR REPLACE FUNCTION totalbalance() RETURNS numeric AS $$ DECLARE tmp RECORD; result numeric; BEGIN result := 0.00; FOR tmp IN SELECT * FROM foo LOOP result := result + tmp.f1; END LOOP; RETURN result; END; $$ LANGUAGE plpgsql; SELECT totalbalance(); totalbalance -------------- 83.00

Error Handling PL/pg CREATE OR REPLACE FUNCTION safe_add(a integer, b integer) RETURNS integer AS $$ BEGIN RETURN a + b; EXCEPTION WHEN numeric_value_out_of_range THEN -- do some important stuff RETURN -1; WHEN OTHERS THEN -- do some other important stuff RETURN -1; END; $$ LANGUAGE plpgsql; http://www.postgresql.org/docs/9.1/interactive/errcodes-appendix.html

Nested Exception Blocks PL/pg CREATE FUNCTION merge_db(key integer, data text) RETURNS void AS $$ BEGIN LOOP UPDATE db SET b = data WHERE a = key; IF found THEN RETURN; END IF; BEGIN INSERT INTO db (a, b) VALUES (key, data); RETURN; EXCEPTION WHEN unique_violation THEN -- do nothing END; END LOOP; EXCEPTION WHEN OTHERS THEN -- do something else END; $$ LANGUAGE plpgsql;

Thank You PL/pg Questions?