PgSection: User Contributed Perl Documentation (3)Updated: 2003-11-17 |
PgSection: User Contributed Perl Documentation (3)Updated: 2003-11-17 |
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=$dbname", "", "");
# for some advanced uses you may need PostgreSQL type values: use DBD::Pg qw(:pg_types);
# See the DBI module documentation for full details
$dbh = DBI->connect("dbi:Pg:dbname=$dbname", "", "");
This connects to the database $dbname at localhost without any user authentication. This is sufficient for the defaults of PostgreSQL.
The following connect statement shows all possible parameters:
$dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;" .
"options=$options;tty=$tty", "$username", "$password");
If a parameter is undefined PostgreSQL first looks for specific environment variables and then it uses hard coded defaults:
parameter environment variable hard coded default -------------------------------------------------- dbname PGDATABASE current userid host PGHOST localhost port PGPORT 5432 options PGOPTIONS "" tty PGTTY "" username PGUSER current userid password PGPASSWORD ""
If a host is specified, the postmaster on this host needs to be started with the "-i" option (TCP/IP sockets).
The options parameter specifies runtime options for the Postgres backend. Common usage is to increase the number of buffers with the "-B" option. Also important is the "-F" option, which disables automatic fsync() call after each transaction. For further details please refer to the postgres.
For authentication with username and password appropriate entries have to be made in pg_hba.conf. Please refer to the pg_hba.conf and the pg_passwd for the different types of authentication. Note that for these two parameters DBI distinguishes between empty and undefined. If these parameters are undefined DBI substitutes the values of the environment variables DBI_USER and DBI_PASS if present.
@driver_names = DBI->available_drivers;
Implemented by DBI, no driver-specific impact.
@data_sources = DBI->data_sources('Pg');
The driver supports this method. Note that the necessary database connection to the database template1 will be done on the localhost without any user-authentication. Other preferences can only be set with the environment variables PGHOST, DBI_USER and DBI_PASS.
DBI->trace($trace_level, $trace_file)
Implemented by DBI, no driver-specific impact.
$rv = $h->err;
Supported by the driver as proposed by DBI. For the connect method it returns PQstatus. In all other cases it returns PQresultStatus of the current handle.
$str = $h->errstr;
Supported by the driver as proposed by DBI. It returns the PQerrorMessage related to the current handle.
$str = $h->state;
This driver does not (yet) support the state method.
$h->trace($trace_level, $trace_filename);
Implemented by DBI, no driver-specific impact.
$h->trace_msg($message_text);
Implemented by DBI, no driver-specific impact.
$attrs = $dbh->func($table, 'table_attributes');
The "table_attributes" function is no longer recommended. Instead, you can use the more portable "column_info" and "primary_key" functions to access all the same information.
This method returns for the given table a reference to an array of hashes:
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
$lobjId = $dbh->func($mode, 'lo_creat');
Creates a new large object and returns the object-id. $mode is a bit-mask describing different attributes of the new object. Use the following constants:
$dbh->{pg_INV_WRITE}
$dbh->{pg_INV_READ}
Upon failure it returns undef.
$lobj_fd = $dbh->func($lobjId, $mode, 'lo_open');
Opens an existing large object and returns an object-descriptor for use in subsequent lo_* calls. For the mode bits see lo_create. Returns undef upon failure. Note that 0 is a perfectly correct object descriptor!
$nbytes = $dbh->func($lobj_fd, $buf, $len, 'lo_write');
Writes $len bytes of $buf into the large object $lobj_fd. Returns the number of bytes written and undef upon failure.
$nbytes = $dbh->func($lobj_fd, $buf, $len, 'lo_read');
Reads $len bytes into $buf from large object $lobj_fd. Returns the number of bytes read and undef upon failure.
$loc = $dbh->func($lobj_fd, $offset, $whence, 'lo_lseek');
Change the current read or write location on the large object $obj_id. Currently $whence can only be 0 (L_SET). Returns the current location and undef upon failure.
$loc = $dbh->func($lobj_fd, 'lo_tell');
Returns the current read or write location on the large object $lobj_fd and undef upon failure.
$lobj_fd = $dbh->func($lobj_fd, 'lo_close');
Closes an existing large object. Returns true upon success and false upon failure.
$lobj_fd = $dbh->func($lobj_fd, 'lo_unlink');
Deletes an existing large object. Returns true upon success and false upon failure.
$lobjId = $dbh->func($filename, 'lo_import');
Imports a Unix file as large object and returns the object id of the new object or undef upon failure.
$ret = $dbh->func($lobjId, $filename, 'lo_export');
Exports a large object into a Unix file. Returns false upon failure, true otherwise.
$ret = $dbh->func($line, 'putline');
Used together with the SQL-command 'COPY table FROM STDIN' to copy large amount of data into a table avoiding the overhead of using single insert commands. The application must explicitly send the two characters ``\.'' to indicate to the backend that it has finished sending its data.
$ret = $dbh->func($buffer, length, 'getline');
Used together with the SQL-command 'COPY table TO STDOUT' to dump a complete table.
$ret = $dbh->func('pg_notifies');
Returns either undef or a reference to two-element array [ $table, $backend_pid ] of asynchronous notifications received.
$fd = $dbh->func('getfd');
Returns fd of the actual connection to server. Can be used with select() and func('pg_notifies').
@row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact.
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact.
$hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact.
$ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact.
$hash_ref = $dbh->selectall_hashref($statement, $key_field);
Implemented by DBI, no driver-specific impact.
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact.
$sth = $dbh->prepare($statement, \%attr);
PostgreSQL does not have the concept of preparing a statement. Hence the prepare method just stores the statement after checking for place-holders. No information about the statement is available after preparing it.
$sth = $dbh->prepare_cached($statement, \%attr);
Implemented by DBI, no driver-specific impact. This method is not useful for this driver, because preparing a statement has no database interaction.
$rv = $dbh->do($statement, \%attr, @bind_values);
Implemented by DBI, no driver-specific impact. See the notes for the execute method elsewhere in this document.
$rc = $dbh->commit;
Supported by the driver as proposed by DBI. See also the notes about Transactions elsewhere in this document.
$rc = $dbh->rollback;
Supported by the driver as proposed by DBI. See also the notes about Transactions elsewhere in this document.
$rc = $dbh->disconnect;
Supported by the driver as proposed by DBI.
$rc = $dbh->ping;
This driver supports the ping-method, which can be used to check the validity of a database-handle. The ping method issues an empty query and checks the result status.
$sth = $dbh->column_info( $catalog, $schema, $table, $column );
Supported by the driver as proposed by the DBI with the follow exceptions. These fields are currently always returned with NULL values:
TABLE_CAT BUFFER_LENGTH DECIMAL_DIGITS NUM_PREC_RADIX SQL_DATA_TYPE SQL_DATETIME_SUB CHAR_OCTET_LENGTH
Also, four additional non-standard fields are returned:
pg_type pg_type_only pg_attypmod pg_constraint - holds column constraint definition
$sth = $dbh->table_info( $catalog, $schema, $table, $type );
Supported by the driver as proposed by DBI. This method returns all tables and views visible to the current user. The $catalog argument is currently unused. The schema and table arguments will do a 'LIKE' search if a percent sign (%) or an underscore (_) are detected in the argument. The $type argument accepts a value of wither ``TABLE'' or ``VIEW'' (using both is the default action).
$sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table,
$fk_catalog, $fk_schema, $fk_table );
Supported by the driver as proposed by DBI. Unimplemented for Postgres servers before 7.3 (returns undef). Currently only returns information about first column of any multiple-column keys.
@names = $dbh->tables( $catalog, $schema, $table, $type );
Supported by the driver as proposed by DBI. This method returns all tables and views which are visible to the current user. If the database is version 7.3 or higher, the name of the schema appears before the table or view name.
$type_info_all = $dbh->type_info_all;
Supported by the driver as proposed by DBI. Only for SQL data-types and for frequently used data-types information is provided. The mapping between the PostgreSQL typename and the SQL92 data-type (if possible) has been done according to the following table:
+---------------+------------------------------------+ | typname | SQL92 | |---------------+------------------------------------| | bool | BOOL | | text | / | | bpchar | CHAR(n) | | varchar | VARCHAR(n) | | int2 | SMALLINT | | int4 | INT | | int8 | / | | money | / | | float4 | FLOAT(p) p<7=float4, p<16=float8 | | float8 | REAL | | abstime | / | | reltime | / | | tinterval | / | | date | / | | time | / | | datetime | / | | timespan | TINTERVAL | | timestamp | TIMESTAMP | +---------------+------------------------------------+
For further details concerning the PostgreSQL specific data-types please read the pgbuiltin.
@type_info = $dbh->type_info($data_type);
Implemented by DBI, no driver-specific impact.
$sql = $dbh->quote($value, $data_type);
This module implements its own quote method. In addition to the DBI method it also doubles the backslash, because PostgreSQL treats a backslash as an escape character.
NOTE: The undocumented (and invalid) support for the "SQL_BINARY" data type is officially deprecated. Use "PG_BYTEA" with "bind_param()" instead:
$rv = $sth->bind_param($param_num, $bind_value,
{ pg_type => DBD::Pg::PG_BYTEA });
escape quote with a quote (SQL) escape backslash with a backslash
The default is on. Note, that PostgreSQL also accepts quotes, which are escaped by a backslash. Any other ASCII character can be used directly in a string constant.
NB: This attribute is experimental and may be subject to change.
$rv = $sth->bind_param($param_num, $bind_value, \%attr);
Supported by the driver as proposed by DBI.
NOTE: The undocumented (and invalid) support for the "SQL_BINARY" SQL type is officially deprecated. Use "PG_BYTEA" instead:
$rv = $sth->bind_param($param_num, $bind_value,
{ pg_type => DBD::Pg::PG_BYTEA });
$rv = $sth->execute(@bind_values);
Supported by the driver as proposed by DBI. In addition to 'UPDATE', 'DELETE', 'INSERT' statements, for which it returns always the number of affected rows, the execute method can also be used for 'SELECT ... INTO table' statements.
$ary_ref = $sth->fetchrow_arrayref;
Supported by the driver as proposed by DBI.
@ary = $sth->fetchrow_array;
Supported by the driver as proposed by DBI.
$hash_ref = $sth->fetchrow_hashref;
Supported by the driver as proposed by DBI.
$tbl_ary_ref = $sth->fetchall_arrayref;
Implemented by DBI, no driver-specific impact.
$rc = $sth->finish;
Supported by the driver as proposed by DBI.
$rv = $sth->rows;
Supported by the driver as proposed by DBI. In contrast to many other drivers the number of rows is available immediately after executing the statement.
$rc = $sth->bind_col($column_number, \$var_to_bind, \%attr);
Supported by the driver as proposed by DBI.
$rc = $sth->bind_columns(\%attr, @list_of_refs_to_vars_to_bind);
Supported by the driver as proposed by DBI.
$rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
Implemented by DBI, no driver-specific impact.
$blob = $sth->blob_read($id, $offset, $len);
Supported by this driver as proposed by DBI. Implemented by DBI but not documented, so this method might change.
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 (data-type LONG), PostgreSQL handles its blobs independent of any table by using so called object identifiers. This explains why the blob_read method is blessed into the STATEMENT package and not part of the DATABASE package. Here the field parameter has been used to handle this object identifier. The offset and len parameter may be set to zero, in which case the driver fetches the whole blob at once.
Starting with PostgreSQL-6.5 every access to a blob has to be put into a transaction. This holds even for a read-only access.
See also the PostgreSQL-specific functions concerning blobs which are available via the func-interface.
For further information and examples about blobs, please read the chapter about Large Objects in the PostgreSQL Programmer's Guide.
According to the DBI specification the default for AutoCommit is TRUE. In this mode, any change to the database becomes valid immediately. Any 'begin', 'commit' or 'rollback' statement will be rejected.
If AutoCommit is switched-off, immediately a transaction will be started by issuing a 'begin' statement. Any 'commit' or 'rollback' will start a new transaction. A disconnect will issue a 'rollback' statement.
Boolean values can be passed to PostgreSQL as TRUE, 't', 'true', 'y', 'yes' or '1' for true and FALSE, 'f', 'false', 'n', 'no' or '0' for false.
Currently 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.
my $res = $dbh->selectall_arrayref("SELECT * FROM my_schema.my_table");
or by manipulating the schema search path with SET search_path, e.g.
$dbh->do("SET search_path TO my_schema, public");
DBD-Pg by Edmund Mergl (E.Mergl@bawue.de) and Jeffrey W. Baker (jwbaker@acm.org). By David Wheeler <david@wheeler.net>, Jason Stewart <jason@openinformatics.com> and Bruce Momjian <pgman@candle.pha.pa.us> and others after v1.13.
Major parts of this package have been copied from DBI and DBD-Oracle.
Mailing List
The current maintainers may be reached through the 'dbdpg-general' mailing list: http://gborg.postgresql.org/mailman/listinfo/dbdpg-general
This list is available through Gmane (http://www.gmane.org) as a newsgroup with the name: "gmane.comp.db.postgresql.dbdpg"