postgresql procedures

Upload: albasud

Post on 14-Apr-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 Postgresql Procedures

    1/5

    Technobabble

    Practical java, unix, and xml

    HomeAPI LinksCurrent ProjectsHa Ha.About

    Write a Stored Procedure in Postgres 8+

    May 5, 2010 /Ant posted in sql, Technobable / No Comments

    Stored Procs

    Sometimes as a developer were tasked with data intensive work like importing datainto a database, cleaning up sets of incomplete records or transferring data from onetable to another through some kind offilter. While our application would normally bein charge of creating and maintaining the data, sometimes we dont want to end upwriting an entire module or mini application to address these tasks. Since theyredata intensive, a stored procedure might be a good approach to take. Storedprocedures are a type of program written using a more robust version of sql(structured query language) that allows for the manipulation of data records directlywithin a database environment.

    If we were to write the equivalent code using a layer written in java, .net, or php,

    there would be a lot of overhead cost in terms of processing power and performance orders of magnitude more. As data is processed, results would normally be returnedto that calling layer and shuffled around that layers memory, essentially addinganother step to the process. If we make these changes as close to the data aspossible, well be able to squeeze as much performance as possible and suffer theleast amount of overhead. Just for perspective heres an example: a 1 gigabyte filecould take several hours to import using java business logic, while a stored proc couldtake less than half an hour. Mileage may vary of course, but thatll give you an idea ofthe performance cost you could save with data intensive tasks like that. A word ofcaution though: Im not saying a stored proc is the way to go for your entireapplication; its merely a tool that can be used in your arsenal to get the job done with

    the most efficient means possible.

    Example

    Heres an example of a generic stored proc written in psql (postgres version).

    CREATE OR REPLACEFUNCTION example_stored_proc() RETURNS void AS $$DECLARE

    userRecord record;user_property_id bigint;

    BEGINFOR userRecord IN

    e a Stored Procedure in Postgres 8+ http://www.openscope.net/2010/05/05/write-a-stor

    5 07/10/1

  • 7/27/2019 Postgresql Procedures

    2/5

    SELECT * FROM tb_user u ORDERBY u.user_idLOOP

    SELECTINTO user_property_id nextval('sq_user_property');

    -- user_property_id now has a value we can insert hereINSERTINTO tb_user_property VALUES(

    user_property_id ,'user_id',userRecord.id

    ) ;

    IF userRecord.email like '[email protected]'THEN

    update userRecord set email = '[email protected]'where id = userRecord.id;

    ELSEIF userRecord.email is null THEN

    update userRecord set active = falsewhere id = userRecord.id;

    ELSE

    RAISE NOTICE 'didn't update any record';

    END IF;

    RAISE NOTICE 'added property foruser id: %', userRecord.id;

    END LOOP;RETURN;

    END;$$ LANGUAGE plpgsql;

    CREATE OR REPLACE FUNCTION example_stored_proc() RETURNS integerAS $$CREATE OR REPLACE FUNCTION will create the stored proc in the database.RETURNS declares the data type returned at the end. This example returns aninteger, but a record or a result set may also be returned. The text in between the twopairs of $$ is the body of the procedure.

    DECLAREThis keyword initializes the variables the stored proc will be using. It essentially letsthe database know to allocate memory for use.

    BEGINThis marks the beginning of the stored proc logic. It naturally ends with END.

    FOR userRecord INSELECT * FROM tb_user u ORDER BY u.user_id

    LOOP

    - do stuff

    END LOOP;

    This is the basic looping structure used in psql. Notice the loop is built around astraight forward sql query here is where the magic happens. The looping variable inthis example is userRecord it holds the currently fetched data record and allowsyou to manipulate it for your own means in the body of the loop. So, if you wanted toinsert the value of userRecord.id into a table, you could just stick in the insert

    e a Stored Procedure in Postgres 8+ http://www.openscope.net/2010/05/05/write-a-stor

    5 07/10/1

  • 7/27/2019 Postgresql Procedures

    3/5

    3 0

    statement as a variable as shown in the insert statement in particular loops body.

    SELECT INTO

    Using this construct allows you to create a temporary table to hold query results forlater use. Your variable can be a record or a single column value. In order for it towork you need to declare the variable thats going to take the value in the DECLRAREsection of the stored proc. Inline variable declaration is not supported.

    Conditionals

    As expected, the IF/THEN/ELSEIF/ELSE/END IF construct can be used to createconditional sequences of logic. The conditionals need to be any kind of expressionpostgres can evaluate. The ELSEIF can be used to wrap secondary conditionals, whilethe ELSE of course is the default if no other conditions are met. Fairly selfexplanatory.

    RAISE NOTICE

    This is your standard psql logging output statement. The text in the single quotes isoutput to the console/message window, and every % is substituted with the orderedvalue after each comma in the statement. So, in this case userRecord.id issubstituted into the first % to appear in the output text. If you wanted to havemultiple values output you could construct your RAISE NOTICE like this:

    RAISE NOTICE 'this is record % out of 1000, and its value is %', record_number, record_value;

    It would substitute record_number into the first % and record_value into the second% appearing in the text.

    Related posts:

    Subverting foreign key constraints in postgres or mysql1.Set up postgres2.Run a huge query as fast and safely as possible3.

    < postgres, sql, stored procedure >

    *nix commands I cant do withoutJars and Class Loading, Jboss v5.x

    Comments (0)

    No comments yet.

    Leave a Reply

    Name (*)

    e a Stored Procedure in Postgres 8+ http://www.openscope.net/2010/05/05/write-a-stor

    5 07/10/1

  • 7/27/2019 Postgresql Procedures

    4/5

    Email (*)

    Website

    Allowed Tags - You may use these HTML tags and attributes in your comment.

    Post Comment (Ctrl+Enter) Preview

    Click the "Preview" button to preview your comment here.

    Pingbacks (0)

    No pingbacks yet.

    About this blog..

    This blog is a collection of java development articles mixed in with some unix,sql, xsl/xml, and other little gems that help make development just a little easier.

    Feel free to leave comments, suggestions, questions and feedback on the posts.

    Search...

    Need kick-ass unix web hosting?I use phpwebhosting.com

    Categories

    Fedora (9)Java (13)Jboss (13)

    sql (4)Technobable (11)xml (5)

    Archives

    August 2012 (1)September 2011 (1)August 2011 (1)January 2011 (2)

    e a Stored Procedure in Postgres 8+ http://www.openscope.net/2010/05/05/write-a-stor

    5 07/10/1

  • 7/27/2019 Postgresql Procedures

    5/5

    August 2010 (2)July 2010 (4)May 2010 (1)February 2010 (5)January 2010 (22)

    Recent Articles

    Subverting foreign key constraints in postgres or mysqlRun a huge query as fast and safely as possibleConfiguring Data Sources, JBoss 7Manually override and launch quartz jobsConfigure ssh authorized keys for cvs accessThe conf directory, JBoss v5.xApache XSL-FO sho v1.0Sardine powered webdav client?Sending Attachments with the Javamail 1.4.x APIThe Deploy vs Deployers directory, JBoss v5.x

    Logrolling

    Aspire2inspire.org UI/IX Design Expert for hire.Damn Handy A blog about java, REST and other stuffExit Condition Andrew Lee Rubinger, JBoss dudeMastertheboss.com greats resource on jboss projects and useful tips foreveryday development

    Powered by WordPress / Theme SimpleDarkby Justice

    e a Stored Procedure in Postgres 8+ http://www.openscope.net/2010/05/05/write-a-stor

    5 07/10/1