SlideShare a Scribd company logo
PostgreSQL and PL/Java

     Server-Side Functions in Java

                 Peter Eisentraut
           petere@postgresql.org
Agenda
•   Functions in PostgreSQL
•   Enter PL/Java
•   Features of PL/Java
•   Support and Compatibility
•   Outlook and Wrap-Up




                                2
Defining a Function
Example of an SQL function:

CREATE FUNCTION add(int, int) RETURNS int
 LANGUAGE SQL
 AS 'SELECT $1 + $2;';


SELECT add(4, 5);
add
-----
   9



                                            3
Defining a Function
Example of a C function:

PG_FUNCTION_INFO_V1(funcname);
Datum add(PG_FUNCTION_ARGS)
{
    int32 a = PG_GETARG_INT32(0);
    int32 b = PG_GETARG_INT32(1);


    PG_RETURN_INT32(a + b);
}


                                    4
Defining a Function
Example of a C function, continued:

gcc -fPIC -c file.c
gcc -shared -o file.so file.o


CREATE FUNCTION add(int, int) RETURNS int
 LANGUAGE C
 AS 'file.so', 'add';




                                            5
Features of Functions
• Overloading
• Processing sets/tables
• Caching options
  (deterministic/nondeterministic)
• Execution privileges




                                     6
Advantages of Server-Side
             Functions
•   Encapsulation
•   Faster database access
•   Plan caching, inlining
•   Data validation through triggers
•   Side effects through triggers




                                       7
Functions as Building Blocks
•   Operators
•   Data types
•   Aggregate functions
•   Index access methods
•   Type casts
•   Character set conversions



                                    8
Procedural Languages
• Choice of SQL vs. C quite limited
• Solution: pluggable language handlers

• Available languages:
  Tcl, PL/pgSQL, Perl, Ruby, Python, Shell,
  R, Java, PHP



                                              9
Procedural Language Example:
          PL/pgSQL
CREATE FUNCTION logfunc(logtxt text)
 RETURNS timestamp
AS '
 DECLARE
       curtime timestamp;
 BEGIN
       curtime := ''now'';
       INSERT INTO logtable VALUES (logtxt, curtime);
       RETURN curtime;
 END;
' LANGUAGE plpgsql;

                                                        10
Procedural Language Example:
            PL/Perl
CREATE OR REPLACE FUNCTION valid_id()
 RETURNS trigger
AS '
 if (($_TD->{new}{i} >= 100) || ($_TD->{new}{i} <= 0)) {
     return "SKIP";     # skip INSERT/UPDATE command
 } elsif ($_TD->{new}{v} ne "immortal") {
     $_TD->{new}{v} .= "(modified by trigger)";
     return "MODIFY";   # modify row and run INSERT/UPDATE
 } else {
     return;            # execute INSERT/UPDATE command
 }
' LANGUAGE plperl;

                                                             11
Enter PL/Java
• Developed by Thomas Hallgren

• Stored procedures written in the Java
  language
• Java the most popular (client) language for
  PostgreSQL



                                            12
Standardization
SQL standard: ISO/IEC 9075-13:2003
SQL Routines and Types for the Java
  Programming Language ("SQL/JRT")
(210 pages)
driven by Oracle and IBM




                                      13
Timeline of PL/Java
•   Nov. 2000: first attempt with Kaffe 1.0.6
•   Dec. 2003: PL/Java project launched
•   Jan. 2004: first alpha release
•   Jan. 2005: release 1.0.0 (for PG 7.4)
•   Apr. 2005: release 1.1.0 (for PG 8.0)
•   currently “stable”



                                                14
Concept
•   Write a Java class
•   Designate static method as entry point
•   Pack into JAR
•   Load JAR into database
•   Adjust classpath
•   Create function in PostgreSQL



                                             15
Simple Example: Code
package com.example;


public class Foo
{
    static int add(int a, int b)
    {
        return a + b;
    }
}




                                   16
Simple Example: Deployment
javac com/example/Foo.java
jar cf foo.jar com/example/Foo.class


SELECT
  sqlj.install_jar('file:/home/peter/tmp/foo.jar',
  'foo', false);


SELECT sqlj.set_classpath('public', 'foo:bar:etc');


CREATE FUNCTION add(int, int) RETURNS int
 LANGUAGE java
 AS 'com.example.Foo.add';
                                                      17
Deployment Descriptor
Optional way to integrate install/uninstall SQL
 statements into the JAR file:
SQLActions[] = {
    "BEGIN INSTALL
      CREATE FUNCTION add(int, int) RETURNS int
        LANGUAGE java
        AS 'com.example.Foo.add';
    END INSTALL",
    "BEGIN REMOVE
      DROP FUNCTION add(int, int);
    END REMOVE"
}


                                                  18
Configuration
New parameters for postgresql.conf:

custom_variable_classes = 'pljava'


pljava.classpath = '/some/where/pljava.jar'
pljava.statement_cache_size = 10
pljava.release_lingering_savepoints = true
pljava.vmoptions = '-Xmx64M'
pljava.debug = false




                                              19
Parameter Type Mapping
Parameter types are mapped automatically:
  PostgreSQL         Java
  boolean            boolean
  shortint           short
  int                int
  bigint             long
  real               float
  double precision   double
  varchar, text      java.lang.String
  bytea              byte[]
  date               java.sql.Date
  time               java.sql.Time
  timestamp          java.sql.Timestamp
  other              java.lang.String


                                            20
Composite Types
CREATE TYPE compositeTest AS (
     base    integer,
     incbase integer,
     ctime   timestamp
);


CREATE FUNCTION useCompositeTest (compositeTest)
     RETURNS varchar
     AS 'foo.fee.Fum.useCompositeTest'
     LANGUAGE java;



                                                   21
Composite Types
Represented as java.sql.ResultSet with one
 row.
public static String useCompositeTest(ResultSet
   compositeTest) throws SQLException
{
    int base = compositeTest.getInt(1);
    int incbase = compositeTest.getInt(2);
    Timestamp ctime = compositeTest.getTimestamp(3);
    return "Base = "" + base +
     "", incbase = "" + incbase +
     "", ctime = "" + ctime + """;
}

                                                       22
Returning Sets
CREATE FUNCTION getNames() RETURNS SETOF varchar
   AS 'Bar.getNames'
   LANGUAGE java;


import java.util.Iterator;
public class Bar {
    public static Iterator getNames() {
        ArrayList names = new ArrayList();
        names.add("Lisa");
        names.add("Bob");
        names.add("Bill");
        return names.iterator();
    }
}

                                                   23
Built-in JDBC Driver
• Prepare/execute queries
• Query metadata
• No transaction management (can use
  savepoints)

Connection conn =
  DriverManager.getConnection("jdbc:default:connectio
  n");




                                                   24
Triggers
static void moddatetime(TriggerData td) throws SQLException
{
    if(td.isFiredForStatement())
     throw new TriggerException(td, "can't process STATEMENT events");
    if(td.isFiredAfter())
     throw new TriggerException(td, "must be fired before event");
    if(!td.isFiredByUpdate())
     throw new TriggerException(td, "can only process UPDATE events");


    ResultSet _new = td.getNew();
    String[] args = td.getArguments();
    if (args.length != 1)
     throw new TriggerException(td, "one argument was expected");
    _new.updateTimestamp(args[0], new Timestamp(System.currentTimeMillis()));
}

                                                                            25
Other Features
•   Exception handling
•   Logging
•   DatabaseMetaData
•   Multithreading
•   IN/OUT parameters (PostgreSQL 8.1)
•   Security



                                         26
Problem Areas
• Memory usage
• Performance?
• Stack handling




                           27
Build Options
• Builds with:
  • Sun JDK ≥ 1.4 (shared library + JAR)
  • GCJ ≥ 4.0 (shared library)
• Does not work with:
  • Kaffe
  • SableVM




                                           28
GCJ Issues
• Missing java.security implementation
• GCJ-based PL/Java installations are
  untrusted.




                                         29
Supported Platforms
• Linux (most architectures)
• Cygwin
• Windows (PostgreSQL 8.1/recent)

• More reports welcome!




                                    30
Compatibility
• vs. Oracle:
  • data type system not as good
  • trigger procedures not compatible (wrappers
    possible)
• vs. DB/2, Firebird, ...:
  • unknown




                                                  31
The Future
• Dynamic type system (SQL:2003)
• Work on SQL conformance and
  compatibility
• More work on J4SQL
• Cooperation with PL/J project




                                   32
Conclusion
•   PL/Java is stable today.
•   It is being used.
•   It is almost feature complete.
•   Get it now!




http://gborg.postgresql.org/project/pljava/projdisplay.php

                                                       33

More Related Content

What's hot

IBM - Introduction to Cloudant
IBM - Introduction to CloudantIBM - Introduction to Cloudant
IBM - Introduction to Cloudant
Francisco González Jiménez
 
Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
baabtra.com - No. 1 supplier of quality freshers
 
Content Management with MongoDB by Mark Helmstetter
 Content Management with MongoDB by Mark Helmstetter Content Management with MongoDB by Mark Helmstetter
Content Management with MongoDB by Mark Helmstetter
MongoDB
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with Flyway
Joris Kuipers
 
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
Databricks
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
Uwe Printz
 
Architecting a datalake
Architecting a datalakeArchitecting a datalake
Architecting a datalake
Laurent Leturgez
 
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
Edureka!
 
Anything-to-Graph
Anything-to-GraphAnything-to-Graph
Anything-to-Graph
Joshua Shinavier
 
Multidimensional Database Design & Architecture
Multidimensional Database Design & ArchitectureMultidimensional Database Design & Architecture
Multidimensional Database Design & Architecture
hasanshan
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
Nick Buytaert
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
NeoClova
 
An Overview of Apache Cassandra
An Overview of Apache CassandraAn Overview of Apache Cassandra
An Overview of Apache Cassandra
DataStax
 
Zero Downtime Schema Changes in Galera Cluster
Zero Downtime Schema Changes in Galera ClusterZero Downtime Schema Changes in Galera Cluster
Zero Downtime Schema Changes in Galera Cluster
Codership Oy - Creators of Galera Cluster
 
Engineering data quality
Engineering data qualityEngineering data quality
Engineering data quality
Lars Albertsson
 
Hadoop
HadoopHadoop
Mobile dbms
Mobile dbmsMobile dbms
Mobile dbms
Tech_MX
 
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
PgDay.Seoul
 
Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개
NeoClova
 
Data modeling star schema
Data modeling star schemaData modeling star schema
Data modeling star schema
Sayed Ahmed
 

What's hot (20)

IBM - Introduction to Cloudant
IBM - Introduction to CloudantIBM - Introduction to Cloudant
IBM - Introduction to Cloudant
 
Stored procedure in sql server
Stored procedure in sql serverStored procedure in sql server
Stored procedure in sql server
 
Content Management with MongoDB by Mark Helmstetter
 Content Management with MongoDB by Mark Helmstetter Content Management with MongoDB by Mark Helmstetter
Content Management with MongoDB by Mark Helmstetter
 
Come Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with FlywayCome Fly With Me: Database Migration Patterns with Flyway
Come Fly With Me: Database Migration Patterns with Flyway
 
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
The Modern Data Team for the Modern Data Stack: dbt and the Role of the Analy...
 
MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)MongoDB for Coder Training (Coding Serbia 2013)
MongoDB for Coder Training (Coding Serbia 2013)
 
Architecting a datalake
Architecting a datalakeArchitecting a datalake
Architecting a datalake
 
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
 
Anything-to-Graph
Anything-to-GraphAnything-to-Graph
Anything-to-Graph
 
Multidimensional Database Design & Architecture
Multidimensional Database Design & ArchitectureMultidimensional Database Design & Architecture
Multidimensional Database Design & Architecture
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바MariaDB 마이그레이션 - 네오클로바
MariaDB 마이그레이션 - 네오클로바
 
An Overview of Apache Cassandra
An Overview of Apache CassandraAn Overview of Apache Cassandra
An Overview of Apache Cassandra
 
Zero Downtime Schema Changes in Galera Cluster
Zero Downtime Schema Changes in Galera ClusterZero Downtime Schema Changes in Galera Cluster
Zero Downtime Schema Changes in Galera Cluster
 
Engineering data quality
Engineering data qualityEngineering data quality
Engineering data quality
 
Hadoop
HadoopHadoop
Hadoop
 
Mobile dbms
Mobile dbmsMobile dbms
Mobile dbms
 
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG[Pgday.Seoul 2018]  이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
[Pgday.Seoul 2018] 이기종 DB에서 PostgreSQL로의 Migration을 위한 DB2PG
 
Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개Percona server for MySQL 제품 소개
Percona server for MySQL 제품 소개
 
Data modeling star schema
Data modeling star schemaData modeling star schema
Data modeling star schema
 

Similar to PostgreSQL and PL/Java

New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
Deniz Oguz
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
Mattias Karlsson
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
Ivan Krylov
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
india_mani
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
catherinewall
 
Spring Boot
Spring BootSpring Boot
Spring Boot
Jiayun Zhou
 
Java 9-10 What's New
Java 9-10 What's NewJava 9-10 What's New
Java 9-10 What's New
Nicola Pedot
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
Agora Group
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Spock
SpockSpock
Meetup cassandra sfo_jdbc
Meetup cassandra sfo_jdbcMeetup cassandra sfo_jdbc
Meetup cassandra sfo_jdbc
zznate
 
Gradle
GradleGradle
Jdbc
JdbcJdbc
Jdbc
lathasiva
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
Knoldus Inc.
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDK
Shu-Jeng Hsieh
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
Sunghyouk Bae
 
De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14
Víctor Leonel Orozco López
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
Anis Bouhachem Djer
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
FITC
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
Sunghyouk Bae
 

Similar to PostgreSQL and PL/Java (20)

New Features Of JDK 7
New Features Of JDK 7New Features Of JDK 7
New Features Of JDK 7
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
What to expect from Java 9
What to expect from Java 9What to expect from Java 9
What to expect from Java 9
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java 9-10 What's New
Java 9-10 What's NewJava 9-10 What's New
Java 9-10 What's New
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Spock
SpockSpock
Spock
 
Meetup cassandra sfo_jdbc
Meetup cassandra sfo_jdbcMeetup cassandra sfo_jdbc
Meetup cassandra sfo_jdbc
 
Gradle
GradleGradle
Gradle
 
Jdbc
JdbcJdbc
Jdbc
 
Slickdemo
SlickdemoSlickdemo
Slickdemo
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDK
 
Spring data requery
Spring data requerySpring data requery
Spring data requery
 
De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14De Java 8 a Java 11 y 14
De Java 8 a Java 11 y 14
 
Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)Angularjs Test Driven Development (TDD)
Angularjs Test Driven Development (TDD)
 
Test-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS ApplicationsTest-Driven Development of AngularJS Applications
Test-Driven Development of AngularJS Applications
 
JUnit5 and TestContainers
JUnit5 and TestContainersJUnit5 and TestContainers
JUnit5 and TestContainers
 

More from Peter Eisentraut

Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
Peter Eisentraut
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
Peter Eisentraut
 
Linux distribution for the cloud
Linux distribution for the cloudLinux distribution for the cloud
Linux distribution for the cloud
Peter Eisentraut
 
Most Wanted: Future PostgreSQL Features
Most Wanted: Future PostgreSQL FeaturesMost Wanted: Future PostgreSQL Features
Most Wanted: Future PostgreSQL Features
Peter Eisentraut
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
Peter Eisentraut
 
Porting Oracle Applications to PostgreSQL
Porting Oracle Applications to PostgreSQLPorting Oracle Applications to PostgreSQL
Porting Oracle Applications to PostgreSQL
Peter Eisentraut
 
PostgreSQL and XML
PostgreSQL and XMLPostgreSQL and XML
PostgreSQL and XML
Peter Eisentraut
 
XML Support: Specifications and Development
XML Support: Specifications and DevelopmentXML Support: Specifications and Development
XML Support: Specifications and Development
Peter Eisentraut
 
PostgreSQL: Die Freie Datenbankalternative
PostgreSQL: Die Freie DatenbankalternativePostgreSQL: Die Freie Datenbankalternative
PostgreSQL: Die Freie Datenbankalternative
Peter Eisentraut
 
The Road to the XML Type: Current and Future Developments
The Road to the XML Type: Current and Future DevelopmentsThe Road to the XML Type: Current and Future Developments
The Road to the XML Type: Current and Future Developments
Peter Eisentraut
 
Access ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-FrontendsAccess ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-Frontends
Peter Eisentraut
 
Replication Solutions for PostgreSQL
Replication Solutions for PostgreSQLReplication Solutions for PostgreSQL
Replication Solutions for PostgreSQL
Peter Eisentraut
 
PostgreSQL News
PostgreSQL NewsPostgreSQL News
PostgreSQL News
Peter Eisentraut
 
PostgreSQL News
PostgreSQL NewsPostgreSQL News
PostgreSQL News
Peter Eisentraut
 
Access ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-FrontendsAccess ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-Frontends
Peter Eisentraut
 
Docbook: Textverarbeitung mit XML
Docbook: Textverarbeitung mit XMLDocbook: Textverarbeitung mit XML
Docbook: Textverarbeitung mit XML
Peter Eisentraut
 
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
Peter Eisentraut
 
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail S...
Collateral Damage:
Consequences of Spam and Virus Filtering for the E-Mail S...Collateral Damage:
Consequences of Spam and Virus Filtering for the E-Mail S...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail S...
Peter Eisentraut
 
Spaß mit PostgreSQL
Spaß mit PostgreSQLSpaß mit PostgreSQL
Spaß mit PostgreSQL
Peter Eisentraut
 
The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)
Peter Eisentraut
 

More from Peter Eisentraut (20)

Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Getting Started with PL/Proxy
Getting Started with PL/ProxyGetting Started with PL/Proxy
Getting Started with PL/Proxy
 
Linux distribution for the cloud
Linux distribution for the cloudLinux distribution for the cloud
Linux distribution for the cloud
 
Most Wanted: Future PostgreSQL Features
Most Wanted: Future PostgreSQL FeaturesMost Wanted: Future PostgreSQL Features
Most Wanted: Future PostgreSQL Features
 
Porting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQLPorting Applications From Oracle To PostgreSQL
Porting Applications From Oracle To PostgreSQL
 
Porting Oracle Applications to PostgreSQL
Porting Oracle Applications to PostgreSQLPorting Oracle Applications to PostgreSQL
Porting Oracle Applications to PostgreSQL
 
PostgreSQL and XML
PostgreSQL and XMLPostgreSQL and XML
PostgreSQL and XML
 
XML Support: Specifications and Development
XML Support: Specifications and DevelopmentXML Support: Specifications and Development
XML Support: Specifications and Development
 
PostgreSQL: Die Freie Datenbankalternative
PostgreSQL: Die Freie DatenbankalternativePostgreSQL: Die Freie Datenbankalternative
PostgreSQL: Die Freie Datenbankalternative
 
The Road to the XML Type: Current and Future Developments
The Road to the XML Type: Current and Future DevelopmentsThe Road to the XML Type: Current and Future Developments
The Road to the XML Type: Current and Future Developments
 
Access ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-FrontendsAccess ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-Frontends
 
Replication Solutions for PostgreSQL
Replication Solutions for PostgreSQLReplication Solutions for PostgreSQL
Replication Solutions for PostgreSQL
 
PostgreSQL News
PostgreSQL NewsPostgreSQL News
PostgreSQL News
 
PostgreSQL News
PostgreSQL NewsPostgreSQL News
PostgreSQL News
 
Access ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-FrontendsAccess ohne Access: Freie Datenbank-Frontends
Access ohne Access: Freie Datenbank-Frontends
 
Docbook: Textverarbeitung mit XML
Docbook: Textverarbeitung mit XMLDocbook: Textverarbeitung mit XML
Docbook: Textverarbeitung mit XML
 
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail Sy...
 
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail S...
Collateral Damage:
Consequences of Spam and Virus Filtering for the E-Mail S...Collateral Damage:
Consequences of Spam and Virus Filtering for the E-Mail S...
Collateral Damage: Consequences of Spam and Virus Filtering for the E-Mail S...
 
Spaß mit PostgreSQL
Spaß mit PostgreSQLSpaß mit PostgreSQL
Spaß mit PostgreSQL
 
The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)
 

Recently uploaded

[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
BibashShahi
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
Fwdays
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
UiPathCommunity
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
christinelarrosa
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
ScyllaDB
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
Antonios Katsarakis
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
Fwdays
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
DianaGray10
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 

Recently uploaded (20)

[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Principle of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptxPrinciple of conventional tomography-Bibash Shahi ppt..pptx
Principle of conventional tomography-Bibash Shahi ppt..pptx
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
"What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w..."What does it really mean for your system to be available, or how to define w...
"What does it really mean for your system to be available, or how to define w...
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Day 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio FundamentalsDay 2 - Intro to UiPath Studio Fundamentals
Day 2 - Intro to UiPath Studio Fundamentals
 
Christine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptxChristine's Product Research Presentation.pptx
Christine's Product Research Presentation.pptx
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 
A Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's ArchitectureA Deep Dive into ScyllaDB's Architecture
A Deep Dive into ScyllaDB's Architecture
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Dandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity serverDandelion Hashtable: beyond billion requests per second on a commodity server
Dandelion Hashtable: beyond billion requests per second on a commodity server
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba"NATO Hackathon Winner: AI-Powered Drug Search",  Taras Kloba
"NATO Hackathon Winner: AI-Powered Drug Search", Taras Kloba
 
What is an RPA CoE? Session 2 – CoE Roles
What is an RPA CoE?  Session 2 – CoE RolesWhat is an RPA CoE?  Session 2 – CoE Roles
What is an RPA CoE? Session 2 – CoE Roles
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
Northern Engraving | Modern Metal Trim, Nameplates and Appliance Panels
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 

PostgreSQL and PL/Java

  • 1. PostgreSQL and PL/Java Server-Side Functions in Java Peter Eisentraut petere@postgresql.org
  • 2. Agenda • Functions in PostgreSQL • Enter PL/Java • Features of PL/Java • Support and Compatibility • Outlook and Wrap-Up 2
  • 3. Defining a Function Example of an SQL function: CREATE FUNCTION add(int, int) RETURNS int LANGUAGE SQL AS 'SELECT $1 + $2;'; SELECT add(4, 5); add ----- 9 3
  • 4. Defining a Function Example of a C function: PG_FUNCTION_INFO_V1(funcname); Datum add(PG_FUNCTION_ARGS) { int32 a = PG_GETARG_INT32(0); int32 b = PG_GETARG_INT32(1); PG_RETURN_INT32(a + b); } 4
  • 5. Defining a Function Example of a C function, continued: gcc -fPIC -c file.c gcc -shared -o file.so file.o CREATE FUNCTION add(int, int) RETURNS int LANGUAGE C AS 'file.so', 'add'; 5
  • 6. Features of Functions • Overloading • Processing sets/tables • Caching options (deterministic/nondeterministic) • Execution privileges 6
  • 7. Advantages of Server-Side Functions • Encapsulation • Faster database access • Plan caching, inlining • Data validation through triggers • Side effects through triggers 7
  • 8. Functions as Building Blocks • Operators • Data types • Aggregate functions • Index access methods • Type casts • Character set conversions 8
  • 9. Procedural Languages • Choice of SQL vs. C quite limited • Solution: pluggable language handlers • Available languages: Tcl, PL/pgSQL, Perl, Ruby, Python, Shell, R, Java, PHP 9
  • 10. Procedural Language Example: PL/pgSQL CREATE FUNCTION logfunc(logtxt text) RETURNS timestamp AS ' DECLARE curtime timestamp; BEGIN curtime := ''now''; INSERT INTO logtable VALUES (logtxt, curtime); RETURN curtime; END; ' LANGUAGE plpgsql; 10
  • 11. Procedural Language Example: PL/Perl CREATE OR REPLACE FUNCTION valid_id() RETURNS trigger AS ' if (($_TD->{new}{i} >= 100) || ($_TD->{new}{i} <= 0)) { return "SKIP"; # skip INSERT/UPDATE command } elsif ($_TD->{new}{v} ne "immortal") { $_TD->{new}{v} .= "(modified by trigger)"; return "MODIFY"; # modify row and run INSERT/UPDATE } else { return; # execute INSERT/UPDATE command } ' LANGUAGE plperl; 11
  • 12. Enter PL/Java • Developed by Thomas Hallgren • Stored procedures written in the Java language • Java the most popular (client) language for PostgreSQL 12
  • 13. Standardization SQL standard: ISO/IEC 9075-13:2003 SQL Routines and Types for the Java Programming Language ("SQL/JRT") (210 pages) driven by Oracle and IBM 13
  • 14. Timeline of PL/Java • Nov. 2000: first attempt with Kaffe 1.0.6 • Dec. 2003: PL/Java project launched • Jan. 2004: first alpha release • Jan. 2005: release 1.0.0 (for PG 7.4) • Apr. 2005: release 1.1.0 (for PG 8.0) • currently “stable” 14
  • 15. Concept • Write a Java class • Designate static method as entry point • Pack into JAR • Load JAR into database • Adjust classpath • Create function in PostgreSQL 15
  • 16. Simple Example: Code package com.example; public class Foo { static int add(int a, int b) { return a + b; } } 16
  • 17. Simple Example: Deployment javac com/example/Foo.java jar cf foo.jar com/example/Foo.class SELECT sqlj.install_jar('file:/home/peter/tmp/foo.jar', 'foo', false); SELECT sqlj.set_classpath('public', 'foo:bar:etc'); CREATE FUNCTION add(int, int) RETURNS int LANGUAGE java AS 'com.example.Foo.add'; 17
  • 18. Deployment Descriptor Optional way to integrate install/uninstall SQL statements into the JAR file: SQLActions[] = { "BEGIN INSTALL CREATE FUNCTION add(int, int) RETURNS int LANGUAGE java AS 'com.example.Foo.add'; END INSTALL", "BEGIN REMOVE DROP FUNCTION add(int, int); END REMOVE" } 18
  • 19. Configuration New parameters for postgresql.conf: custom_variable_classes = 'pljava' pljava.classpath = '/some/where/pljava.jar' pljava.statement_cache_size = 10 pljava.release_lingering_savepoints = true pljava.vmoptions = '-Xmx64M' pljava.debug = false 19
  • 20. Parameter Type Mapping Parameter types are mapped automatically: PostgreSQL Java boolean boolean shortint short int int bigint long real float double precision double varchar, text java.lang.String bytea byte[] date java.sql.Date time java.sql.Time timestamp java.sql.Timestamp other java.lang.String 20
  • 21. Composite Types CREATE TYPE compositeTest AS ( base integer, incbase integer, ctime timestamp ); CREATE FUNCTION useCompositeTest (compositeTest) RETURNS varchar AS 'foo.fee.Fum.useCompositeTest' LANGUAGE java; 21
  • 22. Composite Types Represented as java.sql.ResultSet with one row. public static String useCompositeTest(ResultSet compositeTest) throws SQLException { int base = compositeTest.getInt(1); int incbase = compositeTest.getInt(2); Timestamp ctime = compositeTest.getTimestamp(3); return "Base = "" + base + "", incbase = "" + incbase + "", ctime = "" + ctime + """; } 22
  • 23. Returning Sets CREATE FUNCTION getNames() RETURNS SETOF varchar AS 'Bar.getNames' LANGUAGE java; import java.util.Iterator; public class Bar { public static Iterator getNames() { ArrayList names = new ArrayList(); names.add("Lisa"); names.add("Bob"); names.add("Bill"); return names.iterator(); } } 23
  • 24. Built-in JDBC Driver • Prepare/execute queries • Query metadata • No transaction management (can use savepoints) Connection conn = DriverManager.getConnection("jdbc:default:connectio n"); 24
  • 25. Triggers static void moddatetime(TriggerData td) throws SQLException { if(td.isFiredForStatement()) throw new TriggerException(td, "can't process STATEMENT events"); if(td.isFiredAfter()) throw new TriggerException(td, "must be fired before event"); if(!td.isFiredByUpdate()) throw new TriggerException(td, "can only process UPDATE events"); ResultSet _new = td.getNew(); String[] args = td.getArguments(); if (args.length != 1) throw new TriggerException(td, "one argument was expected"); _new.updateTimestamp(args[0], new Timestamp(System.currentTimeMillis())); } 25
  • 26. Other Features • Exception handling • Logging • DatabaseMetaData • Multithreading • IN/OUT parameters (PostgreSQL 8.1) • Security 26
  • 27. Problem Areas • Memory usage • Performance? • Stack handling 27
  • 28. Build Options • Builds with: • Sun JDK ≥ 1.4 (shared library + JAR) • GCJ ≥ 4.0 (shared library) • Does not work with: • Kaffe • SableVM 28
  • 29. GCJ Issues • Missing java.security implementation • GCJ-based PL/Java installations are untrusted. 29
  • 30. Supported Platforms • Linux (most architectures) • Cygwin • Windows (PostgreSQL 8.1/recent) • More reports welcome! 30
  • 31. Compatibility • vs. Oracle: • data type system not as good • trigger procedures not compatible (wrappers possible) • vs. DB/2, Firebird, ...: • unknown 31
  • 32. The Future • Dynamic type system (SQL:2003) • Work on SQL conformance and compatibility • More work on J4SQL • Cooperation with PL/J project 32
  • 33. Conclusion • PL/Java is stable today. • It is being used. • It is almost feature complete. • Get it now! http://gborg.postgresql.org/project/pljava/projdisplay.php 33