Immediate Download PostgreSQL Server Programming - Second Edition Dar Ebooks 2024
Immediate Download PostgreSQL Server Programming - Second Edition Dar Ebooks 2024
com
https://textbookfull.com/product/postgresql-server-
programming-second-edition-dar/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/learn-postgresql-second-edition/
textboxfull.com
https://textbookfull.com/product/postgresql-9-administration-cookbook-
second-edition-simon-riggs/
textboxfull.com
https://textbookfull.com/product/dar-darverius-house-of-dar-1-1st-
edition-jennifer-julie-miller/
textboxfull.com
https://textbookfull.com/product/windows-server-2016-cookbook-second-
edition-krause/
textboxfull.com
https://textbookfull.com/product/hands-on-microsoft-windows-
server-2016-second-edition-edition-palmer/
textboxfull.com
https://textbookfull.com/product/learn-python-programming-second-
edition-fabrizio-romano/
textboxfull.com
https://textbookfull.com/product/foundations-of-programming-languages-
second-edition-lee/
textboxfull.com
Table of Contents
PostgreSQL Server Programming Second Edition
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. What Is a PostgreSQL Server?
Why program in the server?
Using PL/pgSQL for integrity checks
About this book's code examples
Switching to the expanded display
Moving beyond simple functions
Data comparisons using operators
Managing related data with triggers
Auditing changes
Data cleaning
Custom sort orders
Programming best practices
KISS – keep it simple stupid
DRY – don't repeat yourself
YAGNI – you ain't gonna need it
SOA – service-oriented architecture
Type extensibility
Caching
Wrapping up – why program in the server?
Performance
Ease of maintenance
Improved productivity
Simple ways to tighten security
Summary
2. Server Programming Environments
Cost of acquisition
Availability of developers
Licensing
Predictability
Community
Procedural languages
Third-party tools
Platform compatibility
Application design
Databases are considered harmful
Encapsulation
What does PostgreSQL offer?
Data locality
More basics
Transactions
General error reporting and error handling
User-defined functions
Other parameters
More control
Summary
3. Your First PL/pgSQL Function
Why PL/pgSQL?
The structure of a PL/pgSQL function
Accessing function arguments
Conditional expressions
Loops with counters
Statement termination
Looping through query results
PERFORM versus SELECT
Looping Through Arrays
Returning a record
Acting on the function's results
Summary
4. Returning Structured Data
Sets and arrays
Returning sets
Returning a set of integers
Using a set returning function
Functions based on views
OUT parameters and records
OUT parameters
Returning records
Using RETURNS TABLE
Returning with no predefined structure
Returning SETOF ANY
Variadic argument lists
A summary of the RETURN SETOF variants
Returning cursors
Iterating over cursors returned from another function
Wrapping up of functions returning cursors
Other ways to work with structured data
Complex data types for the modern world – XML and JSON
XML data type and returning data as XML from functions
Returning data in the JSON format
Summary
5. PL/pgSQL Trigger Functions
Creating the trigger function
Creating the trigger
Working on a simple "Hey, I'm called" trigger
The audit trigger
Disallowing DELETE
Disallowing TRUNCATE
Modifying the NEW record
The timestamping trigger
The immutable fields trigger
Controlling when a trigger is called
Conditional triggers
Triggers on specific field changes
Visibility
Most importantly – use triggers cautiously!
Variables passed to the PL/pgSQL TRIGGER function
Summary
6. PostgreSQL Event Triggers
Use cases for creating event triggers
Creating event triggers
Creating an audit trail
Preventing schema changes
A roadmap of event triggers
Summary
7. Debugging PL/pgSQL
Manual debugging with RAISE NOTICE
Throwing exceptions
Logging to a file
The advantages of RAISE NOTICE
The disadvantages of RAISE NOTICE
Visual debugging
Installing the debugger
Installing the debugger from the source
Installing pgAdmin3
Using the debugger
The advantages of the debugger
The disadvantages of the debugger
Summary
8. Using Unrestricted Languages
Are untrusted languages inferior to trusted ones?
Can you use untrusted languages for important functions?
Will untrusted languages corrupt the database?
Why untrusted?
Why PL/Python?
Quick introduction to PL/Python
A minimal PL/Python function
Data type conversions
Writing simple functions in PL/Python
A simple function
Functions returning a record
Table functions
Running queries in the database
Running simple queries
Using prepared queries
Caching prepared queries
Writing trigger functions in PL/Python
Exploring the inputs of a trigger
A log trigger
Constructing queries
Handling exceptions
Atomicity in Python
Debugging PL/Python
Using plpy.notice() to track the function's progress
Using assert
Redirecting sys.stdout and sys.stderr
Thinking out of the "SQL database server" box
Generating thumbnails when saving images
Sending an e-mail
Listing directory contents
Summary
9. Writing Advanced Functions in C
The simplest C function – return (a + b)
add_func.c
Version 0 call conventions
Makefile
CREATE FUNCTION add(int, int)
add_func.sql.in
Summary for writing a C function
Adding functionality to add(int, int)
Smart handling of NULL arguments
Working with any number of arguments
Basic guidelines for writing C code
Memory allocation
Use palloc() and pfree()
Zero-fill the structures
Include files
Public symbol names
Error reporting from C functions
"Error" states that are not errors
When are messages sent to the client?
Running queries and calling PostgreSQL functions
A sample C function using SPI
Visibility of data changes
More info on SPI_* functions
Handling records as arguments or returned values
Returning a single tuple of a complex type
Extracting fields from an argument tuple
Constructing a return tuple
Interlude – what is Datum?
Returning a set of records
Fast capturing of database changes
Doing something at commit/rollback
Synchronizing between backends
Writing functions in C++
Additional resources for C
Summary
10. Scaling Your Database with PL/Proxy
Creating a simple single-server chat
Dealing with success – splitting tables over multiple databases
What expansion plans work and when?
Moving to a bigger server
Master-slave replication – moving reads to slave
Multimaster replication
Data partitioning across multiple servers
Splitting the data
PL/Proxy – the partitioning language
Installing PL/Proxy
The PL/Proxy language syntax
CONNECT, CLUSTER, and RUN ON
SELECT and TARGET
SPLIT – distributing array elements over several partitions
The distribution of data
Configuring the PL/Proxy cluster using functions
Configuring the PL/Proxy cluster using SQL/MED
Moving data from the single to the partitioned database
Connection Pooling
Summary
11. PL/Perl – Perl Procedural Language
When to use PL/Perl
Installing PL/Perl
A simple PL/Perl function
Passing and returning non-scalar types
Writing PL/Perl triggers
Untrusted Perl
Summary
12. PL/Tcl – Tcl Procedural Language
Installing PL/Tcl
A simple PL/Tcl function
Null checking with Strict functions
The parameter format
Passing and returning arrays
Passing composite-type arguments
Accessing databases
Writing PL/Tcl triggers
Untrusted Tcl
Summary
13. Publishing Your Code as PostgreSQL Extensions
When to create an extension
Unpackaged extensions
Extension versions
The .control file
Building an extension
Installing an extension
Viewing extensions
Publishing your extension
Introduction to PostgreSQL Extension Network
Signing up to publish your extension
Creating an extension project the easy way
Providing the metadata about the extension
Writing your extension code
Creating the package
Submitting the package to PGXN
Installing an extension from PGXN
Summary
14. PostgreSQL as an Extensible RDBMS
What can't be extended?
Creating a new operator
Overloading an operator
Optimizing operators
COMMUTATOR
NEGATOR
Creating index access methods
Creating user-defined aggregates
Using foreign data wrappers
Summary
Index
PostgreSQL Server
Programming Second Edition
PostgreSQL Server
Programming Second Edition
Copyright © 2015 Packt Publishing
Every effort has been made in the preparation of this book to ensure
the accuracy of the information presented. However, the information
contained in this book is sold without warranty, either express or
implied. Neither the authors, nor Packt Publishing, and its dealers
and distributors will be held liable for any damages caused or
alleged to be caused directly or indirectly by this book.
Livery Place
35 Livery Street
www.packtpub.com
Credits
Authors
Usama Dar
Hannu Krosing
Jim Mlodgenski
Kirk Roybal
Reviewers
Stephen Frost
Vibhor Kumar
Jeff Lawson
Mariano Reingart
Julien Tachoires
Commissioning Editor
Usha Iyer
Acquisition Editors
Antony Lowe
Meeta Rajani
Sam Wood
Content Development Editor
Adrian Raposo
Technical Editors
Mrunmayee Patil
Chinmay Puranik
Copy Editors
Dipti Kapadia
Aarti Saldanha
Project Coordinator
Kinjal Bari
Proofreaders
Maria Gould
Linda Morris
Indexer
Production Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
About the Authors
Usama Dar is a seasoned software developer and architect. During
his 14 years' career, he has worked extensively with PostgreSQL and
other database technologies. He worked on PostgreSQL internals
extensively while he was working for EnterpriseDB. Currently, he
lives in Munich where he works for Huawei's European Research
Center. He designs the next generation of high-performance
database systems based on open source technologies, such as
PostgreSQL, which are used under high workloads and strict
performance requirements.
Kirk has stood by his choice of PostgreSQL for many years now. His
expertise is founded on keeping up with features and capabilities as
they become available.
A book only has the value that the readers give it. Thank you to
the PostgreSQL community for all the technical, personal, and
professional development help you have provided. The
PostgreSQL community is a great bunch of people, and I have
enjoyed the company of many of them. I hope to contribute
more to this project in the future, and I hope you find my
contributions as valuable as I find yours.
Have you ever had your family ask you what you were doing and
answered them with a function? Try it. No, then again, don't try
it. They may just have you involuntarily checked in somewhere.
About the Reviewers
Stephen Frost is a major contributor and committer to PostgreSQL,
who has been involved with PostgreSQL since 2002, and has
developed features such as the role system and column-level
privileges.
Jeff Lawson has been a fan and user of PostgreSQL since the time
he discovered it in 2001. Over the years, he has also developed and
deployed applications for IBM DB2, Oracle, MySQL, Microsoft SQL
Server, Sybase, and others, but he always prefers PostgreSQL for its
balance of features and openness. Much of his experience involves
developing for Internet-facing websites/projects that require highly
scalable databases with high availability or with provisions for
disaster recovery.
Did you know that Packt offers eBook versions of every book
published, with PDF and ePub files available? You can upgrade to the
eBook version at www.PacktPub.com and as a print book customer,
you are entitled to a discount on the eBook copy. Get in touch with
us at <[email protected]> for more details.
https://www2.packtpub.com/books/subscription/packtlib
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Free access for Packt account
holders
If you have an account with Packt at www.PacktPub.com, you can
use this to access PacktLib today and view 9 entirely free books.
Simply use your login credentials for immediate access.
Preface
This fascinating guide to server programming will take your skills of
PostgreSQL to a whole new level. A step-by-step approach with
illuminating examples will educate you about the full range of
possibilities. You will understand the extension framework of
PostgreSQL and leverage it in ways you haven't even invented yet.
You will learn how to write functions and create your own data
types, all in your favorite programming language. It is a step-by-step
tutorial, with plenty of tips and tricks to kick-start server
programming.
What this book covers
Chapter 1, What Is a PostgreSQL Server?, introduces you to the
PostgreSQL server and will set the tone for the rest of the book. It
introduces you to the ways in which a PostgreSQL server is
extendible, and shows you that it can be treated as a complete
software development framework instead of just a database server.
Chapter 10, Scaling Your Database with PL/Proxy, explains the use
of a special programming language in PostgreSQL called PL/Proxy
and how to use it in order to partition and shard your database.
The next morning I was up before six and had early breakfast. It
was a wonderful day for the trip, brilliantly clear. The corporal in our
office took me out to the airfield, the one near Hanau where Craig
Smyth and I had landed weeks before. It was going to be fun to see
Craig again and find out what he had been up to since we had
parted that morning in Bad Homburg. The drive to the airfield took
about forty-five minutes. There was a wait of half an hour at the field,
and it was after ten when we took off in our big C-47. We flew over
little villages with red roofs, occasionally a large town—but none that
I could identify—and now and then a silvery lake.
Just before we reached Munich, someone said, “There’s Dachau.”
Directly below us, on one side of a broad sweep of dark pine trees,
we saw a group of low buildings and a series of fenced-in
enclosures. On that sunny morning the place looked deserted and
singularly peaceful. Yet only a few weeks before it had been filled
with the miserable victims of Nazi brutality.
In another ten minutes we landed on the dusty field of the principal
Munich airport. Most of the administration buildings had a slightly
battered look but were in working order. It was a welcome relief to
take refuge from the blazing sunshine in the cool hallway of the main
building. The imposing yellow brick lobby was decorated with painted
shields of the different German states or “Länder.” The arms of
Bavaria, Saxony, Hesse-Nassau and the rest formed a colorful frieze
around the walls.
A conveyance of some kind was scheduled to leave for town in a
few minutes. Meanwhile there were sandwiches and coffee for the
plane passengers. By the time we had finished, a weapons carrier
had pulled up before the entrance. Several of us climbed into its
dust-encrusted interior. It took me a little while to get my bearings as
we drove toward Munich. I had spotted the familiar pepper-pot
domes of the Frauenkirche from the air but had recognized no other
landmark of the flat, sprawling city which I had known well before the
war.
It was not until we turned into the broad Prinz Regenten-Strasse
that I knew exactly where I was. As we drove down this handsome
avenue, I got a good look at a long, colonnaded building of white
stone. The roof was draped with what appeared to be an enormous,
dark green fishnet. The billowing scallops of the net flapped about
the gleaming cornice of the building. It was the Haus der Deutschen
Kunst, the huge exhibition gallery dedicated by Hitler in the middle
thirties to the kind of art of which he approved—an art in which there
was no place for untrammeled freedom of expression, only the
pictorial and plastic representation of all the Nazi regime stood for.
The dangling fishnet was part of the elaborate camouflage. I judged
from the condition of the building that the net had admirably served
its purpose.
In a moment we rounded the corner by the Prinz Karl Palais.
Despite the disfiguring coat of ugly olive paint which covered its
classic façade, it had not escaped the bombs. The little palace,
where Mussolini had stayed, had a hollow, battered look and the
formal garden behind it was a waste of furrowed ground and
straggling weeds. We turned left into the wide Ludwig-Strasse and
came to a grinding halt beside a bleak gray building whose walls
were pockmarked with artillery fire. I asked our driver if this were
Lucky Rear headquarters and was told curtly that it wasn’t, but that it
was the end of the line. It was MP headquarters and I’d have to see
if they’d give me a car to take me to my destination, which the driver
said was “’way the hell” on the other side of town.
Before going inside I looked down the street to the left. The
familiar old buildings were still standing, but they were no longer the
trim, cream-colored structures which had once given that part of the
city such a clean, orderly air. Most of them were burned out. Farther
along on the right, the Theatinerkirche was masked with scaffolding.
At the end of the street the Feldherren-Halle, Ludwig I’s copy of the
Loggia dei Lanzi, divested of its statuary, reared its columns in the
midst of the desolation.
It was gray and cool in the rooms of the MP building, but the place
was crowded. Soldiers were everywhere and things seemed to be at
sixes and sevens. After making several inquiries and being passed
from one desk to another, I finally got hold of a brisk young sergeant
to whom I explained my troubles. At first he said there wasn’t a
chance of getting a ride out to Lucky Rear. Every jeep was tied up
and would be for hours. They had just moved into Munich and hadn’t
got things organized yet. Then all at once he relented and with a grin
said, “Oh, you’re Navy, aren’t you? In that case I’ll have to fix you up
somehow. We can’t have the Navy saying the Army doesn’t co-
operate.”
He walked over to a window that looked down on the courtyard
below, shouted instructions to someone and then told me I’d find a
jeep and driver outside. “Think nothing of it, Lieutenant,” he said in
answer to my thanks. “Maybe I’ll be wanting a ship to take me home
one of these days before long. Have to keep on the good side of the
Navy.”
In the Kaiser Josef chamber of the Alt Aussee mine Karl Sieber
and Lieutenant Kern view Michelangelo’s Madonna and Child,
stolen from a church at Bruges.
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