Tải bản đầy đủ (.pdf) (1,876 trang)

Sams PostgreSQL the comprehensive guide to buildin 001

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (10.42 MB, 1,876 trang )

PostgreSQL:Thecomprehensiveguidetobuilding,
programming,andadministeringPostgreSQL
databases,SecondEdition
ByKorryDouglas,SusanDouglas
...............................................
Publisher:SamsPublishing
PubDate:July26,2005
ISBN:0-672-32756-2
Pages:1032

TableofContents|Index

Thesecondeditionofthebest-sellingPostgreSQLhasbeenupdatedtocompletelycover
newfeaturesandcapabilitiesofthe8.0versionofPostgreSQL.Youwillbeleadthrough
theinternalsofthepowerfulPostgreSQLopensourcedatabasechapter,offeringaneasyto-read,code-basedapproachthatmakesiteasytounderstandhoweachfeatureis
implemented,howtobestuseeachfeature,andhowtogetmoreperformancefrom
databaseapplications.Thisdefinitiveguidetobuilding,programmingandadministering
thepowerfulPostgreSQLopen-sourcedatabasesystemwillhelpyouharnessoneofthe
mostwidelyusedopensource,enterprise-leveldatabasesystems.


PostgreSQL:Thecomprehensiveguidetobuilding,
programming,andadministeringPostgreSQL
databases,SecondEdition
ByKorryDouglas,SusanDouglas
...............................................
Publisher:SamsPublishing
PubDate:July26,2005
ISBN:0-672-32756-2
Pages:1032


TableofContents|Index










































Copyright
TheRealValueinFreeSoftware
AbouttheAuthors
Acknowledgments
WeWanttoHearfromYou!
ReaderServices
Introduction
PostgreSQLFeatures
WhatVersionsDoesThisBookCover?
WhatTopicsDoesThisBookCover?
What'sNewintheSecondEdition?
PartI:GeneralPostgreSQLUse
Chapter1.IntroductiontoPostgreSQLandSQL
ASampleDatabase
BasicDatabaseTerminology
Prerequisites
ConnectingtoaDatabase
CreatingTables

ViewingTableDescriptions
AddingNewRecordstoaTable
InstallingtheSampleDatabase
RetrievingDatafromtheSampleDatabase
TheCASEExpression




















































































Aggregates
Multi-TableJoins
UPDATE

DELETE
A(Very)ShortIntroductiontoTransactionProcessing
CreatingNewTablesUsingCREATETABLE...AS
UsingVIEW
Summary
Chapter2.WorkingwithDatainPostgreSQL
NULLValues
CharacterValues
NumericValues
Date/TimeValues
Boolean(Logical)Values
GeometricDataTypes
ObjectIDs(OID)
BLOBs
NetworkAddressDataTypes
Sequences
Arrays
ColumnConstraints
ExpressionEvaluationandTypeConversion
CreatingYourOwnDataTypes
Summary
Chapter3.PostgreSQLSQLSyntaxandUse
PostgreSQLNamingRules
Creating,Destroying,andViewingDatabases
CreatingNewTables
AddingIndexestoaTable
GettingInformationAboutDatabasesandTables
TransactionProcessing
Summary
Chapter4.Performance

HowPostgreSQLOrganizesData
GatheringPerformanceInformation
UnderstandingHowPostgreSQLExecutesaQuery
ExecutionPlansGeneratedbythePlanner
TheARCBufferManager
TableStatistics


















































































PerformanceTips
PartII:ProgrammingwithPostgreSQL
Chapter5.IntroductiontoPostgreSQLProgramming
Server-SideProgramming

Client-SideAPIs
GeneralStructureofClientApplications
ChoosinganApplicationEnvironment
Summary
Chapter6.ExtendingPostgreSQL
ExtendingthePostgreSQLServerwithCustomFunctions
ReturningMultipleValuesfromanExtensionFunction
ThePostgreSQLSRFInterface
ReturningCompleteRowsfromanExtensionFunction
ExtendingthePostgreSQLServerwithCustomDataTypes
InternalandExternalForms
DefiningaSimpleDataTypeinPostgreSQL
DefiningtheDataTypeinC
DefiningtheInputandOutputFunctionsinC
DefiningtheInputandOutputFunctionsinPostgreSQL
DefiningtheDataTypeinPostgreSQL
IndexingCustomDataTypes
Summary
Chapter7.PL/pgSQL
InstallingPL/pgSQL
LanguageStructure
FunctionBody
Cursors
Triggers
PolymorphicFunctions
PL/pgSQLandSecurity
Summary
Chapter8.ThePostgreSQLCAPIlibpq
Prerequisites
Client1ConnectingtotheServer

Client2AddingErrorChecking
Client3SimpleProcessingPQexec()andPQprint()
Client4AnInteractiveQueryProcessor
Summary
Chapter9.ASimplerCAPIlibpgeasy



















































































Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3ProcessingQueries

Client4AnInteractiveQueryProcessor
Summary
Chapter10.TheNewPostgreSQLC++APIlibpqxx
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3ProcessingQueries
Client4Workingwithtransactors
Summary
Chapter11.EmbeddingSQLCommandsinCProgramsecpg
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3ProcessingSQLCommands
Client4AnInteractiveQueryProcessor
Summary
Chapter12.UsingPostgreSQLfromanODBCClientApplication
ODBCArchitectureOverview
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3ProcessingQueries
Client4AnInteractiveQueryProcessor
Summary
Resources
Chapter13.UsingPostgreSQLfromaJavaClientApplication
JDBCArchitectureOverview
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking

Client3ProcessingQueries
Client4AnInteractiveQueryProcessor
Summary
Chapter14.UsingPostgreSQLwithPerl
DBIArchitectureOverview

















































































Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3ProcessingQueries
Client4AnInteractiveQueryProcessor
Summary

Chapter15.UsingPostgreSQLwithPHP
PHPArchitectureOverview
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3QueryProcessing
Client4AnInteractiveQueryProcessor
OtherFeatures
Summary
Chapter16.UsingPostgreSQLwithTclandTcl/Tk
Prerequisites
Client1ConnectingtotheServer
Client2QueryProcessing
Client3AnInteractiveQueryProcessor
ThelibpgtclLarge-ObjectAPI
Summary
Chapter17.UsingPostgreSQLwithPython
Python/PostgreSQLInterfaceArchitecture
Prerequisites
Client1ConnectingtotheServer
Client2AddingErrorChecking
Client3QueryProcessing
Client4AnInteractiveCommandProcessor
Summary
Chapter18.Npgsql:The.NETDataProvider
Prerequisites
PreparingVisualStudio
UnderstandingtheADO.NETClassHierarchy
CreatinganNpgsql-enabledVBProject
Client1ConnectingtotheServer

Client2AnInteractiveQueryProcessor
Client3UpdatingtheDatabasewithaDataSet




Client4AMoreRobustQueryProcessor



Client5UsingaTypedDataSet












































































Summary
Chapter19.OtherUsefulProgrammingTools
PL/JavaWritingStoredProceduresinJava
pgcurlWeb-enablingYourPostgreSQLServer
pgbashWritingPostgreSQL-enabledShellScripts

PartIII:PostgreSQLAdministration
Chapter20.IntroductiontoPostgreSQLAdministration
Security
UserAccounts
BackupandRestore
ServerStartupandShutdown
RunningPostgreSQLonaWindowsHost
Tuning
InstallingUpdates
Localization
Summary
Chapter21.PostgreSQLAdministration
Roadmap(Where'sAllMyStuff?)
InstallingPostgreSQL
ManagingDatabases
ThePostgreSQLBGWRITERprocess
ManagingUserAccounts
ConfiguringYourPostgreSQLRuntimeEnvironment
ArrangingforPostgreSQLStartupandShutdown
BackingUpandCopyingDatabases
Point-in-timeRecovery
Summary
Endnotes
Chapter22.InternationalizationandLocalization
LocaleSupport
Multi-ByteCharacterSets
Summary
Endnotes
Chapter23.Security
SecuringthePostgreSQLDataFiles

SecuringNetworkAccess




SecuringTables




SecuringFunctions
Summary





























Chapter24.ReplicatingPostgreSQLDatawithSlony
Overview
Requirements
CreatingaReplicationCluster
StartingtheReplicationDaemons
CreatingaReplicationSet
SubscribingtoaReplicationSet
ChangingtheClusterTopology(Re-masteringandFailover)
Summary
Chapter25.ContributedModules
ExchangingPostgreSQLDatawithXML
UsingFull-textSearch
Index


Copyright
Copyright©2006bySamsPublishing
Allrightsreserved.Nopartofthisbookshallbereproduced,
storedinaretrievalsystem,ortransmittedbyanymeans,
electronic,mechanical,photocopying,recording,orotherwise,

withoutwrittenpermissionfromthepublisher.Nopatent
liabilityisassumedwithrespecttotheuseoftheinformation
containedherein.Althougheveryprecautionhasbeentakenin
thepreparationofthisbook,thepublisherandauthorassume
noresponsibilityforerrorsoromissions.Norisanyliability
assumedfordamagesresultingfromtheuseoftheinformation
containedherein.
LibraryofCongressCatalogCardNumber:2004097929
PrintedintheUnitedStatesofAmerica
FirstPrinting:July2005
080706054321

Trademarks
Alltermsmentionedinthisbookthatareknowntobe
trademarksorservicemarkshavebeenappropriately
capitalized.SamsPublishingcannotattesttotheaccuracyof
thisinformation.Useofaterminthisbookshouldnotbe
regardedasaffectingthevalidityofanytrademarkorservice
mark.

WarningandDisclaimer


Everyefforthasbeenmadetomakethisbookascompleteand
asaccurateaspossible,butnowarrantyorfitnessisimplied.
Theinformationprovidedisonan"asis"basis.Theauthorsand
thepublishershallhaveneitherliabilitynorresponsibilitytoany
personorentitywithrespecttoanylossordamagesarising
fromtheinformationcontainedinthisbook.


BulkSales
SamsPublishingoffersexcellentdiscountsonthisbookwhen
orderedinquantityforbulkpurchasesorspecialsales.For
moreinformation,pleasecontact
U.S.CorporateandGovernmentSales
1-800-382-3419

ForsalesoutsideoftheU.S.,pleasecontact
InternationalSales


Credits
AcquisitionsEditor
ShelleyJohnston
DevelopmentEditor
DamonJordan
ManagingEditor
CharlotteClapp


ProjectEditor
DanKnott
CopyEditor
LindaSeifert
Indexer
LarrySweazy
Proofreader
WendyOstermeyer
TechnicalEditor
VinceVielhaber

PublishingCoordinator
VanessaEvans
MultimediaDeveloper
DanScherf
BookDesigner
GaryAdair
PageLayout
JeffHenn


TheRealValueinFreeSoftware
Thesedays,itseemsthatmostdiscussionofopen-source
softwarecentersaroundtheideathatyoushouldnothaveto
tieyourfuturetothewhimofsomegiantcorporation.People
saythatopen-sourcesoftwareisbetterthanproprietary
softwarebecauseitisdevelopedandmaintainedbytheusers
insteadofafacelesscompanyouttolightenyourwallet.
Ithinkthattherealvalueinfreesoftwareiseducation.Ihave
neverlearnedanythingbyreadingmyowncode[1].Ontheother
hand,it'sarareoccasionwhenI'velookedatcodewrittenby
someoneelseandhaven'tcomeawaywithanothertoolinmy
toolkit.Peopledon'tthinkalike.Idon'tmeanthatpeople
disagreewitheachother;Imeanthatpeoplesolveproblemsin
differentways.Eachpersonbringsauniquesetofexperiences
tothetable.Eachpersonhashisownsetofgoalsandbiases.
Eachpersonhashisowninterests.Allofthesethingswillshape
thewayyouthinkaboutaproblem.Often,I'llfindmyselfina
heateddisagreementwithacolleagueonlytorealizethatwe
areeachcorrectinourapproach.JustbecauseI'mright,
doesn'tmeanthatmycolleaguecan'tberightaswell.

[1]MaybeIshouldsaythatIhaveneverlearnedanythingnewbyreadingmyowncode.I'vecertainlylookedat
codethatI'vewrittenandwonderedwhatIwasthinkingatthetime,learningthatI'mnotnearlyascleverasI
hadremembered.Oddlyenough,thosewhohavereadmycodehavereachedasimilarconclusion.

Open-sourcesoftwareisagreatwaytolearn.Youcanlearn
aboutprogramming.Youcanlearnaboutdesign.Youcanlearn
aboutdebugging.Sometimes,you'lllearnhownottodesign,
code,ordebug;butthat'savaluablelesson,too.Youcanlearn
smallthings,likehowtocachefiledescriptorsonsystems
wherefiledescriptorsareascarceandexpensiveresource,or
howtousetheselect()functiontoimplementfine-grained
timers.Youcanlearnbigthings,likehowaqueryoptimizer
worksorhowtowriteaparser,orhowtodevelopagood


memory-managementstrategy.
PostgreSQLisagreatexample.I'vebeenusingdatabasesfor
thelasttwodecades.I'veusedmostofthemajorcommercial
databases:Oracle,Sybase,DB2,andMSSQLServer.Witheach
commercialdatabase,thereisawallofknowledgebetweenmy
needsandthevendor'sneedtoprotecthisintellectualproperty.
UntilIstartedexploringopen-sourcedatabases,Ihadan
incompleteunderstandingofhowadatabaseworks.Whywas
thisparticularfeatureimplementedthatway?WhyamIgetting
poorperformancewhenItrythis?That'saneatfeature;I
wonderhowtheydidthat?Everycommercialdatabasetriesto
exposeasmallpieceofitsinnerworkings.Theexplain
statementwillshowyouwhythedatabasemakesits
optimizationdecisions.But,youonlygettoseewhatthevendor
wantsyoutosee.Thevendorisn'ttryingtohidethingsfrom

you(inmostcases),butwithoutcompleteaccesstothesource
code,theyhavetopickandchoosehowtoexposeinformation
inameaningfulway.Withopen-sourcesoftware,youcandive
deepintothesourcecodeandpulloutalltheinformationyou
need.Whilewritingthisbook,I'vespentalotoftimereading
throughthePostgreSQLsourcecode.I'veaddedalotofmy
owncodetorevealmoreinformationsothatIcouldexplain
thingsmoreclearly.Ican'tdothatwithacommercialdatabase.
Therearegemsofbrillianceinmostopen-sourceprojects.Ina
well-designed,well-factoredproject,youwillfinddesignsand
codethatyoucanuseinyourownprojects.Manyopen-source
projectsarestartingtosplittheircodeintoreusablelibraries.
TheApachePortableRuntimeisagoodexample.TheApache
Webserverrunsonmanydiverseplatforms.TheApache
developmentteamsawtheneedforalayerofabstractionthat
wouldprovideaportableinterfacetosystemfunctionssuchas
sharedmemoryandnetworkaccess.Theydecidedtofactorthe
portabilitylayerintoalibraryseparatefromtheirmainproject.
TheresultistheApachePortableRuntimealibraryofcodethat
canbeusedinotheropen-sourceprojects(suchas


PostgreSQL).
Somedevelopershatetoworkonsomeoneelse'scode.Ilove
workingoncodewrittenbyanotherdeveloperIalwayslearn
somethingfromtheexperience.Istronglyencourageyouto
diveintothePostgreSQLsourcecode.Youwilllearnfromit.You
mightevendecidetocontributetotheproject.
KorryDouglas



AbouttheAuthors
KorryDouglasisthedirectorofresearchanddevelopmentfor
AppxSoftware.Overthelasttwodecades,hehasworkedon
thedesignandimplementationofanumberofhigh-level,highproductivitylanguagesanddevelopmentenvironments.His
productsinterfacewithmanyrelational(andnon-relational)
databases.Workingwithsomanydifferentdatabaseproducts
(Oracle,Sybase,SQLServer,DB2,PostgreSQL,MySQL,MSQL)
hasgivenhimabroadunderstandingofthecommonalitiesof,
anddifferencesbetween,databases.
SusanDouglasisthepresidentandCEOofConjectrix,Inc.,a
softwarecompanyspecializingindatabasetechnologiesand
securitytools.Consultingtotheend-usercommunityhasgiven
herwidespreaddatabaseexperienceandarealappreciationfor
high-qualityprogramsandflexibletoolspowerfulenoughto
handledatawellandintuitiveenoughtoactuallyuse.
Korryandhiswife(andbestfriend)Susanraisehorsesinrural
Virginia.BotharenativesofthePacificNorthwest,butprefer
thesunshineandopenspacesofferedbyVirginia.Theyboth
telecommute,preferringtospendasmuchtimeaspossiblewith
their200orsoanimalfriends(whonevercomplainaboutbuggy
code,inelegantdesign,orpoorperformance).Susanisanavid
equestrienne;Korrygetstocleanthebarn.


Acknowledgments
ThankyoutoourtechnicalreviewerVinceVielhaber.We
appreciatehismanyhoursspentporingovermanuscripts
exposingtechnicalinaccuracies.Hisknowledgeandexpertise
havebeeninvaluable.We'dalsoliketothankPeterEisentraut

andBarryStinsonforreviewingthefirsteditionofthisbookand
PaulDuBois(ofMySQLfame)forhisguidancewhilewe
struggledforclarityinthefirstedition.
WewouldespeciallyliketothankthedevelopersofPostgreSQL
fortheyearsofdevelopmentspentproducinganexcellent
database.Withouttheirdevotiontotheproject,itwouldn'thave
evolvedintothemasterpieceweallknowtoday.
Mostofthebooksthatwereadarededicatedtovarious
householdmembersforthelonghoursdevotedtotheirwriting
projectratherthantofamilylife.Instead,wehaveenjoyedthe
longhoursofR&Dspenttogether,interspersedwithscreaming
(duringbreaks,ontherollercoastersatKing'sDominionnotat
eachother).


WeWanttoHearfromYou!
Asthereaderofthisbook,youareourmostimportantcritic
andcommentator.Wevalueyouropinionandwanttoknow
whatwe'redoingright,whatwecoulddobetter,whatareas
you'dliketoseeuspublishin,andanyotherwordsofwisdom
you'rewillingtopassourway.
Youcanemailorwritemedirectlytoletmeknowwhatyoudid
ordidn'tlikeaboutthisbookaswellaswhatwecandotomake
ourbooksstronger.
PleasenotethatIcannothelpyouwithtechnicalproblems
relatedtothetopicofthisbook,andthatduetothehigh
volumeofmailIreceive,Imightnotbeabletoreplytoevery
message.
Whenyouwrite,pleasebesuretoincludethisbook'stitleand
authoraswellasyournameandphoneoremailaddress.Iwill

carefullyreviewyourcommentsandsharethemwiththeauthor
andeditorswhoworkedonthebook.

Email:



Mail:

MarkTaber
AssociatePublisher
SamsPublishing
800East96thStreet
Indianapolis,IN46240USA


ReaderServices
FormoreinformationaboutthisbookoranotherSams
Publishingtitle,visitourwebsiteatwww.samspublishing.com.
TypetheISBN(excludinghyphens)orthetitleofabookinthe
Searchfieldtofindthepageyou'relookingfor.


Introduction
PostgreSQLisarelationaldatabasewithalonghistory.Inthe
late1970s,theUniversityofCaliforniaatBerkeleybegan
developmentofPostgreSQL'sancestorarelationaldatabase
knownasIngres.RelationalTechnologiesturnedIngresintoa
commercialproduct.RelationalTechnologiesbecameIngres
CorporationandwaslateracquiredbyComputerAssociates.

Around1986,MichaelStonebrakerfromUCBerkeleyledateam
thataddedobject-orientedfeaturestothecoreofIngres;the
newversionbecameknownasPostgres.Postgreswasagain
commercialized;thistimebyacompanynamedIllustra,which
becamepartoftheInformixCorporation.AndrewYuandJolly
ChenaddedSQLsupporttoPostgresinthemid-'90s.Prior
versionshadusedadifferent,Postgres-specificquerylanguage
knownasPostquel.In1996,manynewfeatureswereadded,
includingtheMVCCtransactionmodel,moreadherencetothe
SQL92standard,andmanyperformanceimprovements.
Postgresonceagaintookonanewname:PostgreSQL.
Today,PostgreSQLisdevelopedbyaninternationalgroupof
open-sourcesoftwareproponentsknownasthePostgreSQL
GlobalDevelopmentgroup.PostgreSQLisanopen-source
productitisnotproprietaryinanyway.RedHathasrecently
commercializedPostgreSQL,creatingtheRedHatDatabase,but
PostgreSQLitselfwillremainfreeandopensource.


PostgreSQLFeatures
PostgreSQLhasbenefitedwellfromitslonghistory.Today,
PostgreSQLisoneofthemostadvanceddatabaseservers
available.Hereareafewofthefeaturesfoundinastandard
PostgreSQLdistribution:
Object-relationalInPostgreSQL,everytabledefinesaclass.
PostgreSQLimplementsinheritancebetweentables(or,if
youlike,betweenclasses).Functionsandoperatorsare
polymorphic.
StandardscompliantPostgreSQLsyntaximplementsmost
oftheSQL92standardandmanyfeaturesofSQL99.Where

differencesinsyntaxoccur,theyaremostoftenrelatedto
featuresuniquetoPostgreSQL.
OpensourceAninternationalteamofdevelopersmaintains
PostgreSQL.Teammemberscomeandgo,butthecore
membershavebeenenhancingPostgreSQL'sperformance
andfeaturesetsinceatleast1996.Oneadvantageto
PostgreSQL'sopen-sourcenatureisthattalentand
knowledgecanberecruitedasneeded.Thefactthatthis
teamisinternationalensuresthatPostgreSQLisaproduct
thatcanbeusedproductivelyinanynaturallanguage,not
justEnglish.
TransactionprocessingPostgreSQLprotectsdataand
coordinatesmultipleconcurrentusersthroughfull
transactionprocessing.Thetransactionmodelusedby
PostgreSQLisbasedonmulti-versionconcurrencycontrol
(MVCC).MVCCprovidesmuchbetterperformancethanyou
wouldfindwithotherproductsthatcoordinatemultiple
usersthroughtable-,page-,orrow-levellocking.


ReferentialintegrityPostgreSQLimplementscomplete
referentialintegritybysupportingforeignandprimarykey
relationshipsaswellastriggers.Businessrulescanbe
expressedwithinthedatabaseratherthanrelyingonan
externaltool.
MultipleprocedurallanguagesTriggersandother
procedurescanbewritteninanyofseveralprocedural
languages.Server-sidecodeismostcommonlywrittenin
PL/pgSQL,aprocedurallanguagesimilartoOracle's
PL/SQL.Youcanalsodevelopserver-sidecodeinTcl,Perl,

evenbash(theopen-sourceLinux/Unixshell).
Multiple-clientAPIsPostgreSQLsupportsthedevelopment
ofclientapplicationsinmanylanguages.Thisbook
describeshowtointerfacetoPostgreSQLfromC,C++,
ODBC,Perl,PHP,Tcl/Tk,andPython.
UniquedatatypesPostgreSQLprovidesavarietyofdata
types.Besidestheusualnumeric,string,anddatatypes,
youwillalsofindgeometrictypes,aBooleandatatype,and
datatypesdesignedspecificallytodealwithnetwork
addresses.
ExtensibilityOneofthemostimportantfeaturesof
PostgreSQListhatitcanbeextended.Ifyoudon'tfind
somethingthatyouneed,youcanusuallyaddityourself.
Forexample,youcanaddnewdatatypes,newfunctions
andoperators,andevennewproceduralandclient
languages.Therearemanycontributedpackagesavailable
ontheInternet.Forexample,RefractionsResearch,Inc.
hasdevelopedasetofgeographicdatatypesthatcanbe
usedtoefficientlymodelspatial(GIS)data.


WhatVersionsDoesThisBookCover?
Thefirsteditionofthisbookcoveredversions7.1through7.3.
Inthisedition,we'veupdatedthebasicsandaddedcoverage
forthenewfeaturesintroducedinversions7.4and8.0.
Throughoutthebook,I'llbesuretoletyouknowwhichfeatures
workonlyinnewreleases,and,inafewcases,I'llexplain
featuresthathavebeendeprecated(thatis,featuresthatare
obsolete).Youcanusethisbooktoinstall,configure,tune,
program,andmanagePostgreSQLversions7.1through8.0.

Fortunately,thePostgreSQLdeveloperstryveryhardto
maintainforwardcompatibilitynewfeaturestendnottobreak
existingapplications.Thismeansthatallthefeaturesdiscussed
inthisbookshouldstillbeavailableandsubstantiallysimilarin
laterversionsofPostgreSQL.Ihavetriedtoavoidtalkingabout
featuresthathavenotbeenreleasedatthetimeof
writingwhereIhavementionedfuturedevelopments,Iwillpoint
themout.

WhoIsThisBookFor?
IfyouarealreadyusingPostgreSQL,youshouldfindthisbooka
usefulguidetosomeofthefeaturesthatyoumightbeless
familiarwith.Thefirstpartofthebookprovidesanintroduction
toSQLandPostgreSQLforthenewuser.You'llalsofind
informationthatshowshowtoobtainandinstallPostgreSQLon
aUnix/Linuxhost,aswellasonMicrosoftWindows.
Ifyouaredevelopinganapplicationthatwillstoredatain
PostgreSQL,thesecondpartofthisbookwillprovideyouwitha
greatdealofinformationrelatingtoPostgreSQLprogramming.
You'llfindinformationonbothserver-sideandclient-side
programminginavarietyoflanguages.


Everydatabaseneedsoccasionaladministrativework.Thefinal
partofthebookshouldbeofhelpifyouareaPostgreSQL
administrator,oradeveloperoruserthatneedstodo
occasionaladministration.Youwillalsofindinformationonhow
tosecureyourdataagainstinappropriateuse.
Finally,ifyouaretryingtodecidewhichdatabasetousefor
yourcurrentproject(orforfutureprojects),thisbookshould

providealltheinformationyouneedtoevaluatewhether
PostgreSQLwillfityourneeds.


WhatTopicsDoesThisBookCover?
PostgreSQLisahugeproduct.It'snoteasytofindtherightmix
oftopicswhenyouaretryingtofiteverythingintoasingle
book.Thisbookisdividedintothreeparts.
Thefirstpart,"GeneralPostgreSQLUse,"isanintroductionand
user'sguideforPostgreSQL.Chapter1,"Introductionto
PostgreSQLandSQL,"coversthebasicshowtoobtainand
installPostgreSQL(ifyouarerunningLinux,chancesareyou
alreadyhavePostgreSQLanditmaybeinstalled).Thefirst
chapteralsoprovidesagentleintroductiontoSQLand
discussesthesampledatabasewe'llbeusingthroughoutthe
book.Chapter2,"WorkingwithDatainPostgreSQL,"describes
themanydatatypessupportedbyastandardPostgreSQL
distribution;you'lllearnhowtoentervalues(literals)foreach
datatype,whatkindofdatayoucanstorewitheachtype,and
howthosedatatypesarecombinedintoexpressions.Chapter
3,"PostgreSQLSQLSyntaxandUse,"fillsinsomeofthedetails
weglossedoverinthefirsttwochapters.You'lllearnhowto
createnewdatabases,newtablesandindexes,andhow
PostgreSQLkeepsyourdatasafethroughtheuseof
transactions.Chapter4,"Performance,"describesthe
PostgreSQLoptimizer.I'llshowyouhowtogetinformation
aboutthedecisionsmadebytheoptimizer,howtodecipherthat
information,andhowtoinfluencethosedecisions.
PartII,"ProgrammingwithPostgreSQL,"isallaboutPostgreSQL
programming.InChapter5,"IntroductiontoPostgreSQL

Programming,"westartoffbydescribingtheoptionsyouhave
whendevelopingadatabaseapplicationthatworkswith
PostgreSQL(andtherearealotofoptions).Chapter6,
"ExtendingPostgreSQL,"brieflydescribeshowtoextend
PostgreSQLbyaddingnewfunctions,datatypes,andoperators.
Chapter7,"PL/pgSQL,"describesthePL/pgSQLlanguage.
PL/pgSQLisaserver-basedprocedurallanguage.Codethatyou


writeinPL/pgSQLexecuteswithinthePostgreSQLserverand
hasveryfastaccesstodata.Eachchapterintheremainderof
theprogrammingsectiondealswithaclient-basedAPI.Youcan
connecttoaPostgreSQLserverusinganumberoflanguages.I
showyouhowtointerfacetoPostgreSQLusingC,C++,ecpg,
ODBC,JDBC,Perl,PHP,Tcl/Tk,Python,andMicrosoft's.NET.
Chapters8through18allfollowthesamepattern:youdevelop
aseriesofclientapplicationsinagivenlanguage.Thefirst
clientapplicationshowsyouhowtoestablishaconnectionto
thedatabase(andhowthatconnectionisrepresentedbythe
languageinquestion).Thenextclientaddserrorcheckingso
thatyoucaninterceptandreacttounusualconditions.The
thirdclientineachchapterdemonstrateshowtoprocessSQL
commandsfromwithintheclient.Thefinalclientwraps
everythingtogetherandshowsyouhowtobuildaninteractive
queryprocessorusingthelanguagebeingdiscussed.Evenif
youprograminonlyoneortwolanguages,Iwouldencourage
youtostudytheotherchaptersinthissection.Ithinkyou'llfind
thatlookingatthesameapplicationwritteninavarietyof
languageswillhelpyouunderstandthephilosophyfollowedby
thePostgreSQLdevelopmentteam,andit'sagreatwaytostart

learninganewlanguage.Chapter19,"OtherUseful
ProgrammingTools,"introducesyoutoafewprogrammingtools
(andinterfaces)thatyoumightfinduseful:PL/JavaandPL/Perl.
I'llalsoshowyouhowtousePostgreSQLinsideofbashshell
scripts.
Thefinalpartofthisbook(PartIII,"PostgreSQL
Administration")dealswithadministrativeissues.Thefinalsix
chaptersofthisbookshowyouhowtoperformtheoccasional
dutiesrequiredofaPostgreSQLadministrator.Inthefirsttwo
chapters,Chapter20,"IntroductiontoPostgreSQL
Administration,"andChapter21,"PostgreSQLAdministration,"
you'lllearnhowtostartup,shutdown,backup,andrestorea
server.InChapter22,"InternationalizationandLocalization,"
youwilllearnhowPostgreSQLsupportsinternationalizationand
localization.PostgreSQLunderstandshowtostoreandprocess


×