Download Complete Procedural Programming with PostgreSQL PL/pgSQL: Design Complex Database-Centric Applications with PL/pgSQL 1st Edition Baji Shaik PDF for All Chapters
Download Complete Procedural Programming with PostgreSQL PL/pgSQL: Design Complex Database-Centric Applications with PL/pgSQL 1st Edition Baji Shaik PDF for All Chapters
com
https://textbookfull.com/product/procedural-programming-
with-postgresql-pl-pgsql-design-complex-database-centric-
applications-with-pl-pgsql-1st-edition-baji-shaik/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/beginning-postgresql-on-the-cloud-
simplifying-database-as-a-service-on-cloud-platforms-baji-shaik/
textboxfull.com
https://textbookfull.com/product/exam-ref-pl-900-microsoft-power-
platform-fundamentals-craig-zacker/
textboxfull.com
https://textbookfull.com/product/complex-analysis-with-
applications-1st-edition-nakhle-h-asmar/
textboxfull.com
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/
textboxfull.com
https://textbookfull.com/product/postgresql-server-programming-second-
edition-dar/
textboxfull.com
https://textbookfull.com/product/learning-postgresql-10-a-beginner-s-
guide-to-building-high-performance-postgresql-database-solutions-juba/
textboxfull.com
https://textbookfull.com/product/sql-server-database-programming-with-
visual-basic-net-concepts-designs-and-implementations-ying-bai/
textboxfull.com
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';
Random documents with unrelated
content Scribd suggests to you:
THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
• You pay a royalty fee of 20% of the gross profits you derive from
the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth in
paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com