Tải bản đầy đủ - 0 (trang)
Chapter 5. Introduction to PostgreSQL Programming

Chapter 5. Introduction to PostgreSQL Programming

Tải bản đầy đủ - 0trang

Server-SideProgramming

ThetaskofprogrammingforPostgreSQLfallsintotwobroad

categories:server-sideprogrammingandclient-side

programming.

Server-sidecode(asthenameimplies)iscodethatexecutes

withinaPostgreSQLserver.Server-sidecodeexecutesthesame

wayregardlessofwhichlanguagewasusedtoimplementany

givenclient.Iftheclientandserverarerunningondifferent

physicalhosts,allserver-sidecodeexecutesontheserver

machineandwithintheserverprocess.Iftheclientandserver

arerunningonthesamemachine,server-sidecodestillruns

withintheserverprocess.Inmostcases,server-sidecodeis

writteninoneoftheprocedurallanguagesdistributedwith

PostgreSQL.

PostgreSQLversion7.1shipswiththreeprocedurallanguages:

PL/pgSQL,PL/Tcl,andPL/Perl.Release7.2addsPL/Pythonto

themix.

Youcanuseprocedurallanguagestocreatefunctionsthat

executewithintheserver.Afunctionisanamedsequenceof

statementsthatyoucanusewithinanSQLexpression.When

youwriteafunctioninaserver-sidelanguage,youare

extendingtheserver.Theseserverextensionsarealsoknown

asstoredprocedures.



PL/pgSQL

IfyouhaveeverusedacommercialdatabasesystemOracle,

Sybase,orSQLServer,forexampleyouhaveprobablyuseda

SQL-basedprocedurallanguage.Oracle'sprocedurallanguageis

calledPL/SQL;SybaseandSQLServeruseTransactSQL.



PL/pgSQLisverysimilartotheseprocedurallanguages.

PL/pgSQLcombinesthedeclarativenatureofSQLcommands

withstructuresofferedbyotherlanguages.Whenyoucreatea

PL/pgSQLfunction,youcandeclarelocalvariablestostore

intermediateresults.PL/pgSQLoffersavarietyofloop

constructs(FORloops,WHILEloops,andcursoriterationloops).

PL/pgSQLgivesyouthecapabilitytoconditionallyexecute

sectionsofcodebasedontheresultsofatest.Youcanpass

parameterstoaPL/pgSQLfunction,makingthefunction

reusable.Youcanalsoinvokeotherfunctionsfromwithina

PL/pgSQLfunction.

Chapter7,"PL/pgSQL,"providesanin-depthdescriptionof

PL/pgSQL.



OtherProceduralLanguagesSupportedby

PostgreSQL

OneofthemoreunusualaspectsofPostgreSQL(comparedto

otherdatabasesystems)isthatyoucanwriteproceduralcode

inmorethanonelanguage.Asnotedpreviously,thestandard

distributionofPostgreSQLincludesPL/pgSQL,PL/Perl,PL/Tcl,

and,asofrelease7.2,PL/Python.

Thelatterthreelanguageseachenableyoutocreatestored

proceduresusingasubsetofthehostlanguage.PostgreSQL

restrictseachtoasubsetofthelanguagetoensurethata

storedprocedurecan'tdonastythingstoyourenvironment.

Specifically,thePostgreSQLprocedurallanguagesarenot

allowedtoperformI/Oexternaltothedatabase(inother

words,youcan'tuseaPostgreSQLprocedurallanguagetodo

anythingoutsideofthecontextoftheserver).Ifyoufindthat

youneedtoaffectyourexternalenvironment,youcanloadan

untrustedprocedurallanguage,butbeawarethatyouwillbe



introducingasecurityriskwhenyoudoso.

Becauseofspacelimitations,Iwon'tbediscussingprocedural

languagesotherthanPL/pgSQLinthisbook.Ifyouwantto

explorePL/Perl,PL/Tcl,orPL/Python,Iwouldrecommendthat

youfindagoodbookaboutthebaselanguageandconsultthe

PostgreSQLreferencedocumentationforPostgreSQL-specific

information.

WhenyouinstallPostgreSQLfromastandarddistribution,none

oftheserver-sidelanguagesareinstalled.Youcanpickand

choosewhichlanguagesyouwanttoinstallintheserver.Ifyou

don'tuseagivenlanguage,youcanchoosenottoinstallit.I'll

showyouhowtoinstallserver-sidelanguagesinChapter7.

Youcanseewhichlanguagesarecurrentlyinstalledinyour

databaseserverwiththefollowingquery:

movies=#select*frompg_language;



lanname|lanispl|lanpltrusted|lanplcallfoid|lancompile



----------+---------+--------------+---------------+----------internal|f|f|0|n/a

C|f|f|0|/bin/cc

sql|f|f|0|postgres

(3rows)

Youcanseethatmyservercurrentlysupportsthreelanguages:

internal,C,andsql.Thelanisplcolumntellsusthatnoneof

theseareconsideredtobeprocedurallanguages.Youmaybe

thinkingthatCshouldbeconsideredaprocedurallanguage,but



inthiscontextaprocedurallanguageisonethatcanbe

installedandde-installedfromtheserver.Youcandetermine

whetheralanguageistrustedbyexaminingthelanpltrusted

column.Atrustedlanguagepromisesnottoprovideelevated

privilegestoauser.Ifalanguageisnotatrustedlanguage,

onlyPostgreSQLsuperuserscancreatenewfunctioninthat

language.



ExtendingPostgreSQLUsingExternal

Languages

PostgreSQL-hostedprocedurallanguagesarenottheonlytools

availableforextendingtheserver.Youcanalsoaddextensions

toaPostgreSQLserverbycreatingcustomdatatypes,new

functions,andnewoperatorswritteninanexternallanguage

(usuallyCorC++).

Whenyoucreateprocedural-languageextensions,thesource

code(andtheobject-code,ifany)forthosefunctionsisstored

intableswithinthedatabase.Whenyoucreateafunctionusing

anexternallanguage,thefunctionisnotstoredinthe

database.Instead,itisstoredinashared-librarythatislinked

intotheserverwhenfirstused.

YoucanfindmanyPostgreSQLextensionsontheweb.For

example,thePostGISprojectaddsasetofdatatypesand

supportingfunctionsfordealingwithgeographicdata.The

contribdirectoryofaPostgreSQLdistributioncontainsan

extensionfordealingwithISBNsandISSNs.

InChapter6,"ExtendingPostgreSQL,"I'llshowyouafew

simpleexamplesofhowtoaddcustomdatatypesandfunctions

writteninC.



Client-SideAPIs

WhenyouwanttobuildapplicationsthataccessaPostgreSQL

database,youuseone(ormore)oftheclientapplication

programminginterfaces(orAPIsforshort).PostgreSQLhasa

richvarietyofAPIsthatsupportanumberofprogramming

languages.

PostgreSQLshipswiththeAPIsshowninTable5.1.

Table5.1.PostgreSQLClientAPIs

InterfaceName



SupportedLanguages



DescribedIn



libpq



C/C++



Chapter8



libpgeasy



C/C++



Chapter9



libpq++



C++



Chapter10



ecpg



C/C++



Chapter11



ODBC



C/C++



Chapter12



JDBC



Java



Chapter13



Perl



Perl



Chapter14



PHP1



PHP



Chapter15



pgtcl



TCL



Chapter16



PyGreSQL



Python



Chapter17



pg.el[1]



EmacsLisp



Notcovered



[1]ThestandardPostgreSQLdistributiondoesnotincludethePHPorEmacsinterfaces,butthey

areavailableseparatelyontheweb.



Table5.1isnotall-inclusive.YoucanwritePostgreSQLclients

usinglanguagesnotmentionedinTable5.1.Forexample,Kylix

(Borland'sPascalofferingforLinux)offersaPostgreSQL

interface.Also,manyotherlanguages(suchasMicrosoftAccess

andVisualBasic)provideaccesstoPostgreSQLthroughthe

ODBCinterface.



GeneralStructureofClientApplications

Thisisagoodtimetodiscuss,ingeneralterms,howaclient

applicationinteractswithaPostgreSQLdatabase.Alltheclient

APIshaveacommonstructure,butthedetailsvarygreatly

fromlanguagetolanguage.

Figure5.1illustratesthebasicflowofaclient'sinteractionwith

aserver.



Figure5.1.Client/serverinteraction.



AnapplicationbeginsinteractingwithaPostgreSQLdatabaseby

establishingaconnection.

BecausePostgreSQLisaclient/serverdatabase,somesortof

connectionmustexistbetweenaclientapplicationanda

databaseserver.InthecaseofPostgreSQL,client/server

communicationtakestheformofanetworklink.Iftheclient



andserverareondifferentsystems,thenetworklinkisa

TCP/IPsocket.Iftheclientandserverareonthesamesystem,

thenetworklinkiseitheraUnix-domainsocketoraTCP/IP

connection.AUnix-domainsocketisalinkthatexistsentirely

withinasinglehostthenetworkisalogicalnetwork(ratherthan

aphysicalnetwork)withintheOSkernel.

Regardlessofwhetheryouareconnectingtoalocalserverora

remoteserver,theAPIusesasetofpropertiestoestablishthe

connection.Connectionpropertiesareusedtoidentifythe

server(anetworkportnumberandhostaddress),thespecific

databasethatyouwanttoconnectto,youruserID(and

passwordifrequired),andvariousdebuggingandlogging

options.EachAPIallowsyoutoexplicitlyspecifyconnection

properties,butyoucanalsousedefaultvaluesforsome(orall)

oftheproperties.I'llcoverthedefaultingmechanismsusedby

eachAPIinlaterchapters.

Afteraserverconnectionhasbeenestablished,theAPIgives

youahandle.Ahandleisnothingmorethanachunkofdata

thatyougetfromtheAPIandthatyougivebacktotheAPI

whenyouwanttosendorreceivedataovertheconnection.The

exactformofahandlevariesdependingonthelanguagethat

youareusing(ormoreprecisely,thedatatypeofahandle

varieswiththeAPIthatyouuse).Forexample,inlibpq(theC

API),ahandleisavoidpointeryoucan'tdoanythingwithavoid

pointerexcepttogiveitbacktotheAPI.Inthecaseoflibpq++

andJDBC,ahandleisembeddedwithinaclass.

AfteryouobtainaconnectionhandlefromtheAPI,youcanuse

thathandletointeractwiththedatabase.Typically,aclientwill

wanttoexecuteSQLqueriesandprocessresults.EachAPI

providesasetoffunctionsthatwillsendaSQLcommandtothe

database.Inthesimplestcase,youuseasinglefunction;more

complexapplications(andAPIs)canseparatecommand

executionintotwophases.Thefirstphasesendsthecommand

totheserver(forerrorcheckingandqueryplanning)andthe



secondphaseactuallycarriesoutthecommand;youcanrepeat

theexecutionphaseasmanytimesasyoulike.Theadvantage

toatwo-phaseexecutionmethodisperformance.Youcanparse

andplanacommandonceandexecuteitmanytimes,rather

thanparsingandplanningeverytimeyouexecutethe

command.Two-phaseexecutioncanalsosimplifyyourcodeby

factoringtheworkrequiredtogenerateacommandintoa

separatefunction:Onefunctioncangenerateacommandanda

separatefunctioncanexecutethecommand.



Two-PhaseExecution

EventhoughsomeAPIssupportatwo-phaseexecutionmodel,theunderlying

PostgreSQLserverdoesnot.Youwillnotgainanyperformanceimprovements

usingtwo-phaseexecutionwithPostgreSQL,butyouwillifyourapplicationuses

aPostgreSQL-compatibleAPItocommunicatewithotherdatabases.Ifyour

clientapplicationusesaportableAPI(meaninganAPIthatcancommunicate

withdatabaseserversotherthanPostgreSQL),youmightwanttouseatwophasestrategysothatyoucanrealizeaperformancegainwhenyourclient

applicationisconnectedtosomeotherdatabase.



AfteryouuseanAPItosendacommandtotheserver,youget

backthreetypesofresults.Thefirstresultthatcomesback

fromtheserverisanindicationofsuccessorfailureevery

commandthatyousendtotheserverwilleitherfailorsucceed.

Ifyourcommandfails,youcanusetheAPItoretrieveanerror

codeandatranslationofthatcodeintosomeformoftextual

message.

Iftheservertellsyouthatthecommandexecutedsuccessfully,

youcanretrievethenexttypeofresult:metadata.Metadatais

dataaboutdata.Specifically,metadataisinformationaboutthe

resultsofthecommandthatyoujustexecuted.Ifyoualready

knowtheformatoftheresultset,youcanignorethemetadata.

WhenyouexecuteacommandsuchasINSERT,UPDATE,or

DELETE,themetadatareturnedbytheserverissimplyacount

ofthenumberofrowsaffectedbythecommand.Some

commandsreturnnometadata.Forexample,whenyouexecute

aCREATETABLEcommand,theonlyresultsthatyougetfrom

theserveraresuccessorfailure(andanerrorcodeifthe

commandfails).WhenyouexecuteaSELECTcommand,the

metadataismorecomplex.RememberthataSELECTstatement

canreturnasetofzeroormorerows,eachcontainingoneor

morecolumns.Thisiscalledtheresultset.Themetadatafora

SELECTstatementdescribeseachofthecolumnsintheresult

set.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 5. Introduction to PostgreSQL Programming

Tải bản đầy đủ ngay(0 tr)

×