PostgreSQL Server Programming 2nd Edition Usama Dar download
PostgreSQL Server Programming 2nd Edition Usama Dar download
download pdf
https://ebookultra.com/download/postgresql-server-programming-2nd-
edition-usama-dar/
https://ebookultra.com/download/postgresql-2nd-edition-korry-douglas/
https://ebookultra.com/download/professional-sql-
server-2005-programming-robert-vieira/
https://ebookultra.com/download/beginning-databases-with-postgresql-
from-novice-to-professional-2nd-edition-matthew/
https://ebookultra.com/download/postgresql-cookbook-1st-edition-
chitij-chauhan/
Learning PostgreSQL Create develop and manage relational
databases in real world applications using PostgreSQL 1st
Edition Juba
https://ebookultra.com/download/learning-postgresql-create-develop-
and-manage-relational-databases-in-real-world-applications-using-
postgresql-1st-edition-juba/
https://ebookultra.com/download/programming-microsoft-sql-
server-2000-with-microsoft-visual-basic-net-1st-edition-edition-rick-
dobson/
https://ebookultra.com/download/building-bluetooth-low-energy-
systems-1st-edition-muhammad-usama-bin-aftab/
https://ebookultra.com/download/computer-networks-an-open-source-
approach-1st-edition-ying-dar-lin/
https://ebookultra.com/download/server-study-guide-2nd-ed-edition-
brad-hryhoruk/
PostgreSQL Server Programming 2nd Edition Usama
Dar Digital Instant Download
Author(s): Usama Dar, Hannu Krosing, Jim Mlodgenski, Kirk Roybal
ISBN(s): 9781783980581, 1783980583
Edition: 2
File Details: PDF, 2.28 MB
Year: 2015
Language: english
PostgreSQL Server Programming Second
Edition
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
All rights reserved. No part of this book may be reproduced, stored in a retrieval system,
or transmitted in any form or by any means, without the prior written permission of the
publisher, except in the case of brief quotations embedded in critical articles or reviews.
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.
Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: June 2013
Second edition: February 2015
Production reference: 1210215
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-058-1
www.packtpub.com
Credits
Authors
Usama Dar
Hannu Krosing
Jim Mlodgenski
Kirk Roybal
Reviewers
Stephen Frost
Rick van Hattem
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
Monica Ajmera Mehta
Production Coordinator
Nitesh Thakur
Cover Work
Nitesh Thakur
Random documents with unrelated
content Scribd suggests to you:
"There's a bullet in there," he said proudly. "I'm going to have it cut
out, and then go right back to the fight. Isn't it lucky it's my left
hand?"
"This water, Madam, was prepared for a raw wound," said Miss
Deborah, sternly. "I must now make the surgeon wait until I get
more."
As she charged down the aisle with a pan of water in her hand,
everybody made way. She had known of my "fine-lady faintness," as
she termed it, and I could see she despised me for it. She had
volunteered, as all the nurses had, and she meant business. She had
no patience with nonsense, and truly she was worth more than all
the rest of us.
"Find it," she rejoined, as she rapidly passed on; but find it I
never did. Ice was an unknown luxury until brought to us later from
private houses.
"He sholy did! Marse Roger cert'nly was comfortable las' night.
He slep' on de field 'twixt two daid horses!"
Then I was placed beside the cot of Mr. (or Captain) Boyd of
Mecklenburg, and was admonished by the matron not to leave him
alone. He was the most patient sufferer in the world, gentle,
courteous, always considerate, never complaining. I observed he
often closed his eyes and sighed. "Are you in pain, Captain?" "No,
no," he would say gently. One day, when I returned from my "rest,"
I found the matron sitting beside him. Tears were running down her
cheeks. She motioned me to take her place, and then added, "No,
no, I will not leave him."
The matron felt his pulse and raised a warning hand. The sick
man's whisper went on:—
The surgeon stood at the foot of the cot and shook his head.
The nurses gathered around with tearful eyes. Presently in clear
tones:—
and in a moment more the Christian soldier had crossed the river
and lain down to rest under the trees.
After one of the bloody battles—I know not if it was Gaines's Mill
or Frazier's Farm or Malvern Hill—a splendid young officer, Colonel
Brokenborough, was taken to our hospital, shot almost to pieces. He
was borne up the stairs and placed in a cot—his broken limbs in
supports swinging from the ceiling. The wife of General Mahone and
I were permitted to assist in nursing him. A young soldier from the
camp was detailed to help us, and a clergyman was in constant
attendance, coming at night that we might rest. Our patient held a
court in his corner of the hospital. Such a dear, gallant, cheery
fellow, handsome, and with a grand air even as he lay prostrate!
Nobody ever heard him complain. He would welcome us in the
morning with the brightest smile. His aide said, "He watches the
head of the stairs and calls up that look for your benefit." "Oh," he
said one day, "you can't guess what's going to happen! Some ladies
have been here and left all these roses, and cologne, and such; and
somebody has sent—champagne! We are going to have a party!"
Ah, but we knew he was very ill! We were bidden to watch him
every minute and not be deceived by his own spirits. Mrs. Mahone
spent her life hunting for ice. My constant care was to keep his
canteen—to which he clung with affection—filled with fresh water
from a spring not far away, and I learned to give it to him so well
that I allowed no one to lift his head for his drink during my hours.
One day, when we were alone, I was fanning him, and thought
he was asleep. He said gravely, "Mrs. Pryor, beyond that curtain they
hung up yesterday poor young Mitchell is lying! They think I don't
know! But I heard when they brought him in,—as I lie here, I listen
to his breathing. I haven't heard it now for some time. Would you
mind seeing if he is all right?"
I passed behind the curtain. The young soldier was dead. His
wide-open eyes seemed to meet mine in mute appeal. I had never
seen or touched a dead man, but I laid my hands upon his eyelids
and closed them. I was standing thus when his nurse, a young
volunteer like myself, came to me.
"I couldn't do that," she said; "I went for the doctor. I'm so glad
you could do it."
"My men are all dead," he said, with anguish, and, falling across
the bed, he gave vent to the passionate grief of his heart.
General McClellan and General Lee both realized that their men
needed rest. My husband was allowed a few days' respite from duty.
Almost without pause he had fought the battles of Williamsburg,
Seven Pines, Mechanicsville, Gaines's Mill, and Frazier's Farm. He
had won his promotion early, but he had lost the loved commander
who appreciated him, had seen old schoolmates and friends fall by
his side,—the dear fellow, George Loyal Gordon, who had been his
best man at our wedding,—old college comrades, valued old
neighbors.
Opposed to him in battle, then and after, were men who in after
years avowed themselves his warm friends,—General Hancock,
General Slocum, General Butterfield, General Sickles, General Fitz-
John Porter, General McClellan, and General Grant. They had fought
loyally under opposing banners, and from time to time, as the war
went on, one and another had been defeated; but over all, and
through all, their allegiance had been given to a banner that has
never surrendered,—the standard of the universal brotherhood of all
true men.
CHAPTER XIV
THE WINTER OF 1861
The histories of these battles have been given again and again
by the military commanders who conducted them. At the close of
the campaign General Lee reported that his men were in the finest
possible condition—only there were too few of them. As the Federal
armies were depleted, they could be reënforced by foreigners. As
our men were lost, we had no fresh troops to take their places.
"Did you know any one from your state, Captain, who was killed
at Sharpsburg?"
With pretty Nelly at the piano, her blue eyes raised to heaven,
and Jack Fleming accompanying her on her guitar, his dark eyes
raised to Nelly, the effect was overwhelming; and lest somebody
should quite finish us by singing, "Flee as a bird to the mountain,"
we would hasten to demand the "Bonnie Blue Flag," or "Dixie," or
the polite invitation to "Joe Hooker" to "come out the Wilderness,"
or, better still, a good story. The latter call would bring many we had
heard before—there are so few good stories in the world—but we
would welcome each one with applause, even if it were no better
than the story of Captain —— (I can't remember the captain's name)
and his black boy "Cæsar." I can only vouch for the story, which ran
thus:—
The captain, going into a skirmish one day, left his tent and its
contents in the care of the boy. "Mayn't I go he'p de cook?" said
Cæsar, much desiring to place himself farther in the rear.
Cæsar, when left alone, grew unhappy, and when straggling shot
fell like hail around the tent, he incontinently fled and hid in the
bushes. When he returned, he found an angry captain indeed.
"I knows it, sah, I knows it! An' I did purtect yo' property, sah! I
sholy did! Dem ole cloes ain' wuth nothin'! I'se feared to bresh 'em
less'n I git a hole in 'em; but dis property," laying his hand proudly
on his breast, "dis property is wuth fifteen hundred dollars!"
"I gwine to git out o' trouble—dar whar I gwine. Dar's too much
powder in dem big things. Dis chile ain't gwine bu'n hisself! An' dar's
dem Minnie bullets, too, comin' frew de a'r, singin': 'Whar—is—you?
Whar—is—you?' I ain't gwine stop an' tell 'em whar I is! I'se a
twenty-two-hundurd-dollar nigger, an' I'se gwine tek keer o' what
b'longs to marster, I is."
Of course we heard again the story of Stonewall Jackson's body-
servant, who always knew before anybody when a battle was
imminent.
"Is that so? Just hold on till I get my gun together, and I will
give you a sort of a salute."[16]
These fellows who didn't fight were all classed under the general
term of "bomb-proofs." One of these officers—a little man—having
appeared in an enormous pair of cavalry boots, ran the gantlet of a
neighboring brigade and heard a frank opinion of himself:—
"I say, Mister, better git out'r them smokestacks! We know you're
in thar 'cause we all kin see yer head stickin' out. You needn' say yer
ain't in thar,—'cause yer ears is workin' powerful."
The allusion to the celebrated long-eared animal was awful!
"Oh, my! Ain't he pooty? Say, Mister! whar'd ye git that biled
shut? Was ye ra-a-ly born so, or was ye put together by corntrack?
Sich a nice-lookin' rooster oughter git down an' scratch for a
wurrum!"
Even when a brigade would pass at double-quick, going into a
battle in which the waiting soldier expected any moment to take
part, the latter would call out:—
They made great fun, too, of their own fears, never considering
them worthy of being treated seriously, or as in any way detrimental.
"Go it, little cotton-tail, go it! I'm jest as skeered as you be, an'
ef I dar'd, I'd run too."
"I ain't runnin' away, Gin'ral! I'm just skeered! Them fellers over
thar are shootin' bullets as big as watermillions! One of 'em went
right peerst my head—right peerst;—an'—an' I wants to go home."
"Well, why didn't you shoot back, sir? You are crying like a
baby."
"I knows it, Gin'ral—I knows it. I wish I was a baby, and a gal-
baby, too, and then I wouldn't hev been cornscripted."
"Blockade on turpentine making? You all hard up? No sale for tar
now?"
"Well—yes!" was the slow rejoinder. "We sell all our tar to Jeff
Davis now."
"The thunder you do! What does the President want with your
tar?"
A good story had found its way into our lines from a Federal
officer. He was commenting upon the fact that all Southern women
were intense rebels—with one exception. He had been with others
marching down a wooded lane which ended in a sharp curve. As
they rounded it, they suddenly came upon a house, before which
was a woman picking up chips. As she had evidently not seen them,
the officer tiptoed up to her, put his arm around her waist, and
kissed her—and stepped back to avoid the box on the ear he knew
he deserved. The woman, however, straightened herself, looked at
him seriously for a moment, and said slowly, "You'll find me right
here every mornin' a-pickin' up chips."
General "Jeb" Stuart was a great hero with these soldier boys,
dashing as he did all over the country with his eight thousand
mounted men. He was our plumed knight—with his gold star and
long feather. They never wearied of stories of his promptness, his
celerity, his meteorlike dashes.
"They'll never catch him!" said one proudly. "They'll always reach
the place where he recently was."
"Fancy him," said another, "with his two hundred weight of iron
on him, and as much on his big cart-horse. Imagine him, armed with
a maul or a lance, a battle-axe, and six-foot pole, going into a fight
at Manassas or Antietam."
"He would never get there," said the General. "A light
cavalryman of the First Virginia would have ridden around King
Arthur or Sir Launcelot half a dozen times while the knight was
bracing himself up for action; and the Chicopee sabre would have
searched out the joints under his chin, or his arm, or his sword-belt,
and would have shucked him like an oyster before he could get his
lance in rest."
But the chief idol of their hearts—of all our hearts—was our
beloved commander, our Bayard sans peur et sans reproche, General
Lee. The hand instinctively sought the cap at the mention of his
name. Indignant comments were made upon the newspaper
criticisms of his early misfortunes in the western part of Virginia in
the autumn of 1861, and one occasion was remembered when, his
own attention having been directed to a fierce newspaper attack, as
unjust in its conclusions as it was untrue in its statements, he was
asked why he silently suffered such unwarranted aspersions; and he
had calmly replied that, while it was very hard to bear, it was
perhaps quite natural that such hasty conclusions should be
announced, and that it was better not to attempt a justification or
defence, but to go steadily on in the discharge of duty to the best of
our ability, leaving all else to the calmer judgment of the future and
to a kind Providence.
Happy was the private soldier who had seen General Lee, thrice
happy the one who had spoken to him. Of the latter, a plain
countryman, having listened to the personal incidents of his fellows,
as they related various occasions when they had been noticed by
General Lee, was fired by a desire to emulate them, and confided
that he, too, had once enjoyed a very interesting and gratifying
interview with General Lee. Importuned to tell it, the soldier
modestly hesitated, but urged by an evident incredulity on the part
of his hearers, he took heart of grace and related as follows:—
"I was jest out of the horspittle an' was natchelly strollin' round
when the scrimmage was goin' on, and I saw Gen'ral Lee on a little
rise not fur off. I santered closer an' closer to him, and when I saw
him look at me I says, 'Pretty warm work over thar, Gen'ral.' He give
me a keen look, an' says he, quiet-like: 'Where do you belong?
Where's your regiment?' An' I says, 'I'm lookin' for my regiment now
—Twelfth Virginia.' 'I can help you,' says he; 'there is your regiment
just going into the fight. Hurry up an' join it.' An' I run off proud as a
pigeon."
"Didn't you think you might get shot?" asked his comrade.
"I suttenly did! I always thinks that. But then, thinks I, Gen'ral
Lee will be mighty sorry 'cause he knowed he sent me into danger
when I was feelin' mighty weak an' poly."
The incidents were many which the officers and soldiers could
remember, illustrating the dear commander's peculiar traits. His aide,
Colonel Taylor, has written me of one most touching incident:—
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.
ebookultra.com