Professional Documents
Culture Documents
Full Chapter Procedural Programming With Postgresql PL PGSQL Design Complex Database Centric Applications With PL PGSQL 1St Edition Baji Shaik PDF
Full Chapter Procedural Programming With Postgresql PL PGSQL Design Complex Database Centric Applications With PL PGSQL 1St Edition Baji Shaik PDF
https://textbookfull.com/product/beginning-postgresql-on-the-
cloud-simplifying-database-as-a-service-on-cloud-platforms-baji-
shaik/
https://textbookfull.com/product/postgresql-for-data-architects-
discover-how-to-design-develop-and-maintain-your-database-
application-effectively-with-postgresql-maymala/
https://textbookfull.com/product/exam-ref-pl-900-microsoft-power-
platform-fundamentals-craig-zacker/
https://textbookfull.com/product/complex-analysis-with-
applications-1st-edition-nakhle-h-asmar/
Elementary Logic with Applications A Procedural
Perspective for Computer Scientists 1st Edition D.M.
Gabbay
https://textbookfull.com/product/elementary-logic-with-
applications-a-procedural-perspective-for-computer-
scientists-1st-edition-d-m-gabbay/
https://textbookfull.com/product/postgresql-server-programming-
second-edition-dar/
https://textbookfull.com/product/learning-
postgresql-10-a-beginner-s-guide-to-building-high-performance-
postgresql-database-solutions-juba/
https://textbookfull.com/product/sql-server-database-programming-
with-visual-basic-net-concepts-designs-and-implementations-ying-
bai/
https://textbookfull.com/product/national-brands-and-private-
labels-in-retailing-first-international-symposium-nb-pl-
barcelona-june-2014-1st-edition-juan-carlos-gazquez-abad/
Baji Shaik and Dinesh Kumar Chemuduru
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional affiliations.
This Apress imprint is published by the registered company APress
Media, LLC, part of Springer Nature.
The registered company address is: 1 New York Plaza, New York, NY
10004, U.S.A.
I extend this dedication to Afrah Razzak, my exceptional wife. Her
enduring support and remarkable patience during the extended writing
sessions have been invaluable to me.
—Baji Shaik
I lovingly extend this dedication to my dear friend, Baji Shaik. Your
unwavering support and encouragement have been my guiding light,
especially in the most challenging moments. Your belief in me has been a
constant source of inspiration, and I am grateful for your presence in my
journey. This book is as much a tribute to our friendship as it is a
testament to the power of steadfast camaraderie. Thank you for always
being there.
—Dinesh Kumar Chemuduru
Introduction
The PostgreSQL engine comes with its own dedicated procedural
language, similar to procedural languages found in other commercial
database engines. This language, known as PL/pgSQL, offers a range of
powerful features that developers have long desired. For instance,
PL/pgSQL includes certain object-oriented programming capabilities
like the ability to define custom operators and types, as well as custom
aggregates.
In contrast to other programming languages supported by
PostgreSQL, PL/pgSQL is intricately linked with the PostgreSQL
database engine interface. This tight integration ensures optimal
performance and a seamless fit for constructing business logic on the
database side. In this book, we not only introduce the fundamentals of
PL/pgSQL, but we also dive deep into specific use cases that we’ve
implemented for particular scenarios. Our aim is to comprehensively
cover the various features, functionalities, and application scenarios of
PL/pgSQL, offering assistance in crafting effective server-side objects
with ease.
Through the content of this book, you will gain an understanding of
PL/pgSQL’s design and dive deep into its transaction model, including
how commit and rollback operations function. You’ll discover strategies
for optimizing PL/pgSQL functions and procedures and explore the
mechanics of inline or anonymous server-side code, along with its
limitations. Furthermore, you’ll acquire insights into debugging and
profiling PL/pgSQL code and learn techniques for conducting statistical
analyses on the PL/pgSQL code you create.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub
(https://github.com/Apress). For more detailed information, please
visit https://www.apress.com/gp/services/source-code.
Acknowledgments
I would like to express my gratitude to several individuals who have
played a crucial role in making this book a reality. A heartfelt thank-you
to Apress Media for providing me with this valuable opportunity. I am
especially grateful to my coauthor and mentor, Dinesh Kumar
Chemuduru, for his exceptional collaboration. I want to express my
gratitude to Divya Modi and Nirmal Selvaraj for being understanding of
our hectic schedules and providing us with continuous support
throughout the entire process. Special thanks to Deepak Mahto for his
thorough review of the book. Lastly, I am profoundly thankful to my
parents, Lalu Saheb Shaik and Nasar Bee, whose unwavering support
has shaped me into the person I am today.
—Baji Shaik
1. Introduction to PL/pgSQL
Baji Shaik1 and Dinesh Kumar Chemuduru2
(1) Texas, TX, USA
(2) Andhra Pradesh, India
PL/pgSQL Installation
PL/pgSQL is already included in PostgreSQL, so if you have PostgreSQL
installed, you should have PL/pgSQL as well. However, you may need to
enable it if it is not already enabled. Here are the steps to enable
PL/pgSQL in PostgreSQL:
1. Install PostgreSQL psql client to connect to the database, or you can
use the pgAdmin client tool.
For Ubuntu, the following are the simple steps to install the client:
# Create the file repository configuration:
wget --quiet -O -
https://www.postgresql.org/media/keys/ACCC4CF8.asc
| sudo apt-key add -
postgres=# \dx
List of installed extensions
Name | Version | Schema | Description
-----+---------+--------+-------------
(0 rows)
postgres=# select * from pg_extension where
extname='plpgsql';
oid | extname | extowner | extnamespace |
extrelocatable | extversion | extconfig |
extcondition
----+---------+----------+--------------+---------
-------+------------+-----------+--------------
(0 rows)
postgres=# \dx
List of installed extensions
Name | Version
| Schema | Description
------ -+---------+------------+------------------
------------
plpgsql | 1.0 | pg_catalog | PL/pgSQL
procedural language
(1 row)
JavaScript
postgres=# select * from pg_extension where
extname='plpgsql';
oid | extname | extowner | extnamespace |
extrelocatable | extversion | extconfig |
extcondition
------+---------+----------+--------------+-------
---------+------------+-----------+-------------
16388 | plpgsql | 10 | 11 |
f | 1.0 | |
(1 row)
PL/pgSQL Execution Flow
PL/pgSQL is like every other “loadable, procedural language.” PL/pgSQL
gets loaded through a function manager called fmgr. The fmgr loads the
language handler when a procedural language function or procedure is
executed and calls it. The execution flow of PL/pgSQL code is similar to
that of other procedural programming languages, with parsing,
compilation, execution, and cleanup stages. However, PL/pgSQL code is
executed on the server side, which means that it has direct access to the
database and can perform database operations more efficiently than
client-side code.
On the first call of a PL/pgSQL function or procedure in a session, the
server first parses the code to check for syntax errors. The call handler
will “compile” a function statement tree once the code is parsed. When
the code is compiled, it turns into an internal form that the server can
execute more efficiently. SQL queries in the function are just kept as a
string at this point, and the expressions like the following are actually
SQL queries:
my_var := some_param * 10
The SQL queries are actually parsed at this point, and parser hooks
are used to replace variables/parameters with PARAM nodes in the parse
tree. The PL/pgSQL statement tree is very similar to a PostgreSQL
execution tree. After the parse and compile, the call handler then executes
that statement tree. On the first execution of a statement node that has an
SQL query in it, that query is prepared via the Server Programming
Interface (SPI). The SPI provides a simple and efficient way to execute
SQL commands, retrieve query results, and manipulate the database. The
compiled code is then executed by the server. Based on any variable and
control structure declaration, the server creates a new execution
environment for the PL/pgSQL code. If the PL/pgSQL code is a function or
stored procedure that returns a result set, the server will send the result
set back to the client. Once the execution of the code is complete, the
server will clean up any resources that were used by the PL/pgSQL code,
including variables and any temporary tables that were created.
Figure 1-1 represents the flow of execution.
Figure 1-1 PL/pgSQL execution flow
This diagram illustrates the high-level steps of the PL/pgSQL
execution flow. However, it's important to note that PL/pgSQL code can
be quite complex and may include multiple control structures, error
handling blocks, and nested and even recursive PL/pgSQL function calls
and trigger invocations and database operations. The actual execution
flow of a specific PL/pgSQL function or stored procedure will depend on
the specific code and logic used. This call hierarchy is not limited to
PL/pgSQL. All procedural languages share the common entry point of the
fmgr, so they can be mixed and matched in trigger and function call
stacks.
PL/pgSQL Blocks
PL/pgSQL is a block-structured language. The basic unit in any PL/pgSQL
code is a block. All PL/pgSQL code is composed of a single block or blocks
that occur either sequentially or nested within another block. There are
two kinds of blocks:
Anonymous or unnamed blocks (DO)
Named blocks (functions)
DO $$
[ <<label>> ]
[ DECLARE
-- Variable declaration here
]
BEGIN
-- Execute statements here
END [ label ];
$$;
Now, let us start with a simple hello world code block, which does not
have any name associated with it:
postgres=# DO
$$
BEGIN
RAISE NOTICE 'Hello World';
END;
$$;
NOTICE: Hello World
DO
In the preceding example, the RAISE NOTICE command will help
us to print the given message on the client console. As you can see here,
the block is declared without a name, and if you want to print Hello
World, then you have to repeat the same set of instructions again.
Now, let us print the Hello World line by line rather than in a single
line:
postgres=# DO
$o$
BEGIN
RAISE NOTICE $i$
Hello
World
$i$;
END;
$o$;
NOTICE:
Hello
World
DO
postgres=# DO
$$
BEGIN
BEGIN
RAISE NOTICE 'Hello World';
Another random document with
no related content on Scribd:
The Project Gutenberg eBook of Kaunis Saksa
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: Finnish
UUNO KAILAS
OTTO MANNISELLE,
suomentajamestarille
kunnioituksella omistettu.
SISÄLLYS:
Uuno Kailas.
WOLFGANG VON GOETHE (1749-
1832)
PROMETHEUS
HYPERIONIN KOHTALOLAULU
ILLASSA
Jo laske, armas aurinko. Tunteneet he eivät sua, palvoen
pyhyyttäs: Sä oothan siivin vaivattomin raskautettujen yli
noussut.
***
HYVÄ YSTÄVÄ
Oli ystävä mulla kerran, oli parhain päällä maan. Kun rummut
soi sotateillä, sama ain’ oli tahti meillä, hänen astuin
rinnallaan.
KIEVARIN TYTÄR
Jano kulkureill’ oli. Poikettiin
siis Reinin varrella kievariin.
YLÖSNOUSEMUSPÄIVÄNÄ
Minä unta näin: tuli takaisin taas onneni päivin keväisin, tuli
ystävät, hyttystanssi, oi – naris silloin rasia – hitto soi! Unet
eivät kimmellä enää – Suru-vanhus niistää nenää.