.\" Automatically generated by Pod::Man 4.14 (Pod::Simple 3.40) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. \*(C+ will .\" give a nicer C++. Capital omega is used to do unbreakable dashes and .\" therefore won't be available. \*(C` and \*(C' expand to `' in nroff, .\" nothing in troff, for use with C<>. .tr \(*W- .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Pg 3pm" .TH Pg 3pm "2020-11-09" "perl v5.32.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH "NAME" DBD::Pg \- PostgreSQL database driver for the DBI module .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& use DBI; \& \& $dbh = DBI\->connect("dbi:Pg:dbname=$dbname", \*(Aq\*(Aq, \*(Aq\*(Aq, {AutoCommit => 0}); \& # The AutoCommit attribute should always be explicitly set \& \& # For some advanced uses you may need PostgreSQL type values: \& use DBD::Pg qw(:pg_types); \& \& $dbh\->do(\*(AqINSERT INTO mytable(a) VALUES (1)\*(Aq); \& \& $sth = $dbh\->prepare(\*(AqINSERT INTO mytable(a) VALUES (?)\*(Aq); \& $sth\->execute(); .Ve .SH "VERSION" .IX Header "VERSION" This documents version 3.14.2 of the DBD::Pg module .SH "DESCRIPTION" .IX Header "DESCRIPTION" DBD::Pg is a Perl module that works with the \s-1DBI\s0 module to provide access to PostgreSQL databases. .SH "MODULE DOCUMENTATION" .IX Header "MODULE DOCUMENTATION" This documentation describes driver specific behavior and restrictions. It is not supposed to be used as the only reference for the user. In any case consult the \fB\s-1DBI\s0\fR documentation first! .PP Latest \s-1DBI\s0 documentation. .SH "THE DBI CLASS" .IX Header "THE DBI CLASS" .SS "\s-1DBI\s0 Class Methods" .IX Subsection "DBI Class Methods" \fI\f(BIconnect\fI\fR .IX Subsection "connect" .PP This method creates a database handle by connecting to a database, and is the \s-1DBI\s0 equivalent of the \*(L"new\*(R" method. To connect to a Postgres database with a minimum of parameters, use the following syntax: .PP .Vb 1 \& $dbh = DBI\->connect("dbi:Pg:dbname=$dbname", \*(Aq\*(Aq, \*(Aq\*(Aq, {AutoCommit => 0}); .Ve .PP This connects to the database named in the \f(CW$dbname\fR variable on the default port (usually 5432) without any user authentication. .PP The following connect statement shows almost all possible parameters: .PP .Vb 5 \& $dbh = DBI\->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;options=$options", \& $username, \& $password, \& {AutoCommit => 0, RaiseError => 1, PrintError => 0} \& ); .Ve .PP Parameters containing unusual characters such as spaces can be wrapped in single quotes around the value e.g. \*(L"dbi:Pg:dbname='spacey name';host=$host\*(R" .PP If a parameter is not given, the \fBconnect()\fR method will first look for specific environment variables, and then fall back to hard-coded defaults: .PP .Vb 11 \& parameter environment variable hard coded default \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& host PGHOST local domain socket \& hostaddr PGHOSTADDR local domain socket \& port PGPORT 5432 \& dbname* PGDATABASE current userid \& username PGUSER current userid \& password PGPASSWORD (none) \& options PGOPTIONS (none) \& service PGSERVICE (none) \& sslmode PGSSLMODE (none) .Ve .PP * May also use the aliases \f(CW\*(C`db\*(C'\fR or \f(CW\*(C`database\*(C'\fR .PP If the username and password values passed via \f(CW\*(C`connect()\*(C'\fR are undefined (as opposed to merely being empty strings), \s-1DBI\s0 will use the environment variables \fI\s-1DBI_USER\s0\fR and \fI\s-1DBI_PASS\s0\fR if they exist. .PP You can also connect by using a service connection file, which is named \&\fIpg_service.conf\fR. The location of this file can be controlled by setting the \fI\s-1PGSYSCONFDIR\s0\fR environment variable. To use one of the named services within the file, set the name by using either the \fIservice\fR parameter or the environment variable \fI\s-1PGSERVICE\s0\fR. Note that when connecting this way, only the minimum parameters should be used. For example, to connect to a service named \*(L"zephyr\*(R", you could use: .PP .Vb 1 \& $dbh = DBI\->connect("dbi:Pg:service=zephyr", \*(Aq\*(Aq, \*(Aq\*(Aq); .Ve .PP You could also set \f(CW$ENV{PGSERVICE}\fR to \*(L"zephyr\*(R" and connect like this: .PP .Vb 1 \& $dbh = DBI\->connect("dbi:Pg:", \*(Aq\*(Aq, \*(Aq\*(Aq); .Ve .PP The format of the \fIpg_service.conf\fR file is simply a bracketed service name, followed by one parameter per line in the format name=value. For example: .PP .Vb 5 \& [zephyr] \& dbname=winds \& user=wisp \& password=W$2Hc00YSgP \& port=6543 .Ve .PP There are four valid arguments to the \fIsslmode\fR parameter, which controls whether to use \s-1SSL\s0 to connect to the database: .IP "\(bu" 4 disable: \s-1SSL\s0 connections are never used .IP "\(bu" 4 allow: try non-SSL, then \s-1SSL\s0 .IP "\(bu" 4 prefer: try \s-1SSL,\s0 then non-SSL .IP "\(bu" 4 require: connect only with \s-1SSL\s0 .PP You can also connect using sockets in a specific directory. This may be needed if the server you are connecting to has a different default socket directory from the one used to compile DBD::Pg. Use the complete path to the socket directory as the name of the host, like this: .PP .Vb 4 \& $dbh = DBI\->connect(\*(Aqdbi:Pg:dbname=foo;host=/var/tmp/socket\*(Aq, \& $username, \& $password, \& {AutoCommit => 0, RaiseError => 1}); .Ve .PP The attribute hash can also contain a key named \f(CW\*(C`dbd_verbose\*(C'\fR, which simply calls \f(CW\*(C`$dbh\->trace(\*(AqDBD\*(Aq)\*(C'\fR after the handle is created. This attribute is not recommended, as it is clearer to simply explicitly call \f(CW\*(C`trace\*(C'\fR explicitly in your script. .PP \fI\f(BIconnect_cached\fI\fR .IX Subsection "connect_cached" .PP .Vb 1 \& $dbh = DBI\->connect_cached("dbi:Pg:dbname=$dbname", $username, $password, \e%options); .Ve .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIdata_sources\fI\fR .IX Subsection "data_sources" .PP .Vb 2 \& @data_sources = DBI\->data_sources(\*(AqPg\*(Aq); \& @data_sources = $dbh\->data_sources(); .Ve .PP Returns a list of available databases. Unless the environment variable \f(CW\*(C`DBI_DSN\*(C'\fR is set, a connection will be attempted to the database \f(CW\*(C`template1\*(C'\fR. The normal connection environment variables also apply, such as \f(CW\*(C`PGHOST\*(C'\fR, \f(CW\*(C`PGPORT\*(C'\fR, \f(CW\*(C`DBI_USER\*(C'\fR, \&\f(CW\*(C`DBI_PASS\*(C'\fR, and \f(CW\*(C`PGSERVICE\*(C'\fR. .PP You can also pass in options to add to the connection string For example, to specify an alternate port and host: .PP .Vb 1 \& @data_sources = DBI\->data_sources(\*(AqPg\*(Aq, \*(Aqport=5824;host=example.com\*(Aq); \& \& or: \& \& @data_sources = $dbh\->data_sources(\*(Aqport=5824;host=example.com\*(Aq); .Ve .SS "Methods Common To All Handles" .IX Subsection "Methods Common To All Handles" For all of the methods below, \fB\f(CB$h\fB\fR can be either a database handle (\fB\f(CB$dbh\fB\fR) or a statement handle (\fB\f(CB$sth\fB\fR). Note that \fI\f(CI$dbh\fI\fR and \fI\f(CI$sth\fI\fR can be replaced with any variable name you choose: these are just the names most often used. Another common variable used in this documentation is $\fIrv\fR, which stands for \*(L"return value\*(R". .PP \fI\f(BIerr\fI\fR .IX Subsection "err" .PP .Vb 1 \& $rv = $h\->err; .Ve .PP Returns the error code from the last method called. For the connect method it returns \&\f(CW\*(C`PQstatus\*(C'\fR, which is a number used by \fIlibpq\fR (the Postgres connection library). A value of 0 indicates no error (\s-1CONNECTION_OK\s0), while any other number indicates a failed connection. The only other number commonly seen is 1 (\s-1CONNECTION_BAD\s0). See the libpq documentation for the complete list of return codes. .PP In all other non-connect methods \f(CW\*(C`$h\->err\*(C'\fR returns the \f(CW\*(C`PQresultStatus\*(C'\fR of the current handle. This is a number used by libpq and is one of: .PP .Vb 8 \& 0 Empty query string \& 1 A command that returns no data successfully completed. \& 2 A command that returns data successfully completed. \& 3 A COPY OUT command is still in progress. \& 4 A COPY IN command is still in progress. \& 5 A bad response was received from the backend. \& 6 A nonfatal error occurred (a notice or warning message) \& 7 A fatal error was returned: the last query failed. .Ve .PP \fI\f(BIerrstr\fI\fR .IX Subsection "errstr" .PP .Vb 1 \& $str = $h\->errstr; .Ve .PP Returns the last error that was reported by Postgres. This message is affected by the pg_errorlevel setting. .PP \fI\f(BIstate\fI\fR .IX Subsection "state" .PP .Vb 1 \& $str = $h\->state; .Ve .PP Returns a five-character \*(L"\s-1SQLSTATE\*(R"\s0 code. Success is indicated by a \f(CW00000\fR code, which gets mapped to an empty string by \s-1DBI. A\s0 code of \f(CW\*(C`S8006\*(C'\fR indicates a connection failure, usually because the connection to the Postgres server has been lost. .PP While this method can be called as either \f(CW\*(C`$sth\->state\*(C'\fR or \f(CW\*(C`$dbh\->state\*(C'\fR, it is usually clearer to always use \f(CW\*(C`$dbh\->state\*(C'\fR. .PP The list of codes used by PostgreSQL can be found at: .PP Note that these codes are part of the \s-1SQL\s0 standard and only a small number of them will be used by PostgreSQL. .PP Common codes: .PP .Vb 4 \& 00000 Successful completion \& 25P01 No active SQL transaction \& 25P02 In failed SQL transaction \& S8006 Connection failure .Ve .PP \fI\f(BItrace\fI\fR .IX Subsection "trace" .PP .Vb 3 \& $h\->trace($trace_settings); \& $h\->trace($trace_settings, $trace_filename); \& $trace_settings = $h\->trace; .Ve .PP Changes the trace settings on a database or statement handle. The optional second argument specifies a file to write the trace information to. If no filename is given, the information is written to \fI\s-1STDERR\s0\fR. Note that tracing can be set globally as well by setting \f(CW\*(C`DBI\->trace\*(C'\fR, or by using the environment variable \fI\s-1DBI_TRACE\s0\fR. .PP The value is either a numeric level or a named flag. For the flags that DBD::Pg uses, see parse_trace_flag. .PP \fI\f(BItrace_msg\fI\fR .IX Subsection "trace_msg" .PP .Vb 2 \& $h\->trace_msg($message_text); \& $h\->trace_msg($message_text, $min_level); .Ve .PP Writes a message to the current trace output (as set by the \*(L"trace\*(R" method). If a second argument is given, the message is only written if the current tracing level is equal to or greater than the \f(CW$min_level\fR. .PP \fI\f(BIparse_trace_flag\fI and \f(BIparse_trace_flags\fI\fR .IX Subsection "parse_trace_flag and parse_trace_flags" .PP .Vb 2 \& $h\->trace($h\->parse_trace_flags(\*(AqSQL|pglibpq\*(Aq)); \& $h\->trace($h\->parse_trace_flags(\*(Aq1|pgstart\*(Aq)); \& \& ## Simpler: \& $h\->trace(\*(AqSQL|pglibpq\*(Aq); \& $h\->trace(\*(Aq1|pgstart\*(Aq); \& \& my $value = DBD::Pg\->parse_trace_flag(\*(Aqpglibpq\*(Aq); \& DBI\->trace($value); .Ve .PP The parse_trace_flags method is used to convert one or more named flags to a number which can passed to the \*(L"trace\*(R" method. DBD::Pg currently supports the DBI-specific flag, \f(CW\*(C`SQL\*(C'\fR, as well as the ones listed below. .PP Flags can be combined by using the parse_trace_flags method, which simply calls \f(CW\*(C`parse_trace_flag\*(C'\fR on each item and combines them. .PP Sometimes you may wish to turn the tracing on before you connect to the database. The second example above shows a way of doing this: the call to \f(CW\*(C`DBD::Pg\->parse_trace_flags\*(C'\fR provides a number than can be fed to \f(CW\*(C`DBI\->trace\*(C'\fR before you create a database handle. .PP DBD::Pg supports the following trace flags: .IP "\s-1SQL\s0" 4 .IX Item "SQL" Outputs all \s-1SQL\s0 statements. Note that the output provided will not necessarily be in a form suitable to passing directly to Postgres, as server-side prepared statements are used extensively by DBD::Pg. For maximum portability of output (but with a potential performance hit), use with \f(CW\*(C`$dbh\->{pg_server_prepare} = 0\*(C'\fR. .IP "\s-1DBD\s0" 4 .IX Item "DBD" Turns on all non-DBI flags, in other words, only the ones that are specific to DBD::Pg (all those below which start with the letters 'pg'). .IP "pglibpq" 4 .IX Item "pglibpq" Outputs the name of each libpq function (without arguments) immediately before running it. This is a good way to trace the flow of your program at a low level. This information is also output if the trace level is set to 4 or greater. .IP "pgstart" 4 .IX Item "pgstart" Outputs the name of each internal DBD::Pg function, and other information such as the function arguments or important global variables, as each function starts. This information is also output if the trace level is set to 4 or greater. .IP "pgend" 4 .IX Item "pgend" Outputs a simple message at the very end of each internal DBD::Pg function. This is also output if the trace level is set to 4 or greater. .IP "pgprefix" 4 .IX Item "pgprefix" Forces each line of trace output to begin with the string \fB\f(CB\*(C`dbdpg: \*(C'\fB\fR. This helps to differentiate it from the normal \s-1DBI\s0 trace output. .IP "pglogin" 4 .IX Item "pglogin" Outputs a message showing the connection string right before a new database connection is attempted, a message when the connection was successful, and a message right after the database has been disconnected. Also output if trace level is 5 or greater. .PP See the \s-1DBI\s0 section on \s-1TRACING\s0 for more information. .PP \fI\f(BIfunc\fI\fR .IX Subsection "func" .PP DBD::Pg uses the \f(CW\*(C`func\*(C'\fR method to support a variety of functions. Note that the name of the function comes \fIlast\fR, after the arguments. .IP "table_attributes" 4 .IX Item "table_attributes" .Vb 1 \& $attrs = $dbh\->func($table, \*(Aqtable_attributes\*(Aq); .Ve .Sp Use of the tables_attributes function is no longer recommended. Instead, you can use the more portable \f(CW\*(C`column_info\*(C'\fR and \f(CW\*(C`primary_key\*(C'\fR methods to access the same information. .Sp The table_attributes method returns, for the given table argument, a reference to an array of hashes, each of which contains the following keys: .Sp .Vb 8 \& NAME attribute name \& TYPE attribute type \& SIZE attribute size (\-1 for variable size) \& NULLABLE flag nullable \& DEFAULT default value \& CONSTRAINT constraint \& PRIMARY_KEY flag is_primary_key \& REMARKS attribute description .Ve .IP "pg_lo_creat" 4 .IX Item "pg_lo_creat" .Vb 1 \& $lobjId = $dbh\->pg_lo_creat($mode); .Ve .Sp Creates a new large object and returns the object-id. \f(CW$mode\fR is a bitmask describing read and write access to the new object. This setting is ignored since Postgres version 8.1. For backwards compatibility, however, you should set a valid mode anyway (see \*(L"pg_lo_open\*(R" for a list of valid modes). .Sp Upon failure it returns \f(CW\*(C`undef\*(C'\fR. This function cannot be used if AutoCommit is enabled. .Sp The old way of calling large objects functions is deprecated: \f(CW$dbh\fR\->func(.., 'lo_); .IP "pg_lo_open" 4 .IX Item "pg_lo_open" .Vb 1 \& $lobj_fd = $dbh\->pg_lo_open($lobjId, $mode); .Ve .Sp Opens an existing large object and returns an object-descriptor for use in subsequent \f(CW\*(C`pg_lo_*\*(C'\fR calls. \f(CW$mode\fR is a bitmask describing read and write access to the opened object. It may be one of: .Sp .Vb 3 \& $dbh\->{pg_INV_READ} \& $dbh\->{pg_INV_WRITE} \& $dbh\->{pg_INV_READ} | $dbh\->{pg_INV_WRITE} .Ve .Sp \&\f(CW\*(C`pg_INV_WRITE\*(C'\fR and \f(CW\*(C`pg_INV_WRITE | pg_INV_READ\*(C'\fR modes are identical; in both modes, the large object can be read from or written to. Reading from the object will provide the object as written in other committed transactions, along with any writes performed by the current transaction. Objects opened with \f(CW\*(C`pg_INV_READ\*(C'\fR cannot be written to. Reading from this object will provide the stored data at the time of the transaction snapshot which was active when \f(CW\*(C`pg_lo_write\*(C'\fR was called. .Sp Returns \f(CW\*(C`undef\*(C'\fR upon failure. Note that 0 is a perfectly correct (and common) object descriptor! This function cannot be used if AutoCommit is enabled. .IP "pg_lo_write" 4 .IX Item "pg_lo_write" .Vb 1 \& $nbytes = $dbh\->pg_lo_write($lobj_fd, $buffer, $len); .Ve .Sp Writes \f(CW$len\fR bytes of c<$buffer> into the large object \f(CW$lobj_fd\fR. Returns the number of bytes written and \f(CW\*(C`undef\*(C'\fR upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_read" 4 .IX Item "pg_lo_read" .Vb 1 \& $nbytes = $dbh\->pg_lo_read($lobj_fd, $buffer, $len); .Ve .Sp Reads \f(CW$len\fR bytes into c<$buffer> from large object \f(CW$lobj_fd\fR. Returns the number of bytes read and \f(CW\*(C`undef\*(C'\fR upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_lseek" 4 .IX Item "pg_lo_lseek" .Vb 1 \& $loc = $dbh\->pg_lo_lseek($lobj_fd, $offset, $whence); .Ve .Sp Changes the current read or write location on the large object \&\f(CW$obj_id\fR. Currently \f(CW$whence\fR can only be 0 (which is L_SET). Returns the current location and \f(CW\*(C`undef\*(C'\fR upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_lseek64" 4 .IX Item "pg_lo_lseek64" .Vb 1 \& $loc = $dbh\->pg_lo_lseek64($lobj_fd, $offset, $whence); .Ve .Sp Same as pg_lo_lseek, but can handle much larger offsets and returned values. Requires Postgres 9.3 or greater. .IP "pg_lo_tell" 4 .IX Item "pg_lo_tell" .Vb 1 \& $loc = $dbh\->pg_lo_tell($lobj_fd); .Ve .Sp Returns the current read or write location on the large object \f(CW$lobj_fd\fR and \f(CW\*(C`undef\*(C'\fR upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_tell64" 4 .IX Item "pg_lo_tell64" .Vb 1 \& $loc = $dbh\->pg_lo_tell64($lobj_fd); .Ve .Sp Same as pg_lo_tell, but can return much larger values. Requires Postgres 9.3 or greater. .IP "pg_lo_truncate" 4 .IX Item "pg_lo_truncate" .Vb 1 \& $loc = $dbh\->pg_lo_truncate($lobj_fd, $len); .Ve .Sp Truncates the given large object to the new size. Returns \f(CW\*(C`undef\*(C'\fR on failure, and 0 on success. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_truncate64" 4 .IX Item "pg_lo_truncate64" .Vb 1 \& $loc = $dbh\->pg_lo_truncate64($lobj_fd, $len); .Ve .Sp Same as pg_lo_truncate, but can handle much larger lengths. Requires Postgres 9.3 or greater. .IP "pg_lo_close" 4 .IX Item "pg_lo_close" .Vb 1 \& $lobj_fd = $dbh\->pg_lo_close($lobj_fd); .Ve .Sp Closes an existing large object. Returns true upon success and false upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_unlink" 4 .IX Item "pg_lo_unlink" .Vb 1 \& $ret = $dbh\->pg_lo_unlink($lobjId); .Ve .Sp Deletes an existing large object. Returns true upon success and false upon failure. This function cannot be used if AutoCommit is enabled. .IP "pg_lo_import" 4 .IX Item "pg_lo_import" .Vb 1 \& $lobjId = $dbh\->pg_lo_import($filename); .Ve .Sp Imports a Unix file as a large object and returns the object id of the new object or \f(CW\*(C`undef\*(C'\fR upon failure. .IP "pg_lo_import_with_oid" 4 .IX Item "pg_lo_import_with_oid" .Vb 1 \& $lobjId = $dbh\->pg_lo_import($filename, $OID); .Ve .Sp Same as pg_lo_import, but attempts to use the supplied \s-1OID\s0 as the large object number. If this number is 0, it falls back to the behavior of pg_lo_import (which assigns the next available \s-1OID\s0). .Sp This is only available when DBD::Pg is compiled against a Postgres server version 8.4 or later. .IP "pg_lo_export" 4 .IX Item "pg_lo_export" .Vb 1 \& $ret = $dbh\->pg_lo_export($lobjId, $filename); .Ve .Sp Exports a large object into a Unix file. Returns false upon failure, true otherwise. .IP "getfd" 4 .IX Item "getfd" .Vb 1 \& $fd = $dbh\->func(\*(Aqgetfd\*(Aq); .Ve .Sp Deprecated, use \f(CW$dbh\fR\->{pg_socket} instead. .PP \fI\f(BIprivate_attribute_info\fI\fR .IX Subsection "private_attribute_info" .PP .Vb 2 \& $hashref = $dbh\->private_attribute_info(); \& $hashref = $sth\->private_attribute_info(); .Ve .PP Returns a hash of all private attributes used by DBD::Pg, for either a database or a statement handle. Currently, all the hash values are undef. .SH "ATTRIBUTES COMMON TO ALL HANDLES" .IX Header "ATTRIBUTES COMMON TO ALL HANDLES" \fI\f(BIInactiveDestroy\fI (boolean)\fR .IX Subsection "InactiveDestroy (boolean)" .PP If set to true, then the \*(L"disconnect\*(R" method will not be automatically called when the database handle goes out of scope. This is required if you are forking, and even then you must tread carefully and ensure that either the parent or the child (but not both!) handles all database calls from that point forwards, so that messages from the Postgres backend are only handled by one of the processes. If you don't set things up properly, you will see messages such as "\fIserver closed the connection unexpectedly\fR\*(L", and \*(R"\fImessage type 0x32 arrived from server while idle\fR". The best solution is to either have the child process reconnect to the database with a fresh database handle, or to rewrite your application not to use forking. See the section on \*(L"Asynchronous Queries\*(R" for a way to have your script continue to work while the database is processing a request. .PP \fI\f(BIAutoInactiveDestroy\fI (boolean)\fR .IX Subsection "AutoInactiveDestroy (boolean)" .PP The InactiveDestroy attribute, described above, needs to be explicitly set in the child process after a fork. If the code that performs the fork is in a third party module such as Sys::Syslog, this can present a problem. Use AutoInactiveDestroy to get around this problem. .PP \fI\f(BIRaiseError\fI (boolean, inherited)\fR .IX Subsection "RaiseError (boolean, inherited)" .PP Forces errors to always raise an exception. Although it defaults to off, it is recommended that this be turned on, as the alternative is to check the return value of every method (prepare, execute, fetch, etc.) manually, which is easy to forget to do. .PP \fI\f(BIPrintError\fI (boolean, inherited)\fR .IX Subsection "PrintError (boolean, inherited)" .PP Forces database errors to also generate warnings, which can then be filtered with methods such as locally redefining \fI\f(CI$SIG\fI{_\|_WARN_\|_}\fR or using modules such as \f(CW\*(C`CGI::Carp\*(C'\fR. This attribute is on by default. .PP \fI\f(BIShowErrorStatement\fI (boolean, inherited)\fR .IX Subsection "ShowErrorStatement (boolean, inherited)" .PP Appends information about the current statement to error messages. If placeholder information is available, adds that as well. Defaults to false. .PP Note that this will not work when using \*(L"do\*(R" without any arguments. .PP \fI\f(BIWarn\fI (boolean, inherited)\fR .IX Subsection "Warn (boolean, inherited)" .PP Enables warnings. This is on by default, and should only be turned off in a local block for a short a time only when absolutely needed. .PP \fI\f(BIExecuted\fI (boolean, read-only)\fR .IX Subsection "Executed (boolean, read-only)" .PP Indicates if a handle has been executed. For database handles, this value is true after the \*(L"do\*(R" method has been called, or when one of the child statement handles has issued an \*(L"execute\*(R". Issuing a \*(L"commit\*(R" or \*(L"rollback\*(R" always resets the attribute to false for database handles. For statement handles, any call to \*(L"execute\*(R" or its variants will flip the value to true for the lifetime of the statement handle. .PP \fI\f(BITraceLevel\fI (integer, inherited)\fR .IX Subsection "TraceLevel (integer, inherited)" .PP Sets the trace level, similar to the \*(L"trace\*(R" method. See the sections on \&\*(L"trace\*(R" and parse_trace_flag for more details. .PP \fI\f(BIActive\fI (boolean, read-only)\fR .IX Subsection "Active (boolean, read-only)" .PP Indicates if a handle is active or not. For database handles, this indicates if the database has been disconnected or not. For statement handles, it indicates if all the data has been fetched yet or not. Use of this attribute is not encouraged. .PP \fI\f(BIKids\fI (integer, read-only)\fR .IX Subsection "Kids (integer, read-only)" .PP Returns the number of child processes created for each handle type. For a driver handle, indicates the number of database handles created. For a database handle, indicates the number of statement handles created. For statement handles, it always returns zero, because statement handles do not create kids. .PP \fI\f(BIActiveKids\fI (integer, read-only)\fR .IX Subsection "ActiveKids (integer, read-only)" .PP Same as \f(CW\*(C`Kids\*(C'\fR, but only returns those that are active. .PP \fI\f(BICachedKids\fI (hash ref)\fR .IX Subsection "CachedKids (hash ref)" .PP Returns a hashref of handles. If called on a database handle, returns all statement handles created by use of the \&\f(CW\*(C`prepare_cached\*(C'\fR method. If called on a driver handle, returns all database handles created by the \*(L"connect_cached\*(R" method. .PP \fI\f(BIChildHandles\fI (array ref)\fR .IX Subsection "ChildHandles (array ref)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIPrintWarn\fI (boolean, inherited)\fR .IX Subsection "PrintWarn (boolean, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIHandleError\fI (boolean, inherited)\fR .IX Subsection "HandleError (boolean, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIHandleSetErr\fI (code ref, inherited)\fR .IX Subsection "HandleSetErr (code ref, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIErrCount\fI (unsigned integer)\fR .IX Subsection "ErrCount (unsigned integer)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIFetchHashKeyName\fI (string, inherited)\fR .IX Subsection "FetchHashKeyName (string, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIChopBlanks\fI (boolean, inherited)\fR .IX Subsection "ChopBlanks (boolean, inherited)" .PP Supported by DBD::Pg as proposed by \s-1DBI.\s0 This method is similar to the \&\s-1SQL\s0 function \f(CW\*(C`RTRIM\*(C'\fR. .PP \fI\f(BITaint\fI (boolean, inherited)\fR .IX Subsection "Taint (boolean, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BITaintIn\fI (boolean, inherited)\fR .IX Subsection "TaintIn (boolean, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BITaintOut\fI (boolean, inherited)\fR .IX Subsection "TaintOut (boolean, inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIProfile\fI (inherited)\fR .IX Subsection "Profile (inherited)" .PP Implemented by \s-1DBI,\s0 no driver-specific impact. .PP \fI\f(BIType\fI (scalar)\fR .IX Subsection "Type (scalar)" .PP Returns \f(CW\*(C`dr\*(C'\fR for a driver handle, \f(CW\*(C`db\*(C'\fR for a database handle, and \f(CW\*(C`st\*(C'\fR for a statement handle. Should be rarely needed. .PP \fI\f(BILongReadLen\fI\fR .IX Subsection "LongReadLen" .PP Not used by DBD::Pg .PP \fI\f(BILongTruncOk\fI\fR .IX Subsection "LongTruncOk" .PP Not used by DBD::Pg .PP \fI\f(BICompatMode\fI\fR .IX Subsection "CompatMode" .PP Not used by DBD::Pg .SH "DBI DATABASE HANDLE OBJECTS" .IX Header "DBI DATABASE HANDLE OBJECTS" .SS "Database Handle Methods" .IX Subsection "Database Handle Methods" \fI\f(BIselectall_arrayref\fI\fR .IX Subsection "selectall_arrayref" .PP .Vb 3 \& $ary_ref = $dbh\->selectall_arrayref($sql); \& $ary_ref = $dbh\->selectall_arrayref($sql, \e%attr); \& $ary_ref = $dbh\->selectall_arrayref($sql, \e%attr, @bind_values); .Ve .PP Returns a reference to an array containing the rows returned by preparing and executing the \s-1SQL\s0 string. See the \s-1DBI\s0 documentation for full details. .PP \fI\f(BIselectall_hashref\fI\fR .IX Subsection "selectall_hashref" .PP .Vb 1 \& $hash_ref = $dbh\->selectall_hashref($sql, $key_field); .Ve .PP Returns a reference to a hash containing the rows returned by preparing and executing the \s-1SQL\s0 string. See the \s-1DBI\s0 documentation for full details. .PP \fI\f(BIselectcol_arrayref\fI\fR .IX Subsection "selectcol_arrayref" .PP .Vb 1 \& $ary_ref = $dbh\->selectcol_arrayref($sql, \e%attr, @bind_values); .Ve .PP Returns a reference to an array containing the first column from each rows returned by preparing and executing the \s-1SQL\s0 string. It is possible to specify exactly which columns to return. See the \s-1DBI\s0 documentation for full details. .PP \fI\f(BIprepare\fI\fR .IX Subsection "prepare" .PP .Vb 1 \& $sth = $dbh\->prepare($statement, \e%attr); .Ve .PP \&\s-1WARNING:\s0 DBD::Pg now (as of version 1.40) uses true prepared statements by sending them to the backend to be prepared by the Postgres server. Statements that were legal before may no longer work. See below for details. .PP The prepare method prepares a statement for later execution. PostgreSQL supports prepared statements, which enables DBD::Pg to only send the query once, and simply send the arguments for every subsequent call to \*(L"execute\*(R". DBD::Pg can use these server-side prepared statements, or it can just send the entire query to the server each time. The best way is automatically chosen for each query. This will be sufficient for most users: keep reading for a more detailed explanation and some optional flags. .PP Queries that do not begin with the word \*(L"\s-1SELECT\*(R", \*(L"INSERT\*(R",\s0 \&\*(L"\s-1UPDATE\*(R",\s0 or \*(L"\s-1DELETE\*(R"\s0 are never sent as server-side prepared statements. .PP Deciding whether or not to use prepared statements depends on many factors, but you can force them to be used or not used by using the pg_server_prepare attribute when calling \*(L"prepare\*(R". Setting this to false means to never use prepared statements. Setting pg_server_prepare to true means that prepared statements should be used whenever possible. This is the default. .PP The pg_server_prepare attribute can also be set at connection time like so: .PP .Vb 5 \& $dbh = DBI\->connect($DBNAME, $DBUSER, $DBPASS, \& { AutoCommit => 0, \& RaiseError => 1, \& pg_server_prepare => 0, \& }); .Ve .PP or you may set it after your database handle is created: .PP .Vb 1 \& $dbh\->{pg_server_prepare} = 1; .Ve .PP To enable it for just one particular statement: .PP .Vb 2 \& $sth = $dbh\->prepare("SELECT id FROM mytable WHERE val = ?", \& { pg_server_prepare => 1 }); .Ve .PP You can even toggle between the two as you go: .PP .Vb 6 \& $sth\->{pg_server_prepare} = 1; \& $sth\->execute(22); \& $sth\->{pg_server_prepare} = 0; \& $sth\->execute(44); \& $sth\->{pg_server_prepare} = 1; \& $sth\->execute(66); .Ve .PP In the above example, the first execute will use the previously prepared statement. The second execute will not, but will build the query into a single string and send it to the server. The third one will act like the first and only send the arguments. Even if you toggle back and forth, a statement is only prepared once. .PP Using prepared statements is in theory quite a bit faster: not only does the PostgreSQL backend only have to prepare the query only once, but DBD::Pg no longer has to worry about quoting each value before sending it to the server. .PP However, there are some drawbacks. The server cannot always choose the ideal parse plan because it will not know the arguments before hand. But for most situations in which you will be executing similar data many times, the default plan will probably work out well. Programs such as PgBouncer which cache connections at a low level should not use prepared statements via DBD::Pg, or must take extra care in the application to account for the fact that prepared statements are not shared across database connections. Further discussion on this subject is beyond the scope of this documentation: please consult the pgsql-performance mailing list, .PP Only certain commands will be sent to a server-side prepare: currently these include \f(CW\*(C`SELECT\*(C'\fR, \f(CW\*(C`INSERT\*(C'\fR, \f(CW\*(C`UPDATE\*(C'\fR, and \f(CW\*(C`DELETE\*(C'\fR. DBD::Pg uses a simple naming scheme for the prepared statements themselves: \fBdbdpg_XY_Z\fR, where \fBY\fR is the current \&\s-1PID,\s0 \fBX\fR is either 'p' or 'n' (depending on if the \s-1PID\s0 is a positive or negative number), and \fBZ\fR is a number that starts at 1 and increases each time a new statement is prepared. This number is tracked at the database handle level, so multiple statement handles will not collide. .PP You cannot send more than one command at a time in the same prepare command (by separating them with semi-colons) when using server-side prepares. .PP The actual \f(CW\*(C`PREPARE\*(C'\fR is usually not performed until the first execute is called, due to the fact that information on the data types (provided by \*(L"bind_param\*(R") may be provided after the prepare but before the execute. .PP A server-side prepare may happen before the first \*(L"execute\*(R", but only if the server can handle the server-side prepare, and the statement contains no placeholders. It will also be prepared if the pg_prepare_now attribute is passed in and set to a true value. Similarly, the pg_prepare_now attribute can be set to 0 to ensure that the statement is \fBnot\fR prepared immediately, although the cases in which you would want this are very rare. Finally, you can set the default behavior of all prepare statements by setting the pg_prepare_now attribute on the database handle: .PP .Vb 1 \& $dbh\->{pg_prepare_now} = 1; .Ve .PP The following two examples will be prepared right away: .PP .Vb 1 \& $sth\->prepare("SELECT 123"); ## no placeholders \& \& $sth\->prepare("SELECT 123, ?", {pg_prepare_now => 1}); .Ve .PP The following two examples will \s-1NOT\s0 be prepared right away: .PP .Vb 1 \& $sth\->prepare("SELECT 123, ?"); ## has a placeholder \& \& $sth\->prepare("SELECT 123", {pg_prepare_now => 0}); .Ve .PP There are times when you may want to prepare a statement yourself. To do this, simply send the \f(CW\*(C`PREPARE\*(C'\fR statement directly to the server (e.g. with the \*(L"do\*(R" method). Create a statement handle and set the prepared name via the pg_prepare_name attribute. The statement handle can be created with a dummy statement, as it will not be executed. However, it should have the same number of placeholders as your prepared statement. Example: .PP .Vb 5 \& $dbh\->do(\*(AqPREPARE mystat AS SELECT COUNT(*) FROM pg_class WHERE reltuples < ?\*(Aq); \& $sth = $dbh\->prepare(\*(AqSELECT ?\*(Aq); \& $sth\->bind_param(1, 1, SQL_INTEGER); \& $sth\->{pg_prepare_name} = \*(Aqmystat\*(Aq; \& $sth\->execute(123); .Ve .PP The above will run the equivalent of this query on the backend: .PP .Vb 1 \& EXECUTE mystat(123); .Ve .PP which is the equivalent of: .PP .Vb 1 \& SELECT COUNT(*) FROM pg_class WHERE reltuples < 123; .Ve .PP You can force DBD::Pg to send your query directly to the server by adding the pg_direct attribute to your prepare call. This is not recommended, but is added just in case you need it. .PP \fBPlaceholders\fR .IX Subsection "Placeholders" .PP There are three types of placeholders that can be used in DBD::Pg. The first is the \*(L"question mark\*(R" type, in which each placeholder is represented by a single question mark character. This is the method recommended by the \s-1DBI\s0 specs and is the most portable. Each question mark is internally replaced by a \*(L"dollar sign number\*(R" in the order in which they appear in the query (important when using \*(L"bind_param\*(R"). .PP The second type of placeholder is \*(L"dollar sign numbers\*(R". This is the method that Postgres uses internally and is overall probably the best method to use if you do not need compatibility with other database systems. DBD::Pg, like PostgreSQL, allows the same number to be used more than once in the query. Numbers must start with \*(L"1\*(R" and increment by one value (but can appear in any order within the query). If the same number appears more than once in a query, it is treated as a single parameter and all instances are replaced at once. Examples: .PP Not legal: .PP .Vb 1 \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages > $2\*(Aq; # Does not start with 1 \& \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $3\*(Aq; # Missing 2 .Ve .PP Legal: .PP .Vb 1 \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages > $1\*(Aq; \& \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $2\*(Aq; \& \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages BETWEEN $2 AND $1\*(Aq; # legal but confusing \& \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $2 AND reltuples > $1\*(Aq; \& \& $SQL = \*(AqSELECT count(*) FROM pg_class WHERE relpages > $1 AND reltuples > $1\*(Aq; .Ve .PP In the final statement above, \s-1DBI\s0 thinks there is only one placeholder, so this statement will replace both placeholders: .PP .Vb 1 \& $sth\->bind_param(1, 2045); .Ve .PP While a simple execute with no bind_param calls requires only a single argument as well: .PP .Vb 1 \& $sth\->execute(2045); .Ve .PP The final placeholder type is \*(L"named parameters\*(R" in the format \*(L":foo\*(R". While this syntax is supported by DBD::Pg, its use is discouraged in favor of dollar-sign numbers. .PP The different types of placeholders cannot be mixed within a statement, but you may use different ones for each statement handle you have. This is confusing at best, so stick to one style within your program. .PP If your queries use operators that contain question marks (e.g. some of the native Postgres geometric operators and \s-1JSON\s0 operators) or array slices (e.g. \f(CW\*(C`data[100:300]\*(C'\fR), there are methods to instruct DBD::Pg to not treat some symbols as placeholders. First, you may simply add a backslash before the start of a placeholder, and DBD::Pg will strip the backslash and not treat the character as a placeholder. .PP You can also tell DBD::Pg to ignore any non-dollar sign placeholders by setting the pg_placeholder_dollaronly attribute at either the database handle or the statement handle level. Examples: .PP .Vb 3 \& $dbh\->{pg_placeholder_dollaronly} = 1; \& $sth = $dbh\->prepare(q{SELECT * FROM mytable WHERE lseg1 ?# lseg2 AND name = $1}); \& $sth\->execute(\*(Aqsegname\*(Aq); .Ve .PP Alternatively, you can set it at prepare time: .PP .Vb 3 \& $sth = $dbh\->prepare(q{SELECT * FROM mytable WHERE lseg1 ?\-| lseg2 AND name = $1}, \& {pg_placeholder_dollaronly => 1}); \& $sth\->execute(\*(Aqsegname\*(Aq); .Ve .PP If your queries use array slices but you still want to use question marks as placeholders, you can tell DBD::Pg to ignore just colon placeholders by setting the \*(L"pg_placeholder_nocolons\*(R" attribute in the same way. Examples: .PP .Vb 3 \& $dbh\->{pg_placeholder_nocolons} = 1; \& $sth = $dbh\->prepare(q{SELECT array[1:2] FROM mytable WHERE id = ?}); \& $sth\->execute(1); .Ve .PP Again, you may set it param time as well: .PP .Vb 3 \& $sth = $dbh\->prepare(q{SELECT array[1:2] FROM mytable WHERE id = ?}, \& {pg_placeholder_nocolons => 1}); \& $sth\->execute(1); .Ve .PP It should be noted that placeholders only work when used outside of a literal string context; i.e., the following examples will \fBnot\fR define/use any placeholders due to appearing inside strings within the \s-1SQL:\s0 .PP .Vb 2 \& $sth = $dbh\->prepare(q{SELECT id FROM mytable WHERE text LIKE \*(Aq%?\*(Aq}); \& $dbh\->do(q{DO LANGUAGE plpgsql $$ BEGIN RAISE NOTICE ?; END $$}, undef, $message); .Ve .PP See the \s-1DBI\s0 placeholder documentation for more details. .PP \fI\f(BIprepare_cached\fI\fR .IX Subsection "prepare_cached" .PP .Vb 1 \& $sth = $dbh\->prepare_cached($statement, \e%attr); .Ve .PP Implemented by \s-1DBI,\s0 no driver-specific impact. This method is most useful when using a server that supports server-side prepares, and you have asked the prepare to happen immediately via the pg_prepare_now attribute. .PP \fI\f(BIdo\fI\fR .IX Subsection "do" .PP .Vb 3 \& $rv = $dbh\->do($statement); \& $rv = $dbh\->do($statement, \e%attr); \& $rv = $dbh\->do($statement, \e%attr, @bind_values); .Ve .PP Prepare and execute a single statement. Returns the number of rows affected if the query was successful, returns undef if an error occurred, and returns \-1 if the number of rows is unknown or not available. Note that this method will return \fB0E0\fR instead of 0 for 'no rows were affected', in order to always return a true value if no error occurred. .PP If neither \f(CW\*(C`\e%attr\*(C'\fR nor \f(CW@bind_values\fR is given, the query will be sent directly to the server without the overhead of internally creating a statement handle and running prepare and execute, for a measurable speed increase. .PP Note that an empty statement (a string with no length) will not be passed to the server; if you want a simple test, use \*(L"\s-1SELECT 123\*(R"\s0 or the \*(L"ping\*(R" method. .PP \fI\f(BIlast_insert_id\fI\fR .IX Subsection "last_insert_id" .PP .Vb 2 \& $rv = $dbh\->last_insert_id(undef, $schema, $table, undef); \& $rv = $dbh\->last_insert_id(undef, $schema, $table, undef, {sequence => $seqname}); .Ve .PP Attempts to return the id of the last value to be inserted into a table. You can either provide a sequence name (preferred) or provide a table name with optional schema, and DBD::Pg will attempt to find the sequence itself. The current value of the sequence is returned by a call to the \f(CW\*(C`CURRVAL()\*(C'\fR PostgreSQL function. This will fail if the sequence has not yet been used in the current database connection. .PP If you do not know the name of the sequence, you can provide a table name and DBD::Pg will attempt to return the correct value. To do this, there must be at least one column in the table with a \f(CW\*(C`NOT NULL\*(C'\fR constraint, that has a unique constraint, and which uses a sequence as a default value (either manually, or via the \f(CW\*(C`SERIAL\*(C'\fR pseudotype or \f(CW\*(C`GENERATED ... AS IDENTITY\*(C'\fR). If more than one column meets these conditions, the primary key will be used. This involves some looking up of things in the system table, so DBD::Pg will cache the sequence name for subsequent calls. If you need to disable this caching for some reason, (such as the sequence name changing), you can control it by adding \f(CW\*(C`pg_cache => 0\*(C'\fR to the final (hashref) argument for last_insert_id. .PP Please keep in mind that this method is far from foolproof, so make your script use it properly. Specifically, make sure that it is called immediately after the insert, and that the insert does not add a value to the column that is using the sequence as a default value. However, because we are using sequences, you can be sure that the value you got back has not been used by any other process. .PP Some examples: .PP .Vb 11 \& $dbh\->do(\*(AqCREATE SEQUENCE lii_seq START 1\*(Aq); \& $dbh\->do(q{CREATE TABLE lii ( \& foobar INTEGER NOT NULL UNIQUE DEFAULT nextval(\*(Aqlii_seq\*(Aq), \& baz VARCHAR)}); \& $SQL = \*(AqINSERT INTO lii(baz) VALUES (?)\*(Aq; \& $sth = $dbh\->prepare($SQL); \& for (qw(uno dos tres cuatro)) { \& $sth\->execute($_); \& my $newid = $dbh\->last_insert_id(undef,undef,undef,undef,{sequence=>\*(Aqlii_seq\*(Aq}); \& print "Last insert id was $newid\en"; \& } .Ve .PP If you did not want to worry about the sequence name: .PP .Vb 10 \& $dbh\->do(\*(AqCREATE TABLE lii2 ( \& foobar SERIAL UNIQUE, \& baz VARCHAR)\*(Aq); \& $SQL = \*(AqINSERT INTO lii2(baz) VALUES (?)\*(Aq; \& $sth = $dbh\->prepare($SQL); \& for (qw(uno dos tres cuatro)) { \& $sth\->execute($_); \& my $newid = $dbh\->last_insert_id(undef,undef,"lii2",undef); \& print "Last insert id was $newid\en"; \& } .Ve .PP \fI\f(BIcommit\fI\fR .IX Subsection "commit" .PP .Vb 1 \& $rv = $dbh\->commit; .Ve .PP Issues a \s-1COMMIT\s0 to the server, indicating that the current transaction is finished and that all changes made will be visible to other processes. If AutoCommit is enabled, then a warning is given and no \s-1COMMIT\s0 is issued. Returns true on success, false on error. See also the section on \*(L"Transactions\*(R". .PP \fI\f(BIrollback\fI\fR .IX Subsection "rollback" .PP .Vb 1 \& $rv = $dbh\->rollback; .Ve .PP Issues a \s-1ROLLBACK\s0 to the server, which discards any changes made in the current transaction. If AutoCommit is enabled, then a warning is given and no \s-1ROLLBACK\s0 is issued. Returns true on success, and false on error. See also the the section on \*(L"Transactions\*(R". .PP \fI\f(BIbegin_work\fI\fR .IX Subsection "begin_work" .PP This method turns on transactions until the next call to \*(L"commit\*(R" or \*(L"rollback\*(R", if AutoCommit is currently enabled. If it is not enabled, calling begin_work will issue an error. Note that the transaction will not actually begin until the first statement after begin_work is called. Example: .PP .Vb 4 \& $dbh\->{AutoCommit} = 1; \& $dbh\->do(\*(AqINSERT INTO foo VALUES (123)\*(Aq); ## Changes committed immediately \& $dbh\->begin_work(); \& ## Not in a transaction yet, but AutoCommit is set to 0 \& \& $dbh\->do("INSERT INTO foo VALUES (345)"); \& ## DBD::PG actually issues two statements here: \& ## BEGIN; \& ## INSERT INTO foo VALUES (345) \& ## We are now in a transaction \& \& $dbh\->commit(); \& ## AutoCommit is now set to 1 again .Ve .PP \fI\f(BIdisconnect\fI\fR .IX Subsection "disconnect" .PP .Vb 1 \& $rv = $dbh\->disconnect; .Ve .PP Disconnects from the Postgres database. Any uncommitted changes will be rolled back upon disconnection. It's good policy to always explicitly call commit or rollback at some point before disconnecting, rather than relying on the default rollback behavior. .PP This method may give warnings about \*(L"disconnect invalidates X active statement handle(s)\*(R". This means that you called \f(CW\*(C`$sth\->execute()\*(C'\fR but did not finish fetching all the rows from them. To avoid seeing this warning, either fetch all the rows or call \f(CW\*(C`$sth\->finish()\*(C'\fR for each executed statement handle. .PP If the script exits before disconnect is called (or, more precisely, if the database handle is no longer referenced by anything), then the database handle's \s-1DESTROY\s0 method will call the \fBrollback()\fR and \fBdisconnect()\fR methods automatically. It is best to explicitly disconnect rather than rely on this behavior. .PP \fI\f(BIquote\fI\fR .IX Subsection "quote" .PP .Vb 1 \& $rv = $dbh\->quote($value, $data_type); .Ve .PP This module implements its own \f(CW\*(C`quote\*(C'\fR method. For simple string types, both backslashes and single quotes are doubled. You may also quote arrayrefs and receive a string suitable for passing into Postgres array columns. .PP If the value contains backslashes, and the server is version 8.1 or higher, then the escaped string syntax will be used (which places a capital E before the first single quote). This syntax is always used when quoting bytea values on servers 8.1 and higher. .PP The \f(CW\*(C`data_type\*(C'\fR argument is optional and should be one of the type constants exported by DBD::Pg (such as \s-1PG_BYTEA\s0). In addition to string, bytea, char, bool, and other standard types, the following geometric types are supported: point, line, lseg, box, path, polygon, and circle (\s-1PG_POINT, PG_LINE, PG_LSEG, PG_BOX,\s0 \&\s-1PG_PATH, PG_POLYGON,\s0 and \s-1PG_CIRCLE\s0 respectively). To quote a Postgres-specific data type, you must use a 'hashref' argument like so: .PP .Vb 1 \& my $quotedval = $dbh\->quote($value, { pg_type => PG_VARCHAR }); .Ve .PP \&\fB\s-1NOTE:\s0\fR The undocumented (and invalid) support for the \f(CW\*(C`SQL_BINARY\*(C'\fR data type is officially deprecated. Use \f(CW\*(C`PG_BYTEA\*(C'\fR with \f(CW\*(C`bind_param()\*(C'\fR instead: .PP .Vb 2 \& $rv = $sth\->bind_param($param_num, $bind_value, \& { pg_type => PG_BYTEA }); .Ve .PP \fI\f(BIquote_identifier\fI\fR .IX Subsection "quote_identifier" .PP .Vb 2 \& $string = $dbh\->quote_identifier( $name ); \& $string = $dbh\->quote_identifier( undef, $schema, $table); .Ve .PP Returns a quoted version of the supplied string, which is commonly a schema, table, or column name. The three argument form will return the schema and the table together, separated by a dot. Examples: .PP .Vb 1 \& print $dbh\->quote_identifier(\*(Aqgrapefruit\*(Aq); ## Prints: "grapefruit" \& \& print $dbh\->quote_identifier(\*(Aqjuicy fruit\*(Aq); ## Prints: "juicy fruit" \& \& print $dbh\->quote_identifier(undef, \*(Aqpublic\*(Aq, \*(Aqpg_proc\*(Aq); \& ## Prints: "public"."pg_proc" .Ve .PP \fI\f(BIpg_notifies\fI\fR .IX Subsection "pg_notifies" .PP .Vb 1 \& $ret = $dbh\->pg_notifies; .Ve .PP Looks for any asynchronous notifications received and returns either \f(CW\*(C`undef\*(C'\fR or a reference to a three-element array consisting of an event name, the \s-1PID\s0 of the backend that sent the \s-1NOTIFY\s0 command, and the optional payload string. Note that this does not check if the connection to the database is still valid first \- for that, use the c method. You may need to commit if not in autocommit mode \- new notices will not be picked up while in the middle of a transaction. An example: .PP .Vb 2 \& $dbh\->do("LISTEN abc"); \& $dbh\->do("LISTEN def"); \& \& ## Hang around until we get the message we want \& LISTENLOOP: { \& while (my $notify = $dbh\->pg_notifies) { \& my ($name, $pid, $payload) = @$notify; \& print qq{I received notice "$name" from PID $pid, payload was "$payload"\en}; \& ## Do something based on the notice received \& } \& $dbh\->ping() or die qq{Ping failed!}; \& $dbh\->commit(); \& sleep(5); \& redo; \& } .Ve .PP Payloads will always be an empty string unless you are connecting to a Postgres server version 9.0 or higher. .PP \fI\f(BIping\fI\fR .IX Subsection "ping" .PP .Vb 1 \& $rv = $dbh\->ping; .Ve .PP The \f(CW\*(C`ping\*(C'\fR method determines if there is a working connection to an active database server. It does this by sending a small query to the server, currently \&\fB'DBD::Pg ping test v3.14.2'\fR. It returns 0 (false) if the connection is not valid, otherwise it returns a positive number (true). The value returned indicates the current state: .PP .Vb 6 \& Value Meaning \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& 1 Database is idle (not in a transaction) \& 2 Database is active, there is a command in progress (usually seen after a COPY command) \& 3 Database is idle within a transaction \& 4 Database is idle, within a failed transaction .Ve .PP Additional information on why a handle is not valid can be obtained by using the \&\*(L"pg_ping\*(R" method. .PP \fI\f(BIpg_ping\fI\fR .IX Subsection "pg_ping" .PP .Vb 1 \& $rv = $dbh\->pg_ping; .Ve .PP This is a DBD::Pg\-specific extension to the \*(L"ping\*(R" method. This will check the validity of a database handle in exactly the same way as \f(CW\*(C`ping\*(C'\fR, but instead of returning a 0 for an invalid connection, it will return a negative number. So in addition to returning the positive numbers documented for \f(CW\*(C`ping\*(C'\fR, it may also return the following: .PP .Vb 6 \& Value Meaning \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\- \& \-1 There is no connection to the database at all (e.g. after disconnect) \& \-2 An unknown transaction status was returned (e.g. after forking) \& \-3 The test query failed (PQexec returned null) \& \-4 PQstatus returned a CONNECTION_BAD .Ve .PP \fI\f(BIpg_error_field\fI\fR .IX Subsection "pg_error_field" .PP .Vb 1 \& $value = $dbh\->pg_error_field(\*(Aqcontext\*(Aq); .Ve .PP The \fBpg_error_field\fR returns specific information about the last error that occurred. It needs to be called as soon as possible after an error occurs, as any other query sent to Postgres (via \f(CW$dbh\fR or \f(CW$sth\fR) will reset all the error information. Note that this is called at the database handle ($dbh) level, but can return errors that occurred via both database handles (e.g. \f(CW$dbh\fR\->do) and statement handles (e.g. \f(CW$sth\fR\->execute). It takes a single argument, indicating which field to return. The value returned will be undef if the previous command was not an error, or if the field is not applicable to the current error. .PP The canonical list of field types can be found at: .PP .PP The literal names on that page can be used (e.g. \fB\s-1PG_DIAG_STATEMENT_HINT\s0\fR), but lowercase is accepted too, as well as the following abbreviated forms: .IP "severity" 4 .IX Item "severity" .PD 0 .IP "severity_nonlocal (only for Postgres 10 and above)" 4 .IX Item "severity_nonlocal (only for Postgres 10 and above)" .IP "state" 4 .IX Item "state" .IP "primary" 4 .IX Item "primary" .IP "detail (does not work well for Postgres < 9.2)" 4 .IX Item "detail (does not work well for Postgres < 9.2)" .IP "hint" 4 .IX Item "hint" .IP "statement_position" 4 .IX Item "statement_position" .IP "internal_position" 4 .IX Item "internal_position" .IP "internal_query" 4 .IX Item "internal_query" .IP "context" 4 .IX Item "context" .IP "schema (only for Postgres 9.3 and above)" 4 .IX Item "schema (only for Postgres 9.3 and above)" .IP "table (only for Postgres 9.3 and above)" 4 .IX Item "table (only for Postgres 9.3 and above)" .IP "column (only for Postgres 9.3 and above)" 4 .IX Item "column (only for Postgres 9.3 and above)" .IP "type (only for Postgres 9.3 and above)" 4 .IX Item "type (only for Postgres 9.3 and above)" .IP "constraint (only for Postgres 9.3 and above)" 4 .IX Item "constraint (only for Postgres 9.3 and above)" .IP "source_file" 4 .IX Item "source_file" .IP "source_line" 4 .IX Item "source_line" .IP "source_function" 4 .IX Item "source_function" .PD .PP \fI\f(BIget_info\fI\fR .IX Subsection "get_info" .PP .Vb 1 \& $value = $dbh\->get_info($info_type); .Ve .PP Supports a very large set (> 250) of the information types, including the minimum recommended by \s-1DBI.\s0 .PP Items of note: .IP "\s-1SQL_KEYWORDS\s0" 4 .IX Item "SQL_KEYWORDS" This returns all items reserved by Postgres but \s-1NOT\s0 reserved by \s-1SQL:2011\s0 standard. See: .Sp http://www.postgresql.org/docs/current/static/sql\-keywords\-appendix.htm .PP \fI\f(BItable_info\fI\fR .IX Subsection "table_info" .PP .Vb 1 \& $sth = $dbh\->table_info(undef, $schema, $table, $type); .Ve .PP Returns all tables and views visible to the current user. The schema and table arguments will do a \f(CW\*(C`LIKE\*(C'\fR search if a percent sign (\f(CW\*(C`%\*(C'\fR) or an underscore (\f(CW\*(C`_\*(C'\fR) is detected in the argument. The \f(CW$type\fR argument accepts any comma-separated combination of \*(L"\s-1TABLE\*(R", \*(L"VIEW\*(R", \*(L"SYSTEM TABLE\*(R", \*(L"SYSTEM VIEW\*(R", \&\*(L"MATERIALIZED VIEW\*(R", \*(L"SYSTEM MATERIALIZED VIEW\*(R", \*(L"FOREIGN TABLE\*(R", \*(L"SYSTEM FOREIGN TABLE\*(R",\s0 or \*(L"\s-1LOCAL TEMPORARY\*(R".\s0 (Using all is the default action.) .PP Note that a statement handle is returned, and not a direct list of tables. See the examples below for ways to handle this. .PP The following fields are returned: .PP \&\fB\s-1TABLE_CAT\s0\fR: The name of the database that the table or view is in (always the current database). .PP \&\fB\s-1TABLE_SCHEM\s0\fR: The name of the schema that the table or view is in. .PP \&\fB\s-1TABLE_NAME\s0\fR: The name of the table or view. .PP \&\fB\s-1TABLE_TYPE\s0\fR: The type of object returned. Will be one of \*(L"\s-1TABLE\*(R", \*(L"VIEW\*(R", \&\*(L"MATERIALIZED VIEW\*(R", \*(L"SYSTEM VIEW\*(R", \*(L"SYSTEM MATERIALIZED VIEW\*(R", \*(L"SYSTEM TABLE\*(R",\s0 \&\*(L"\s-1FOREIGN TABLE\*(R", \*(L"SYSTEM FOREIGN TABLE\*(R",\s0 or \*(L"\s-1LOCAL TEMPORARY\*(R".\s0 .PP The \s-1TABLE_SCHEM\s0 and \s-1TABLE_NAME\s0 will be quoted via \f(CW\*(C`quote_ident()\*(C'\fR. .PP Four additional fields specific to DBD::Pg are returned: .PP \&\fBpg_schema\fR: the unquoted name of the schema .PP \&\fBpg_table\fR: the unquoted name of the table .PP \&\fBpg_tablespace_name\fR: the name of the tablespace the table is in .PP \&\fBpg_tablespace_location\fR: the location of the tablespace the table is in .PP Tables that have not been assigned to a particular tablespace (or views) will return \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) for both of the above field. .PP Rows are returned alphabetically, with all tables first, and then all views. .PP Examples of use: .PP .Vb 5 \& ## Display all tables and views in the public schema: \& $sth = $dbh\->table_info(\*(Aq\*(Aq, \*(Aqpublic\*(Aq, undef, undef); \& for my $rel (@{$sth\->fetchall_arrayref({})}) { \& print "$rel\->{TABLE_TYPE} name is $rel\->{TABLE_NAME}\en"; \& } \& \& \& # Display the schema of all tables named \*(Aqfoo\*(Aq: \& $sth = $dbh\->table_info(\*(Aq\*(Aq, undef, \*(Aqfoo\*(Aq, \*(AqTABLE\*(Aq); \& for my $rel (@{$sth\->fetchall_arrayref({})}) { \& print "Table name is $rel\->{TABLE_SCHEM}.$rel\->{TABLE_NAME}\en"; \& } .Ve .PP \fI\f(BIcolumn_info\fI\fR .IX Subsection "column_info" .PP .Vb 1 \& $sth = $dbh\->column_info( undef, $schema, $table, $column ); .Ve .PP Supported by this driver as proposed by \s-1DBI\s0 with the follow exceptions. These fields are currently always returned with \s-1NULL\s0 (\f(CW\*(C`undef\*(C'\fR) values: .PP .Vb 6 \& BUFFER_LENGTH \& DECIMAL_DIGITS \& NUM_PREC_RADIX \& SQL_DATA_TYPE \& SQL_DATETIME_SUB \& CHAR_OCTET_LENGTH .Ve .PP Also, six additional non-standard fields are returned: .PP \&\fBpg_type\fR: data type with additional info i.e. \*(L"character varying(20)\*(R" .PP \&\fBpg_constraint\fR: holds column constraint definition .PP \&\fBpg_schema\fR: the unquoted name of the schema .PP \&\fBpg_table\fR: the unquoted name of the table .PP \&\fBpg_column\fR: the unquoted name of the column .PP \&\fBpg_enum_values\fR: an array reference of allowed values for an enum column .PP Note that the \s-1TABLE_SCHEM, TABLE_NAME,\s0 and \s-1COLUMN_NAME\s0 fields all return output wrapped in \fBquote_ident()\fR. If you need the unquoted version, use the pg_ fields above. .PP \fI\f(BIprimary_key_info\fI\fR .IX Subsection "primary_key_info" .PP .Vb 1 \& $sth = $dbh\->primary_key_info( undef, $schema, $table, \e%attr ); .Ve .PP Supported by this driver as proposed by \s-1DBI.\s0 There are no search patterns allowed, but leaving the \&\f(CW$schema\fR argument blank will cause the first table found in the schema search path to be used. An additional field, \*(L"\s-1DATA_TYPE\*(R",\s0 is returned and shows the data type for each of the arguments in the \*(L"\s-1COLUMN_NAME\*(R"\s0 field. .PP This method will also return tablespace information for servers that support tablespaces. See the \*(L"table_info\*(R" entry for more information. .PP The five additional custom fields returned are: .PP \&\fBpg_tablespace_name\fR: name of the tablespace, if any .PP \&\fBpg_tablespace_location\fR: location of the tablespace .PP \&\fBpg_schema\fR: the unquoted name of the schema .PP \&\fBpg_table\fR: the unquoted name of the table .PP \&\fBpg_column\fR: the unquoted name of the column .PP In addition to the standard format of returning one row for each column found for the primary key, you can pass the \f(CW\*(C`pg_onerow\*(C'\fR attribute to force a single row to be used. If the primary key has multiple columns, the \&\*(L"\s-1KEY_SEQ\*(R", \*(L"COLUMN_NAME\*(R",\s0 and \*(L"\s-1DATA_TYPE\*(R"\s0 fields will return a comma-delimited string. If the \f(CW\*(C`pg_onerow\*(C'\fR attribute is set to \*(L"2\*(R", the fields will be returned as an arrayref, which can be useful when multiple columns are involved: .PP .Vb 8 \& $sth = $dbh\->primary_key_info(\*(Aq\*(Aq, \*(Aq\*(Aq, \*(Aqdbd_pg_test\*(Aq, {pg_onerow => 2}); \& if (defined $sth) { \& my $pk = $sth\->fetchall_arrayref()\->[0]; \& print "Table $pk\->[2] has a primary key on these columns:\en"; \& for (my $x=0; defined $pk\->[3][$x]; $x++) { \& print "Column: $pk\->[3][$x] (data type: $pk\->[6][$x])\en"; \& } \& } .Ve .PP \fI\f(BIprimary_key\fI\fR .IX Subsection "primary_key" .PP .Vb 1 \& @key_column_names = $dbh\->primary_key(undef, $schema, $table); .Ve .PP Simple interface to the \*(L"primary_key_info\*(R" method. Returns a list of the column names that comprise the primary key of the specified table. The list is in primary key column sequence order. If there is no primary key then an empty list is returned. .PP \fI\f(BIforeign_key_info\fI\fR .IX Subsection "foreign_key_info" .PP .Vb 2 \& $sth = $dbh\->foreign_key_info( $pk_catalog, $pk_schema, $pk_table, \& $fk_catalog, $fk_schema, $fk_table ); .Ve .PP Supported by this driver as proposed by \s-1DBI,\s0 using the \s-1SQL/CLI\s0 variant. There are no search patterns allowed, but leaving the \f(CW$schema\fR argument blank will cause the first table found in the schema search path to be used. Two additional fields, \*(L"\s-1UK_DATA_TYPE\*(R"\s0 and \*(L"\s-1FK_DATA_TYPE\*(R",\s0 are returned to show the data type for the unique and foreign key columns. Foreign keys that have no named constraint (where the referenced column only has an unique index) will return \f(CW\*(C`undef\*(C'\fR for the \*(L"\s-1UK_NAME\*(R"\s0 field. .PP \fI\f(BIstatistics_info\fI\fR .IX Subsection "statistics_info" .PP .Vb 1 \& $sth = $dbh\->statistics_info( undef, $schema, $table, $unique_only, $quick ); .Ve .PP Returns a statement handle that can be fetched from to give statistics information on a specific table and its indexes. The \f(CW$table\fR argument is mandatory. The \&\f(CW$schema\fR argument is optional but recommended. The \f(CW$unique_only\fR argument, if true, causes only information about unique indexes to be returned. The \f(CW$quick\fR argument is not used by DBD::Pg. For information on the format of the standard rows returned, please see the \s-1DBI\s0 documentation. .PP \&\s-1DBI\s0 section on statistics_info .PP In addition, the following Postgres specific columns are returned: .IP "pg_expression" 4 .IX Item "pg_expression" Postgres allows indexes on functions and scalar expressions based on one or more columns. This field will always be populated if an index, but the lack of an entry in the \s-1COLUMN_NAME\s0 should indicate that this is an index expression. .IP "pg_is_key_column" 4 .IX Item "pg_is_key_column" Postgres (since version 11) allows including non-key columns in indexes so they can be retrieved by index-only scans. This field will be false for such columns, and true for normal index columns. .IP "pg_null_ordering" 4 .IX Item "pg_null_ordering" In addition to \f(CW\*(C`ASC\*(C'\fR and \f(CW\*(C`DESC\*(C'\fR, Postgres supports specifying \f(CW\*(C`NULLS FIRST\*(C'\fR or \f(CW\*(C`NULLS LAST\*(C'\fR for index columns. For columns of indexes that support ordering, this field will be \f(CW\*(C`first\*(C'\fR or \&\f(CW\*(C`last\*(C'\fR, otherwise it will be \f(CW\*(C`undef\*(C'\fR; .PP \fI\f(BItables\fI\fR .IX Subsection "tables" .PP .Vb 1 \& @names = $dbh\->tables( undef, $schema, $table, $type, \e%attr ); .Ve .PP Supported by this driver as proposed by \s-1DBI.\s0 This method returns all tables and/or views (including foreign tables and materialized views) which are visible to the current user: see \*(L"table_info\*(R" for more information about the arguments. The name of the schema appears before the table or view name. This can be turned off by adding in the \f(CW\*(C`pg_noprefix\*(C'\fR attribute: .PP .Vb 1 \& my @tables = $dbh\->tables( \*(Aq\*(Aq, \*(Aq\*(Aq, \*(Aqdbd_pg_test\*(Aq, \*(Aq\*(Aq, {pg_noprefix => 1} ); .Ve .PP \fI\f(BItype_info_all\fI\fR .IX Subsection "type_info_all" .PP .Vb 1 \& $type_info_all = $dbh\->type_info_all; .Ve .PP Supported by this driver as proposed by \s-1DBI.\s0 Information is only provided for \&\s-1SQL\s0 datatypes and for frequently used datatypes. The mapping between the PostgreSQL typename and the \s-1SQL92\s0 datatype (if possible) has been done according to the following table: .PP .Vb 10 \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ \& | typname | SQL92 | \& |\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-| \& | bool | BOOL | \& | text | / | \& | bpchar | CHAR(n) | \& | varchar | VARCHAR(n) | \& | int2 | SMALLINT | \& | int4 | INT | \& | int8 | BIGINT | \& | money | / | \& | float4 | FLOAT(p) p<7=float4, p<16=float8 | \& | float8 | REAL | \& | abstime | / | \& | reltime | / | \& | tinterval | / | \& | date | / | \& | time | / | \& | datetime | / | \& | timespan | TINTERVAL | \& | timestamp | TIMESTAMP | \& +\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-+ .Ve .PP \fI\f(BItype_info\fI\fR .IX Subsection "type_info" .PP .Vb 1 \& @type_info = $dbh\->type_info($data_type); .Ve .PP Returns a list of hash references holding information about one or more variants of \f(CW$data_type\fR. See the \s-1DBI\s0 documentation for more details. .PP \fI\f(BIpg_server_trace\fI\fR .IX Subsection "pg_server_trace" .PP .Vb 1 \& $dbh\->pg_server_trace($filehandle); .Ve .PP Writes debugging information from the PostgreSQL backend to a file. This is not related to the \s-1DBI\s0 \*(L"trace\*(R" method and you should not use this method unless you know what you are doing. If you do enable this, be aware that the file will grow very large, very quick. To stop logging to the file, use the \&\*(L"pg_server_untrace\*(R" method. The first argument must be a file handle, not a filename. Example: .PP .Vb 7 \& my $pid = $dbh\->{pg_pid}; \& my $file = "pgbackend.$pid.debug.log"; \& open(my $fh, ">$file") or die qq{Could not open "$file": $!\en}; \& $dbh\->pg_server_trace($fh); \& ## Run code you want to trace here \& $dbh\->pg_server_untrace; \& close($fh); .Ve .PP \fI\f(BIpg_server_untrace\fI\fR .IX Subsection "pg_server_untrace" .PP .Vb 1 \& $dbh\->pg_server_untrace; .Ve .PP Stop server logging to a previously opened file. .PP \fI\f(BIselectrow_array\fI\fR .IX Subsection "selectrow_array" .PP .Vb 3 \& @row_ary = $dbh\->selectrow_array($sql); \& @row_ary = $dbh\->selectrow_array($sql, \e%attr); \& @row_ary = $dbh\->selectrow_array($sql, \e%attr, @bind_values); .Ve .PP Returns an array of row information after preparing and executing the provided \s-1SQL\s0 string. The rows are returned by calling \*(L"fetchrow_array\*(R". The string can also be a statement handle generated by a previous prepare. Note that only the first row of data is returned. If called in a scalar context, only the first column of the first row is returned. Because this is not portable, it is not recommended that you use this method in that way. .PP \fI\f(BIselectrow_arrayref\fI\fR .IX Subsection "selectrow_arrayref" .PP .Vb 3 \& $ary_ref = $dbh\->selectrow_arrayref($statement); \& $ary_ref = $dbh\->selectrow_arrayref($statement, \e%attr); \& $ary_ref = $dbh\->selectrow_arrayref($statement, \e%attr, @bind_values); .Ve .PP Exactly the same as \*(L"selectrow_array\*(R", except that it returns a reference to an array, by internal use of the \*(L"fetchrow_arrayref\*(R" method. .PP \fI\f(BIselectrow_hashref\fI\fR .IX Subsection "selectrow_hashref" .PP .Vb 3 \& $hash_ref = $dbh\->selectrow_hashref($sql); \& $hash_ref = $dbh\->selectrow_hashref($sql, \e%attr); \& $hash_ref = $dbh\->selectrow_hashref($sql, \e%attr, @bind_values); .Ve .PP Exactly the same as \*(L"selectrow_array\*(R", except that it returns a reference to an hash, by internal use of the \*(L"fetchrow_hashref\*(R" method. .PP \fI\f(BIclone\fI\fR .IX Subsection "clone" .PP .Vb 1 \& $other_dbh = $dbh\->clone(); .Ve .PP Creates a copy of the database handle by connecting with the same parameters as the original handle, then trying to merge the attributes. See the \s-1DBI\s0 documentation for complete usage. .SS "Database Handle Attributes" .IX Subsection "Database Handle Attributes" \fI\f(BIAutoCommit\fI (boolean)\fR .IX Subsection "AutoCommit (boolean)" .PP Supported by DBD::Pg as proposed by \s-1DBI.\s0 According to the classification of \&\s-1DBI,\s0 PostgreSQL is a database in which a transaction must be explicitly started. Without starting a transaction, every change to the database becomes immediately permanent. The default of AutoCommit is on, but this may change in the future, so it is highly recommended that you explicitly set it when calling \*(L"connect\*(R". For details see the notes about \*(L"Transactions\*(R" elsewhere in this document. .PP \fI\f(BIParamValues\fI (hash ref, read-only)\fR .IX Subsection "ParamValues (hash ref, read-only)" .PP Ignored unless inside a \f(CW\*(C`do\*(C'\fR method call. There it is temporarily aliased to the \f(CW\*(C`ParamValues\*(C'\fR hash from the temporary statement handle inside an internal \&\f(CW\*(C`prepare / execute / fetch\*(C'\fR routine, invisible from outside, and is treated correspondingly (see \f(CW\*(C`ParamValues\*(C'\fR in \*(L"Statement Handle Attributes\*(R"). This allows for correct reporting of values bound to placeholders to the caller, should the query fail (see \f(CW\*(C`ShowErrorStatement\*(C'\fR). .PP \fI\f(BIpg_bool_tf\fI (boolean)\fR .IX Subsection "pg_bool_tf (boolean)" .PP DBD::Pg specific attribute. If true, boolean values will be returned as the characters 't' and 'f' instead of '1' and '0'. .PP \fI\f(BIReadOnly\fI (boolean)\fR .IX Subsection "ReadOnly (boolean)" .PP \&\f(CW$dbh\fR\->{ReadOnly} = 1; .PP Specifies if the current database connection should be in read-only mode or not. In this mode, changes that change the database are not allowed and will throw an error. Note: this method will \fBnot\fR work if \*(L"AutoCommit\*(R" is true. The read-only effect is accomplished by sending a SET TRANSACTION READ ONLY after every begin. For more details, please see: .PP http://www.postgresql.org/docs/current/interactive/sql\-set\-transaction.html .PP Please not that this method is not foolproof: there are still ways to update the database. Consider this a safety net to catch applications that should not be issuing commands such as \s-1INSERT, UPDATE,\s0 or \s-1DELETE.\s0 .PP This method requires \s-1DBI\s0 version 1.55 or better. .PP \fI\f(BIpg_server_prepare\fI (boolean)\fR .IX Subsection "pg_server_prepare (boolean)" .PP DBD::Pg specific attribute. Indicates if DBD::Pg should attempt to use server-side prepared statements. The default value, true, indicates that prepared statements should be used whenever possible. See the section on the \*(L"prepare\*(R" method for more information. .PP \fI\f(BIpg_switch_prepared\fI (integer)\fR .IX Subsection "pg_switch_prepared (integer)" .PP DBD::Pg specific attribute. Indicates when DBD::Pg will internally switch from using PQexecParams to PQexecPrepared. In other words, when it will start using server-side prepared statements (assuming all other requirements for them are met). The default value, 2, means that a prepared statement will be prepared and used the second and subsequent time execute is called. To always use PQexecPrepared instead of PQexecParams, set pg_switch_prepared to 1 (this was the default behavior in earlier versions). Setting pg_switch_prepared to 0 will force DBD::Pg to always use PQexecParams. .PP \fI\f(BIpg_placeholder_dollaronly\fI (boolean)\fR .IX Subsection "pg_placeholder_dollaronly (boolean)" .PP DBD::Pg specific attribute. Defaults to false. When true, question marks inside of statements are not treated as placeholders. Useful for statements that contain unquoted question marks, such as geometric operators. Note that you may also simply escape question marks with a backslash to prevent them from being treated as placeholders. .PP \fI\f(BIpg_placeholder_nocolons\fI (boolean)\fR .IX Subsection "pg_placeholder_nocolons (boolean)" .PP DBD::Pg specific attribute. Defaults to false. When true, colons inside of statements are not treated as placeholders. Useful for statements that contain an array slice. You may also place a backslash directly before the colon to prevent it from being treated as a placeholder. .PP \fI\f(BIpg_enable_utf8\fI (integer)\fR .IX Subsection "pg_enable_utf8 (integer)" .PP DBD::Pg specific attribute. The behavior of DBD::Pg with regards to this flag has changed as of version 3.0.0. The default value for this attribute, \-1, tells DBD::Pg to UTF8\-decode all strings coming back from the database if the client_encoding is set to \f(CW\*(C`UTF8\*(C'\fR. Use of this default is highly encouraged. If your code was previously using pg_enable_utf8, you can probably remove mention of it entirely. .PP If this attribute is set to 0, then DBD::Pg will \fBnever\fR UTF8\-decode returned data, regardless of the current client_encoding. .PP If this attribute is set to 1, then DBD::Pg will \fBalways\fR UTF8\-decode returned data, regardless of the current client_encoding (with the exception of bytea data). .PP Note that the value of client_encoding is only checked on connection time. If you change the client_encoding to/from '\s-1UTF8\s0' after connecting, you can set pg_enable_utf8 to \-1 to force DBD::Pg to read in the new client_encoding and act accordingly. .PP \fI\f(BIpg_errorlevel\fI (integer)\fR .IX Subsection "pg_errorlevel (integer)" .PP DBD::Pg specific attribute. Sets the amount of information returned by the server's error messages. Valid entries are 0, 1, and 2. Any other number will be forced to the default value of 1. .PP A value of 0 (\*(L"\s-1TERSE\*(R"\s0) will show severity, primary text, and position only and will usually fit on a single line. A value of 1 (\*(L"\s-1DEFAULT\*(R"\s0) will also show any detail, hint, or context fields. A value of 2 (\*(L"\s-1VERBOSE\*(R"\s0) will show all available information. .PP \fI\f(BIpg_lib_version\fI (integer, read-only)\fR .IX Subsection "pg_lib_version (integer, read-only)" .PP DBD::Pg specific attribute. Indicates which version of PostgreSQL that DBD::Pg was compiled against. In other words, which libraries were used. Returns a number with major, minor, and revision together; version 8.1.4 would be returned as \f(CW80104\fR. .PP \fI\f(BIpg_server_version\fI (integer, read-only)\fR .IX Subsection "pg_server_version (integer, read-only)" .PP DBD::Pg specific attribute. Indicates which version of PostgreSQL that the current database handle is connected to. Returns a number with major, minor, and revision together; version 8.0.1 would be \f(CW80001\fR. .PP \fI\f(BIName\fI (string, read-only)\fR .IX Subsection "Name (string, read-only)" .PP Returns the name of the current database. This is the same as the \s-1DSN,\s0 without the \&\*(L"dbi:Pg:\*(R" part. Before version 2.0.0, this only returned the bare database name (e.g. 'foo'). From version 2.0.0 onwards, it returns the more correct output (e.g. 'dbname=foo') .PP \fI\f(BIUsername\fI (string, read-only)\fR .IX Subsection "Username (string, read-only)" .PP Returns the name of the user connected to the database. .PP \fI\f(BIpg_db\fI (string, read-only)\fR .IX Subsection "pg_db (string, read-only)" .PP DBD::Pg specific attribute. Returns the name of the current database. .PP \fI\f(BIpg_user\fI (string, read-only)\fR .IX Subsection "pg_user (string, read-only)" .PP DBD::Pg specific attribute. Returns the name of the user that connected to the server. .PP \fI\f(BIpg_host\fI (string, read-only)\fR .IX Subsection "pg_host (string, read-only)" .PP DBD::Pg specific attribute. Returns the host of the current server connection. Locally connected hosts will return an empty string. .PP \fI\f(BIpg_port\fI (integer, read-only)\fR .IX Subsection "pg_port (integer, read-only)" .PP DBD::Pg specific attribute. Returns the port of the connection to the server. .PP \fI\f(BIpg_socket\fI (integer, read-only)\fR .IX Subsection "pg_socket (integer, read-only)" .PP DBD::Pg specific attribute. Returns the file description number of the connection socket to the server. .PP \fI\f(BIpg_pass\fI (string, read-only)\fR .IX Subsection "pg_pass (string, read-only)" .PP DBD::Pg specific attribute. Returns the password used to connect to the server. .PP \fI\f(BIpg_options\fI (string, read-only)\fR .IX Subsection "pg_options (string, read-only)" .PP DBD::Pg specific attribute. Returns the command-line options passed to the server. May be an empty string. .PP \fI\f(BIpg_default_port\fI (integer, read-only)\fR .IX Subsection "pg_default_port (integer, read-only)" .PP DBD::Pg specific attribute. Returns the default port used if none is specifically given. .PP \fI\f(BIpg_pid\fI (integer, read-only)\fR .IX Subsection "pg_pid (integer, read-only)" .PP DBD::Pg specific attribute. Returns the process id (\s-1PID\s0) of the backend server process handling the connection. .PP \fI\f(BIpg_prepare_now\fI (boolean)\fR .IX Subsection "pg_prepare_now (boolean)" .PP DBD::Pg specific attribute. Default is off. If true, then the \*(L"prepare\*(R" method will immediately prepare commands, rather than waiting until the first execute. .PP \fI\f(BIpg_expand_array\fI (boolean)\fR .IX Subsection "pg_expand_array (boolean)" .PP DBD::Pg specific attribute. Defaults to true. If false, arrays returned from the server will not be changed into a Perl arrayref, but remain as a string. .PP \fI\f(BIpg_async_status\fI (integer, read-only)\fR .IX Subsection "pg_async_status (integer, read-only)" .PP DBD::Pg specific attribute. Returns the current status of an asynchronous command. 0 indicates no asynchronous command is in progress, 1 indicates that an asynchronous command has started and \-1 indicated that an asynchronous command has been cancelled. .PP \fI\f(BIpg_standard_conforming_strings\fI (boolean, read-only)\fR .IX Subsection "pg_standard_conforming_strings (boolean, read-only)" .PP DBD::Pg specific attribute. Returns true if the server is currently using standard conforming strings. Only available if the target server is version 8.2 or better. .PP \fI\f(BIpg_INV_READ\fI (integer, read-only)\fR .IX Subsection "pg_INV_READ (integer, read-only)" .PP Constant to be used for the mode in \*(L"pg_lo_creat\*(R" and \*(L"pg_lo_open\*(R". .PP \fI\f(BIpg_INV_WRITE\fI (integer, read-only)\fR .IX Subsection "pg_INV_WRITE (integer, read-only)" .PP Constant to be used for the mode in \*(L"pg_lo_creat\*(R" and \*(L"pg_lo_open\*(R". .PP \fI\f(BIDriver\fI (handle, read-only)\fR .IX Subsection "Driver (handle, read-only)" .PP Holds the handle of the parent driver. The only recommended use for this is to find the name of the driver using: .PP .Vb 1 \& $dbh\->{Driver}\->{Name} .Ve .PP \fI\f(BIpg_protocol\fI (integer, read-only)\fR .IX Subsection "pg_protocol (integer, read-only)" .PP DBD::Pg specific attribute. Returns the version of the PostgreSQL server. If DBD::Pg is unable to figure out the version, it will return a \*(L"0\*(R". Otherwise, a \*(L"3\*(R" is returned. .PP \fI\f(BIRowCacheSize\fI\fR .IX Subsection "RowCacheSize" .PP Not used by DBD::Pg .SH "DBI STATEMENT HANDLE OBJECTS" .IX Header "DBI STATEMENT HANDLE OBJECTS" .SS "Statement Handle Methods" .IX Subsection "Statement Handle Methods" \fI\f(BIbind_param\fI\fR .IX Subsection "bind_param" .PP .Vb 3 \& $rv = $sth\->bind_param($param_num, $bind_value); \& $rv = $sth\->bind_param($param_num, $bind_value, $bind_type); \& $rv = $sth\->bind_param($param_num, $bind_value, \e%attr); .Ve .PP Allows the user to bind a value and/or a data type to a placeholder. This is especially important when using server-side prepares. See the \&\*(L"prepare\*(R" method for more information. .PP The value of \f(CW$param_num\fR is a number if using the '?' or '$1' style placeholders. If using \*(L":foo\*(R" style placeholders, the complete name (e.g. \*(L":foo\*(R") must be given. For numeric values, you can either use a number or use a literal '$1'. See the examples below. .PP The \f(CW$bind_value\fR argument is fairly self-explanatory. A value of \f(CW\*(C`undef\*(C'\fR will bind a \f(CW\*(C`NULL\*(C'\fR to the placeholder. Using \f(CW\*(C`undef\*(C'\fR is useful when you want to change just the type and will be overwriting the value later. (Any value is actually usable, but \f(CW\*(C`undef\*(C'\fR is easy and efficient). .PP The \f(CW\*(C`\e%attr\*(C'\fR hash is used to indicate the data type of the placeholder. The default value is \*(L"varchar\*(R". If you need something else, you must use one of the values provided by \s-1DBI\s0 or by DBD::Pg. To use a \s-1SQL\s0 value, modify your \*(L"use \s-1DBI\*(R"\s0 statement at the top of your script as follows: .PP .Vb 1 \& use DBI qw(:sql_types); .Ve .PP This will import some constants into your script. You can plug those directly into the \*(L"bind_param\*(R" call. Some common ones that you will encounter are: .PP .Vb 1 \& SQL_INTEGER .Ve .PP To use PostgreSQL data types, import the list of values like this: .PP .Vb 1 \& use DBD::Pg qw(:pg_types); .Ve .PP You can then set the data types by setting the value of the \f(CW\*(C`pg_type\*(C'\fR key in the hash passed to \*(L"bind_param\*(R". The current list of Postgres data types exported is: .PP .Vb 10 \& PG_ACLITEM PG_ACLITEMARRAY PG_ANY PG_ANYARRAY PG_ANYCOMPATIBLE PG_ANYCOMPATIBLEARRAY \& PG_ANYCOMPATIBLENONARRAY PG_ANYCOMPATIBLERANGE PG_ANYELEMENT PG_ANYENUM PG_ANYNONARRAY PG_ANYRANGE \& PG_BIT PG_BITARRAY PG_BOOL PG_BOOLARRAY PG_BOX PG_BOXARRAY \& PG_BPCHAR PG_BPCHARARRAY PG_BYTEA PG_BYTEAARRAY PG_CHAR PG_CHARARRAY \& PG_CID PG_CIDARRAY PG_CIDR PG_CIDRARRAY PG_CIRCLE PG_CIRCLEARRAY \& PG_CSTRING PG_CSTRINGARRAY PG_DATE PG_DATEARRAY PG_DATERANGE PG_DATERANGEARRAY \& PG_EVENT_TRIGGER PG_FDW_HANDLER PG_FLOAT4 PG_FLOAT4ARRAY PG_FLOAT8 PG_FLOAT8ARRAY \& PG_GTSVECTOR PG_GTSVECTORARRAY PG_INDEX_AM_HANDLER PG_INET PG_INETARRAY PG_INT2 \& PG_INT2ARRAY PG_INT2VECTOR PG_INT2VECTORARRAY PG_INT4 PG_INT4ARRAY PG_INT4RANGE \& PG_INT4RANGEARRAY PG_INT8 PG_INT8ARRAY PG_INT8RANGE PG_INT8RANGEARRAY PG_INTERNAL \& PG_INTERVAL PG_INTERVALARRAY PG_JSON PG_JSONARRAY PG_JSONB PG_JSONBARRAY \& PG_JSONPATH PG_JSONPATHARRAY PG_LANGUAGE_HANDLER PG_LINE PG_LINEARRAY PG_LSEG \& PG_LSEGARRAY PG_MACADDR PG_MACADDR8 PG_MACADDR8ARRAY PG_MACADDRARRAY PG_MONEY \& PG_MONEYARRAY PG_NAME PG_NAMEARRAY PG_NUMERIC PG_NUMERICARRAY PG_NUMRANGE \& PG_NUMRANGEARRAY PG_OID PG_OIDARRAY PG_OIDVECTOR PG_OIDVECTORARRAY PG_PATH \& PG_PATHARRAY PG_PG_ATTRIBUTE PG_PG_ATTRIBUTEARRAY PG_PG_CLASS PG_PG_CLASSARRAY PG_PG_DDL_COMMAND \& PG_PG_DEPENDENCIES PG_PG_LSN PG_PG_LSNARRAY PG_PG_MCV_LIST PG_PG_NDISTINCT PG_PG_NODE_TREE \& PG_PG_PROC PG_PG_PROCARRAY PG_PG_SNAPSHOT PG_PG_SNAPSHOTARRAY PG_PG_TYPE PG_PG_TYPEARRAY \& PG_POINT PG_POINTARRAY PG_POLYGON PG_POLYGONARRAY PG_RECORD PG_RECORDARRAY \& PG_REFCURSOR PG_REFCURSORARRAY PG_REGCLASS PG_REGCLASSARRAY PG_REGCOLLATION PG_REGCOLLATIONARRAY \& PG_REGCONFIG PG_REGCONFIGARRAY PG_REGDICTIONARY PG_REGDICTIONARYARRAY PG_REGNAMESPACE PG_REGNAMESPACEARRAY \& PG_REGOPER PG_REGOPERARRAY PG_REGOPERATOR PG_REGOPERATORARRAY PG_REGPROC PG_REGPROCARRAY \& PG_REGPROCEDURE PG_REGPROCEDUREARRAY PG_REGROLE PG_REGROLEARRAY PG_REGTYPE PG_REGTYPEARRAY \& PG_TABLE_AM_HANDLER PG_TEXT PG_TEXTARRAY PG_TID PG_TIDARRAY PG_TIME \& PG_TIMEARRAY PG_TIMESTAMP PG_TIMESTAMPARRAY PG_TIMESTAMPTZ PG_TIMESTAMPTZARRAY PG_TIMETZ \& PG_TIMETZARRAY PG_TRIGGER PG_TSM_HANDLER PG_TSQUERY PG_TSQUERYARRAY PG_TSRANGE \& PG_TSRANGEARRAY PG_TSTZRANGE PG_TSTZRANGEARRAY PG_TSVECTOR PG_TSVECTORARRAY PG_TXID_SNAPSHOT \& PG_TXID_SNAPSHOTARRAY PG_UNKNOWN PG_UUID PG_UUIDARRAY PG_VARBIT PG_VARBITARRAY \& PG_VARCHAR PG_VARCHARARRAY PG_VOID PG_XID PG_XID8 PG_XID8ARRAY \& PG_XIDARRAY PG_XML PG_XMLARRAY .Ve .PP Data types are \*(L"sticky,\*(R" in that once a data type is set to a certain placeholder, it will remain for that placeholder, unless it is explicitly set to something else afterwards. If the statement has already been prepared, and you switch the data type to something else, DBD::Pg will re-prepare the statement for you before doing the next execute. .PP Examples: .PP .Vb 2 \& use DBI qw(:sql_types); \& use DBD::Pg qw(:pg_types); \& \& $SQL = "SELECT id FROM ptable WHERE size > ? AND title = ?"; \& $sth = $dbh\->prepare($SQL); \& \& ## Both arguments below are bound to placeholders as "varchar" \& $sth\->execute(123, "Merk"); \& \& ## Reset the datatype for the first placeholder to an integer \& $sth\->bind_param(1, undef, SQL_INTEGER); \& \& ## The "undef" bound above is not used, since we supply params to execute \& $sth\->execute(123, "Merk"); \& \& ## Set the first placeholder\*(Aqs value and data type \& $sth\->bind_param(1, 234, { pg_type => PG_TIMESTAMP }); \& \& ## Set the second placeholder\*(Aqs value and data type. \& ## We don\*(Aqt send a third argument, so the default "varchar" is used \& $sth\->bind_param(\*(Aq$2\*(Aq, "Zool"); \& \& ## We realize that the wrong data type was set above, so we change it: \& $sth\->bind_param(\*(Aq$1\*(Aq, 234, { pg_type => SQL_INTEGER }); \& \& ## We also got the wrong value, so we change that as well. \& ## Because the data type is sticky, we don\*(Aqt need to change it \& $sth\->bind_param(1, 567); \& \& ## This executes the statement with 567 (integer) and "Zool" (varchar) \& $sth\->execute(); .Ve .PP \fI\f(BIbind_param_inout\fI\fR .IX Subsection "bind_param_inout" .PP .Vb 1 \& $rv = $sth\->bind_param_inout($param_num, \e$scalar, 0); .Ve .PP Experimental support for this feature is provided. The first argument to bind_param_inout should be a placeholder number. The second argument should be a reference to a scalar variable in your script. The third argument is not used and should simply be set to 0. Note that what this really does is assign a returned column to the variable, in the order in which the column appears. For example: .PP .Vb 6 \& my $foo = 123; \& $sth = $dbh\->prepare("SELECT 1+?::int"); \& $sth\->bind_param_inout(1, \e$foo, 0); \& $foo = 222; \& $sth\->execute(444); \& $sth\->fetch; .Ve .PP The above will cause \f(CW$foo\fR to have a new value of \*(L"223\*(R" after the final fetch. Note that the variables bound in this manner are very sticky, and will trump any values passed in to execute. This is because the binding is done as late as possible, at the \fBexecute()\fR stage, allowing the value to be changed between the time it was bound and the time the query is executed. Thus, the above execute is the same as: .PP .Vb 1 \& $sth\->execute(); .Ve .PP \fI\f(BIbind_param_array\fI\fR .IX Subsection "bind_param_array" .PP .Vb 3 \& $rv = $sth\->bind_param_array($param_num, $array_ref_or_value) \& $rv = $sth\->bind_param_array($param_num, $array_ref_or_value, $bind_type) \& $rv = $sth\->bind_param_array($param_num, $array_ref_or_value, \e%attr) .Ve .PP Binds an array of values to a placeholder, so that each is used in turn by a call to the \*(L"execute_array\*(R" method. .PP \fI\f(BIexecute\fI\fR .IX Subsection "execute" .PP .Vb 1 \& $rv = $sth\->execute(@bind_values); .Ve .PP Executes a previously prepared statement. In addition to \f(CW\*(C`UPDATE\*(C'\fR, \f(CW\*(C`DELETE\*(C'\fR, \&\f(CW\*(C`INSERT\*(C'\fR statements, for which it returns always the number of affected rows, the \f(CW\*(C`execute\*(C'\fR method can also be used for \f(CW\*(C`SELECT ... INTO table\*(C'\fR statements. .PP The \*(L"prepare/bind/execute\*(R" process has changed significantly for PostgreSQL servers 7.4 and later: please see the \f(CW\*(C`prepare()\*(C'\fR and \f(CW\*(C`bind_param()\*(C'\fR entries for much more information. .PP Setting one of the bind_values to \*(L"undef\*(R" is the equivalent of setting the value to \s-1NULL\s0 in the database. Setting the bind_value to \f(CW$DBDPG_DEFAULT\fR is equivalent to sending the literal string '\s-1DEFAULT\s0' to the backend. Note that using this option will force server-side prepares off until such time as PostgreSQL supports using \s-1DEFAULT\s0 in prepared statements. .PP DBD::Pg also supports passing in arrays to execute: simply pass in an arrayref, and DBD::Pg will flatten it into a string suitable for input on the backend. .PP If you are using Postgres version 8.2 or greater, you can also use any of the fetch methods to retrieve the values of a \f(CW\*(C`RETURNING\*(C'\fR clause after you execute an \f(CW\*(C`UPDATE\*(C'\fR, \f(CW\*(C`DELETE\*(C'\fR, or \f(CW\*(C`INSERT\*(C'\fR. For example: .PP .Vb 7 \& $dbh\->do(q{CREATE TABLE abc (id SERIAL, country TEXT)}); \& $SQL = q{INSERT INTO abc (country) VALUES (?) RETURNING id}; \& $sth = $dbh\->prepare($SQL); \& $sth\->execute(\*(AqFrance\*(Aq); \& $countryid = $sth\->fetch()\->[0]; \& $sth\->execute(\*(AqNew Zealand\*(Aq); \& $countryid = $sth\->fetch()\->[0]; .Ve .PP \fI\f(BIexecute_array\fI\fR .IX Subsection "execute_array" .PP .Vb 3 \& $tuples = $sth\->execute_array() or die $sth\->errstr; \& $tuples = $sth\->execute_array(\e%attr) or die $sth\->errstr; \& $tuples = $sth\->execute_array(\e%attr, @bind_values) or die $sth\->errstr; \& \& ($tuples, $rows) = $sth\->execute_array(\e%attr) or die $sth\->errstr; \& ($tuples, $rows) = $sth\->execute_array(\e%attr, @bind_values) or die $sth\->errstr; .Ve .PP Execute a prepared statement once for each item in a passed-in hashref, or items that were previously bound via the \*(L"bind_param_array\*(R" method. See the \s-1DBI\s0 documentation for more details. .PP \fI\f(BIexecute_for_fetch\fI\fR .IX Subsection "execute_for_fetch" .PP .Vb 2 \& $tuples = $sth\->execute_for_fetch($fetch_tuple_sub); \& $tuples = $sth\->execute_for_fetch($fetch_tuple_sub, \e@tuple_status); \& \& ($tuples, $rows) = $sth\->execute_for_fetch($fetch_tuple_sub); \& ($tuples, $rows) = $sth\->execute_for_fetch($fetch_tuple_sub, \e@tuple_status); .Ve .PP Used internally by the \*(L"execute_array\*(R" method, and rarely used directly. See the \&\s-1DBI\s0 documentation for more details. .PP \fI\f(BIfetchrow_arrayref\fI\fR .IX Subsection "fetchrow_arrayref" .PP .Vb 1 \& $ary_ref = $sth\->fetchrow_arrayref; .Ve .PP Fetches the next row of data from the statement handle, and returns a reference to an array holding the column values. Any columns that are \s-1NULL\s0 are returned as undef within the array. .PP If there are no more rows or if an error occurs, then this method return undef. You should check \f(CW\*(C`$sth\->err\*(C'\fR afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error. .PP Note that the same array reference is returned for each fetch, so don't store the reference and then use it after a later fetch. Also, the elements of the array are also reused for each row, so take care if you want to take a reference to an element. See also \*(L"bind_columns\*(R". .PP \fI\f(BIfetchrow_array\fI\fR .IX Subsection "fetchrow_array" .PP .Vb 1 \& @ary = $sth\->fetchrow_array; .Ve .PP Similar to the \*(L"fetchrow_arrayref\*(R" method, but returns a list of column information rather than a reference to a list. Do not use this in a scalar context. .PP \fI\f(BIfetchrow_hashref\fI\fR .IX Subsection "fetchrow_hashref" .PP .Vb 2 \& $hash_ref = $sth\->fetchrow_hashref; \& $hash_ref = $sth\->fetchrow_hashref($name); .Ve .PP Fetches the next row of data and returns a hashref containing the name of the columns as the keys and the data itself as the values. Any \s-1NULL\s0 value is returned as an undef value. .PP If there are no more rows or if an error occurs, then this method return undef. You should check \f(CW\*(C`$sth\->err\*(C'\fR afterwards (or use the RaiseError attribute) to discover if the undef returned was due to an error. .PP The optional \f(CW$name\fR argument should be either \f(CW\*(C`NAME\*(C'\fR, \f(CW\*(C`NAME_lc\*(C'\fR or \f(CW\*(C`NAME_uc\*(C'\fR, and indicates what sort of transformation to make to the keys in the hash. .PP \fI\f(BIfetchall_arrayref\fI\fR .IX Subsection "fetchall_arrayref" .PP .Vb 3 \& $tbl_ary_ref = $sth\->fetchall_arrayref(); \& $tbl_ary_ref = $sth\->fetchall_arrayref( $slice ); \& $tbl_ary_ref = $sth\->fetchall_arrayref( $slice, $max_rows ); .Ve .PP Returns a reference to an array of arrays that contains all the remaining rows to be fetched from the statement handle. If there are no more rows, an empty arrayref will be returned. If an error occurs, the data read in so far will be returned. Because of this, you should always check \f(CW\*(C`$sth\->err\*(C'\fR after calling this method, unless RaiseError has been enabled. .PP If \f(CW$slice\fR is an array reference, fetchall_arrayref uses the \*(L"fetchrow_arrayref\*(R" method to fetch each row as an array ref. If the \f(CW$slice\fR array is not empty then it is used as a slice to select individual columns by perl array index number (starting at 0, unlike column and parameter numbers which start at 1). .PP With no parameters, or if \f(CW$slice\fR is undefined, fetchall_arrayref acts as if passed an empty array ref. .PP If \f(CW$slice\fR is a hash reference, fetchall_arrayref uses \*(L"fetchrow_hashref\*(R" to fetch each row as a hash reference. .PP See the \s-1DBI\s0 documentation for a complete discussion. .PP \fI\f(BIfetchall_hashref\fI\fR .IX Subsection "fetchall_hashref" .PP .Vb 1 \& $hash_ref = $sth\->fetchall_hashref( $key_field ); .Ve .PP Returns a hashref containing all rows to be fetched from the statement handle. See the \s-1DBI\s0 documentation for a full discussion. .PP \fI\f(BIfinish\fI\fR .IX Subsection "finish" .PP .Vb 1 \& $rv = $sth\->finish; .Ve .PP Indicates to \s-1DBI\s0 that you are finished with the statement handle and are not going to use it again. Only needed when you have not fetched all the possible rows. .PP \fI\f(BIrows\fI\fR .IX Subsection "rows" .PP .Vb 1 \& $rv = $sth\->rows; .Ve .PP Returns the number of rows returned by the last query. In contrast to many other \s-1DBD\s0 modules, the number of rows is available immediately after calling \f(CW\*(C`$sth\->execute\*(C'\fR. Note that the \*(L"execute\*(R" method itself returns the number of rows itself, which means that this method is rarely needed. .PP \fI\f(BIbind_col\fI\fR .IX Subsection "bind_col" .PP .Vb 3 \& $rv = $sth\->bind_col($column_number, \e$var_to_bind); \& $rv = $sth\->bind_col($column_number, \e$var_to_bind, \e%attr ); \& $rv = $sth\->bind_col($column_number, \e$var_to_bind, $bind_type ); .Ve .PP Binds a Perl variable and/or some attributes to an output column of a \s-1SELECT\s0 statement. Column numbers count up from 1. You do not need to bind output columns in order to fetch data. .PP See the \s-1DBI\s0 documentation for a discussion of the optional parameters \f(CW\*(C`\e%attr\*(C'\fR and \f(CW$bind_type\fR .PP \fI\f(BIbind_columns\fI\fR .IX Subsection "bind_columns" .PP .Vb 1 \& $rv = $sth\->bind_columns(@list_of_refs_to_vars_to_bind); .Ve .PP Calls the \*(L"bind_col\*(R" method for each column in the \s-1SELECT\s0 statement, using the supplied list. .PP \fI\f(BIdump_results\fI\fR .IX Subsection "dump_results" .PP .Vb 1 \& $rows = $sth\->dump_results($maxlen, $lsep, $fsep, $fh); .Ve .PP Fetches all the rows from the statement handle, calls \f(CW\*(C`DBI::neat_list\*(C'\fR for each row, and prints the results to \f(CW$fh\fR (which defaults to \fI\s-1STDOUT\s0\fR). Rows are separated by \f(CW$lsep\fR (which defaults to a newline). Columns are separated by \f(CW$fsep\fR (which defaults to a comma). The \f(CW$maxlen\fR controls how wide the output can be, and defaults to 35. .PP This method is designed as a handy utility for prototyping and testing queries. Since it uses \&\*(L"neat_list\*(R" to format and edit the string for reading by humans, it is not recommended for data transfer applications. .PP \fI\f(BIblob_read\fI\fR .IX Subsection "blob_read" .PP .Vb 1 \& $blob = $sth\->blob_read($id, $offset, $len); .Ve .PP Supported by DBD::Pg. This method is implemented by \s-1DBI\s0 but not currently documented by \s-1DBI,\s0 so this method might change. .PP This method seems to be heavily influenced by the current implementation of blobs in Oracle. Nevertheless we try to be as compatible as possible. Whereas Oracle suffers from the limitation that blobs are related to tables and every table can have only one blob (datatype \s-1LONG\s0), PostgreSQL handles its blobs independent of any table by using so-called object identifiers. This explains why the \f(CW\*(C`blob_read\*(C'\fR method is blessed into the \s-1STATEMENT\s0 package and not part of the \s-1DATABASE\s0 package. Here the field parameter has been used to handle this object identifier. The offset and len parameters may be set to zero, in which case the whole blob is fetched at once. .PP See also the PostgreSQL-specific functions concerning blobs, which are available via the \f(CW\*(C`func\*(C'\fR interface. .PP For further information and examples about blobs, please read the chapter about Large Objects in the PostgreSQL Programmer's Guide at . .PP \fI\f(BIpg_canonical_ids\fI\fR .IX Subsection "pg_canonical_ids" .PP .Vb 1 \& $data = $sth\->pg_canonical_ids; .Ve .PP DBD::Pg specific method. It returns Oid of table and position in table for every column in result set. .PP Returns array of arrays with \fITable Oid\fR and \fIColumn Position\fR for every column in result set or undef if current column is not a simple reference. .PP \fI\f(BIpg_canonical_names\fI\fR .IX Subsection "pg_canonical_names" .PP .Vb 1 \& $data = $sth\->pg_canonical_names; .Ve .PP DBD::Pg specific method. It returns array of original (or canonical) names (from where this data is actually came from) of columns in \&\fISchema\fR.\fITable\fR.\fIColumn\fR format or undef if current column is not a simple reference. .PP Note that this method is quite slow because it need additional information from server for every column that is simple reference. Consider to use \*(L"pg_canonical_ids\*(R" instead. .PP \fI\f(BIlast_insert_id\fI\fR .IX Subsection "last_insert_id" .PP .Vb 2 \& $rv = $sth\->last_insert_id(undef, $schema, $table, undef); \& $rv = $sth\->last_insert_id(undef, $schema, $table, undef, {sequence => $seqname}); .Ve .PP This is simply an alternative way to return the same information as \&\f(CW\*(C`$dbh\->last_insert_id\*(C'\fR. .SS "Statement Handle Attributes" .IX Subsection "Statement Handle Attributes" \fI\f(BI\s-1NUM_OF_FIELDS\s0\fI (integer, read-only)\fR .IX Subsection "NUM_OF_FIELDS (integer, read-only)" .PP Returns the number of columns returned by the current statement. A number will only be returned for \&\s-1SELECT\s0 statements, for \s-1SHOW\s0 statements (which always return \f(CW1\fR), and for \s-1INSERT,\s0 \&\s-1UPDATE,\s0 and \s-1DELETE\s0 statements which contain a \s-1RETURNING\s0 clause. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BI\s-1NUM_OF_PARAMS\s0\fI (integer, read-only)\fR .IX Subsection "NUM_OF_PARAMS (integer, read-only)" .PP Returns the number of placeholders in the current statement. .PP \fI\f(BI\s-1NAME\s0\fI (arrayref, read-only)\fR .IX Subsection "NAME (arrayref, read-only)" .PP Returns an arrayref of column names for the current statement. This method will only work for \s-1SELECT\s0 statements, for \s-1SHOW\s0 statements, and for \&\s-1INSERT, UPDATE,\s0 and \s-1DELETE\s0 statements which contain a \s-1RETURNING\s0 clause. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BINAME_lc\fI (arrayref, read-only)\fR .IX Subsection "NAME_lc (arrayref, read-only)" .PP The same as the \f(CW\*(C`NAME\*(C'\fR attribute, except that all column names are forced to lower case. .PP \fI\f(BINAME_uc\fI (arrayref, read-only)\fR .IX Subsection "NAME_uc (arrayref, read-only)" .PP The same as the \f(CW\*(C`NAME\*(C'\fR attribute, except that all column names are forced to upper case. .PP \fI\f(BINAME_hash\fI (hashref, read-only)\fR .IX Subsection "NAME_hash (hashref, read-only)" .PP Similar to the \f(CW\*(C`NAME\*(C'\fR attribute, but returns a hashref of column names instead of an arrayref. The names of the columns are the keys of the hash, and the values represent the order in which the columns are returned, starting at 0. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BINAME_lc_hash\fI (hashref, read-only)\fR .IX Subsection "NAME_lc_hash (hashref, read-only)" .PP The same as the \f(CW\*(C`NAME_hash\*(C'\fR attribute, except that all column names are forced to lower case. .PP \fI\f(BINAME_uc_hash\fI (hashref, read-only)\fR .IX Subsection "NAME_uc_hash (hashref, read-only)" .PP The same as the \f(CW\*(C`NAME_hash\*(C'\fR attribute, except that all column names are forced to lower case. .PP \fI\f(BI\s-1TYPE\s0\fI (arrayref, read-only)\fR .IX Subsection "TYPE (arrayref, read-only)" .PP Returns an arrayref indicating the data type for each column in the statement. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BI\s-1PRECISION\s0\fI (arrayref, read-only)\fR .IX Subsection "PRECISION (arrayref, read-only)" .PP Returns an arrayref of integer values for each column returned by the statement. The number indicates the precision for \f(CW\*(C`NUMERIC\*(C'\fR columns, the size in number of characters for \f(CW\*(C`CHAR\*(C'\fR and \f(CW\*(C`VARCHAR\*(C'\fR columns, and for all other types of columns it returns the number of \fIbytes\fR. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BI\s-1SCALE\s0\fI (arrayref, read-only)\fR .IX Subsection "SCALE (arrayref, read-only)" .PP Returns an arrayref of integer values for each column returned by the statement. The number indicates the scale of the that column. The only type that will return a value is \f(CW\*(C`NUMERIC\*(C'\fR. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BI\s-1NULLABLE\s0\fI (arrayref, read-only)\fR .IX Subsection "NULLABLE (arrayref, read-only)" .PP Returns an arrayref of integer values for each column returned by the statement. The number indicates if the column is nullable or not. 0 = not nullable, 1 = nullable, 2 = unknown. This method returns undef if called before \f(CW\*(C`execute()\*(C'\fR. .PP \fI\f(BIDatabase\fI (dbh, read-only)\fR .IX Subsection "Database (dbh, read-only)" .PP Returns the database handle this statement handle was created from. .PP \fI\f(BIParamValues\fI (hash ref, read-only)\fR .IX Subsection "ParamValues (hash ref, read-only)" .PP Returns a reference to a hash containing the values currently bound to placeholders. If the \*(L"named parameters\*(R" type of placeholders are being used (such as \*(L":foo\*(R"), then the keys of the hash will be the names of the placeholders (without the colon). If the \*(L"dollar sign numbers\*(R" type of placeholders are being used, the keys of the hash will be the numbers, without the dollar signs. If the \*(L"question mark\*(R" type is used, integer numbers will be returned, starting at one and increasing for every placeholder. .PP If this method is called before \*(L"execute\*(R", the literal values passed in are returned. If called after \&\*(L"execute\*(R", then the quoted versions of the values are returned. .PP \fI\f(BIParamTypes\fI (hash ref, read-only)\fR .IX Subsection "ParamTypes (hash ref, read-only)" .PP Returns a reference to a hash containing the type names currently bound to placeholders. The keys are the same as returned by the ParamValues method. The values are hashrefs containing a single key value pair, in which the key is either '\s-1TYPE\s0' if the type has a generic \s-1SQL\s0 equivalent, and 'pg_type' if the type can only be expressed by a Postgres type. The value is the internal number corresponding to the type originally passed in. (Placeholders that have not yet been bound will return undef as the value). This allows the output of ParamTypes to be passed back to the \*(L"bind_param\*(R" method. .PP \fI\f(BIStatement\fI (string, read-only)\fR .IX Subsection "Statement (string, read-only)" .PP Returns the statement string passed to the most recent \*(L"prepare\*(R" method called in this database handle, even if that method failed. This is especially useful where \*(L"RaiseError\*(R" is enabled and the exception handler checks $@ and sees that a \f(CW\*(C`prepare\*(C'\fR method call failed. .PP \fI\f(BIpg_current_row\fI (integer, read-only)\fR .IX Subsection "pg_current_row (integer, read-only)" .PP DBD::Pg specific attribute. Returns the number of the tuple (row) that was most recently fetched. Returns zero before and after fetching is performed. .PP \fI\f(BIpg_numbound\fI (integer, read-only)\fR .IX Subsection "pg_numbound (integer, read-only)" .PP DBD::Pg specific attribute. Returns the number of placeholders that are currently bound (via bind_param). .PP \fI\f(BIpg_bound\fI (hashref, read-only)\fR .IX Subsection "pg_bound (hashref, read-only)" .PP DBD::Pg specific attribute. Returns a hash of all named placeholders. The key is the name of the placeholder, and the value is a 0 or a 1, indicating if the placeholder has been bound yet (e.g. via bind_param) .PP \fI\f(BIpg_size\fI (arrayref, read-only)\fR .IX Subsection "pg_size (arrayref, read-only)" .PP DBD::Pg specific attribute. It returns a reference to an array of integer values for each column. The integer shows the size of the column in bytes. Variable length columns are indicated by \-1. .PP \fI\f(BIpg_type\fI (arrayref, read-only)\fR .IX Subsection "pg_type (arrayref, read-only)" .PP DBD::Pg specific attribute. It returns a reference to an array of strings for each column. The string shows the name of the data_type. .PP \fI\f(BIpg_segments\fI (arrayref, read-only)\fR .IX Subsection "pg_segments (arrayref, read-only)" .PP DBD::Pg specific attribute. Returns an arrayref of the query split on the placeholders. .PP \fI\f(BIpg_oid_status\fI (integer, read-only)\fR .IX Subsection "pg_oid_status (integer, read-only)" .PP DBD::Pg specific attribute. It returns the \s-1OID\s0 of the last \s-1INSERT\s0 command. .PP \fI\f(BIpg_cmd_status\fI (integer, read-only)\fR .IX Subsection "pg_cmd_status (integer, read-only)" .PP DBD::Pg specific attribute. It returns the type of the last command. Possible types are: \*(L"\s-1INSERT\*(R", \*(L"DELETE\*(R", \*(L"UPDATE\*(R", \*(L"SELECT\*(R".\s0 .PP \fI\f(BIpg_direct\fI (boolean)\fR .IX Subsection "pg_direct (boolean)" .PP DBD::Pg specific attribute. Default is false. If true, the query is passed directly to the backend without parsing for placeholders. .PP \fI\f(BIpg_prepare_now\fI (boolean)\fR .IX Subsection "pg_prepare_now (boolean)" .PP DBD::Pg specific attribute. Default is off. If true, the query will be immediately prepared, rather than waiting for the \*(L"execute\*(R" call. .PP \fI\f(BIpg_prepare_name\fI (string)\fR .IX Subsection "pg_prepare_name (string)" .PP DBD::Pg specific attribute. Specifies the name of the prepared statement to use for this statement handle. Not normally needed, see the section on the \*(L"prepare\*(R" method for more information. .PP \fI\f(BIpg_server_prepare\fI (boolean)\fR .IX Subsection "pg_server_prepare (boolean)" .PP DBD::Pg specific attribute. Indicates if DBD::Pg should attempt to use server-side prepared statements for this statement handle. The default value, true, indicates that prepared statements should be used whenever possible. See the section on the \*(L"prepare\*(R" method for more information. .PP \fI\f(BIpg_switch_prepared\fI (integer)\fR .IX Subsection "pg_switch_prepared (integer)" .PP DBD::Pg specific attribute. Indicates when DBD::Pg will internally switch from using PQexecParams to PQexecPrepared. In other words, when it will start using server-side prepared statements (assuming all other requirements for them are met). The default value, 2, means that a prepared statement will be prepared and used the second and subsequent time execute is called. To always use PQexecPrepared instead of PQexecParams, set pg_switch_prepared to 1 (this was the default behavior in earlier versions). Setting pg_switch_prepared to 0 will force DBD::Pg to always use PQexecParams. .PP \fI\f(BIpg_placeholder_dollaronly\fI (boolean)\fR .IX Subsection "pg_placeholder_dollaronly (boolean)" .PP DBD::Pg specific attribute. Defaults to false. When true, question marks inside of the query being prepared are not treated as placeholders. Useful for statements that contain unquoted question marks, such as geometric operators. Note that you may also simply escape question marks with a backslash to prevent them from being treated as placeholders. .PP \fI\f(BIpg_placeholder_nocolons\fI (boolean)\fR .IX Subsection "pg_placeholder_nocolons (boolean)" .PP DBD::Pg specific attribute. Defaults to false. When true, colons inside of statements are not treated as placeholders. Useful for statements that contain an array slice. You may also place a backslash directly before the colon to prevent it from being treated as a placeholder. .PP \fI\f(BIpg_async\fI (integer)\fR .IX Subsection "pg_async (integer)" .PP DBD::Pg specific attribute. Indicates the current behavior for asynchronous queries. See the section on \*(L"Asynchronous Constants\*(R" for more information. .PP \fI\f(BIpg_async_status\fI (integer, read-only)\fR .IX Subsection "pg_async_status (integer, read-only)" .PP DBD::Pg specific attribute. Returns the current status of an asynchronous command. 0 indicates no asynchronous command is in progress, 1 indicates that an asynchronous command has started and \-1 indicated that an asynchronous command has been cancelled. .PP \fI\f(BIRowsInCache\fI\fR .IX Subsection "RowsInCache" .PP Not used by DBD::Pg .PP \fI\f(BIRowCache\fI\fR .IX Subsection "RowCache" .PP Not used by DBD::Pg .PP \fI\f(BICursorName\fI\fR .IX Subsection "CursorName" .PP Not used by DBD::Pg. See the note about \*(L"Cursors\*(R" elsewhere in this document. .SH "FURTHER INFORMATION" .IX Header "FURTHER INFORMATION" .SS "Encoding" .IX Subsection "Encoding" DBD::Pg has extensive support for a client_encoding of \s-1UTF\-8,\s0 and most things like encoding and decoding should happen automatically. If you are using a different encoding, you will need do the encoding and decoding yourself. For this reason, it is highly recommended to always use a client_encoding of \s-1UTF\-8.\s0 The server_encoding can be anything, and no recommendations are made there, other than avoid \s-1SQL_ASCII\s0 whenever possible. .SS "Transactions" .IX Subsection "Transactions" Transaction behavior is controlled via the \*(L"AutoCommit\*(R" attribute. For a complete definition of \f(CW\*(C`AutoCommit\*(C'\fR please refer to the \s-1DBI\s0 documentation. .PP According to the \s-1DBI\s0 specification the default for \f(CW\*(C`AutoCommit\*(C'\fR is a true value. In this mode, any change to the database becomes valid immediately. Any \&\f(CW\*(C`BEGIN\*(C'\fR, \f(CW\*(C`COMMIT\*(C'\fR or \f(CW\*(C`ROLLBACK\*(C'\fR statements will be rejected. Note that preparing a statement does not always contact the server, as the actual \&\f(CW\*(C`PREPARE\*(C'\fR is usually postponed until the first call to \*(L"execute\*(R". .SS "Savepoints" .IX Subsection "Savepoints" PostgreSQL version 8.0 introduced the concept of savepoints, which allows transactions to be rolled back to a certain point without affecting the rest of the transaction. DBD::Pg encourages using the following methods to control savepoints: .PP \fI\f(CI\*(C`pg_savepoint\*(C'\fI\fR .IX Subsection "pg_savepoint" .PP Creates a savepoint. This will fail unless you are inside of a transaction. The only argument is the name of the savepoint. Note that PostgreSQL \s-1DOES\s0 allow multiple savepoints with the same name to exist. .PP .Vb 1 \& $dbh\->pg_savepoint("mysavepoint"); .Ve .PP \fI\f(CI\*(C`pg_rollback_to\*(C'\fI\fR .IX Subsection "pg_rollback_to" .PP Rolls the database back to a named savepoint, discarding any work performed after that point. If more than one savepoint with that name exists, rolls back to the most recently created one. .PP .Vb 1 \& $dbh\->pg_rollback_to("mysavepoint"); .Ve .PP \fI\f(CI\*(C`pg_release\*(C'\fI\fR .IX Subsection "pg_release" .PP Releases (or removes) a named savepoint. If more than one savepoint with that name exists, it will only destroy the most recently created one. Note that all savepoints created after the one being released are also destroyed. .PP .Vb 1 \& $dbh\->pg_release("mysavepoint"); .Ve .SS "Asynchronous Queries" .IX Subsection "Asynchronous Queries" It is possible to send a query to the backend and have your script do other work while the query is running on the backend. Both queries sent by the \*(L"do\*(R" method, and by the \*(L"execute\*(R" method can be sent asynchronously. The basic usage is as follows: .PP .Vb 10 \& print "Async do() example:\en"; \& $dbh\->do("SELECT long_running_query()", {pg_async => PG_ASYNC}); \& do_something_else(); \& { \& if ($dbh\->pg_ready()) { \& $res = $dbh\->pg_result(); \& print "Result of do(): $res\en"; \& } \& print "Query is still running...\en"; \& if (cancel_request_received) { \& $dbh\->pg_cancel(); \& } \& sleep 1; \& redo; \& } \& \& print "Async prepare/execute example:\en"; \& $sth = $dbh\->prepare("SELECT long_running_query(1)", {pg_async => PG_ASYNC}); \& $sth\->execute(); \& \& ## Changed our mind, cancel and run again: \& $sth = $dbh\->prepare("SELECT 678", {pg_async => PG_ASYNC + PG_OLDQUERY_CANCEL}); \& $sth\->execute(); \& \& do_something_else(); \& \& if (!$sth\->pg_ready) { \& do_another_thing(); \& } \& \& ## We wait until it is done, and get the result: \& $res = $dbh\->pg_result(); .Ve .PP \fIAsynchronous Constants\fR .IX Subsection "Asynchronous Constants" .PP There are currently three asynchronous constants automatically exported by DBD::Pg. .IP "\s-1PG_ASYNC\s0" 4 .IX Item "PG_ASYNC" This is a constant for the number 1. It is passed to either the \*(L"do\*(R" or the \*(L"prepare\*(R" method as a value to the pg_async key and indicates that the query should be sent asynchronously. .IP "\s-1PG_OLDQUERY_CANCEL\s0" 4 .IX Item "PG_OLDQUERY_CANCEL" This is a constant for the number 2. When passed to either the \*(L"do\*(R" or the \*(L"prepare\*(R" method, it causes any currently running asynchronous query to be cancelled and rolled back. It has no effect if no asynchronous query is currently running. .IP "\s-1PG_OLDQUERY_WAIT\s0" 4 .IX Item "PG_OLDQUERY_WAIT" This is a constant for the number 4. When passed to either the \*(L"do\*(R" or the \*(L"prepare\*(R" method, it waits for any currently running asynchronous query to complete. It has no effect if there is no asynchronous query currently running. .PP \fIAsynchronous Methods\fR .IX Subsection "Asynchronous Methods" .IP "\fBpg_cancel\fR" 4 .IX Item "pg_cancel" This database-level method attempts to cancel any currently running asynchronous query. It returns true if the cancel succeeded, and false otherwise. Note that a query that has finished before this method is executed will also return false. \fB\s-1WARNING\s0\fR: a successful cancellation may leave the database in an unusable state, so you may need to \s-1ROLLBACK\s0 or \s-1ROLLBACK TO\s0 a savepoint. As of version 2.17.0 of DBD::Pg, rollbacks are not done automatically. .Sp .Vb 1 \& $result = $dbh\->pg_cancel(); .Ve .IP "\fBpg_ready\fR" 4 .IX Item "pg_ready" This method can be called as a database handle method or (for convenience) as a statement handle method. Both simply see if a previously issued asynchronous query has completed yet. It returns true if the statement has finished, in which case you should then call the \*(L"pg_result\*(R" method. Calls to \f(CW\*(C`pg_ready()\*(C'\fR should only be used when you have other things to do while the query is running. If you simply want to wait until the query is done, do not call \fBpg_ready()\fR over and over, but simply call the \fBpg_result()\fR method. .Sp .Vb 7 \& my $time = 0; \& while (!$dbh\->pg_ready) { \& print "Query is still running. Seconds: $time\en"; \& $time++; \& sleep 1; \& } \& $result = $dbh\->pg_result; .Ve .IP "\fBpg_result\fR" 4 .IX Item "pg_result" This database handle method returns the results of a previously issued asynchronous query. If the query is still running, this method will wait until it has finished. The result returned is the number of rows: the same thing that would have been returned by the asynchronous \*(L"do\*(R" or \*(L"execute\*(R" if it had been called without an asynchronous flag. .Sp .Vb 1 \& $result = $dbh\->pg_result; .Ve .PP \fIAsynchronous Examples\fR .IX Subsection "Asynchronous Examples" .PP Here are some working examples of asynchronous queries. Note that we'll use the \fBpg_sleep\fR function to emulate a long-running query. .PP .Vb 4 \& use strict; \& use warnings; \& use Time::HiRes \*(Aqsleep\*(Aq; \& use DBD::Pg \*(Aq:async\*(Aq; \& \& my $dbh = DBI\->connect(\*(Aqdbi:Pg:dbname=postgres\*(Aq, \*(Aqpostgres\*(Aq, \*(Aq\*(Aq, {AutoCommit=>0,RaiseError=>1}); \& \& ## Kick off a long running query on the first database: \& my $sth = $dbh\->prepare("SELECT pg_sleep(?)", {pg_async => PG_ASYNC}); \& $sth\->execute(5); \& \& ## While that is running, do some other things \& print "Your query is processing. Thanks for waiting\en"; \& check_on_the_kids(); ## Expensive sub, takes at least three seconds. \& \& while (!$dbh\->pg_ready) { \& check_on_the_kids(); \& ## If the above function returns quickly for some reason, we add a small sleep \& sleep 0.1; \& } \& \& print "The query has finished. Gathering results\en"; \& my $result = $sth\->pg_result; \& print "Result: $result\en"; \& my $info = $sth\->fetchall_arrayref(); .Ve .PP Without asynchronous queries, the above script would take about 8 seconds to run: five seconds waiting for the execute to finish, then three for the \fBcheck_on_the_kids()\fR function to return. With asynchronous queries, the script takes about 6 seconds to run, and gets in two iterations of check_on_the_kids in the process. .PP Here's an example showing the ability to cancel a long-running query. Imagine two slave databases in different geographic locations over a slow network. You need information as quickly as possible, so you query both at once. When you get an answer, you tell the other one to stop working on your query, as you don't need it anymore. .PP .Vb 4 \& use strict; \& use warnings; \& use Time::HiRes \*(Aqsleep\*(Aq; \& use DBD::Pg \*(Aq:async\*(Aq; \& \& my $dbhslave1 = DBI\->connect(\*(Aqdbi:Pg:dbname=postgres;host=slave1\*(Aq, \*(Aqpostgres\*(Aq, \*(Aq\*(Aq, {AutoCommit=>0,RaiseError=>1}); \& my $dbhslave2 = DBI\->connect(\*(Aqdbi:Pg:dbname=postgres;host=slave2\*(Aq, \*(Aqpostgres\*(Aq, \*(Aq\*(Aq, {AutoCommit=>0,RaiseError=>1}); \& \& $SQL = "SELECT count(*) FROM largetable WHERE flavor=\*(Aqblueberry\*(Aq"; \& \& my $sth1 = $dbhslave1\->prepare($SQL, {pg_async => PG_ASYNC}); \& my $sth2 = $dbhslave2\->prepare($SQL, {pg_async => PG_ASYNC}); \& \& $sth1\->execute(); \& $sth2\->execute(); \& \& my $winner; \& while (!defined $winner) { \& if ($sth1\->pg_ready) { \& $winner = 1; \& } \& elsif ($sth2\->pg_ready) { \& $winner = 2; \& } \& Time::HiRes::sleep 0.05; \& } \& \& my $count; \& if ($winner == 1) { \& $sth2\->pg_cancel(); \& $sth1\->pg_result(); \& $count = $sth1\->fetchall_arrayref()\->[0][0]; \& } \& else { \& $sth1\->pg_cancel(); \& $sth2\->pg_result(); \& $count = $sth2\->fetchall_arrayref()\->[0][0]; \& } .Ve .SS "Array support" .IX Subsection "Array support" DBD::Pg allows arrays (as arrayrefs) to be passed in to both the \*(L"quote\*(R" and the \*(L"execute\*(R" methods. In both cases, the array is flattened into a string representing a Postgres array. .PP When fetching rows from a table that contains a column with an array type, the result will be passed back to your script as an arrayref. .PP To turn off the automatic parsing of returned arrays into arrayrefs, you can set the attribute pg_expand_array, which is true by default. .PP .Vb 1 \& $dbh\->{pg_expand_array} = 0; .Ve .SS "\s-1COPY\s0 support" .IX Subsection "COPY support" DBD::Pg allows for quick (bulk) reading and storing of data by using the \fB\s-1COPY\s0\fR command. The basic process is to use \f(CW\*(C`$dbh\->do\*(C'\fR to issue a \&\s-1COPY\s0 command, and then to either add rows using \*(L"pg_putcopydata\*(R", or to read them by using \*(L"pg_getcopydata\*(R". .PP The first step is to put the server into \*(L"\s-1COPY\*(R"\s0 mode. This is done by sending a complete \s-1COPY\s0 command to the server, by using the \*(L"do\*(R" method. For example: .PP .Vb 1 \& $dbh\->do("COPY foobar FROM STDIN"); .Ve .PP This would tell the server to enter a \s-1COPY IN\s0 mode (yes, that's confusing, but the \fImode\fR is \s-1COPY IN\s0 because of the \fIcommand\fR \s-1COPY FROM\s0). It is now ready to receive information via the \*(L"pg_putcopydata\*(R" method. The complete syntax of the \&\s-1COPY\s0 command is more complex and not documented here: the canonical PostgreSQL documentation for \s-1COPY\s0 can be found at: .PP http://www.postgresql.org/docs/current/static/sql\-copy.html .PP Once a \s-1COPY\s0 command has been issued, no other \s-1SQL\s0 commands are allowed until \*(L"pg_putcopyend\*(R" has been issued (for \s-1COPY FROM\s0), or the final \&\*(L"pg_getcopydata\*(R" has been called (for \s-1COPY TO\s0). .PP Note: All other \s-1COPY\s0 methods (pg_putline, pg_getline, etc.) are now heavily deprecated in favor of the pg_getcopydata, pg_putcopydata, and pg_putcopyend methods. .PP \fI\f(BIpg_getcopydata\fI\fR .IX Subsection "pg_getcopydata" .PP Used to retrieve data from a table after the server has been put into a \&\s-1COPY OUT\s0 mode by calling \*(L"\s-1COPY\s0 tablename \s-1TO STDOUT\*(R".\s0 Data is always returned one data row at a time. The first argument to pg_getcopydata is the variable into which the data will be stored (this variable should not be undefined, or it may throw a warning, although it may be a reference). The pg_getcopydata method returns a number greater than 1 indicating the new size of the variable, or a \-1 when the \s-1COPY\s0 has finished. Once a \-1 has been returned, no other action is necessary, as \s-1COPY\s0 mode will have already terminated. Example: .PP .Vb 4 \& $dbh\->do("COPY mytable TO STDOUT"); \& my @data; \& my $x=0; \& 1 while $dbh\->pg_getcopydata($data[$x++]) >= 0; .Ve .PP There is also a variation of this method called \fBpg_getcopydata_async\fR, which, as the name suggests, returns immediately. The only difference from the original method is that this version may return a 0, indicating that the row is not ready to be delivered yet. When this happens, the variable has not been changed, and you will need to call the method again until you get a non-zero result. (Data is still always returned one data row at a time.) .PP \fI\f(BIpg_putcopydata\fI\fR .IX Subsection "pg_putcopydata" .PP Used to put data into a table after the server has been put into \s-1COPY IN\s0 mode by calling \*(L"\s-1COPY\s0 tablename \s-1FROM STDIN\*(R".\s0 The only argument is the data you want inserted. Issue a \fBpg_putcopyend()\fR when you have added all your rows. .PP The default delimiter is a tab character, but this can be changed in the \s-1COPY\s0 statement. Returns a 1 on successful input. Examples: .PP .Vb 6 \& ## Simple example: \& $dbh\->do("COPY mytable FROM STDIN"); \& $dbh\->pg_putcopydata("123\etPepperoni\et3\en"); \& $dbh\->pg_putcopydata("314\etMushroom\et8\en"); \& $dbh\->pg_putcopydata("6\etAnchovies\et100\en"); \& $dbh\->pg_putcopyend(); \& \& ## This example uses explicit columns and a custom delimiter \& $dbh\->do("COPY mytable(flavor, slices) FROM STDIN WITH DELIMITER \*(Aq~\*(Aq"); \& $dbh\->pg_putcopydata("Pepperoni~123\en"); \& $dbh\->pg_putcopydata("Mushroom~314\en"); \& $dbh\->pg_putcopydata("Anchovies~6\en"); \& $dbh\->pg_putcopyend(); .Ve .PP \fI\f(BIpg_putcopyend\fI\fR .IX Subsection "pg_putcopyend" .PP When you are finished with pg_putcopydata, call pg_putcopyend to let the server know that you are done, and it will return to a normal, non-COPY state. Returns a 1 on success. This method will fail if called when not in \s-1COPY IN\s0 mode. .SS "Postgres limits" .IX Subsection "Postgres limits" For convenience, DBD::Pg can export certain constants representing the limits of Postgres data types. To use them, just add \f(CW\*(C`:pg_limits\*(C'\fR when DBD::Pg is used: .PP .Vb 1 \& use DBD::Pg qw/:pg_limits/; .Ve .PP The constants and their values are: .PP .Vb 12 \& PG_MIN_SMALLINT \-32768 \& PG_MAX_SMALLINT 32767 \& PG_MIN_INTEGER \-2147483648 \& PG_MAX_INTEGER 2147483647 \& PG_MIN_BIGINT \-9223372036854775808 \& PG_MAX_BIGINT 9223372036854775807 \& PG_MIN_SMALLSERIAL 1 \& PG_MAX_SMALLSERIAL 32767 \& PG_MIN_SERIAL 1 \& PG_MAX_SERIAL 2147483647 \& PG_MIN_BIGSERIAL 1 \& PG_MAX_BIGSERIAL 9223372036854775807 .Ve .SS "Large Objects" .IX Subsection "Large Objects" DBD::Pg supports all largeobject functions provided by libpq via the \&\f(CW\*(C`$dbh\->pg_lo*\*(C'\fR methods. Please note that access to a large object, even read-only large objects, must be put into a transaction. .SS "Cursors" .IX Subsection "Cursors" Although PostgreSQL supports cursors, they have not been used in the current implementation. When DBD::Pg was created, cursors in PostgreSQL could only be used inside a transaction block. Because only one transaction block at a time is allowed, this would have implied the restriction not to use any nested \&\f(CW\*(C`SELECT\*(C'\fR statements. Therefore the \*(L"execute\*(R" method fetches all data at once into data structures located in the front-end application. This fact must to be considered when selecting large amounts of data! .PP You can use cursors in your application, but you'll need to do a little work. First you must declare your cursor. Now you can issue queries against the cursor, then select against your queries. This typically results in a double loop, like this: .PP .Vb 6 \& # WITH HOLD is not needed if AutoCommit is off \& $dbh\->do("DECLARE csr CURSOR WITH HOLD FOR $sql"); \& while (1) { \& my $sth = $dbh\->prepare("fetch 1000 from csr"); \& $sth\->execute; \& last if 0 == $sth\->rows; \& \& while (my $row = $sth\->fetchrow_hashref) { \& # Do something with the data. \& } \& } \& $dbh\->do("CLOSE csr"); .Ve .SS "Datatype bool" .IX Subsection "Datatype bool" The current implementation of PostgreSQL returns 't' for true and 'f' for false. From the Perl point of view, this is a rather unfortunate choice. DBD::Pg therefore translates the result for the \f(CW\*(C`BOOL\*(C'\fR data type in a Perlish manner: 'f' becomes the number \f(CW0\fR and 't' becomes the number \f(CW1\fR. This way the application does not have to check the database-specific returned values for the data-type \f(CW\*(C`BOOL\*(C'\fR because Perl treats \f(CW0\fR as false and \f(CW1\fR as true. You may set the pg_bool_tf attribute to a true value to change the values back to 't' and \&'f' if you wish. .PP Boolean values can be passed to PostgreSQL as \s-1TRUE,\s0 't', 'true', 'y', 'yes' or \&'1' for true and \s-1FALSE,\s0 'f', 'false', 'n', 'no' or '0' for false. .SS "Schema support" .IX Subsection "Schema support" The PostgreSQL schema concept may differ from those of other databases. In a nutshell, a schema is a named collection of objects within a single database. Please refer to the PostgreSQL documentation for more details: .PP .PP DBD::Pg does not provide explicit support for PostgreSQL schemas. However, schema functionality may be used without any restrictions by explicitly addressing schema objects, e.g. .PP .Vb 1 \& my $res = $dbh\->selectall_arrayref("SELECT * FROM my_schema.my_table"); .Ve .PP or by manipulating the schema search path with \f(CW\*(C`SET search_path\*(C'\fR, e.g. .PP .Vb 1 \& $dbh\->do("SET search_path TO my_schema, public"); .Ve .SH "SEE ALSO" .IX Header "SEE ALSO" The \fB\s-1DBI\s0\fR module .SH "BUGS" .IX Header "BUGS" To report a bug, or view the current list of bugs, please visit http://rt.cpan.org/Public/Dist/Display.html?Name=DBD\-Pg .SH "DEVELOPMENT" .IX Header "DEVELOPMENT" Patches can be submitted to rt.cpan.org. Detailed information on how to help out with this module can be found in the \s-1README\s0.dev file. The latest development version can be obtained via: git clone git://github.com/bucardo/dbdpg.git .SH "AUTHORS" .IX Header "AUTHORS" \&\s-1DBI\s0 by Tim Bunce .PP The original DBD-Pg was by Edmund Mergl (E.Mergl@bawue.de) and Jeffrey W. Baker (jwbaker@acm.org). Major developers include David Wheeler , Jason Stewart , Bruce Momjian , and Greg Sabino Mullane , with help from many others: see the Changes file () for a complete list. .PP Parts of this package were originally copied from \s-1DBI\s0 and DBD-Oracle. .PP \&\fBMailing List\fR .PP The current maintainers may be reached through the 'dbd\-pg' mailing list: . Subscribe by sending an email to dbd\-pg\-subscribe@perl.org. Visit the archives at http://grokbase.com/g/perl/dbd\-pg .SH "COPYRIGHT AND LICENSE" .IX Header "COPYRIGHT AND LICENSE" Copyright (C) 1994\-2020, Greg Sabino Mullane .PP This module (DBD::Pg) is free software; you can redistribute it and/or modify it under the same terms as Perl 5.10.0. For more details, see the full text of the licenses in the directory \s-1LICENSES.\s0