Pg(3pm)
π NAME π
Pg β the Perl5 extension for PostgreSQL, bestie. That's it, that's the whole vibe. πβ¨
(Also hey, this is the Pg(3pm) page, a User Contributed Perl Documentation situation, and it's long so it's coming to you in parts. Buckle up. π)
β¨ SYNOPSIS β¨
Like, here's the whole thing in one glance:
use Pg;
$conn = Pg::connectdb("dbname=template1");
$res = $conn->exec("SELECT * from pg_user");
while (@row = $res->fetchrow) {
print join(" ", @row);
}
π¦ DESCRIPTION π¦
So the Pg module lets you get at all the functions of the Libpq interface of PostgreSQL. Libpq is the programmer's interface to PostgreSQL β the main character, honestly. π
If you want examples of how to actually use this module, go look at the file test.pl. It's giving tutorial energy. πΈ
π GUIDELINES π
This perl interface uses blessed references as objects. The way that works is: after you create a new connection or result object, the relevant Libpq functions serve as virtual methods. And here's the slay part β you do not have to care about freeing the connection- and result-structures. Perl calls the destructor whenever the last reference to an object goes away. Automatic cleanup, no cap. π§
The method fetchrow can be used to fetch the next row from the server, like while (@row = $result->fetchrow). And heads up: columns which have NULL as value will be set to "undef". π
Pg.pm contains one convenience function: doQuery. It fills a two-dimensional array with the result of your query. Usage:
Pg::doQuery($conn, "select attr1, attr2 from tbl", \@ary);
for $i ( 0 .. $#ary ) {
for $j ( 0 .. $#{$ary[$i]} ) {
print "$ary[$i][$j]\t";
}
print "\n";
}
Notice the inner loop ! π Don't skip it, bestie, that's where the rows live.
π₯ FUNCTIONS π₯
The functions have been divided into three sections: Connection, Result, Large Objects. For details please read libpq. π
π«Ά 1. Connection π«Ά
With these functions you can establish and close a connection to a database. In Libpq a connection is represented by a structure called PGconn.
When opening a connection a given database name is always converted to lower-case, unless it is surrounded by double quotes. All unspecified parameters are replaced by environment variables or by hard coded defaults:
parameter environment variable hard coded default
------------------------------------------------------
host PGHOST localhost
port PGPORT 5432
options PGOPTIONS ""
tty PGTTY ""
dbname PGDATABASE current userid
user PGUSER current userid
password PGPASSWORD ""
passwordfile PGPASSWORDFILE ""
Using appropriate methods you can access almost all fields of the returned PGconn structure. Iconic. π
$conn = Pg::setdbLogin($pghost, $pgport, $pgoptions, $pgtty, $dbname, $login, $pwd)β Opens a new connection to the backend. The connection identifier$conn( a pointer to thePGconnstructure ) must be used in subsequent commands for unique identification. Before using$connyou should call$conn->statusto ensure, that the connection was properly made. Closing a connection is done by deleting the connection handle, eg'undef $conn;'.$conn = Pg::setdb($pghost, $pgport, $pgoptions, $pgtty, $dbname)β The methodsetdbshould be used when username/password authentication is not needed.$conn = Pg::connectdb("option1=value option2=value ...")β Opens a new connection to the backend using connection information in a string. Possible options are:host,port,options,tty,dbname,user,password. The connection identifier$conn(a pointer to thePGconnstructure) must be used in subsequent commands for unique identification. Before using$connyou should call$conn->statusto ensure, that the connection was properly made.$Option_ref = Pg::conndefaults()β Returns a reference to a hash containing as keys all possible options forconnectdb(). The values are the current defaults. This function differs from his C-counterpart, which returns the completeconninfoOptionstructure.
while(($key, $val) = each %$Option_ref) {
print "$key, $val\n";
$conn->resetβ Resets the communication port with the backend and tries to establish a new connection.$ret = $conn->requestCancelβ Abandon processing of the current query. Regardless of the return value ofrequestCancel, the application must continue with the normal result-reading sequence usinggetResult. If the current query is part of a transaction, cancellation will abort the whole transaction.
Bestie, read that again. You cannot just bail β you have to keep reading results withgetResultno matter whatrequestCancelhanded back, or you're gonna have a bad time. π
$dbname = $conn->dbβ Returns the database name of the connection.$pguser = $conn->userβ Returns the Postgres user name of the connection.$pguser = $conn->passβ Returns the Postgres password of the connection.$pghost = $conn->hostβ Returns the host name of the connection.$pgport = $conn->portβ Returns the port of the connection.$pgtty = $conn->ttyβ Returns the tty of the connection.$pgoptions = $conn->optionsβ Returns the options used in the connection.$status = $conn->statusβ Returns the status of the connection. For comparing the status you may use the following constants:PGRES_CONNECTION_OKPGRES_CONNECTION_BAD
$errorMessage = $conn->errorMessageβ Returns the last error message associated with this connection.$fd = $conn->socketβ Obtain the file descriptor number for the backend connection socket. A result of-1indicates that no backend connection is currently open.$pid = $conn->backendPIDβ Returns the process-id of the corresponding backend proceess.$conn->trace(debug_port)β Messages passed between frontend and backend are echoed to thedebug_portfile stream.$conn->untraceβ Disables tracing.$result = $conn->exec($query)β Submits a query to the backend. The return value is a pointer to thePGresultstructure, which contains the complete query-result returned by the backend. In case of failure, the pointer points to an empty structure. Before using$resultyou should callresultStatusto ensure, that the query was properly executed.($table, $pid) = $conn->notifiesβ Checks for asynchronous notifications. This functions differs from the C-counterpart which returns a pointer to a new allocated structure, whereas the perl implementation returns a list.$tableis the table which has been listened to and$pidis the process id of the backend.$ret = $conn->sendQuery($string, $query)β Submit a query to Postgres without waiting for the result(s). After successfully callingPQsendQuery, callPQgetResultone or more times to obtain the query results.PQsendQuerymay not be called again untilgetResulthas returnedNULL, indicating that the query is done.$result = $conn->getResultβ Wait for the next result from a priorPQsendQuery, and return it.NULLis returned when the query is complete and there will be no more results.getResultwill block only if a query is active and the necessary response data has not yet been read byPQconsumeInput.$ret = $conn->isBusyβ ReturnsTRUEif a query is busy, that is,PQgetResultwould block waiting for input. AFALSEreturn indicates thatPQgetResultcan be called with assurance of not blocking.$result = $conn->consumeInputβ If input is available from the backend, consume it. After callingconsumeInput, the application may checkisBusyand/ornotifiesto see if their state has changed.$ret = $conn->getline($string, $length)β Reads a string up to$length - 1characters from the backend.getlinereturnsEOFat EOF,0if the entire line has been read, and1if the buffer is full. If a line consists of the two characters"\."the backend has finished sending the results of the copy command.$ret = $conn->putline($string)β Sends a string to the backend. The application must explicitly send the two characters"\."to indicate to the backend that it has finished sending its data.$ret = $conn->getlineAsync($buffer, $bufsize)β Non-blocking version ofgetline. It reads up to$bufsizecharacters from the backend.getlineAsyncreturns-1if the end-of-copy-marker has been recognized,0if no data is avilable, and>0the number of bytes returned.$ret = $conn->putnbytes($buffer, $nbytes)β Sends n bytes to the backend. Returns0if OK,EOFif not.$ret = $conn->endcopyβ This function waits until the backend has finished the copy. It should either be issued when the last string has been sent to the backend usingputlineor when the last string has been received from the backend usinggetline.endcopyreturns0on success,1on failure.$result = $conn->makeEmptyPGresult($status);β Returns a newly allocated, initialized result with given status.
π 2. Result π
With these functions you can send commands to a database and investigate the results. In Libpq the result of a command is represented by a structure called PGresult. Using the appropriate methods you can access almost all fields of this structure.
$result_status = $result->resultStatusβ Returns the status of the result. For comparing the status you may use one of the following constants depending upon the command executed:PGRES_EMPTY_QUERYPGRES_COMMAND_OKPGRES_TUPLES_OKPGRES_COPY_OUTPGRES_COPY_INPGRES_BAD_RESPONSEPGRES_NONFATAL_ERRORPGRES_FATAL_ERROR
Use the functions below to access the contents of the PGresult structure. π
$ntuples = $result->ntuplesβ Returns the number of tuples in the query result.$nfields = $result->nfieldsβ Returns the number of fields in the query result.$ret = $result->binaryTuplesβ Returns1if the tuples in the query result are bianry.$fname = $result->fname($field_num)β Returns the field name associated with the given field number.$fnumber = $result->fnumber($field_name)β Returns the field number associated with the given field name.$ftype = $result->ftype($field_num)β Returns the oid of the type of the given field number.$fsize = $result->fsize($field_num)β Returns the size in bytes of the type of the given field number. It returns-1if the field has a variable length.$fmod = $result->fmod($field_num)β Returns the type-specific modification data of the field associated with the given field index. Field indices start at0.$cmdStatus = $result->cmdStatusβ Returns the command status of the last query command. In case ofDELETEit returns also the number of deleted tuples. In case ofINSERTit returns also the OID of the inserted tuple followed by1(the number of affected tuples).$oid = $result->oidStatusβ In case the last query was anINSERTcommand it returns the oid of the inserted tuple.$oid = $result->cmdTuples
Oh and btw bestie, if the last query was an INSERT or DELETE command, it returns the number of affected tuples. No cap. π
$value = $result->getvalue($tup_num, $field_num)
Returns the value of the given tuple and field. This is a null-terminated ASCII string. But heads up: binary cursors will not work. π«
$length = $result->getlength($tup_num, $field_num)
Returns the length of the value for a given tuple and field. Slay. β¨
$null_status = $result->getisnull($tup_num, $field_num)
Returns the NULL status for a given tuple and field. Iconic.
$res->fetchrow
Fetches the next row from the server and returns NULL if all rows have been processed. Columns which have NULL as value will be set to "undef". Lowkey important.
$result->print($fout, $header, $align, $standard, $html3, $expanded, $pager, $fieldSep, $tableOpt, $caption, ...)
Prints out all the tuples in an intelligent manner. This function differs from the C-counterpart. The struct PQprintOpt has been implemented with a list. This list is of variable length, in order to care for the character array fieldName in PQprintOpt. The arguments $header, $align, $standard, $html3, $expanded, $pager are boolean flags. The arguments $fieldSep, $tableOpt, $caption are strings. You may append additional strings, which will be taken as replacement for the field names. Periodt. π
$result->displayTuples($fp, $fillAlign, $fieldSep, $printHeader, qiet)
Kept for backward compatibility. Use print.
$result->printTuples($fout, $printAttName, $terseOutput, $width)
Kept for backward compatibility. Use print.
β¨ 3. Large Objects β¨
These functions provide file-oriented access to user data. The large object interface is modeled after the Unix file system interface with analogies of open, close, read, write, lseek, tell. It's giving very Unix-core. π§
Starting withpostgresql-6.5it is required to use large objects only inside a transaction! Seeeg/lo_demo.plfor an example, how to handle large objects. Don't skip this, bestie. π¨
$lobj_fd = $conn->lo_open($lobjId, $mode)
Opens an existing large object and returns an object id. For the mode bits see lo_create. Returns -1 upon failure. π
$ret = $conn->lo_close($lobj_fd)
Closes an existing large object. Returns 0 upon success and -1 upon failure.
$nbytes = $conn->lo_read($lobj_fd, $buf, $len)
Reads $len bytes into $buf from large object $lobj_fd. Returns the number of bytes read and -1 upon failure.
$nbytes = $conn->lo_write($lobj_fd, $buf, $len)
Writes $len bytes of $buf into the large object $lobj_fd. Returns the number of bytes written and -1 upon failure.
$ret = $conn->lo_lseek($lobj_fd, $offset, $whence)
Change the current read or write location on the large object $obj_id. Currently $whence can only be 0 (L_SET). That's the vibe.
$lobjId = $conn->lo_creat($mode)
Creates a new large object. $mode is a bit-mask describing different attributes of the new object. Use the following constants:
PGRES_INV_SMGRMASKPGRES_INV_WRITEPGRES_INV_READ
Upon failure it returns PGRES_InvalidOid. So watch out.
$location = $conn->lo_tell($lobj_fd)
Returns the current read or write location on the large object $lobj_fd.
$ret = $conn->lo_unlink($lobjId)
Deletes a large object. Returns -1 upon failure.
$lobjId = $conn->lo_import($filename)
Imports a Unix file as large object and returns the object id of the new object.
$ret = $conn->lo_export($lobjId, $filename)
Exports a large object into a Unix file. Returns -1 upon failure, 1 otherwise. Slay. π
β¨ AUTHOR β¨
Edmund Mergl <E.Mergl@bawue.de> β icon, legend, the moment. π
β¨ SEE ALSO β¨
PostgreSQL Programmer's Guide, Large Objects and libpq. That's the reading list, bestie. π
This page is from perl v5.40.1, dated 2025-04-09, and it's Pg(3pm). Bye! π
π¦ where this page comes from
- debian trixie: libpg-perl 1:2.1.1-11 Β· GPL-2.0-or-later
- ubuntu questing: libpg-perl 1:2.1.1-11
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms