1Pg(3) User Contributed Perl Documentation Pg(3)
2
3
4
6 DBD::Pg - PostgreSQL database driver for the DBI module
7
9 use DBI;
10
11 $dbh = DBI->connect("dbi:Pg:dbname=$dbname", '', '', {AutoCommit => 0});
12 # The AutoCommit attribute should always be explicitly set
13
14 # For some advanced uses you may need PostgreSQL type values:
15 use DBD::Pg qw(:pg_types);
16
17 # For asynchronous calls, import the async constants:
18 use DBD::Pg qw(:async);
19
20 $dbh->do('INSERT INTO mytable(a) VALUES (1)');
21
22 $sth = $dbh->prepare('INSERT INTO mytable(a) VALUES (?)');
23 $sth->execute();
24
26 This documents version 2.19.3 of the DBD::Pg module
27
29 DBD::Pg is a Perl module that works with the DBI module to provide
30 access to PostgreSQL databases.
31
33 This documentation describes driver specific behavior and restrictions.
34 It is not supposed to be used as the only reference for the user. In
35 any case consult the DBI documentation first!
36
38 DBI Class Methods
39 connect
40
41 This method creates a database handle by connecting to a database, and
42 is the DBI equivalent of the "new" method. To connect to a Postgres
43 database with a minimum of parameters, use the following syntax:
44
45 $dbh = DBI->connect("dbi:Pg:dbname=$dbname", '', '', {AutoCommit => 0});
46
47 This connects to the database named in the $dbname variable on the
48 default port (usually 5432) without any user authentication.
49
50 The following connect statement shows almost all possible parameters:
51
52 $dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;options=$options",
53 $username,
54 $password,
55 {AutoCommit => 0, RaiseError => 1, PrintError => 0}
56 );
57
58 If a parameter is not given, the connect() method will first look for
59 specific environment variables, and then fall back to hard-coded
60 defaults:
61
62 parameter environment variable hard coded default
63 ------------------------------------------------------
64 host PGHOST local domain socket
65 hostaddr PGHOSTADDR local domain socket
66 port PGPORT 5432
67 dbname* PGDATABASE current userid
68 username PGUSER current userid
69 password PGPASSWORD (none)
70 options PGOPTIONS (none)
71 service PGSERVICE (none)
72 sslmode PGSSLMODE (none)
73
74 * May also use the aliases "db" or "database"
75
76 If the username and password values passed via "connect()" are
77 undefined (as opposed to merely being empty strings), DBI will use the
78 environment variables DBI_USER and DBI_PASS if they exist.
79
80 You can also connect by using a service connection file, which is named
81 pg_service.conf. The location of this file can be controlled by setting
82 the PGSYSCONFDIR environment variable. To use one of the named services
83 within the file, set the name by using either the service parameter or
84 the environment variable PGSERVICE. Note that when connecting this way,
85 only the minimum parameters should be used. For example, to connect to
86 a service named "zephyr", you could use:
87
88 $dbh = DBI->connect("dbi:Pg:service=zephyr", '', '');
89
90 You could also set $ENV{PGSERVICE} to "zephyr" and connect like this:
91
92 $dbh = DBI->connect("dbi:Pg:", '', '');
93
94 The format of the pg_service.conf file is simply a bracketed service
95 name, followed by one parameter per line in the format name=value. For
96 example:
97
98 [zephyr]
99 dbname=winds
100 user=wisp
101 password=W$2Hc00YSgP
102 port=6543
103
104 There are four valid arguments to the sslmode parameter, which controls
105 whether to use SSL to connect to the database:
106
107 · disable: SSL connections are never used
108
109 · allow: try non-SSL, then SSL
110
111 · prefer: try SSL, then non-SSL
112
113 · require: connect only with SSL
114
115 You can also connect using sockets in a specific directory. This may be
116 needed if the server you are connecting to has a different default
117 socket directory from the one used to compile DBD::Pg. Use the
118 complete path to the socket directory as the name of the host, like
119 this:
120
121 $dbh = DBI->connect('dbi:Pg:dbname=foo;host=/var/tmp/socket',
122 $username,
123 $password,
124 {AutoCommit => 0, RaiseError => 1});
125
126 The attribute hash can also contain a key named "dbd_verbose", which
127 simply calls "$dbh->trace('DBD')" after the handle is created. This
128 attribute is not recommended, as it is clearer to simply explicitly
129 call "trace" explicitly in your script.
130
131 connect_cached
132
133 $dbh = DBI->connect_cached("dbi:Pg:dbname=$dbname", $username, $password, \%options);
134
135 Implemented by DBI, no driver-specific impact.
136
137 data_sources
138
139 @data_sources = DBI->data_sources('Pg');
140 @data_sources = $dbh->data_sources();
141
142 Returns a list of available databases. Unless the environment variable
143 "DBI_DSN" is set, a connection will be attempted to the database
144 "template1". The normal connection environment variables also apply,
145 such as "PGHOST", "PGPORT", "DBI_USER", "DBI_PASS", and "PGSERVICE".
146
147 You can also pass in options to add to the connection string For
148 example, to specify an alternate port and host:
149
150 @data_sources = DBI->data_sources('Pg', 'port=5824;host=example.com');
151
152 or:
153
154 @data_sources = $dbh->data_sources('port=5824;host=example.com');
155
156 Methods Common To All Handles
157 For all of the methods below, $h can be either a database handle ($dbh)
158 or a statement handle ($sth). Note that $dbh and $sth can be replaced
159 with any variable name you choose: these are just the names most often
160 used. Another common variable used in this documentation is $rv, which
161 stands for "return value".
162
163 err
164
165 $rv = $h->err;
166
167 Returns the error code from the last method called. For the connect
168 method it returns "PQstatus", which is a number used by libpq (the
169 Postgres connection library). A value of 0 indicates no error
170 (CONNECTION_OK), while any other number indicates a failed connection.
171 The only other number commonly seen is 1 (CONNECTION_BAD). See the
172 libpq documentation for the complete list of return codes.
173
174 In all other non-connect methods "$h->err" returns the "PQresultStatus"
175 of the current handle. This is a number used by libpq and is one of:
176
177 0 Empty query string
178 1 A command that returns no data successfully completed.
179 2 A command that returns data sucessfully completed.
180 3 A COPY OUT command is still in progress.
181 4 A COPY IN command is still in progress.
182 5 A bad response was received from the backend.
183 6 A nonfatal error occurred (a notice or warning message)
184 7 A fatal error was returned: the last query failed.
185
186 errstr
187
188 $str = $h->errstr;
189
190 Returns the last error that was reported by Postgres. This message is
191 affected by the "pg_errorlevel" setting.
192
193 state
194
195 $str = $h->state;
196
197 Returns a five-character "SQLSTATE" code. Success is indicated by a
198 00000 code, which gets mapped to an empty string by DBI. A code of
199 "S8006" indicates a connection failure, usually because the connection
200 to the Postgres server has been lost.
201
202 While this method can be called as either "$sth->state" or
203 "$dbh->state", it is usually clearer to always use "$dbh->state".
204
205 The list of codes used by PostgreSQL can be found at:
206 <http://www.postgresql.org/docs/current/static/errcodes-appendix.html>
207
208 Note that these codes are part of the SQL standard and only a small
209 number of them will be used by PostgreSQL.
210
211 Common codes:
212
213 00000 Successful completion
214 25P01 No active SQL transaction
215 25P02 In failed SQL transaction
216 S8006 Connection failure
217
218 trace
219
220 $h->trace($trace_settings);
221 $h->trace($trace_settings, $trace_filename);
222 $trace_settings = $h->trace;
223
224 Changes the trace settings on a database or statement handle. The
225 optional second argument specifies a file to write the trace
226 information to. If no filename is given, the information is written to
227 STDERR. Note that tracing can be set globally as well by setting
228 "DBI->trace", or by using the environment variable DBI_TRACE.
229
230 The value is either a numeric level or a named flag. For the flags that
231 DBD::Pg uses, see parse_trace_flag.
232
233 trace_msg
234
235 $h->trace_msg($message_text);
236 $h->trace_msg($message_text, $min_level);
237
238 Writes a message to the current trace output (as set by the "trace"
239 method). If a second argument is given, the message is only written if
240 the current tracing level is equal to or greater than the $min_level.
241
242 parse_trace_flag and parse_trace_flags
243
244 $h->trace($h->parse_trace_flags('SQL|pglibpq'));
245 $h->trace($h->parse_trace_flags('1|pgstart'));
246
247 ## Simpler:
248 $h->trace('SQL|pglibpq');
249 $h->trace('1|pgstart');
250
251 my $value = DBD::Pg->parse_trace_flag('pglibpq');
252 DBI->trace($value);
253
254 The parse_trace_flags method is used to convert one or more named flags
255 to a number which can passed to the "trace" method. DBD::Pg currently
256 supports the DBI-specific flag, "SQL", as well as the ones listed
257 below.
258
259 Flags can be combined by using the parse_trace_flags method, which
260 simply calls "parse_trace_flag" on each item and combines them.
261
262 Sometimes you may wish to turn the tracing on before you connect to the
263 database. The second example above shows a way of doing this: the call
264 to "DBD::Pg->parse_trace_flags" provides a number than can be fed to
265 "DBI->trace" before you create a database handle.
266
267 DBD::Pg supports the following trace flags:
268
269 SQL Outputs all SQL statements. Note that the output provided will not
270 necessarily be in a form suitable to passing directly to Postgres,
271 as server-side prepared statements are used extensively by DBD::Pg.
272 For maximum portability of output (but with a potential performance
273 hit), use with "$dbh->{pg_server_prepare} = 0".
274
275 DBD Turns on all non-DBI flags, in other words, only the ones that are
276 specific to DBD::Pg (all those below which start with the letters
277 'pg').
278
279 pglibpq
280 Outputs the name of each libpq function (without arguments)
281 immediately before running it. This is a good way to trace the flow
282 of your program at a low level. This information is also output if
283 the trace level is set to 4 or greater.
284
285 pgstart
286 Outputs the name of each internal DBD::Pg function, and other
287 information such as the function arguments or important global
288 variables, as each function starts. This information is also output
289 if the trace level is set to 4 or greater.
290
291 pgend
292 Outputs a simple message at the very end of each internal DBD::Pg
293 function. This is also output if the trace level is set to 4 or
294 greater.
295
296 pgprefix
297 Forces each line of trace output to begin with the string "dbdpg:
298 ". This helps to differentiate it from the normal DBI trace output.
299
300 pglogin
301 Outputs a message showing the connection string right before a new
302 database connection is attempted, a message when the connection was
303 successful, and a message right after the database has been
304 disconnected. Also output if trace level is 5 or greater.
305
306 func
307
308 DBD::Pg uses the "func" method to support a variety of functions. Note
309 that the name of the function comes last, after the arguments.
310
311 table_attributes
312 $attrs = $dbh->func($table, 'table_attributes');
313
314 Use of the tables_attributes function is no longer recommended.
315 Instead, you can use the more portable "column_info" and
316 "primary_key" methods to access the same information.
317
318 The table_attributes method returns, for the given table argument,
319 a reference to an array of hashes, each of which contains the
320 following keys:
321
322 NAME attribute name
323 TYPE attribute type
324 SIZE attribute size (-1 for variable size)
325 NULLABLE flag nullable
326 DEFAULT default value
327 CONSTRAINT constraint
328 PRIMARY_KEY flag is_primary_key
329 REMARKS attribute description
330
331 pg_lo_creat
332 $lobjId = $dbh->pg_lo_creat($mode);
333
334 Creates a new large object and returns the object-id. $mode is a
335 bitmask describing read and write access to the new object. This
336 setting is ignored since Postgres version 8.1. For backwards
337 compatibility, however, you should set a valid mode anyway (see
338 "pg_lo_open" for a list of valid modes).
339
340 Upon failure it returns "undef". This function cannot be used if
341 AutoCommit is enabled.
342
343 The old way of calling large objects functions is deprecated:
344 $dbh->func(.., 'lo_);
345
346 lo_open
347 $lobj_fd = $dbh->pg_lo_open($lobjId, $mode);
348
349 Opens an existing large object and returns an object-descriptor for
350 use in subsequent "lo_*" calls. $mode is a bitmask describing read
351 and write access to the opened object. It may be one of:
352
353 $dbh->{pg_INV_READ}
354 $dbh->{pg_INV_WRITE}
355 $dbh->{pg_INV_READ} | $dbh->{pg_INV_WRITE}
356
357 "pg_INV_WRITE" and "pg_INV_WRITE | pg_INV_READ" modes are
358 identical; in both modes, the large object can be read from or
359 written to. Reading from the object will provide the object as
360 written in other committed transactions, along with any writes
361 performed by the current transaction. Objects opened with
362 "pg_INV_READ" cannot be written to. Reading from this object will
363 provide the stored data at the time of the transaction snapshot
364 which was active when "lo_write" was called.
365
366 Returns "undef" upon failure. Note that 0 is a perfectly correct
367 (and common) object descriptor! This function cannot be used if
368 AutoCommit is enabled.
369
370 lo_write
371 $nbytes = $dbh->pg_lo_write($lobj_fd, $buffer, $len);
372
373 Writes $len bytes of c<$buffer> into the large object $lobj_fd.
374 Returns the number of bytes written and "undef" upon failure. This
375 function cannot be used if AutoCommit is enabled.
376
377 lo_read
378 $nbytes = $dbh->pg_lo_read($lobj_fd, $buffer, $len);
379
380 Reads $len bytes into c<$buffer> from large object $lobj_fd.
381 Returns the number of bytes read and "undef" upon failure. This
382 function cannot be used if AutoCommit is enabled.
383
384 lo_lseek
385 $loc = $dbh->pg_lo_lseek($lobj_fd, $offset, $whence);
386
387 Changes the current read or write location on the large object
388 $obj_id. Currently $whence can only be 0 (which is L_SET). Returns
389 the current location and "undef" upon failure. This function cannot
390 be used if AutoCommit is enabled.
391
392 lo_tell
393 $loc = $dbh->pg_lo_tell($lobj_fd);
394
395 Returns the current read or write location on the large object
396 $lobj_fd and "undef" upon failure. This function cannot be used if
397 AutoCommit is enabled.
398
399 lo_close
400 $lobj_fd = $dbh->pg_lo_close($lobj_fd);
401
402 Closes an existing large object. Returns true upon success and
403 false upon failure. This function cannot be used if AutoCommit is
404 enabled.
405
406 lo_unlink
407 $ret = $dbh->pg_lo_unlink($lobjId);
408
409 Deletes an existing large object. Returns true upon success and
410 false upon failure. This function cannot be used if AutoCommit is
411 enabled.
412
413 lo_import
414 $lobjId = $dbh->pg_lo_import($filename);
415
416 Imports a Unix file as a large object and returns the object id of
417 the new object or "undef" upon failure.
418
419 lo_import_with_oid
420 $lobjId = $dbh->pg_lo_import($filename, $OID);
421
422 Same as lo_import, but attempts to use the supplied OID as the
423 large object number. If this number is 0, it falls back to the
424 behavior of lo_import (which assigns the next available OID).
425
426 This is only available when DBD::Pg is compiled against a Postgres
427 server version 8.4 or later.
428
429 lo_export
430 $ret = $dbh->pg_lo_export($lobjId, $filename);
431
432 Exports a large object into a Unix file. Returns false upon
433 failure, true otherwise.
434
435 getfd
436 $fd = $dbh->func('getfd');
437
438 Deprecated, use $dbh->{pg_socket} instead.
439
440 private_attribute_info
441
442 $hashref = $dbh->private_attribute_info();
443 $hashref = $sth->private_attribute_info();
444
445 Returns a hash of all private attributes used by DBD::Pg, for either a
446 database or a statement handle. Currently, all the hash values are
447 undef.
448
450 InactiveDestroy (boolean)
451
452 If set to true, then the "disconnect" method will not be automatically
453 called when the database handle goes out of scope. This is required if
454 you are forking, and even then you must tread carefully and ensure that
455 either the parent or the child (but not both!) handles all database
456 calls from that point forwards, so that messages from the Postgres
457 backend are only handled by one of the processes. If you don't set
458 things up properly, you will see messages such as "server closed the
459 connection unexpectedly", and "message type 0x32 arrived from server
460 while idle". The best solution is to either have the child process
461 reconnect to the database with a fresh database handle, or to rewrite
462 your application not to use use forking. See the section on
463 "Asynchronous Queries" for a way to have your script continue to work
464 while the database is processing a request.
465
466 RaiseError (boolean, inherited)
467
468 Forces errors to always raise an exception. Although it defaults to
469 off, it is recommended that this be turned on, as the alternative is to
470 check the return value of every method (prepare, execute, fetch, etc.)
471 manually, which is easy to forget to do.
472
473 PrintError (boolean, inherited)
474
475 Forces database errors to also generate warnings, which can then be
476 filtered with methods such as locally redefining $SIG{__WARN__} or
477 using modules such as "CGI::Carp". This attribute is on by default.
478
479 ShowErrorStatement (boolean, inherited)
480
481 Appends information about the current statement to error messages. If
482 placeholder information is available, adds that as well. Defaults to
483 false.
484
485 Warn (boolean, inherited)
486
487 Enables warnings. This is on by default, and should only be turned off
488 in a local block for a short a time only when absolutely needed.
489
490 Executed (boolean, read-only)
491
492 Indicates if a handle has been executed. For database handles, this
493 value is true after the "do" method has been called, or when one of the
494 child statement handles has issued an "execute". Issuing a "commit" or
495 "rollback" always resets the attribute to false for database handles.
496 For statement handles, any call to "execute" or its variants will flip
497 the value to true for the lifetime of the statement handle.
498
499 TraceLevel (integer, inherited)
500
501 Sets the trace level, similar to the "trace" method. See the sections
502 on "trace" and "parse_trace_flag" for more details.
503
504 Active (boolean, read-only)
505
506 Indicates if a handle is active or not. For database handles, this
507 indicates if the database has been disconnected or not. For statement
508 handles, it indicates if all the data has been fetched yet or not. Use
509 of this attribute is not encouraged.
510
511 Kids (integer, read-only)
512
513 Returns the number of child processes created for each handle type. For
514 a driver handle, indicates the number of database handles created. For
515 a database handle, indicates the number of statement handles created.
516 For statement handles, it always returns zero, because statement
517 handles do not create kids.
518
519 ActiveKids (integer, read-only)
520
521 Same as "Kids", but only returns those that are active.
522
523 CachedKids (hash ref)
524
525 Returns a hashref of handles. If called on a database handle, returns
526 all statement handles created by use of the "prepare_cached" method. If
527 called on a driver handle, returns all database handles created by the
528 "connect_cached" method.
529
530 ChildHandles (array ref)
531
532 Implemented by DBI, no driver-specific impact.
533
534 PrintWarn (boolean, inherited)
535
536 Implemented by DBI, no driver-specific impact.
537
538 HandleError (boolean, inherited)
539
540 Implemented by DBI, no driver-specific impact.
541
542 HandleSetErr (code ref, inherited)
543
544 Implemented by DBI, no driver-specific impact.
545
546 ErrCount (unsigned integer)
547
548 Implemented by DBI, no driver-specific impact.
549
550 FetchHashKeyName (string, inherited)
551
552 Implemented by DBI, no driver-specific impact.
553
554 ChopBlanks (boolean, inherited)
555
556 Supported by DBD::Pg as proposed by DBI. This method is similar to the
557 SQL function "RTRIM".
558
559 Taint (boolean, inherited)
560
561 Implemented by DBI, no driver-specific impact.
562
563 TaintIn (boolean, inherited)
564
565 Implemented by DBI, no driver-specific impact.
566
567 TaintOut (boolean, inherited)
568
569 Implemented by DBI, no driver-specific impact.
570
571 Profile (inherited)
572
573 Implemented by DBI, no driver-specific impact.
574
575 Type (scalar)
576
577 Returns "dr" for a driver handle, "db" for a database handle, and "st"
578 for a statement handle. Should be rarely needed.
579
580 LongReadLen
581
582 Not used by DBD::Pg
583
584 LongTruncOk
585
586 Not used by DBD::Pg
587
588 CompatMode
589
590 Not used by DBD::Pg
591
593 Database Handle Methods
594 selectall_arrayref
595
596 $ary_ref = $dbh->selectall_arrayref($sql);
597 $ary_ref = $dbh->selectall_arrayref($sql, \%attr);
598 $ary_ref = $dbh->selectall_arrayref($sql, \%attr, @bind_values);
599
600 Returns a reference to an array containing the rows returned by
601 preparing and executing the SQL string. See the DBI documentation for
602 full details.
603
604 selectall_hashref
605
606 $hash_ref = $dbh->selectall_hashref($sql, $key_field);
607
608 Returns a reference to a hash containing the rows returned by preparing
609 and executing the SQL string. See the DBI documentation for full
610 details.
611
612 selectcol_arrayref
613
614 $ary_ref = $dbh->selectcol_arrayref($sql, \%attr, @bind_values);
615
616 Returns a reference to an array containing the first column from each
617 rows returned by preparing and executing the SQL string. It is possible
618 to specify exactly which columns to return. See the DBI documentation
619 for full details.
620
621 prepare
622
623 $sth = $dbh->prepare($statement, \%attr);
624
625 WARNING: DBD::Pg now (as of version 1.40) uses true prepared statements
626 by sending them to the backend to be prepared by the Postgres server.
627 Statements that were legal before may no longer work. See below for
628 details.
629
630 The prepare method prepares a statement for later execution. PostgreSQL
631 supports prepared statements, which enables DBD::Pg to only send the
632 query once, and simply send the arguments for every subsequent call to
633 "execute". DBD::Pg can use these server-side prepared statements, or
634 it can just send the entire query to the server each time. The best way
635 is automatically chosen for each query. This will be sufficient for
636 most users: keep reading for a more detailed explanation and some
637 optional flags.
638
639 Queries that do not begin with the word "SELECT", "INSERT", "UPDATE",
640 or "DELETE" are never sent as server-side prepared statements.
641
642 Deciding whether or not to use prepared statements depends on many
643 factors, but you can force them to be used or not used by using the
644 "pg_server_prepare" attribute when calling "prepare". Setting this to
645 "0" means to never use prepared statements. Setting "pg_server_prepare"
646 to "1" means that prepared statements should be used whenever possible.
647 This is the default when connected to Postgres servers version 8.0 or
648 higher. Servers that are version 7.4 get a special default value of
649 "2", because server-side statements were only partially supported in
650 that version. In this case, it only uses server-side prepares if all
651 parameters are specifically bound.
652
653 The "pg_server_prepare" attribute can also be set at connection time
654 like so:
655
656 $dbh = DBI->connect($DBNAME, $DBUSER, $DBPASS,
657 { AutoCommit => 0,
658 RaiseError => 1,
659 pg_server_prepare => 0,
660 });
661
662 or you may set it after your database handle is created:
663
664 $dbh->{pg_server_prepare} = 1;
665
666 To enable it for just one particular statement:
667
668 $sth = $dbh->prepare("SELECT id FROM mytable WHERE val = ?",
669 { pg_server_prepare => 1 });
670
671 You can even toggle between the two as you go:
672
673 $sth->{pg_server_prepare} = 1;
674 $sth->execute(22);
675 $sth->{pg_server_prepare} = 0;
676 $sth->execute(44);
677 $sth->{pg_server_prepare} = 1;
678 $sth->execute(66);
679
680 In the above example, the first execute will use the previously
681 prepared statement. The second execute will not, but will build the
682 query into a single string and send it to the server. The third one
683 will act like the first and only send the arguments. Even if you
684 toggle back and forth, a statement is only prepared once.
685
686 Using prepared statements is in theory quite a bit faster: not only
687 does the PostgreSQL backend only have to prepare the query only once,
688 but DBD::Pg no longer has to worry about quoting each value before
689 sending it to the server.
690
691 However, there are some drawbacks. The server cannot always choose the
692 ideal parse plan because it will not know the arguments before hand.
693 But for most situations in which you will be executing similar data
694 many times, the default plan will probably work out well. Programs such
695 as PgBouncer which cache connections at a low level should not use
696 prepared statements via DBD::Pg, or must take extra care in the
697 application to account for the fact that prepared statements are not
698 shared across database connections. Further discussion on this subject
699 is beyond the scope of this documentation: please consult the pgsql-
700 performance mailing list,
701 <http://archives.postgresql.org/pgsql-performance/>
702
703 Only certain commands will be sent to a server-side prepare: currently
704 these include "SELECT", "INSERT", "UPDATE", and "DELETE". DBD::Pg uses
705 a simple naming scheme for the prepared statements themselves:
706 dbdpg_XY_Z, where Y is the current PID, X is either 'p' or 'n'
707 (depending on if the PID is a positive or negative number), and Z is a
708 number that starts at 1 and increases each time a new statement is
709 prepared. This number is tracked at the database handle level, so
710 multiple statement handles will not collide.
711
712 You cannot send more than one command at a time in the same prepare
713 command (by separating them with semi-colons) when using server-side
714 prepares.
715
716 The actual "PREPARE" is usually not performed until the first execute
717 is called, due to the fact that information on the data types (provided
718 by "bind_param") may be provided after the prepare but before the
719 execute.
720
721 A server-side prepare may happen before the first "execute", but only
722 if the server can handle the server-side prepare, and the statement
723 contains no placeholders. It will also be prepared if the
724 "pg_prepare_now" attribute is passed in and set to a true value.
725 Similarly, the "pg_prepare_now" attribute can be set to 0 to ensure
726 that the statement is not prepared immediately, although the cases in
727 which you would want this are very rare. Finally, you can set the
728 default behavior of all prepare statements by setting the
729 "pg_prepare_now" attribute on the database handle:
730
731 $dbh->{pg_prepare_now} = 1;
732
733 The following two examples will be prepared right away:
734
735 $sth->prepare("SELECT 123"); ## no placeholders
736
737 $sth->prepare("SELECT 123, ?", {pg_prepare_now => 1});
738
739 The following two examples will NOT be prepared right away:
740
741 $sth->prepare("SELECT 123, ?"); ## has a placeholder
742
743 $sth->prepare("SELECT 123", {pg_prepare_now => 0});
744
745 There are times when you may want to prepare a statement yourself. To
746 do this, simply send the "PREPARE" statement directly to the server
747 (e.g. with the "do" method). Create a statement handle and set the
748 prepared name via the "pg_prepare_name" attribute. The statement handle
749 can be created with a dummy statement, as it will not be executed.
750 However, it should have the same number of placeholders as your
751 prepared statement. Example:
752
753 $dbh->do('PREPARE mystat AS SELECT COUNT(*) FROM pg_class WHERE reltuples < ?');
754 $sth = $dbh->prepare('SELECT ?');
755 $sth->bind_param(1, 1, SQL_INTEGER);
756 $sth->{pg_prepare_name} = 'mystat';
757 $sth->execute(123);
758
759 The above will run the equivalent of this query on the backend:
760
761 EXECUTE mystat(123);
762
763 which is the equivalent of:
764
765 SELECT COUNT(*) FROM pg_class WHERE reltuples < 123;
766
767 You can force DBD::Pg to send your query directly to the server by
768 adding the "pg_direct" attribute to your prepare call. This is not
769 recommended, but is added just in case you need it.
770
771 Placeholders
772
773 There are three types of placeholders that can be used in DBD::Pg. The
774 first is the "question mark" type, in which each placeholder is
775 represented by a single question mark character. This is the method
776 recommended by the DBI specs and is the most portable. Each question
777 mark is internally replaced by a "dollar sign number" in the order in
778 which they appear in the query (important when using "bind_param").
779
780 The method second type of placeholder is "dollar sign numbers". This is
781 the method that Postgres uses internally and is overall probably the
782 best method to use if you do not need compatibility with other database
783 systems. DBD::Pg, like PostgreSQL, allows the same number to be used
784 more than once in the query. Numbers must start with "1" and increment
785 by one value (but can appear in any order within the query). If the
786 same number appears more than once in a query, it is treated as a
787 single parameter and all instances are replaced at once. Examples:
788
789 Not legal:
790
791 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages > $2'; # Does not start with 1
792
793 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $3'; # Missing 2
794
795 Legal:
796
797 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages > $1';
798
799 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $2';
800
801 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages BETWEEN $2 AND $1'; # legal but confusing
802
803 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages BETWEEN $1 AND $2 AND reltuples > $1';
804
805 $SQL = 'SELECT count(*) FROM pg_class WHERE relpages > $1 AND reltuples > $1';
806
807 In the final statement above, DBI thinks there is only one placeholder,
808 so this statement will replace both placeholders:
809
810 $sth->bind_param(1, 2045);
811
812 While a simple execute with no bind_param calls requires only a single
813 argument as well:
814
815 $sth->execute(2045);
816
817 The final placeholder type is "named parameters" in the format ":foo".
818 While this syntax is supported by DBD::Pg, its use is discouraged in
819 favor of dollar-sign numbers.
820
821 The different types of placeholders cannot be mixed within a statement,
822 but you may use different ones for each statement handle you have. This
823 is confusing at best, so stick to one style within your program.
824
825 If your queries use operators that contain question marks (e.g. some of
826 the native Postgres geometric operators) or array slices (e.g.
827 "data[100:300]"), you can tell DBD::Pg to ignore any non-dollar sign
828 placeholders by setting the "pg_placeholder_dollaronly" attribute at
829 either the database handle or the statement handle level. Examples:
830
831 $dbh->{pg_placeholder_dollaronly} = 1;
832 $sth = $dbh->prepare(q{SELECT * FROM mytable WHERE lseg1 ?# lseg2 AND name = $1});
833 $sth->execute('segname');
834
835 Alternatively, you can set it at prepare time:
836
837 $sth = $dbh->prepare(q{SELECT * FROM mytable WHERE lseg1 ?-| lseg2 AND name = $1},
838 {pg_placeholder_dollaronly = 1});
839 $sth->execute('segname');
840
841 prepare_cached
842
843 $sth = $dbh->prepare_cached($statement, \%attr);
844
845 Implemented by DBI, no driver-specific impact. This method is most
846 useful when using a server that supports server-side prepares, and you
847 have asked the prepare to happen immediately via the "pg_prepare_now"
848 attribute.
849
850 do
851
852 $rv = $dbh->do($statement);
853 $rv = $dbh->do($statement, \%attr);
854 $rv = $dbh->do($statement, \%attr, @bind_values);
855
856 Prepare and execute a single statement. Returns the number of rows
857 affected if the query was successful, returns undef if an error
858 occurred, and returns -1 if the number of rows is unknown or not
859 available. Note that this method will return 0E0 instead of 0 for 'no
860 rows were affected', in order to always return a true value if no error
861 occurred.
862
863 If neither "\%attr" nor @bind_values is given, the query will be sent
864 directly to the server without the overhead of internally creating a
865 statement handle and running prepare and execute, for a measurable
866 speed increase.
867
868 Note that an empty statement (a string with no length) will not be
869 passed to the server; if you want a simple test, use "SELECT 123" or
870 the "ping" method.
871
872 last_insert_id
873
874 $rv = $dbh->last_insert_id(undef, $schema, $table, undef);
875 $rv = $dbh->last_insert_id(undef, $schema, $table, undef, {sequence => $seqname});
876
877 Attempts to return the id of the last value to be inserted into a
878 table. You can either provide a sequence name (preferred) or provide a
879 table name with optional schema, and DBD::Pg will attempt to find the
880 sequence itself. The current value of the sequence is returned by a
881 call to the "CURRVAL()" PostgreSQL function. This will fail if the
882 sequence has not yet been used in the current database connection.
883
884 If you do not know the name of the sequence, you can provide a table
885 name and DBD::Pg will attempt to return the correct value. To do this,
886 there must be at least one column in the table with a "NOT NULL"
887 constraint, that has a unique constraint, and which uses a sequence as
888 a default value. If more than one column meets these conditions, the
889 primary key will be used. This involves some looking up of things in
890 the system table, so DBD::Pg will cache the sequence name for
891 subsequent calls. If you need to disable this caching for some reason,
892 (such as the sequence name changing), you can control it by adding
893 "pg_cache => 0" to the final (hashref) argument for last_insert_id.
894
895 Please keep in mind that this method is far from foolproof, so make
896 your script use it properly. Specifically, make sure that it is called
897 immediately after the insert, and that the insert does not add a value
898 to the column that is using the sequence as a default value. However,
899 because we are using sequences, you can be sure that the value you got
900 back has not been used by any other process.
901
902 Some examples:
903
904 $dbh->do('CREATE SEQUENCE lii_seq START 1');
905 $dbh->do(q{CREATE TABLE lii (
906 foobar INTEGER NOT NULL UNIQUE DEFAULT nextval('lii_seq'),
907 baz VARCHAR)});
908 $SQL = 'INSERT INTO lii(baz) VALUES (?)';
909 $sth = $dbh->prepare($SQL);
910 for (qw(uno dos tres cuatro)) {
911 $sth->execute($_);
912 my $newid = $dbh->last_insert_id(undef,undef,undef,undef,{sequence=>'lii_seq'});
913 print "Last insert id was $newid\n";
914 }
915
916 If you did not want to worry about the sequence name:
917
918 $dbh->do('CREATE TABLE lii2 (
919 foobar SERIAL UNIQUE,
920 baz VARCHAR)');
921 $SQL = 'INSERT INTO lii2(baz) VALUES (?)';
922 $sth = $dbh->prepare($SQL);
923 for (qw(uno dos tres cuatro)) {
924 $sth->execute($_);
925 my $newid = $dbh->last_insert_id(undef,undef,"lii2",undef);
926 print "Last insert id was $newid\n";
927 }
928
929 commit
930
931 $rv = $dbh->commit;
932
933 Issues a COMMIT to the server, indicating that the current transaction
934 is finished and that all changes made will be visible to other
935 processes. If AutoCommit is enabled, then a warning is given and no
936 COMMIT is issued. Returns true on success, false on error. See also
937 the the section on "Transactions".
938
939 rollback
940
941 $rv = $dbh->rollback;
942
943 Issues a ROLLBACK to the server, which discards any changes made in the
944 current transaction. If AutoCommit is enabled, then a warning is given
945 and no ROLLBACK is issued. Returns true on success, and false on error.
946 See also the the section on "Transactions".
947
948 begin_work
949
950 This method turns on transactions until the next call to "commit" or
951 "rollback", if "AutoCommit" is currently enabled. If it is not enabled,
952 calling begin_work will issue an error. Note that the transaction will
953 not actually begin until the first statement after begin_work is
954 called. Example:
955
956 $dbh->{AutoCommit} = 1;
957 $dbh->do('INSERT INTO foo VALUES (123)'); ## Changes committed immediately
958 $dbh->begin_work();
959 ## Not in a transaction yet, but AutoCommit is set to 0
960
961 $dbh->do("INSERT INTO foo VALUES (345)");
962 ## DBD::PG actually issues two statements here:
963 ## BEGIN;
964 ## INSERT INTO foo VALUES (345)
965 ## We are now in a transaction
966
967 $dbh->commit();
968 ## AutoCommit is now set to 1 again
969
970 disconnect
971
972 $rv = $dbh->disconnect;
973
974 Disconnects from the Postgres database. Any uncommitted changes will be
975 rolled back upon disconnection. It's good policy to always explicitly
976 call commit or rollback at some point before disconnecting, rather than
977 relying on the default rollback behavior.
978
979 This method may give warnings about "disconnect invalidates X active
980 statement handle(s)". This means that you called "$sth->execute()" but
981 did not finish fetching all the rows from them. To avoid seeing this
982 warning, either fetch all the rows or call "$sth->finish()" for each
983 executed statement handle.
984
985 If the script exits before disconnect is called (or, more precisely, if
986 the database handle is no longer referenced by anything), then the
987 database handle's DESTROY method will call the rollback() and
988 disconnect() methods automatically. It is best to explicitly disconnect
989 rather than rely on this behavior.
990
991 quote
992
993 $rv = $dbh->quote($value, $data_type);
994
995 This module implements its own "quote" method. For simple string types,
996 both backslashes and single quotes are doubled. You may also quote
997 arrayrefs and receive a string suitable for passing into Postgres array
998 columns.
999
1000 If the value contains backslashes, and the server is version 8.1 or
1001 higher, then the escaped string syntax will be used (which places a
1002 capital E before the first single quote). This syntax is always used
1003 when quoting bytea values on servers 8.1 and higher.
1004
1005 The "data_type" argument is optional and should be one of the type
1006 constants exported by DBD::Pg (such as PG_BYTEA). In addition to
1007 string, bytea, char, bool, and other standard types, the following
1008 geometric types are supported: point, line, lseg, box, path, polygon,
1009 and circle (PG_POINT, PG_LINE, PG_LSEG, PG_BOX, PG_PATH, PG_POLYGON,
1010 and PG_CIRCLE respectively). To quote a Postgres-specific data type,
1011 you must use a 'hashref' argument like so:
1012
1013 my $quotedval = $dbh->quote($value, { pg_type => PG_VARCHAR });
1014
1015 NOTE: The undocumented (and invalid) support for the "SQL_BINARY" data
1016 type is officially deprecated. Use "PG_BYTEA" with "bind_param()"
1017 instead:
1018
1019 $rv = $sth->bind_param($param_num, $bind_value,
1020 { pg_type => PG_BYTEA });
1021
1022 quote_identifier
1023
1024 $string = $dbh->quote_identifier( $name );
1025 $string = $dbh->quote_identifier( undef, $schema, $table);
1026
1027 Returns a quoted version of the supplied string, which is commonly a
1028 schema, table, or column name. The three argument form will return the
1029 schema and the table together, separated by a dot. Examples:
1030
1031 print $dbh->quote_identifier('grapefruit'); ## Prints: "grapefruit"
1032
1033 print $dbh->quote_identifier('juicy fruit'); ## Prints: "juicy fruit"
1034
1035 print $dbh->quote_identifier(undef, 'public', 'pg_proc');
1036 ## Prints: "public"."pg_proc"
1037
1038 pg_notifies
1039
1040 $ret = $dbh->pg_notifies;
1041
1042 Looks for any asynchronous notifications received and returns either
1043 "undef" or a reference to a three-element array consisting of an event
1044 name, the PID of the backend that sent the NOTIFY command, and the
1045 optional payload string. Note that this does not check if the
1046 connection to the database is still valid first - for that, use the
1047 c<ping> method. You may need to commit if not in autocommit mode - new
1048 notices will not be picked up while in the middle of a transaction. An
1049 example:
1050
1051 $dbh->do("LISTEN abc");
1052 $dbh->do("LISTEN def");
1053
1054 ## Hang around until we get the message we want
1055 LISTENLOOP: {
1056 while (my $notify = $dbh->pg_notifies) {
1057 my ($name, $pid, $payload) = @$notify;
1058 print qq{I received notice "$name" from PID $pid, payload was "$payload"\n};
1059 ## Do something based on the notice received
1060 }
1061 $dbh->ping() or die qq{Ping failed!};
1062 $dbh->commit();
1063 sleep(5);
1064 redo;
1065 }
1066
1067 Payloads will always be an empty string unless you are connecting to a
1068 Postgres server version 9.0 or higher.
1069
1070 ping
1071
1072 $rv = $dbh->ping;
1073
1074 This "ping" method is used to check the validity of a database handle.
1075 The value returned is either 0, indicating that the connection is no
1076 longer valid, or a positive integer, indicating the following:
1077
1078 Value Meaning
1079 --------------------------------------------------
1080 1 Database is idle (not in a transaction)
1081 2 Database is active, there is a command in progress (usually seen after a COPY command)
1082 3 Database is idle within a transaction
1083 4 Database is idle, within a failed transaction
1084
1085 Additional information on why a handle is not valid can be obtained by
1086 using the "pg_ping" method.
1087
1088 pg_ping
1089
1090 $rv = $dbh->pg_ping;
1091
1092 This is a DBD::Pg-specific extension to the "ping" method. This will
1093 check the validity of a database handle in exactly the same way as
1094 "ping", but instead of returning a 0 for an invalid connection, it will
1095 return a negative number. So in addition to returning the positive
1096 numbers documented for "ping", it may also return the following:
1097
1098 Value Meaning
1099 --------------------------------------------------
1100 -1 There is no connection to the database at all (e.g. after disconnect)
1101 -2 An unknown transaction status was returned (e.g. after forking)
1102 -3 The handle exists, but no data was returned from a test query.
1103
1104 In practice, you should only ever see -1 and -2.
1105
1106 get_info
1107
1108 $value = $dbh->get_info($info_type);
1109
1110 Supports a very large set (> 250) of the information types, including
1111 the minimum recommended by DBI.
1112
1113 table_info
1114
1115 $sth = $dbh->table_info(undef, $schema, $table, $type);
1116
1117 Returns all tables and views visible to the current user. The schema
1118 and table arguments will do a "LIKE" search if a percent sign ("%") or
1119 an underscore ("_") is detected in the argument. The $type argument
1120 accepts a value of either "TABLE" or "VIEW" (using both is the default
1121 action). Note that a statement handle is returned, and not a direct
1122 list of tables. See the examples below for ways to handle this.
1123
1124 The following fields are returned:
1125
1126 TABLE_CAT: Always NULL, as Postgres does not have the concept of
1127 catalogs.
1128
1129 TABLE_SCHEM: The name of the schema that the table or view is in.
1130
1131 TABLE_NAME: The name of the table or view.
1132
1133 TABLE_TYPE: The type of object returned. Will be one of "TABLE",
1134 "VIEW", or "SYSTEM TABLE".
1135
1136 The TABLE_SCHEM and TABLE_NAME will be quoted via "quote_ident()".
1137
1138 Two additional fields specific to DBD::Pg are returned:
1139
1140 pg_schema: the unquoted name of the schema
1141
1142 pg_table: the unquoted name of the table
1143
1144 If your database supports tablespaces (version 8.0 or greater), two
1145 additional DBD::Pg specific fields are returned:
1146
1147 pg_tablespace_name: the name of the tablespace the table is in
1148
1149 pg_tablespace_location: the location of the tablespace the table is in
1150
1151 Tables that have not been assigned to a particular tablespace (or
1152 views) will return NULL ("undef") for both of the above field.
1153
1154 Rows are returned alphabetically, with all tables first, and then all
1155 views.
1156
1157 Examples of use:
1158
1159 ## Display all tables and views in the public schema:
1160 $sth = $dbh->table_info('', 'public', undef, undef);
1161 for my $rel (@{$sth->fetchall_arrayref({})}) {
1162 print "$rel->{TABLE_TYPE} name is $rel->{TABLE_NAME}\n";
1163 }
1164
1165
1166 # Display the schema of all tables named 'foo':
1167 $sth = $dbh->table_info('', undef, 'foo', 'TABLE');
1168 for my $rel (@{$sth->fetchall_arrayref({})}) {
1169 print "Table name is $rel->{TABLE_SCHEM}.$rel->{TABLE_NAME}\n";
1170 }
1171
1172 column_info
1173
1174 $sth = $dbh->column_info( undef, $schema, $table, $column );
1175
1176 Supported by this driver as proposed by DBI with the follow exceptions.
1177 These fields are currently always returned with NULL ("undef") values:
1178
1179 TABLE_CAT
1180 BUFFER_LENGTH
1181 DECIMAL_DIGITS
1182 NUM_PREC_RADIX
1183 SQL_DATA_TYPE
1184 SQL_DATETIME_SUB
1185 CHAR_OCTET_LENGTH
1186
1187 Also, six additional non-standard fields are returned:
1188
1189 pg_type: data type with additional info i.e. "character varying(20)"
1190
1191 pg_constraint: holds column constraint definition
1192
1193 pg_schema: the unquoted name of the schema
1194
1195 pg_table: the unquoted name of the table
1196
1197 pg_column: the unquoted name of the column
1198
1199 pg_enum_values: an array reference of allowed values for an enum column
1200
1201 Note that the TABLE_SCHEM, TABLE_NAME, and COLUMN_NAME fields all
1202 return output wrapped in quote_ident(). If you need the unquoted
1203 version, use the pg_ fields above.
1204
1205 primary_key_info
1206
1207 $sth = $dbh->primary_key_info( undef, $schema, $table, \%attr );
1208
1209 Supported by this driver as proposed by DBI. There are no search
1210 patterns allowed, but leaving the $schema argument blank will cause the
1211 first table found in the schema search path to be used. An additional
1212 field, "DATA_TYPE", is returned and shows the data type for each of the
1213 arguments in the "COLUMN_NAME" field.
1214
1215 This method will also return tablespace information for servers that
1216 support tablespaces. See the "table_info" entry for more information.
1217
1218 The five additional custom fields returned are:
1219
1220 pg_tablespace_name: name of the tablespace, if any
1221
1222 pg_tablespace_location: location of the tablespace
1223
1224 pg_schema: the unquoted name of the schema
1225
1226 pg_table: the unquoted name of the table
1227
1228 pg_column: the unquoted name of the column
1229
1230 In addition to the standard format of returning one row for each column
1231 found for the primary key, you can pass the "pg_onerow" attribute to
1232 force a single row to be used. If the primary key has multiple columns,
1233 the "KEY_SEQ", "COLUMN_NAME", and "DATA_TYPE" fields will return a
1234 comma-delimited string. If the "pg_onerow" attribute is set to "2", the
1235 fields will be returned as an arrayref, which can be useful when
1236 multiple columns are involved:
1237
1238 $sth = $dbh->primary_key_info('', '', 'dbd_pg_test', {pg_onerow => 2});
1239 if (defined $sth) {
1240 my $pk = $sth->fetchall_arrayref()->[0];
1241 print "Table $pk->[2] has a primary key on these columns:\n";
1242 for (my $x=0; defined $pk->[3][$x]; $x++) {
1243 print "Column: $pk->[3][$x] (data type: $pk->[6][$x])\n";
1244 }
1245 }
1246
1247 primary_key
1248
1249 @key_column_names = $dbh->primary_key(undef, $schema, $table);
1250
1251 Simple interface to the "primary_key_info" method. Returns a list of
1252 the column names that comprise the primary key of the specified table.
1253 The list is in primary key column sequence order. If there is no
1254 primary key then an empty list is returned.
1255
1256 foreign_key_info
1257
1258 $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table,
1259 $fk_catalog, $fk_schema, $fk_table );
1260
1261 Supported by this driver as proposed by DBI, using the SQL/CLI variant.
1262 There are no search patterns allowed, but leaving the $schema argument
1263 blank will cause the first table found in the schema search path to be
1264 used. Two additional fields, "UK_DATA_TYPE" and "FK_DATA_TYPE", are
1265 returned to show the data type for the unique and foreign key columns.
1266 Foreign keys that have no named constraint (where the referenced column
1267 only has an unique index) will return "undef" for the "UK_NAME" field.
1268
1269 statistics_info
1270
1271 $sth = $dbh->statistics_info( undef, $schema, $table, $unique_only, $quick );
1272
1273 Returns a statement handle that can be fetched from to give statistics
1274 information on a specific table and its indexes. The $table argument is
1275 mandatory. The $schema argument is optional but recommended. The
1276 $unique_only argument, if true, causes only information about unique
1277 indexes to be returned. The $quick argument is not used by DBD::Pg. For
1278 information on the format of the rows returned, please see the DBI
1279 documentation.
1280
1281 tables
1282
1283 @names = $dbh->tables( undef, $schema, $table, $type, \%attr );
1284
1285 Supported by this driver as proposed by DBI. This method returns all
1286 tables and/or views which are visible to the current user: see
1287 "table_info" for more information about the arguments. The name of the
1288 schema appears before the table or view name. This can be turned off by
1289 adding in the "pg_noprefix" attribute:
1290
1291 my @tables = $dbh->tables( '', '', 'dbd_pg_test', '', {pg_noprefix => 1} );
1292
1293 type_info_all
1294
1295 $type_info_all = $dbh->type_info_all;
1296
1297 Supported by this driver as proposed by DBI. Information is only
1298 provided for SQL datatypes and for frequently used datatypes. The
1299 mapping between the PostgreSQL typename and the SQL92 datatype (if
1300 possible) has been done according to the following table:
1301
1302 +---------------+------------------------------------+
1303 | typname | SQL92 |
1304 |---------------+------------------------------------|
1305 | bool | BOOL |
1306 | text | / |
1307 | bpchar | CHAR(n) |
1308 | varchar | VARCHAR(n) |
1309 | int2 | SMALLINT |
1310 | int4 | INT |
1311 | int8 | / |
1312 | money | / |
1313 | float4 | FLOAT(p) p<7=float4, p<16=float8 |
1314 | float8 | REAL |
1315 | abstime | / |
1316 | reltime | / |
1317 | tinterval | / |
1318 | date | / |
1319 | time | / |
1320 | datetime | / |
1321 | timespan | TINTERVAL |
1322 | timestamp | TIMESTAMP |
1323 +---------------+------------------------------------+
1324
1325 type_info
1326
1327 @type_info = $dbh->type_info($data_type);
1328
1329 Returns a list of hash references holding information about one or more
1330 variants of $data_type. See the DBI documentation for more details.
1331
1332 pg_server_trace
1333
1334 $dbh->pg_server_trace($filehandle);
1335
1336 Writes debugging information from the PostgreSQL backend to a file.
1337 This is not related to the DBI "trace" method and you should not use
1338 this method unless you know what you are doing. If you do enable this,
1339 be aware that the file will grow very large, very quick. To stop
1340 logging to the file, use the "pg_server_untrace" method. The first
1341 argument must be a file handle, not a filename. Example:
1342
1343 my $pid = $dbh->{pg_pid};
1344 my $file = "pgbackend.$pid.debug.log";
1345 open(my $fh, ">$file") or die qq{Could not open "$file": $!\n};
1346 $dbh->pg_server_trace($fh);
1347 ## Run code you want to trace here
1348 $dbh->pg_server_untrace;
1349 close($fh);
1350
1351 pg_server_untrace
1352
1353 $dbh->pg_server_untrace;
1354
1355 Stop server logging to a previously opened file.
1356
1357 selectrow_array
1358
1359 @row_ary = $dbh->selectrow_array($sql);
1360 @row_ary = $dbh->selectrow_array($sql, \%attr);
1361 @row_ary = $dbh->selectrow_array($sql, \%attr, @bind_values);
1362
1363 Returns an array of row information after preparing and executing the
1364 provided SQL string. The rows are returned by calling "fetchrow_array".
1365 The string can also be a statement handle generated by a previous
1366 prepare. Note that only the first row of data is returned. If called in
1367 a scalar context, only the first column of the first row is returned.
1368 Because this is not portable, it is not recommended that you use this
1369 method in that way.
1370
1371 selectrow_arrayref
1372
1373 $ary_ref = $dbh->selectrow_arrayref($statement);
1374 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
1375 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
1376
1377 Exactly the same as "selectrow_array", except that it returns a
1378 reference to an array, by internal use of the "fetchrow_arrayref"
1379 method.
1380
1381 selectrow_hashref
1382
1383 $hash_ref = $dbh->selectrow_hashref($sql);
1384 $hash_ref = $dbh->selectrow_hashref($sql, \%attr);
1385 $hash_ref = $dbh->selectrow_hashref($sql, \%attr, @bind_values);
1386
1387 Exactly the same as "selectrow_array", except that it returns a
1388 reference to an hash, by internal use of the "fetchrow_hashref" method.
1389
1390 clone
1391
1392 $other_dbh = $dbh->clone();
1393
1394 Creates a copy of the database handle by connecting with the same
1395 parameters as the original handle, then trying to merge the attributes.
1396 See the DBI documentation for complete usage.
1397
1398 Database Handle Attributes
1399 AutoCommit (boolean)
1400
1401 Supported by DBD::Pg as proposed by DBI. According to the
1402 classification of DBI, PostgreSQL is a database in which a transaction
1403 must be explicitly started. Without starting a transaction, every
1404 change to the database becomes immediately permanent. The default of
1405 AutoCommit is on, but this may change in the future, so it is highly
1406 recommended that you explicitly set it when calling "connect". For
1407 details see the notes about "Transactions" elsewhere in this document.
1408
1409 pg_bool_tf (boolean)
1410
1411 DBD::Pg specific attribute. If true, boolean values will be returned as
1412 the characters 't' and 'f' instead of '1' and '0'.
1413
1414 ReadOnly (boolean)
1415
1416 $dbh->{ReadOnly} = 1;
1417
1418 Specifies if the current database connection should be in read-only
1419 mode or not. In this mode, changes that change the database are not
1420 allowed and will throw an error. Note: this method will not work if
1421 "AutoCommit" is true. The read-only effect is accomplished by sending a
1422 SET TRANSACTION READ ONLY after every begin. For more details, please
1423 see:
1424
1425 http://www.postgresql.org/docs/current/interactive/sql-set-transaction.html
1426
1427 Please not that this method is not foolproof: there are still ways to
1428 update the database. Consider this a safety net to catch applications
1429 that should not be issuing commands such as INSERT, UPDATE, or DELETE.
1430
1431 This method method requires DBI version 1.55 or better.
1432
1433 pg_server_prepare (integer)
1434
1435 DBD::Pg specific attribute. Indicates if DBD::Pg should attempt to use
1436 server-side prepared statements. The default value, 1, indicates that
1437 prepared statements should be used whenever possible. See the section
1438 on the "prepare" method for more information.
1439
1440 pg_placeholder_dollaronly (boolean)
1441
1442 DBD::Pg specific attribute. Defaults to false. When true, question
1443 marks inside of statements are not treated as placeholders. Useful for
1444 statements that contain unquoted question marks, such as geometric
1445 operators.
1446
1447 pg_enable_utf8 (boolean)
1448
1449 DBD::Pg specific attribute. If true, then the "utf8" flag will be
1450 turned on for returned character data (if the data is valid UTF-8). For
1451 details about the "utf8" flag, see the "Encode" module. This attribute
1452 is only relevant under perl 5.8 and later.
1453
1454 pg_errorlevel (integer)
1455
1456 DBD::Pg specific attribute. Sets the amount of information returned by
1457 the server's error messages. Valid entries are 0, 1, and 2. Any other
1458 number will be forced to the default value of 1.
1459
1460 A value of 0 ("TERSE") will show severity, primary text, and position
1461 only and will usually fit on a single line. A value of 1 ("DEFAULT")
1462 will also show any detail, hint, or context fields. A value of 2
1463 ("VERBOSE") will show all available information.
1464
1465 pg_lib_version (integer, read-only)
1466
1467 DBD::Pg specific attribute. Indicates which version of PostgreSQL that
1468 DBD::Pg was compiled against. In other words, which libraries were
1469 used. Returns a number with major, minor, and revision together;
1470 version 8.1.4 would be returned as 80104.
1471
1472 pg_server_version (integer, read-only)
1473
1474 DBD::Pg specific attribute. Indicates which version of PostgreSQL that
1475 the current database handle is connected to. Returns a number with
1476 major, minor, and revision together; version 8.0.1 would be 80001.
1477
1478 Name (string, read-only)
1479
1480 Returns the name of the current database. This is the same as the DSN,
1481 without the "dbi:Pg:" part. Before version 2.0.0, this only returned
1482 the bare database name (e.g. 'foo'). From version 2.0.0 onwards, it
1483 returns the more correct output (e.g. 'dbname=foo')
1484
1485 Username (string, read-only)
1486
1487 Returns the name of the user connected to the database.
1488
1489 pg_db (string, read-only)
1490
1491 DBD::Pg specific attribute. Returns the name of the current database.
1492
1493 pg_user (string, read-only)
1494
1495 DBD::Pg specific attribute. Returns the name of the user that connected
1496 to the server.
1497
1498 pg_host (string, read-only)
1499
1500 DBD::Pg specific attribute. Returns the host of the current server
1501 connection. Locally connected hosts will return an empty string.
1502
1503 pg_port (integer, read-only)
1504
1505 DBD::Pg specific attribute. Returns the port of the connection to the
1506 server.
1507
1508 pg_socket (integer, read-only)
1509
1510 DBD::Pg specific attribute. Returns the file description number of the
1511 connection socket to the server.
1512
1513 pg_pass (string, read-only)
1514
1515 DBD::Pg specific attribute. Returns the password used to connect to the
1516 server.
1517
1518 pg_options (string, read-only)
1519
1520 DBD::Pg specific attribute. Returns the command-line options passed to
1521 the server. May be an empty string.
1522
1523 pg_default_port (integer, read-only)
1524
1525 DBD::Pg specific attribute. Returns the default port used if none is
1526 specifically given.
1527
1528 pg_pid (integer, read-only)
1529
1530 DBD::Pg specific attribute. Returns the process id (PID) of the backend
1531 server process handling the connection.
1532
1533 pg_prepare_now (boolean)
1534
1535 DBD::Pg specific attribute. Default is off. If true, then the "prepare"
1536 method will immediately prepare commands, rather than waiting until the
1537 first execute.
1538
1539 pg_expand_array (boolean)
1540
1541 DBD::Pg specific attribute. Defaults to true. If false, arrays returned
1542 from the server will not be changed into a Perl arrayref, but remain as
1543 a string.
1544
1545 pg_async_status (integer, read-only)
1546
1547 DBD::Pg specific attribute. Returns the current status of an
1548 asynchronous command. 0 indicates no asynchronous command is in
1549 progress, 1 indicates that an asynchronous command has started and -1
1550 indicated that an asynchronous command has been cancelled.
1551
1552 pg_standard_conforming_strings (boolean, read-only)
1553
1554 DBD::Pg specific attribute. Returns true if the server is currently
1555 using standard conforming strings. Only available if the target server
1556 is version 8.2 or better.
1557
1558 pg_INV_READ (integer, read-only)
1559
1560 Constant to be used for the mode in "lo_creat" and "lo_open".
1561
1562 pg_INV_WRITE (integer, read-only)
1563
1564 Constant to be used for the mode in "lo_creat" and "lo_open".
1565
1566 Driver (handle, read-only)
1567
1568 Holds the handle of the parent driver. The only recommended use for
1569 this is to find the name of the driver using:
1570
1571 $dbh->{Driver}->{Name}
1572
1573 pg_protocol (integer, read-only)
1574
1575 DBD::Pg specific attribute. Returns the version of the PostgreSQL
1576 server. If DBD::Pg is unable to figure out the version, it will return
1577 a "0". Otherwise, a "3" is returned.
1578
1579 RowCacheSize
1580
1581 Not used by DBD::Pg
1582
1584 Statement Handle Methods
1585 bind_param
1586
1587 $rv = $sth->bind_param($param_num, $bind_value);
1588 $rv = $sth->bind_param($param_num, $bind_value, $bind_type);
1589 $rv = $sth->bind_param($param_num, $bind_value, \%attr);
1590
1591 Allows the user to bind a value and/or a data type to a placeholder.
1592 This is especially important when using server-side prepares. See the
1593 "prepare" method for more information.
1594
1595 The value of $param_num is a number if using the '?' or '$1' style
1596 placeholders. If using ":foo" style placeholders, the complete name
1597 (e.g. ":foo") must be given. For numeric values, you can either use a
1598 number or use a literal '$1'. See the examples below.
1599
1600 The $bind_value argument is fairly self-explanatory. A value of "undef"
1601 will bind a "NULL" to the placeholder. Using "undef" is useful when you
1602 want to change just the type and will be overwriting the value later.
1603 (Any value is actually usable, but "undef" is easy and efficient).
1604
1605 The "\%attr" hash is used to indicate the data type of the placeholder.
1606 The default value is "varchar". If you need something else, you must
1607 use one of the values provided by DBI or by DBD::Pg. To use a SQL
1608 value, modify your "use DBI" statement at the top of your script as
1609 follows:
1610
1611 use DBI qw(:sql_types);
1612
1613 This will import some constants into your script. You can plug those
1614 directly into the "bind_param" call. Some common ones that you will
1615 encounter are:
1616
1617 SQL_INTEGER
1618
1619 To use PostgreSQL data types, import the list of values like this:
1620
1621 use DBD::Pg qw(:pg_types);
1622
1623 You can then set the data types by setting the value of the "pg_type"
1624 key in the hash passed to "bind_param". The current list of Postgres
1625 data types exported is:
1626
1627 PG_ABSTIME PG_ABSTIMEARRAY PG_ACLITEM PG_ACLITEMARRAY PG_ANY PG_ANYARRAY
1628 PG_ANYELEMENT PG_ANYENUM PG_ANYNONARRAY PG_BIT PG_BITARRAY PG_BOOL
1629 PG_BOOLARRAY PG_BOX PG_BOXARRAY PG_BPCHAR PG_BPCHARARRAY PG_BYTEA
1630 PG_BYTEAARRAY PG_CHAR PG_CHARARRAY PG_CID PG_CIDARRAY PG_CIDR
1631 PG_CIDRARRAY PG_CIRCLE PG_CIRCLEARRAY PG_CSTRING PG_CSTRINGARRAY PG_DATE
1632 PG_DATEARRAY PG_FDW_HANDLER PG_FLOAT4 PG_FLOAT4ARRAY PG_FLOAT8 PG_FLOAT8ARRAY
1633 PG_GTSVECTOR PG_GTSVECTORARRAY PG_INET PG_INETARRAY PG_INT2 PG_INT2ARRAY
1634 PG_INT2VECTOR PG_INT2VECTORARRAY PG_INT4 PG_INT4ARRAY PG_INT8 PG_INT8ARRAY
1635 PG_INTERNAL PG_INTERVAL PG_INTERVALARRAY PG_LANGUAGE_HANDLER PG_LINE PG_LINEARRAY
1636 PG_LSEG PG_LSEGARRAY PG_MACADDR PG_MACADDRARRAY PG_MONEY PG_MONEYARRAY
1637 PG_NAME PG_NAMEARRAY PG_NUMERIC PG_NUMERICARRAY PG_OID PG_OIDARRAY
1638 PG_OIDVECTOR PG_OIDVECTORARRAY PG_OPAQUE PG_PATH PG_PATHARRAY PG_PG_ATTRIBUTE
1639 PG_PG_CLASS PG_PG_NODE_TREE PG_PG_PROC PG_PG_TYPE PG_POINT PG_POINTARRAY
1640 PG_POLYGON PG_POLYGONARRAY PG_RECORD PG_RECORDARRAY PG_REFCURSOR PG_REFCURSORARRAY
1641 PG_REGCLASS PG_REGCLASSARRAY PG_REGCONFIG PG_REGCONFIGARRAY PG_REGDICTIONARY PG_REGDICTIONARYARRAY
1642 PG_REGOPER PG_REGOPERARRAY PG_REGOPERATOR PG_REGOPERATORARRAY PG_REGPROC PG_REGPROCARRAY
1643 PG_REGPROCEDURE PG_REGPROCEDUREARRAY PG_REGTYPE PG_REGTYPEARRAY PG_RELTIME PG_RELTIMEARRAY
1644 PG_SMGR PG_TEXT PG_TEXTARRAY PG_TID PG_TIDARRAY PG_TIME
1645 PG_TIMEARRAY PG_TIMESTAMP PG_TIMESTAMPARRAY PG_TIMESTAMPTZ PG_TIMESTAMPTZARRAY PG_TIMETZ
1646 PG_TIMETZARRAY PG_TINTERVAL PG_TINTERVALARRAY PG_TRIGGER PG_TSQUERY PG_TSQUERYARRAY
1647 PG_TSVECTOR PG_TSVECTORARRAY PG_TXID_SNAPSHOT PG_TXID_SNAPSHOTARRAY PG_UNKNOWN PG_UUID
1648 PG_UUIDARRAY PG_VARBIT PG_VARBITARRAY PG_VARCHAR PG_VARCHARARRAY PG_VOID
1649 PG_XID PG_XIDARRAY PG_XML PG_XMLARRAY
1650
1651 Data types are "sticky," in that once a data type is set to a certain
1652 placeholder, it will remain for that placeholder, unless it is
1653 explicitly set to something else afterwards. If the statement has
1654 already been prepared, and you switch the data type to something else,
1655 DBD::Pg will re-prepare the statement for you before doing the next
1656 execute.
1657
1658 Examples:
1659
1660 use DBI qw(:sql_types);
1661 use DBD::Pg qw(:pg_types);
1662
1663 $SQL = "SELECT id FROM ptable WHERE size > ? AND title = ?";
1664 $sth = $dbh->prepare($SQL);
1665
1666 ## Both arguments below are bound to placeholders as "varchar"
1667 $sth->execute(123, "Merk");
1668
1669 ## Reset the datatype for the first placeholder to an integer
1670 $sth->bind_param(1, undef, SQL_INTEGER);
1671
1672 ## The "undef" bound above is not used, since we supply params to execute
1673 $sth->execute(123, "Merk");
1674
1675 ## Set the first placeholder's value and data type
1676 $sth->bind_param(1, 234, { pg_type => PG_TIMESTAMP });
1677
1678 ## Set the second placeholder's value and data type.
1679 ## We don't send a third argument, so the default "varchar" is used
1680 $sth->bind_param('$2', "Zool");
1681
1682 ## We realize that the wrong data type was set above, so we change it:
1683 $sth->bind_param('$1', 234, { pg_type => SQL_INTEGER });
1684
1685 ## We also got the wrong value, so we change that as well.
1686 ## Because the data type is sticky, we don't need to change it
1687 $sth->bind_param(1, 567);
1688
1689 ## This executes the statement with 567 (integer) and "Zool" (varchar)
1690 $sth->execute();
1691
1692 bind_param_inout
1693
1694 $rv = $sth->bind_param_inout($param_num, \$scalar, 0);
1695
1696 Experimental support for this feature is provided. The first argument
1697 to bind_param_inout should be a placeholder number. The second argument
1698 should be a reference to a scalar variable in your script. The third
1699 argument is not used and should simply be set to 0. Note that what this
1700 really does is assign a returned column to the variable, in the order
1701 in which the column appears. For example:
1702
1703 my $foo = 123;
1704 $sth = $dbh->prepare("SELECT 1+?::int");
1705 $sth->bind_param_inout(1, \$foo, 0);
1706 $foo = 222;
1707 $sth->execute(444);
1708 $sth->fetch;
1709
1710 The above will cause $foo to have a new value of "223" after the final
1711 fetch. Note that the variables bound in this manner are very sticky,
1712 and will trump any values passed in to execute. This is because the
1713 binding is done as late as possible, at the execute() stage, allowing
1714 the value to be changed between the time it was bound and the time the
1715 query is executed. Thus, the above execute is the same as:
1716
1717 $sth->execute();
1718
1719 bind_param_array
1720
1721 $rv = $sth->bind_param_array($param_num, $array_ref_or_value)
1722 $rv = $sth->bind_param_array($param_num, $array_ref_or_value, $bind_type)
1723 $rv = $sth->bind_param_array($param_num, $array_ref_or_value, \%attr)
1724
1725 Binds an array of values to a placeholder, so that each is used in turn
1726 by a call to the "execute_array" method.
1727
1728 execute
1729
1730 $rv = $sth->execute(@bind_values);
1731
1732 Executes a previously prepared statement. In addition to "UPDATE",
1733 "DELETE", "INSERT" statements, for which it returns always the number
1734 of affected rows, the "execute" method can also be used for "SELECT ...
1735 INTO table" statements.
1736
1737 The "prepare/bind/execute" process has changed significantly for
1738 PostgreSQL servers 7.4 and later: please see the "prepare()" and
1739 "bind_param()" entries for much more information.
1740
1741 Setting one of the bind_values to "undef" is the equivalent of setting
1742 the value to NULL in the database. Setting the bind_value to
1743 $DBDPG_DEFAULT is equivalent to sending the literal string 'DEFAULT' to
1744 the backend. Note that using this option will force server-side
1745 prepares off until such time as PostgreSQL supports using DEFAULT in
1746 prepared statements.
1747
1748 DBD::Pg also supports passing in arrays to execute: simply pass in an
1749 arrayref, and DBD::Pg will flatten it into a string suitable for input
1750 on the backend.
1751
1752 If you are using Postgres version 8.2 or greater, you can also use any
1753 of the fetch methods to retrieve the values of a "RETURNING" clause
1754 after you execute an "UPDATE", "DELETE", or "INSERT". For example:
1755
1756 $dbh->do(q{CREATE TABLE abc (id SERIAL, country TEXT)});
1757 $SQL = q{INSERT INTO abc (country) VALUES (?) RETURNING id};
1758 $sth = $dbh->prepare($SQL);
1759 $sth->execute('France');
1760 $countryid = $sth->fetch()->[0];
1761 $sth->execute('New Zealand');
1762 $countryid = $sth->fetch()->[0];
1763
1764 execute_array
1765
1766 $tuples = $sth->execute_array() or die $sth->errstr;
1767 $tuples = $sth->execute_array(\%attr) or die $sth->errstr;
1768 $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
1769
1770 ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr;
1771 ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
1772
1773 Execute a prepared statement once for each item in a passed-in hashref,
1774 or items that were previously bound via the "bind_param_array" method.
1775 See the DBI documentation for more details.
1776
1777 execute_for_fetch
1778
1779 $tuples = $sth->execute_for_fetch($fetch_tuple_sub);
1780 $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
1781
1782 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub);
1783 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
1784
1785 Used internally by the "execute_array" method, and rarely used
1786 directly. See the DBI documentation for more details.
1787
1788 fetchrow_arrayref
1789
1790 $ary_ref = $sth->fetchrow_arrayref;
1791
1792 Fetches the next row of data from the statement handle, and returns a
1793 reference to an array holding the column values. Any columns that are
1794 NULL are returned as undef within the array.
1795
1796 If there are no more rows or if an error occurs, the this method return
1797 undef. You should check "$sth->err" afterwards (or use the "RaiseError"
1798 attribute) to discover if the undef returned was due to an error.
1799
1800 Note that the same array reference is returned for each fetch, so don't
1801 store the reference and then use it after a later fetch. Also, the
1802 elements of the array are also reused for each row, so take care if you
1803 want to take a reference to an element. See also "bind_columns".
1804
1805 fetchrow_array
1806
1807 @ary = $sth->fetchrow_array;
1808
1809 Similar to the "fetchrow_arrayref" method, but returns a list of column
1810 information rather than a reference to a list. Do not use this in a
1811 scalar context.
1812
1813 fetchrow_hashref
1814
1815 $hash_ref = $sth->fetchrow_hashref;
1816 $hash_ref = $sth->fetchrow_hashref($name);
1817
1818 Fetches the next row of data and returns a hashref containing the name
1819 of the columns as the keys and the data itself as the values. Any NULL
1820 value is returned as as undef value.
1821
1822 If there are no more rows or if an error occurs, the this method return
1823 undef. You should check "$sth->err" afterwards (or use the "RaiseError"
1824 attribute) to discover if the undef returned was due to an error.
1825
1826 The optional $name argument should be either "NAME", "NAME_lc" or
1827 "NAME_uc", and indicates what sort of transformation to make to the
1828 keys in the hash.
1829
1830 fetchall_arrayref
1831
1832 $tbl_ary_ref = $sth->fetchall_arrayref();
1833 $tbl_ary_ref = $sth->fetchall_arrayref( $slice );
1834 $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
1835
1836 Returns a reference to an array of arrays that contains all the
1837 remaining rows to be fetched from the statement handle. If there are no
1838 more rows, an empty arrayref will be returned. If an error occurs, the
1839 data read in so far will be returned. Because of this, you should
1840 always check "$sth->err" after calling this method, unless "RaiseError"
1841 has been enabled.
1842
1843 If $slice is an array reference, fetchall_arrayref uses the
1844 "fetchrow_arrayref" method to fetch each row as an array ref. If the
1845 $slice array is not empty then it is used as a slice to select
1846 individual columns by perl array index number (starting at 0, unlike
1847 column and parameter numbers which start at 1).
1848
1849 With no parameters, or if $slice is undefined, fetchall_arrayref acts
1850 as if passed an empty array ref.
1851
1852 If $slice is a hash reference, fetchall_arrayref uses
1853 "fetchrow_hashref" to fetch each row as a hash reference.
1854
1855 See the DBI documentation for a complete discussion.
1856
1857 fetchall_hashref
1858
1859 $hash_ref = $sth->fetchall_hashref( $key_field );
1860
1861 Returns a hashref containing all rows to be fetched from the statement
1862 handle. See the DBI documentation for a full discussion.
1863
1864 finish
1865
1866 $rv = $sth->finish;
1867
1868 Indicates to DBI that you are finished with the statement handle and
1869 are not going to use it again. Only needed when you have not fetched
1870 all the possible rows.
1871
1872 rows
1873
1874 $rv = $sth->rows;
1875
1876 Returns the number of rows returned by the last query. In contrast to
1877 many other DBD modules, the number of rows is available immediately
1878 after calling "$sth->execute". Note that the "execute" method itself
1879 returns the number of rows itself, which means that this method is
1880 rarely needed.
1881
1882 bind_col
1883
1884 $rv = $sth->bind_col($column_number, \$var_to_bind);
1885 $rv = $sth->bind_col($column_number, \$var_to_bind, \%attr );
1886 $rv = $sth->bind_col($column_number, \$var_to_bind, $bind_type );
1887
1888 Binds a Perl variable and/or some attributes to an output column of a
1889 SELECT statement. Column numbers count up from 1. You do not need to
1890 bind output columns in order to fetch data.
1891
1892 See the DBI documentation for a discussion of the optional parameters
1893 "\%attr" and $bind_type
1894
1895 bind_columns
1896
1897 $rv = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
1898
1899 Calls the "bind_col" method for each column in the SELECT statement,
1900 using the supplied list.
1901
1902 dump_results
1903
1904 $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
1905
1906 Fetches all the rows from the statement handle, calls "DBI::neat_list"
1907 for each row, and prints the results to $fh (which defaults to STDOUT).
1908 Rows are separated by $lsep (which defaults to a newline). Columns are
1909 separated by $fsep (which defaults to a comma). The $maxlen controls
1910 how wide the output can be, and defaults to 35.
1911
1912 This method is designed as a handy utility for prototyping and testing
1913 queries. Since it uses "neat_list" to format and edit the string for
1914 reading by humans, it is not recommended for data transfer
1915 applications.
1916
1917 blob_read
1918
1919 $blob = $sth->blob_read($id, $offset, $len);
1920
1921 Supported by DBD::Pg. This method is implemented by DBI but not
1922 currently documented by DBI, so this method might change.
1923
1924 This method seems to be heavily influenced by the current
1925 implementation of blobs in Oracle. Nevertheless we try to be as
1926 compatible as possible. Whereas Oracle suffers from the limitation that
1927 blobs are related to tables and every table can have only one blob
1928 (datatype LONG), PostgreSQL handles its blobs independent of any table
1929 by using so-called object identifiers. This explains why the
1930 "blob_read" method is blessed into the STATEMENT package and not part
1931 of the DATABASE package. Here the field parameter has been used to
1932 handle this object identifier. The offset and len parameters may be set
1933 to zero, in which case the whole blob is fetched at once.
1934
1935 See also the PostgreSQL-specific functions concerning blobs, which are
1936 available via the "func" interface.
1937
1938 For further information and examples about blobs, please read the
1939 chapter about Large Objects in the PostgreSQL Programmer's Guide at
1940 <http://www.postgresql.org/docs/current/static/largeobjects.html>.
1941
1942 Statement Handle Attributes
1943 NUM_OF_FIELDS (integer, read-only)
1944
1945 Returns the number of columns returned by the current statement. A
1946 number will only be returned for SELECT statements, for SHOW statements
1947 (which always return 1), and for INSERT, UPDATE, and DELETE statements
1948 which contain a RETURNING clause. This method returns undef if called
1949 before "execute()".
1950
1951 NUM_OF_PARAMS (integer, read-only)
1952
1953 Returns the number of placeholders in the current statement.
1954
1955 NAME (arrayref, read-only)
1956
1957 Returns an arrayref of column names for the current statement. This
1958 method will only work for SELECT statements, for SHOW statements, and
1959 for INSERT, UPDATE, and DELETE statements which contain a RETURNING
1960 clause. This method returns undef if called before "execute()".
1961
1962 NAME_lc (arrayref, read-only)
1963
1964 The same as the "NAME" attribute, except that all column names are
1965 forced to lower case.
1966
1967 NAME_uc (arrayref, read-only)
1968
1969 The same as the "NAME" attribute, except that all column names are
1970 forced to upper case.
1971
1972 NAME_hash (hashref, read-only)
1973
1974 Similar to the "NAME" attribute, but returns a hashref of column names
1975 instead of an arrayref. The names of the columns are the keys of the
1976 hash, and the values represent the order in which the columns are
1977 returned, starting at 0. This method returns undef if called before
1978 "execute()".
1979
1980 NAME_lc_hash (hashref, read-only)
1981
1982 The same as the "NAME_hash" attribute, except that all column names are
1983 forced to lower case.
1984
1985 NAME_uc_hash (hashref, read-only)
1986
1987 The same as the "NAME_hash" attribute, except that all column names are
1988 forced to lower case.
1989
1990 TYPE (arrayref, read-only)
1991
1992 Returns an arrayref indicating the data type for each column in the
1993 statement. This method returns undef if called before "execute()".
1994
1995 PRECISION (arrayref, read-only)
1996
1997 Returns an arrayref of integer values for each column returned by the
1998 statement. The number indicates the precision for "NUMERIC" columns,
1999 the size in number of characters for "CHAR" and "VARCHAR" columns, and
2000 for all other types of columns it returns the number of bytes. This
2001 method returns undef if called before "execute()".
2002
2003 SCALE (arrayref, read-only)
2004
2005 Returns an arrayref of integer values for each column returned by the
2006 statement. The number indicates the scale of the that column. The only
2007 type that will return a value is "NUMERIC". This method returns undef
2008 if called before "execute()".
2009
2010 NULLABLE (arrayref, read-only)
2011
2012 Returns an arrayref of integer values for each column returned by the
2013 statement. The number indicates if the column is nullable or not. 0 =
2014 not nullable, 1 = nullable, 2 = unknown. This method returns undef if
2015 called before "execute()".
2016
2017 Database (dbh, read-only)
2018
2019 Returns the database handle this statement handle was created from.
2020
2021 ParamValues (hash ref, read-only)
2022
2023 Returns a reference to a hash containing the values currently bound to
2024 placeholders. If the "named parameters" type of placeholders are being
2025 used (such as ":foo"), then the keys of the hash will be the names of
2026 the placeholders (without the colon). If the "dollar sign numbers" type
2027 of placeholders are being used, the keys of the hash will be the
2028 numbers, without the dollar signs. If the "question mark" type is used,
2029 integer numbers will be returned, starting at one and increasing for
2030 every placeholder.
2031
2032 If this method is called before "execute", the literal values passed in
2033 are returned. If called after "execute", then the quoted versions of
2034 the values are returned.
2035
2036 ParamTypes (hash ref, read-only)
2037
2038 Returns a reference to a hash containing the type names currently bound
2039 to placeholders. The keys are the same as returned by the ParamValues
2040 method. The values are hashrefs containing a single key value pair, in
2041 which the key is either 'TYPE' if the type has a generic SQL
2042 equivalent, and 'pg_type' if the type can only be expressed by a
2043 Postgres type. The value is the internal number corresponding to the
2044 type originally passed in. (Placeholders that have not yet been bound
2045 will return undef as the value). This allows the output of ParamTypes
2046 to be passed back to the "bind_param" method.
2047
2048 Statement (string, read-only)
2049
2050 Returns the statement string passed to the most recent "prepare" method
2051 called in this database handle, even if that method failed. This is
2052 especially useful where "RaiseError" is enabled and the exception
2053 handler checks $@ and sees that a "prepare" method call failed.
2054
2055 pg_current_row (integer, read-only)
2056
2057 DBD::Pg specific attribute. Returns the number of the tuple (row) that
2058 was most recently fetched. Returns zero before and after fetching is
2059 performed.
2060
2061 pg_numbound (integer, read-only)
2062
2063 DBD::Pg specific attribute. Returns the number of placeholders that are
2064 currently bound (via bind_param).
2065
2066 pg_bound (hashref, read-only)
2067
2068 DBD::Pg specific attribute. Returns a hash of all named placeholders.
2069 The key is the name of the placeholder, and the value is a 0 or a 1,
2070 indicating if the placeholder has been bound yet (e.g. via bind_param)
2071
2072 pg_size (arrayref, read-only)
2073
2074 DBD::Pg specific attribute. It returns a reference to an array of
2075 integer values for each column. The integer shows the size of the
2076 column in bytes. Variable length columns are indicated by -1.
2077
2078 pg_type (arrayref, read-only)
2079
2080 DBD::Pg specific attribute. It returns a reference to an array of
2081 strings for each column. The string shows the name of the data_type.
2082
2083 pg_segments (arrayref, read-only)
2084
2085 DBD::Pg specific attribute. Returns an arrayref of the query split on
2086 the placeholders.
2087
2088 pg_oid_status (integer, read-only)
2089
2090 DBD::Pg specific attribute. It returns the OID of the last INSERT
2091 command.
2092
2093 pg_cmd_status (integer, read-only)
2094
2095 DBD::Pg specific attribute. It returns the type of the last command.
2096 Possible types are: "INSERT", "DELETE", "UPDATE", "SELECT".
2097
2098 pg_direct (boolean)
2099
2100 DBD::Pg specific attribute. Default is false. If true, the query is
2101 passed directly to the backend without parsing for placeholders.
2102
2103 pg_prepare_now (boolean)
2104
2105 DBD::Pg specific attribute. Default is off. If true, the query will be
2106 immediately prepared, rather than waiting for the "execute" call.
2107
2108 pg_prepare_name (string)
2109
2110 DBD::Pg specific attribute. Specifies the name of the prepared
2111 statement to use for this statement handle. Not normally needed, see
2112 the section on the "prepare" method for more information.
2113
2114 pg_server_prepare (integer)
2115
2116 DBD::Pg specific attribute. Indicates if DBD::Pg should attempt to use
2117 server-side prepared statements for this statement handle. The default
2118 value, 1, indicates that prepared statements should be used whenever
2119 possible. See the section on the "prepare" method for more information.
2120
2121 pg_placeholder_dollaronly (boolean)
2122
2123 DBD::Pg specific attribute. Defaults to off. When true, question marks
2124 inside of the query being prepared are not treated as placeholders.
2125 Useful for statements that contain unquoted question marks, such as
2126 geometric operators.
2127
2128 pg_async (integer)
2129
2130 DBD::Pg specific attribute. Indicates the current behavior for
2131 asynchronous queries. See the section on "Asynchronous Constants" for
2132 more information.
2133
2134 RowsInCache
2135
2136 Not used by DBD::Pg
2137
2138 RowCache
2139
2140 Not used by DBD::Pg
2141
2142 CursorName
2143
2144 Not used by DBD::Pg. See the note about "Cursors" elsewhere in this
2145 document.
2146
2148 Transactions
2149 Transaction behavior is controlled via the "AutoCommit" attribute. For
2150 a complete definition of "AutoCommit" please refer to the DBI
2151 documentation.
2152
2153 According to the DBI specification the default for "AutoCommit" is a
2154 true value. In this mode, any change to the database becomes valid
2155 immediately. Any "BEGIN", "COMMIT" or "ROLLBACK" statements will be
2156 rejected. DBD::Pg implements "AutoCommit" by issuing a "BEGIN"
2157 statement immediately before executing a statement, and a "COMMIT"
2158 afterwards. Note that preparing a statement is not always enough to
2159 trigger the first "BEGIN", as the actual "PREPARE" is usually postponed
2160 until the first call to "execute".
2161
2162 Savepoints
2163 PostgreSQL version 8.0 introduced the concept of savepoints, which
2164 allows transactions to be rolled back to a certain point without
2165 affecting the rest of the transaction. DBD::Pg encourages using the
2166 following methods to control savepoints:
2167
2168 "pg_savepoint"
2169
2170 Creates a savepoint. This will fail unless you are inside of a
2171 transaction. The only argument is the name of the savepoint. Note that
2172 PostgreSQL DOES allow multiple savepoints with the same name to exist.
2173
2174 $dbh->pg_savepoint("mysavepoint");
2175
2176 "pg_rollback_to"
2177
2178 Rolls the database back to a named savepoint, discarding any work
2179 performed after that point. If more than one savepoint with that name
2180 exists, rolls back to the most recently created one.
2181
2182 $dbh->pg_rollback_to("mysavepoint");
2183
2184 "pg_release"
2185
2186 Releases (or removes) a named savepoint. If more than one savepoint
2187 with that name exists, it will only destroy the most recently created
2188 one. Note that all savepoints created after the one being released are
2189 also destroyed.
2190
2191 $dbh->pg_release("mysavepoint");
2192
2193 Asynchronous Queries
2194 It is possible to send a query to the backend and have your script do
2195 other work while the query is running on the backend. Both queries sent
2196 by the "do" method, and by the "execute" method can be sent
2197 asynchronously. (NOTE: This will only work if DBD::Pg has been compiled
2198 against Postgres libraries of version 8.0 or greater) The basic usage
2199 is as follows:
2200
2201 use DBD::Pg ':async';
2202
2203 print "Async do() example:\n";
2204 $dbh->do("SELECT long_running_query()", {pg_async => PG_ASYNC});
2205 do_something_else();
2206 {
2207 if ($dbh->pg_ready()) {
2208 $res = $dbh->pg_result();
2209 print "Result of do(): $res\n";
2210 }
2211 print "Query is still running...\n";
2212 if (cancel_request_received) {
2213 $dbh->pg_cancel();
2214 }
2215 sleep 1;
2216 redo;
2217 }
2218
2219 print "Async prepare/execute example:\n";
2220 $sth = $dbh->prepare("SELECT long_running_query(1)", {pg_async => PG_ASYNC});
2221 $sth->execute();
2222
2223 ## Changed our mind, cancel and run again:
2224 $sth = $dbh->prepare("SELECT 678", {pg_async => PG_ASYNC + PG_OLDQUERY_CANCEL});
2225 $sth->execute();
2226
2227 do_something_else();
2228
2229 if (!$sth->pg_ready) {
2230 do_another_thing();
2231 }
2232
2233 ## We wait until it is done, and get the result:
2234 $res = $dbh->pg_result();
2235
2236 Asynchronous Constants
2237
2238 There are currently three asynchronous constants exported by DBD::Pg.
2239 You can import all of them by putting either of these at the top of
2240 your script:
2241
2242 use DBD::Pg;
2243
2244 use DBD::Pg ':async';
2245
2246 You may also use the numbers instead of the constants, but using the
2247 constants is recommended as it makes your script more readable.
2248
2249 PG_ASYNC
2250 This is a constant for the number 1. It is passed to either the
2251 "do" or the "prepare" method as a value to the pg_async key and
2252 indicates that the query should be sent asynchronously.
2253
2254 PG_OLDQUERY_CANCEL
2255 This is a constant for the number 2. When passed to either the "do"
2256 or the "prepare" method, it causes any currently running
2257 asynchronous query to be cancelled and rolled back. It has no
2258 effect if no asynchronous query is currently running.
2259
2260 PG_OLDQUERY_WAIT
2261 This is a constant for the number 4. When passed to either the "do"
2262 or the "prepare" method, it waits for any currently running
2263 asynchronous query to complete. It has no effect if there is no
2264 asynchronous query currently running.
2265
2266 Asynchronous Methods
2267
2268 pg_cancel
2269 This database-level method attempts to cancel any currently running
2270 asynchronous query. It returns true if the cancel succeeded, and
2271 false otherwise. Note that a query that has finished before this
2272 method is executed will also return false. WARNING: a successful
2273 cancellation may leave the database in an unusable state, so you
2274 may need to ROLLBACK or ROLLBACK TO a savepoint. As of version
2275 2.17.0 of DBD::Pg, rollbacks are not done automatically.
2276
2277 $result = $dbh->pg_cancel();
2278
2279 pg_ready
2280 This method can be called as a database handle method or (for
2281 convenience) as a statement handle method. Both simply see if a
2282 previously issued asynchronous query has completed yet. It returns
2283 true if the statement has finished, in which case you should then
2284 call the "pg_result" method. Calls to "pg_ready()" should only be
2285 used when you have other things to do while the query is running.
2286 If you simply want to wait until the query is done, do not call
2287 pg_ready() over and over, but simply call the pg_result() method.
2288
2289 my $time = 0;
2290 while (!$dbh->pg_ready) {
2291 print "Query is still running. Seconds: $time\n";
2292 $time++;
2293 sleep 1;
2294 }
2295 $result = $dbh->pg_result;
2296
2297 pg_result
2298 This database handle method returns the results of a previously
2299 issued asynchronous query. If the query is still running, this
2300 method will wait until it has finished. The result returned is the
2301 number of rows: the same thing that would have been returned by the
2302 asynchronous "do" or "execute" if it had been called without an
2303 asynchronous flag.
2304
2305 $result = $dbh->pg_result;
2306
2307 Asynchronous Examples
2308
2309 Here are some working examples of asynchronous queries. Note that we'll
2310 use the pg_sleep function to emulate a long-running query.
2311
2312 use strict;
2313 use warnings;
2314 use Time::HiRes 'sleep';
2315 use DBD::Pg ':async';
2316
2317 my $dbh = DBI->connect('dbi:Pg:dbname=postgres', 'postgres', '', {AutoCommit=>0,RaiseError=>1});
2318
2319 ## Kick off a long running query on the first database:
2320 my $sth = $dbh->prepare("SELECT pg_sleep(?)", {pg_async => PG_ASYNC});
2321 $sth->execute(5);
2322
2323 ## While that is running, do some other things
2324 print "Your query is processing. Thanks for waiting\n";
2325 check_on_the_kids(); ## Expensive sub, takes at least three seconds.
2326
2327 while (!$dbh->pg_ready) {
2328 check_on_the_kids();
2329 ## If the above function returns quickly for some reason, we add a small sleep
2330 sleep 0.1;
2331 }
2332
2333 print "The query has finished. Gathering results\n";
2334 my $result = $sth->pg_result;
2335 print "Result: $result\n";
2336 my $info = $sth->fetchall_arrayref();
2337
2338 Without asynchronous queries, the above script would take about 8
2339 seconds to run: five seconds waiting for the execute to finish, then
2340 three for the check_on_the_kids() function to return. With asynchronous
2341 queries, the script takes about 6 seconds to run, and gets in two
2342 iterations of check_on_the_kids in the process.
2343
2344 Here's an example showing the ability to cancel a long-running query.
2345 Imagine two slave databases in different geographic locations over a
2346 slow network. You need information as quickly as possible, so you query
2347 both at once. When you get an answer, you tell the other one to stop
2348 working on your query, as you don't need it anymore.
2349
2350 use strict;
2351 use warnings;
2352 use Time::HiRes 'sleep';
2353 use DBD::Pg ':async';
2354
2355 my $dbhslave1 = DBI->connect('dbi:Pg:dbname=postgres;host=slave1', 'postgres', '', {AutoCommit=>0,RaiseError=>1});
2356 my $dbhslave2 = DBI->connect('dbi:Pg:dbname=postgres;host=slave2', 'postgres', '', {AutoCommit=>0,RaiseError=>1});
2357
2358 $SQL = "SELECT count(*) FROM largetable WHERE flavor='blueberry'";
2359
2360 my $sth1 = $dbhslave1->prepare($SQL, {pg_async => PG_ASYNC});
2361 my $sth2 = $dbhslave2->prepare($SQL, {pg_async => PG_ASYNC});
2362
2363 $sth1->execute();
2364 $sth2->execute();
2365
2366 my $winner;
2367 while (!defined $winner) {
2368 if ($sth1->pg_ready) {
2369 $winner = 1;
2370 }
2371 elsif ($sth2->pg_ready) {
2372 $winner = 2;
2373 }
2374 Time::HiRes::sleep 0.05;
2375 }
2376
2377 my $count;
2378 if ($winner == 1) {
2379 $sth2->pg_cancel();
2380 $sth1->pg_result();
2381 $count = $sth1->fetchall_arrayref()->[0][0];
2382 }
2383 else {
2384 $sth1->pg_cancel();
2385 $sth2->pg_result();
2386 $count = $sth2->fetchall_arrayref()->[0][0];
2387 }
2388
2389 Array support
2390 DBD::Pg allows arrays (as arrayrefs) to be passed in to both the
2391 "quote" and the "execute" methods. In both cases, the array is
2392 flattened into a string representing a Postgres array.
2393
2394 When fetching rows from a table that contains a column with an array
2395 type, the result will be passed back to your script as an arrayref.
2396
2397 To turn off the automatic parsing of returned arrays into arrayrefs,
2398 you can set the attribute pg_expand_array, which is true by default.
2399
2400 $dbh->{pg_expand_array} = 0;
2401
2402 COPY support
2403 DBD::Pg allows for quick (bulk) reading and storing of data by using
2404 the COPY command. The basic process is to use "$dbh->do" to issue a
2405 COPY command, and then to either add rows using "pg_putcopydata", or to
2406 read them by using "pg_getcopydata".
2407
2408 The first step is to put the server into "COPY" mode. This is done by
2409 sending a complete COPY command to the server, by using the "do"
2410 method. For example:
2411
2412 $dbh->do("COPY foobar FROM STDIN");
2413
2414 This would tell the server to enter a COPY IN mode (yes, that's
2415 confusing, but the mode is COPY IN because of the command COPY FROM).
2416 It is now ready to receive information via the "pg_putcopydata" method.
2417 The complete syntax of the COPY command is more complex and not
2418 documented here: the canonical PostgreSQL documentation for COPY can be
2419 found at:
2420
2421 http://www.postgresql.org/docs/current/static/sql-copy.html
2422
2423 Once a COPY command has been issued, no other SQL commands are allowed
2424 until "pg_putcopyend" has been issued (for COPY FROM), or the final
2425 "pg_getcopydata" has been called (for COPY TO).
2426
2427 Note: All other COPY methods (pg_putline, pg_getline, etc.) are now
2428 heavily deprecated in favor of the pg_getcopydata, pg_putcopydata, and
2429 pg_putcopyend methods.
2430
2431 pg_getcopydata
2432
2433 Used to retrieve data from a table after the server has been put into a
2434 COPY OUT mode by calling "COPY tablename TO STDOUT". Data is always
2435 returned one data row at a time. The first argument to pg_getcopydata
2436 is the variable into which the data will be stored (this variable
2437 should not be undefined, or it may throw a warning, although it may be
2438 a reference). The pg_gecopydata method returns a number greater than 1
2439 indicating the new size of the variable, or a -1 when the COPY has
2440 finished. Once a -1 has been returned, no other action is necessary, as
2441 COPY mode will have already terminated. Example:
2442
2443 $dbh->do("COPY mytable TO STDOUT");
2444 my @data;
2445 my $x=0;
2446 1 while $dbh->pg_getcopydata($data[$x++]) >= 0;
2447
2448 There is also a variation of this method called pg_getcopydata_async,
2449 which, as the name suggests, returns immediately. The only difference
2450 from the original method is that this version may return a 0,
2451 indicating that the row is not ready to be delivered yet. When this
2452 happens, the variable has not been changed, and you will need to call
2453 the method again until you get a non-zero result. (Data is still
2454 always returned one data row at a time.)
2455
2456 pg_putcopydata
2457
2458 Used to put data into a table after the server has been put into COPY
2459 IN mode by calling "COPY tablename FROM STDIN". The only argument is
2460 the data you want inserted. Issue a pg_putcopyend() when you have added
2461 all your rows.
2462
2463 The default delimiter is a tab character, but this can be changed in
2464 the COPY statement. Returns a 1 on successful input. Examples:
2465
2466 ## Simple example:
2467 $dbh->do("COPY mytable FROM STDIN");
2468 $dbh->pg_putcopydata("123\tPepperoni\t3\n");
2469 $dbh->pg_putcopydata("314\tMushroom\t8\n");
2470 $dbh->pg_putcopydata("6\tAnchovies\t100\n");
2471 $dbh->pg_putcopyend();
2472
2473 ## This example uses explicit columns and a custom delimiter
2474 $dbh->do("COPY mytable(flavor, slices) FROM STDIN WITH DELIMITER '~'");
2475 $dbh->pg_putcopydata("Pepperoni~123\n");
2476 $dbh->pg_putcopydata("Mushroom~314\n");
2477 $dbh->pg_putcopydata("Anchovies~6\n");
2478 $dbh->pg_putcopyend();
2479
2480 pg_putcopyend
2481
2482 When you are finished with pg_putcopydata, call pg_putcopyend to let
2483 the server know that you are done, and it will return to a normal, non-
2484 COPY state. Returns a 1 on success. This method will fail if called
2485 when not in COPY IN mode.
2486
2487 Large Objects
2488 DBD::Pg supports all largeobject functions provided by libpq via the
2489 "$dbh->pg_lo*" methods. Please note that access to a large object, even
2490 read-only large objects, must be put into a transaction.
2491
2492 Cursors
2493 Although PostgreSQL supports cursors, they have not been used in the
2494 current implementation. When DBD::Pg was created, cursors in PostgreSQL
2495 could only be used inside a transaction block. Because only one
2496 transaction block at a time is allowed, this would have implied the
2497 restriction not to use any nested "SELECT" statements. Therefore the
2498 "execute" method fetches all data at once into data structures located
2499 in the front-end application. This fact must to be considered when
2500 selecting large amounts of data!
2501
2502 You can use cursors in your application, but you'll need to do a little
2503 work. First you must declare your cursor. Now you can issue queries
2504 against the cursor, then select against your queries. This typically
2505 results in a double loop, like this:
2506
2507 # WITH HOLD is not needed if AutoCommit is off
2508 $dbh->do("DECLARE csr CURSOR WITH HOLD FOR $sql");
2509 while (1) {
2510 my $sth = $dbh->prepare("fetch 1000 from csr");
2511 $sth->execute;
2512 last if 0 == $sth->rows;
2513
2514 while (my $row = $sth->fetchrow_hashref) {
2515 # Do something with the data.
2516 }
2517 }
2518 $dbh->do("CLOSE csr");
2519
2520 Datatype bool
2521 The current implementation of PostgreSQL returns 't' for true and 'f'
2522 for false. From the Perl point of view, this is a rather unfortunate
2523 choice. DBD::Pg therefore translates the result for the "BOOL" data
2524 type in a Perlish manner: 'f' becomes the number 0 and 't' becomes the
2525 number 1. This way the application does not have to check the database-
2526 specific returned values for the data-type "BOOL" because Perl treats 0
2527 as false and 1 as true. You may set the pg_bool_tf attribute to a true
2528 value to change the values back to 't' and 'f' if you wish.
2529
2530 Boolean values can be passed to PostgreSQL as TRUE, 't', 'true', 'y',
2531 'yes' or '1' for true and FALSE, 'f', 'false', 'n', 'no' or '0' for
2532 false.
2533
2534 Schema support
2535 The PostgreSQL schema concept may differ from those of other databases.
2536 In a nutshell, a schema is a named collection of objects within a
2537 single database. Please refer to the PostgreSQL documentation for more
2538 details:
2539
2540 <http://www.postgresql.org/docs/current/static/ddl-schemas.html>
2541
2542 DBD::Pg does not provide explicit support for PostgreSQL schemas.
2543 However, schema functionality may be used without any restrictions by
2544 explicitly addressing schema objects, e.g.
2545
2546 my $res = $dbh->selectall_arrayref("SELECT * FROM my_schema.my_table");
2547
2548 or by manipulating the schema search path with "SET search_path", e.g.
2549
2550 $dbh->do("SET search_path TO my_schema, public");
2551
2554 To report a bug, or view the current list of bugs, please visit
2555 http://rt.cpan.org/Public/Dist/Display.html?Name=DBD-Pg
2556
2558 Patches can be submitted to rt.cpan.org. Detailed information on how to
2559 help out with this module can be found in the README.dev file. The
2560 latest development version can be obtained via: git clone
2561 git://bucardo.org/dbdpg.git
2562
2564 DBI by Tim Bunce <http://www.tim.bunce.name>
2565
2566 The original DBD-Pg was by Edmund Mergl (E.Mergl@bawue.de) and Jeffrey
2567 W. Baker (jwbaker@acm.org). Major developers include David Wheeler
2568 <david@justatheory.com>, Jason Stewart <jason@openinformatics.com>,
2569 Bruce Momjian <pgman@candle.pha.pa.us>, and Greg Sabino Mullane
2570 <greg@turnstep.com>, with help from many others: see the Changes file
2571 for a complete list.
2572
2573 Parts of this package were originally copied from DBI and DBD-Oracle.
2574
2575 Mailing List
2576
2577 The current maintainers may be reached through the 'dbd-pg' mailing
2578 list: <dbd-pg@perl.org>
2579
2581 Copyright (C) 1994-2012, Greg Sabino Mullane
2582
2583 This module (DBD::Pg) is free software; you can redistribute it and/or
2584 modify it under the same terms as Perl 5.10.0. For more details, see
2585 the full text of the licenses in the directory LICENSES.
2586
2587
2588
2589perl v5.16.3 2012-08-21 Pg(3)