Tải bản đầy đủ - 0 (trang)
Chapter 8. The PostgreSQL C API - libpq

Chapter 8. The PostgreSQL C API - libpq

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

APIs.AfteryouunderstandhowtointeractwithaPostgreSQL

serverusinglibpq,youwillfindthatmostoftheotherAPIs

simplywrapupthelibpqAPIindifferentflavors.Forexample,

thelibpgeasyAPIcombinessomeofthemorecommonlibpq

operationsintoasetofhigher-levelfunctions.Thelibpgeasy

functionsareeasiertouse,butyoudon'thavequiteasmuch

powerandflexibilityasyouwouldwithalibpqapplication.



Prerequisites

Whenyouwriteaclientapplicationusinglibpq,you'llneedaC

compiler.I'llassumethatyouhavetheGNUCcompiler(gcc)

installedandreadytouse.I'llalsoassumethatyouhaveGNU

makeavailable,andI'llusethattooltoactuallyinvokethe

compiler(andlinker).

APIsthatareusedwithinaCapplicationareusuallymadeupof

twocomponents:asetofheaderfilesandanobjectcode

library.

Theheaderfilescontaindatatypedefinitionsandfunction

prototypes(inotherwords,theheaderfilesdescribetheAPIto

yourCcompiler).Theobjectcodelibrarycontainstheactual

implementationforeachfunctioncontainedintheAPI.When

youuselibpq,youwillneedtoincludethelibpq-fe.hheader

filewithinyourCcode(usingthe#includedirective).Youwill

alsoneedtolinkyourprogramagainstthelibpqobjectlibrary.



Client1ConnectingtotheServer

Ourfirstclientisverysimpleitconnectstoaserver,

disconnects,andthenexits.

Therearetwosetsoffunctionsthatyoucanusetoconnecttoa

PostgreSQLserver:thesimpleformusesthePQconnectdb()

function,whereasthemorecomplexformuses

PQconnectStart()andPQconnectPoll().PQconnectdb()is

easiertousebecauseitisasynchronousfunction;whenyou

callPQconnectdb(),yourprogramwillnotcontinueuntilthe

connectionattemptsucceedsorfails.ThePQconnectStart()

andPQconnectPoll()functionsgiveyourapplicationawayto

connecttoaserverasynchronously.Acallto

PQconnectStart()returnsimmediatelyitwon'twaitforthe

connectionattempttocomplete.ThePQconnectPoll()function

canbeusedtomonitortheprogressofaconnectionattempt

startedbyPQconnectStart().Iusethesynchronousformin

thischapter:

/*

**File:client1.c

*/



#include"libpq-fe.h"



intmain(void)



{

PGconn*connection;



connection=PQconnectdb("");



PQfinish(connection);



return(0);

}



client1.cstartsbyincludingasingleheaderfile:libpq-fe.h.

Thelibpq-fe.hfiledefinesthedatatypesthatweneedto

communicatewithlibpq.libpq-fe.halsocontainsfunction

prototypesforthelibpqAPIfunctions.

ConnectingtoaPostgreSQLdatabasefromlibpqcanbevery

simple.ThePQconnectdb()functionreturnsahandletoa

connectionobject.PQconnectdb()issynchronousitwillnot

returntothecalleruntiltheconnectionattemptsucceedsor

fails.HereistheprototypeforPQconnectdb():

externPGconn*PQconnectdb(constchar*conninfo);



PQconnectdb()takesasingleargumentapointertoanullterminatedconnectionstring.Aconnectionstringisalistof

zeroormoreconnectionattributes.Forexample,theconnection



string"dbname=accountinguser=korry"specifiesthatwe

wanttoconnecttoadatabasenamed"accounting"asuser

"korry".Eachoptionisoftheformkeyword=value.Multiple

attributesareseparatedbywhitespace.

NoticethatIspecifiedanemptyconnectionstringinthis

example.WhenPQconnectdb()findsanemptyconnection

string,itconnectstothedefaultdatabaseusingadefaultsetof

attributes.AnemptystringisnotthesameasaNULLpointer.

Don'tpassaNULLpointertoPQconnectdb()unlessyouwantto

seelibpq(andyourapplication)dieafierydeath.

I'lldescribeconnectionattributesandtheirdefaultvaluesin

moredetailabitlater.WhenyoucallPQconnectdb(),youget

backapointertoaPGconn.PGconnisconsideredahandle.A

handleisanopaquedatatype,meaningthatthereissomething

behindaPGconnpointer,butyoucan'tseeit.Theinformation

behindahandleisfor"internaluseonly".Thelibpqlibraryhas

accesstotheimplementationdetails,butAPIusersdonot.A

PGconnobjectrepresentsadatabaseconnectionwithinyour

application.Youwillusethisobjectwhenyoucallotherlibpq

functions.



CompilingtheClient

Nowlet'scompileclient1.candtrytorunit.Youwillusea

simplemakefiletodrivetheCcompilerandlinker.Hereisthe

makefileyouwillusethroughoutthischapterasyouaddnew

clients,youwilljustaddnewtargetstothemakefile:

##File:Makefile

##



##Rulestocreatelibpqsampleapplications



CPPFLAGS+=-I/usr/local/pgsql/include

CFLAGS+=-g

LDFLAGS+=-g

LDLIBS+=-L/usr/local/pgsql/lib-lpq



client1:client1.o

IfyouhaveinstalledPostgreSQLintoadirectoryotherthan

/usr/local/pgsql,youshouldsubstituteyourdirectorynames

inthemakefile.

Tobuildclient1withthismakefile,youcanusethefollowing

command:

$makeclient1

cc-g-I/usr/local/pg721/include-c-oclient1.oclient1.c

cc-gclient1.o-L/usr/local/pgsql/lib-lpq-oclient1

$

Theclient1applicationdoesn'texpectanycommand-line

parameterssoyoucanrunitlikethis:



$./client1



UsingGNUmaketoBuildlibpqApplications

Themakeutilityisusedtoperformtheoperationsrequiredtoturnasourcefile

(suchasclient1.c)intoanapplication.makedoestwo(extremelyuseful)

thingsforyou.First,makedeterminestheminimumsetofoperationsrequiredto

buildanapplication.Second,makeinvokesthevariouspreprocessors,compilers,

andlinkerstoactuallycarryoutminimumrequiredoperations.

Themakeutilitylearnshowtobuildanapplicationbyconsultingtwosourcesof

information.makehasahugecollectionofbuilt-inrulesthatdescribehowto

convertonetypeoffileintoanothertypeoffile.Forexample,makeknowshow

converta".c"fileintoanexecutable.First,makeconvertsasourcefileintoa

".o"(object)modulebyaskingtheCcompilertocompilethesourcefile.Then,

makeconvertsthe".o"intoanexecutablebyinvokingthelinker.

Thesecondinformationsourcethatmakeusesisknownasamakefile(probably

becausethefileisusuallynamed"makefile"cleverhuh?).Amakefileisasetof

rulesthatdefinehowtobuildyourspecificapplication(orapplications).

makefilesareusuallywrittenintermsoftargetsandprerequisites.Atargetis

somethingthatyouwanttobuild.Aprerequisiteisafilethatthetargetdepends

on.Inthiscase,youwanttobuildanapplicationnamedclient1that'syour

target.Theprerequisiteforyourtargetisclient1.c.Themakefilerulethat

describesthisrelationshipis"client1:client1.c".Thislineisreadas

"client1dependsonclient1.c".Whenmakeseesthisrule,itlooksthroughits

databaseofbuilt-inrulestofindawaytoconvertclient1.cintoclient1.It

findstherule(oractually,rules)toperformthisconversion,invokestheC

compilertoproduceclient1.ofromclient1.c,andtheninvokesthelinkerto

convertclient1.ointotheclientexecutable.

Themakefilethatyouwillusefortheexamplesinthischapterisalittlemore

complexthanthesinglerulethatIjustdescribed.

Thebuilt-inrulethatproducesanobjectmodule(.o)fromaCsourcefile(.c)

lookslikethis:

$(CC)-c$(CPPFLAGS)$(CFLAGS)

ThiscommandinvokestheCcompiler,passingitthecommand-lineflags-c,

$(CPPFLAGS),and$(CFLAGS).$(CPPFLAGS)and$(CFLAGS)arevariablesthat

youcanmodifywithinthemakefile.Tobuildalibpqapplication,youhavetotell

theCcompilerhowtofindthePostgreSQLheaderfiles.Youcandothatby

modifyingthe$(CPPFLAGS)variable:

CPPFLAGS+=-I/usr/local/pgsql/include

IfyouwanttheCcompilertoproducedebuggablecode,youcanmodifythe

$(CFLAGS)variabletoincludethe-gflag:



CFLAGS+=-g

NowwhenmakeinvokestheCcompilertocompileclient1.c,thecommandwill

looklikethis:

cc-c-I/usr/local/pgsql/include-g-oclient1.oclient1.c

Ifthecompilerdoesnotfindanyseriouserrorsinclient1.c,youwillendup

withanobjectmodulenamedclient1.o.Yourtargetisnotclient1.o,but

client1:client1.oisjustanintermediatetarget.Tobuildclient1from

client1.o,makewillinvokethelinkerusingthefollowingbuilt-inrule:

$(CC)$(LDFLAGS)prerequisite.o$(LOADLIBES)$(LDLIBS)

Youwanttolinkclient1.owiththelibpqlibrarytoproduceclient1.Thelibpq

libraryisfoundin/usr/local/pgsql/libonmysystem,soI'lltellmaketo

includelibpqbymodifying$(LDLIBS).Iwantdebuggingsymbolsinmy

executable,soIalsowilladdthe-gflagto$(LDFLAGS):

LDLIBS+=-L/usr/local/pgsql/lib-lpq

LDFLAGS+=-g

Thefinalcommandproducedbymakeis

cc-gclient1.o-L/usr/local/pgsql/lib-lpq-oclient1

Thecompletemakefilelookslikethis:

CPPFLAGS+=-I/usr/local/pgsql/include

CFLAGS+=-g

LDFLAGS+=-g

LDLIBS+=-L/usr/local/pgsql/lib-lpq



client1:client1.o



IdentifyingtheServer

IfyouprovideanemptyconnectionstringtoPQconnectdb(),

howdoesitfindadatabaseserver?libpqusesahierarchyof

defaultvaluestodecidewhichservertotrytoconnectto.

Thelibpqlibraryusesthreedifferentsourceswhentryingtofind

eachconnectionattribute.

First,theconnectionstring(giventoPQconnectedb())can

containasetofkeyword=valuepairs.

Next,libpqlooksforasetofspecificallynamedenvironment

variables.Eachenvironmentvariablecorrespondstooneofthe

keyword=valuepairsthatyoucanuseintheconnectionstring.

Finally,libpqusesasetofvaluesthatarehard-wiredintothe

libraryatbuild-time.

Table8.2showshowthekeywordsandenvironmentvariables

correspondtoeachother.

Table8.2.ConnectionAttributes

Connect-StringKeyword



EnvironmentVariable



Example



user



PGUSER



user=korry



password



PGPASSWORD



password=cows



dbname



PGDATABASE



dbname=accounting



host



PGHOST



host=jersey



hostaddr



PGHOSTADDR



hostaddr=127.0.0.1



port



PGPORT



port=5432



YoucanusethePQconndefaults()functiontofindthedefault

valueforeachconnectionattribute.

1/*

2**File:get_dflts.c

3*/

4

5#include

6#include

7

8intmain(void)

9{

10PQconninfoOption*d;

11PQconninfoOption*start;

12/*

13**Getthedefaultconnectionattributes

14*/

15start=d=PQconndefaults();

16

17while(d->keyword!=NULL)



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

Chapter 8. The PostgreSQL C API - libpq

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

×