-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathlibpq.sgml
8814 lines (7771 loc) · 334 KB
/
libpq.sgml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!-- doc/src/sgml/libpq.sgml -->
<chapter id="libpq">
<title><application>libpq</application> — C Library</title>
<indexterm zone="libpq">
<primary>libpq</primary>
</indexterm>
<indexterm zone="libpq">
<primary>C</primary>
</indexterm>
<para>
<application>libpq</application> is the <acronym>C</acronym>
application programmer's interface to <productname>PostgreSQL</productname>.
<application>libpq</application> is a set of library functions that allow
client programs to pass queries to the <productname>PostgreSQL</productname>
backend server and to receive the results of these queries.
</para>
<para>
<application>libpq</application> is also the underlying engine for several
other <productname>PostgreSQL</productname> application interfaces, including
those written for C++, Perl, Python, Tcl and <application>ECPG</application>.
So some aspects of <application>libpq</application>'s behavior will be
important to you if you use one of those packages. In particular,
<xref linkend="libpq-envars"/>,
<xref linkend="libpq-pgpass"/> and
<xref linkend="libpq-ssl"/>
describe behavior that is visible to the user of any application
that uses <application>libpq</application>.
</para>
<para>
Some short programs are included at the end of this chapter (<xref linkend="libpq-example"/>) to show how
to write programs that use <application>libpq</application>. There are also several
complete examples of <application>libpq</application> applications in the
directory <filename>src/test/examples</filename> in the source code distribution.
</para>
<para>
Client programs that use <application>libpq</application> must
include the header file
<filename>libpq-fe.h</filename><indexterm><primary>libpq-fe.h</primary></indexterm>
and must link with the <application>libpq</application> library.
</para>
<sect1 id="libpq-connect">
<title>Database Connection Control Functions</title>
<para>
The following functions deal with making a connection to a
<productname>PostgreSQL</productname> backend server. An
application program can have several backend connections open at
one time. (One reason to do that is to access more than one
database.) Each connection is represented by a
<structname>PGconn</structname><indexterm><primary>PGconn</primary></indexterm> object, which
is obtained from the function <xref linkend="libpq-PQconnectdb"/>,
<xref linkend="libpq-PQconnectdbParams"/>, or
<xref linkend="libpq-PQsetdbLogin"/>. Note that these functions will always
return a non-null object pointer, unless perhaps there is too
little memory even to allocate the <structname>PGconn</structname> object.
The <xref linkend="libpq-PQstatus"/> function should be called to check
the return value for a successful connection before queries are sent
via the connection object.
<warning>
<para>
If untrusted users have access to a database that has not adopted a
<link linkend="ddl-schemas-patterns">secure schema usage pattern</link>,
begin each session by removing publicly-writable schemas from
<varname>search_path</varname>. One can set parameter key
word <literal>options</literal> to
value <literal>-csearch_path=</literal>. Alternately, one can
issue <literal>PQexec(<replaceable>conn</replaceable>, "SELECT
pg_catalog.set_config('search_path', '', false)")</literal> after
connecting. This consideration is not specific
to <application>libpq</application>; it applies to every interface for
executing arbitrary SQL commands.
</para>
</warning>
<warning>
<para>
On Unix, forking a process with open libpq connections can lead to
unpredictable results because the parent and child processes share
the same sockets and operating system resources. For this reason,
such usage is not recommended, though doing an <function>exec</function> from
the child process to load a new executable is safe.
</para>
</warning>
<variablelist>
<varlistentry id="libpq-PQconnectdbParams">
<term><function>PQconnectdbParams</function><indexterm><primary>PQconnectdbParams</primary></indexterm></term>
<listitem>
<para>
Makes a new connection to the database server.
<synopsis>
PGconn *PQconnectdbParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
</synopsis>
</para>
<para>
This function opens a new database connection using the parameters taken
from two <symbol>NULL</symbol>-terminated arrays. The first,
<literal>keywords</literal>, is defined as an array of strings, each one
being a key word. The second, <literal>values</literal>, gives the value
for each key word. Unlike <xref linkend="libpq-PQsetdbLogin"/> below, the parameter
set can be extended without changing the function signature, so use of
this function (or its nonblocking analogs <xref linkend="libpq-PQconnectStartParams"/>
and <function>PQconnectPoll</function>) is preferred for new application
programming.
</para>
<para>
The currently recognized parameter key words are listed in
<xref linkend="libpq-paramkeywords"/>.
</para>
<para>
The passed arrays can be empty to use all default parameters, or can
contain one or more parameter settings. They must be matched in length.
Processing will stop at the first <symbol>NULL</symbol> entry
in the <literal>keywords</literal> array.
Also, if the <literal>values</literal> entry associated with a
non-<symbol>NULL</symbol> <literal>keywords</literal> entry is
<symbol>NULL</symbol> or an empty string, that entry is ignored and
processing continues with the next pair of array entries.
</para>
<para>
When <literal>expand_dbname</literal> is non-zero, the value for
the first <parameter>dbname</parameter> key word is checked to see
if it is a <firstterm>connection string</firstterm>. If so, it
is <quote>expanded</quote> into the individual connection
parameters extracted from the string. The value is considered to
be a connection string, rather than just a database name, if it
contains an equal sign (<literal>=</literal>) or it begins with a
URI scheme designator. (More details on connection string formats
appear in <xref linkend="libpq-connstring"/>.) Only the first
occurrence of <parameter>dbname</parameter> is treated in this way;
any subsequent <parameter>dbname</parameter> parameter is processed
as a plain database name.
</para>
<para>
In general the parameter arrays are processed from start to end.
If any key word is repeated, the last value (that is
not <symbol>NULL</symbol> or empty) is used. This rule applies in
particular when a key word found in a connection string conflicts
with one appearing in the <literal>keywords</literal> array. Thus,
the programmer may determine whether array entries can override or
be overridden by values taken from a connection string. Array
entries appearing before an expanded <parameter>dbname</parameter>
entry can be overridden by fields of the connection string, and in
turn those fields are overridden by array entries appearing
after <parameter>dbname</parameter> (but, again, only if those
entries supply non-empty values).
</para>
<para>
After processing all the array entries and any expanded connection
string, any connection parameters that remain unset are filled with
default values. If an unset parameter's corresponding environment
variable (see <xref linkend="libpq-envars"/>) is set, its value is
used. If the environment variable is not set either, then the
parameter's built-in default value is used.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQconnectdb">
<term><function>PQconnectdb</function><indexterm><primary>PQconnectdb</primary></indexterm></term>
<listitem>
<para>
Makes a new connection to the database server.
<synopsis>
PGconn *PQconnectdb(const char *conninfo);
</synopsis>
</para>
<para>
This function opens a new database connection using the parameters taken
from the string <literal>conninfo</literal>.
</para>
<para>
The passed string can be empty to use all default parameters, or it can
contain one or more parameter settings separated by whitespace,
or it can contain a <acronym>URI</acronym>.
See <xref linkend="libpq-connstring"/> for details.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQsetdbLogin">
<term><function>PQsetdbLogin</function><indexterm><primary>PQsetdbLogin</primary></indexterm></term>
<listitem>
<para>
Makes a new connection to the database server.
<synopsis>
PGconn *PQsetdbLogin(const char *pghost,
const char *pgport,
const char *pgoptions,
const char *pgtty,
const char *dbName,
const char *login,
const char *pwd);
</synopsis>
</para>
<para>
This is the predecessor of <xref linkend="libpq-PQconnectdb"/> with a fixed
set of parameters. It has the same functionality except that the
missing parameters will always take on default values. Write <symbol>NULL</symbol> or an
empty string for any one of the fixed parameters that is to be defaulted.
</para>
<para>
If the <parameter>dbName</parameter> contains
an <symbol>=</symbol> sign or has a valid connection <acronym>URI</acronym> prefix, it
is taken as a <parameter>conninfo</parameter> string in exactly the same way as
if it had been passed to <xref linkend="libpq-PQconnectdb"/>, and the remaining
parameters are then applied as specified for <xref linkend="libpq-PQconnectdbParams"/>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQsetdb">
<term><function>PQsetdb</function><indexterm><primary>PQsetdb</primary></indexterm></term>
<listitem>
<para>
Makes a new connection to the database server.
<synopsis>
PGconn *PQsetdb(char *pghost,
char *pgport,
char *pgoptions,
char *pgtty,
char *dbName);
</synopsis>
</para>
<para>
This is a macro that calls <xref linkend="libpq-PQsetdbLogin"/> with null pointers
for the <parameter>login</parameter> and <parameter>pwd</parameter> parameters. It is provided
for backward compatibility with very old programs.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQconnectStartParams">
<term><function>PQconnectStartParams</function><indexterm><primary>PQconnectStartParams</primary></indexterm></term>
<term><function>PQconnectStart</function><indexterm><primary>PQconnectStart</primary></indexterm></term>
<term><function>PQconnectPoll</function><indexterm><primary>PQconnectPoll</primary></indexterm></term>
<listitem>
<para>
<indexterm><primary>nonblocking connection</primary></indexterm>
Make a connection to the database server in a nonblocking manner.
<synopsis>
PGconn *PQconnectStartParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
PGconn *PQconnectStart(const char *conninfo);
PostgresPollingStatusType PQconnectPoll(PGconn *conn);
</synopsis>
</para>
<para>
These three functions are used to open a connection to a database server such
that your application's thread of execution is not blocked on remote I/O
whilst doing so. The point of this approach is that the waits for I/O to
complete can occur in the application's main loop, rather than down inside
<xref linkend="libpq-PQconnectdbParams"/> or <xref linkend="libpq-PQconnectdb"/>, and so the
application can manage this operation in parallel with other activities.
</para>
<para>
With <xref linkend="libpq-PQconnectStartParams"/>, the database connection is made
using the parameters taken from the <literal>keywords</literal> and
<literal>values</literal> arrays, and controlled by <literal>expand_dbname</literal>,
as described above for <xref linkend="libpq-PQconnectdbParams"/>.
</para>
<para>
With <function>PQconnectStart</function>, the database connection is made
using the parameters taken from the string <literal>conninfo</literal> as
described above for <xref linkend="libpq-PQconnectdb"/>.
</para>
<para>
Neither <xref linkend="libpq-PQconnectStartParams"/> nor <function>PQconnectStart</function>
nor <function>PQconnectPoll</function> will block, so long as a number of
restrictions are met:
<itemizedlist>
<listitem>
<para>
The <literal>hostaddr</literal> parameter must be used appropriately
to prevent DNS queries from being made. See the documentation of
this parameter in <xref linkend="libpq-paramkeywords"/> for details.
</para>
</listitem>
<listitem>
<para>
If you call <xref linkend="libpq-PQtrace"/>, ensure that the stream object
into which you trace will not block.
</para>
</listitem>
<listitem>
<para>
You must ensure that the socket is in the appropriate state
before calling <function>PQconnectPoll</function>, as described below.
</para>
</listitem>
</itemizedlist>
</para>
<para>
To begin a nonblocking connection request,
call <function>PQconnectStart</function>
or <xref linkend="libpq-PQconnectStartParams"/>. If the result is null,
then <application>libpq</application> has been unable to allocate a
new <structname>PGconn</structname> structure. Otherwise, a
valid <structname>PGconn</structname> pointer is returned (though not
yet representing a valid connection to the database). Next
call <literal>PQstatus(conn)</literal>. If the result
is <symbol>CONNECTION_BAD</symbol>, the connection attempt has already
failed, typically because of invalid connection parameters.
</para>
<para>
If <function>PQconnectStart</function>
or <xref linkend="libpq-PQconnectStartParams"/> succeeds, the next stage
is to poll <application>libpq</application> so that it can proceed with
the connection sequence.
Use <function>PQsocket(conn)</function> to obtain the descriptor of the
socket underlying the database connection.
(Caution: do not assume that the socket remains the same
across <function>PQconnectPoll</function> calls.)
Loop thus: If <function>PQconnectPoll(conn)</function> last returned
<symbol>PGRES_POLLING_READING</symbol>, wait until the socket is ready to
read (as indicated by <function>select()</function>, <function>poll()</function>, or
similar system function).
Then call <function>PQconnectPoll(conn)</function> again.
Conversely, if <function>PQconnectPoll(conn)</function> last returned
<symbol>PGRES_POLLING_WRITING</symbol>, wait until the socket is ready
to write, then call <function>PQconnectPoll(conn)</function> again.
On the first iteration, i.e., if you have yet to call
<function>PQconnectPoll</function>, behave as if it last returned
<symbol>PGRES_POLLING_WRITING</symbol>. Continue this loop until
<function>PQconnectPoll(conn)</function> returns
<symbol>PGRES_POLLING_FAILED</symbol>, indicating the connection procedure
has failed, or <symbol>PGRES_POLLING_OK</symbol>, indicating the connection
has been successfully made.
</para>
<para>
At any time during connection, the status of the connection can be
checked by calling <xref linkend="libpq-PQstatus"/>. If this call returns <symbol>CONNECTION_BAD</symbol>, then the
connection procedure has failed; if the call returns <function>CONNECTION_OK</function>, then the
connection is ready. Both of these states are equally detectable
from the return value of <function>PQconnectPoll</function>, described above. Other states might also occur
during (and only during) an asynchronous connection procedure. These
indicate the current stage of the connection procedure and might be useful
to provide feedback to the user for example. These statuses are:
<variablelist>
<varlistentry id="libpq-connection-started">
<term><symbol>CONNECTION_STARTED</symbol></term>
<listitem>
<para>
Waiting for connection to be made.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-made">
<term><symbol>CONNECTION_MADE</symbol></term>
<listitem>
<para>
Connection OK; waiting to send.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-awaiting-response">
<term><symbol>CONNECTION_AWAITING_RESPONSE</symbol></term>
<listitem>
<para>
Waiting for a response from the server.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-auth-ok">
<term><symbol>CONNECTION_AUTH_OK</symbol></term>
<listitem>
<para>
Received authentication; waiting for backend start-up to finish.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-ssl-startup">
<term><symbol>CONNECTION_SSL_STARTUP</symbol></term>
<listitem>
<para>
Negotiating SSL encryption.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-setenv">
<term><symbol>CONNECTION_SETENV</symbol></term>
<listitem>
<para>
Negotiating environment-driven parameter settings.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-check-writable">
<term><symbol>CONNECTION_CHECK_WRITABLE</symbol></term>
<listitem>
<para>
Checking if connection is able to handle write transactions.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-connection-consume">
<term><symbol>CONNECTION_CONSUME</symbol></term>
<listitem>
<para>
Consuming any remaining response messages on connection.
</para>
</listitem>
</varlistentry>
</variablelist>
Note that, although these constants will remain (in order to maintain
compatibility), an application should never rely upon these occurring in a
particular order, or at all, or on the status always being one of these
documented values. An application might do something like this:
<programlisting>
switch(PQstatus(conn))
{
case CONNECTION_STARTED:
feedback = "Connecting...";
break;
case CONNECTION_MADE:
feedback = "Connected to server...";
break;
.
.
.
default:
feedback = "Connecting...";
}
</programlisting>
</para>
<para>
The <literal>connect_timeout</literal> connection parameter is ignored
when using <function>PQconnectPoll</function>; it is the application's
responsibility to decide whether an excessive amount of time has elapsed.
Otherwise, <function>PQconnectStart</function> followed by a
<function>PQconnectPoll</function> loop is equivalent to
<xref linkend="libpq-PQconnectdb"/>.
</para>
<para>
Note that when <function>PQconnectStart</function>
or <xref linkend="libpq-PQconnectStartParams"/> returns a non-null
pointer, you must call <xref linkend="libpq-PQfinish"/> when you are
finished with it, in order to dispose of the structure and any
associated memory blocks. This must be done even if the connection
attempt fails or is abandoned.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQconndefaults">
<term><function>PQconndefaults</function><indexterm><primary>PQconndefaults</primary></indexterm></term>
<listitem>
<para>
Returns the default connection options.
<synopsis>
PQconninfoOption *PQconndefaults(void);
typedef struct
{
char *keyword; /* The keyword of the option */
char *envvar; /* Fallback environment variable name */
char *compiled; /* Fallback compiled in default value */
char *val; /* Option's current value, or NULL */
char *label; /* Label for field in connect dialog */
char *dispchar; /* Indicates how to display this field
in a connect dialog. Values are:
"" Display entered value as is
"*" Password field - hide value
"D" Debug option - don't show by default */
int dispsize; /* Field size in characters for dialog */
} PQconninfoOption;
</synopsis>
</para>
<para>
Returns a connection options array. This can be used to determine
all possible <xref linkend="libpq-PQconnectdb"/> options and their
current default values. The return value points to an array of
<structname>PQconninfoOption</structname> structures, which ends
with an entry having a null <structfield>keyword</structfield> pointer. The
null pointer is returned if memory could not be allocated. Note that
the current default values (<structfield>val</structfield> fields)
will depend on environment variables and other context. A
missing or invalid service file will be silently ignored. Callers
must treat the connection options data as read-only.
</para>
<para>
After processing the options array, free it by passing it to
<xref linkend="libpq-PQconninfoFree"/>. If this is not done, a small amount of memory
is leaked for each call to <xref linkend="libpq-PQconndefaults"/>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQconninfo">
<term><function>PQconninfo</function><indexterm><primary>PQconninfo</primary></indexterm></term>
<listitem>
<para>
Returns the connection options used by a live connection.
<synopsis>
PQconninfoOption *PQconninfo(PGconn *conn);
</synopsis>
</para>
<para>
Returns a connection options array. This can be used to determine
all possible <xref linkend="libpq-PQconnectdb"/> options and the
values that were used to connect to the server. The return
value points to an array of <structname>PQconninfoOption</structname>
structures, which ends with an entry having a null <structfield>keyword</structfield>
pointer. All notes above for <xref linkend="libpq-PQconndefaults"/> also
apply to the result of <xref linkend="libpq-PQconninfo"/>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQconninfoParse">
<term><function>PQconninfoParse</function><indexterm><primary>PQconninfoParse</primary></indexterm></term>
<listitem>
<para>
Returns parsed connection options from the provided connection string.
<synopsis>
PQconninfoOption *PQconninfoParse(const char *conninfo, char **errmsg);
</synopsis>
</para>
<para>
Parses a connection string and returns the resulting options as an
array; or returns <symbol>NULL</symbol> if there is a problem with the connection
string. This function can be used to extract
the <xref linkend="libpq-PQconnectdb"/> options in the provided
connection string. The return value points to an array of
<structname>PQconninfoOption</structname> structures, which ends
with an entry having a null <structfield>keyword</structfield> pointer.
</para>
<para>
All legal options will be present in the result array, but the
<literal>PQconninfoOption</literal> for any option not present
in the connection string will have <literal>val</literal> set to
<literal>NULL</literal>; default values are not inserted.
</para>
<para>
If <literal>errmsg</literal> is not <symbol>NULL</symbol>, then <literal>*errmsg</literal> is set
to <symbol>NULL</symbol> on success, else to a <function>malloc</function>'d error string explaining
the problem. (It is also possible for <literal>*errmsg</literal> to be
set to <symbol>NULL</symbol> and the function to return <symbol>NULL</symbol>;
this indicates an out-of-memory condition.)
</para>
<para>
After processing the options array, free it by passing it to
<xref linkend="libpq-PQconninfoFree"/>. If this is not done, some memory
is leaked for each call to <xref linkend="libpq-PQconninfoParse"/>.
Conversely, if an error occurs and <literal>errmsg</literal> is not <symbol>NULL</symbol>,
be sure to free the error string using <xref linkend="libpq-PQfreemem"/>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQfinish">
<term><function>PQfinish</function><indexterm><primary>PQfinish</primary></indexterm></term>
<listitem>
<para>
Closes the connection to the server. Also frees
memory used by the <structname>PGconn</structname> object.
<synopsis>
void PQfinish(PGconn *conn);
</synopsis>
</para>
<para>
Note that even if the server connection attempt fails (as
indicated by <xref linkend="libpq-PQstatus"/>), the application should call <xref linkend="libpq-PQfinish"/>
to free the memory used by the <structname>PGconn</structname> object.
The <structname>PGconn</structname> pointer must not be used again after
<xref linkend="libpq-PQfinish"/> has been called.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQreset">
<term><function>PQreset</function><indexterm><primary>PQreset</primary></indexterm></term>
<listitem>
<para>
Resets the communication channel to the server.
<synopsis>
void PQreset(PGconn *conn);
</synopsis>
</para>
<para>
This function will close the connection
to the server and attempt to establish a new
connection, using all the same
parameters previously used. This might be useful for
error recovery if a working connection is lost.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQresetStart">
<term><function>PQresetStart</function><indexterm><primary>PQresetStart</primary></indexterm></term>
<term><function>PQresetPoll</function><indexterm><primary>PQresetPoll</primary></indexterm></term>
<listitem>
<para>
Reset the communication channel to the server, in a nonblocking manner.
<synopsis>
int PQresetStart(PGconn *conn);
PostgresPollingStatusType PQresetPoll(PGconn *conn);
</synopsis>
</para>
<para>
These functions will close the connection to the server and attempt to
establish a new connection, using all the same
parameters previously used. This can be useful for error recovery if a
working connection is lost. They differ from <xref linkend="libpq-PQreset"/> (above) in that they
act in a nonblocking manner. These functions suffer from the same
restrictions as <xref linkend="libpq-PQconnectStartParams"/>, <function>PQconnectStart</function>
and <function>PQconnectPoll</function>.
</para>
<para>
To initiate a connection reset, call
<xref linkend="libpq-PQresetStart"/>. If it returns 0, the reset has
failed. If it returns 1, poll the reset using
<function>PQresetPoll</function> in exactly the same way as you
would create the connection using <function>PQconnectPoll</function>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQpingParams">
<term><function>PQpingParams</function><indexterm><primary>PQpingParams</primary></indexterm></term>
<listitem>
<para>
<xref linkend="libpq-PQpingParams"/> reports the status of the
server. It accepts connection parameters identical to those of
<xref linkend="libpq-PQconnectdbParams"/>, described above. It is not
necessary to supply correct user name, password, or database name
values to obtain the server status; however, if incorrect values
are provided, the server will log a failed connection attempt.
<synopsis>
PGPing PQpingParams(const char * const *keywords,
const char * const *values,
int expand_dbname);
</synopsis>
The function returns one of the following values:
<variablelist>
<varlistentry id="libpq-PQpingParams-PQPING_OK">
<term><literal>PQPING_OK</literal></term>
<listitem>
<para>
The server is running and appears to be accepting connections.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQpingParams-PQPING_REJECT">
<term><literal>PQPING_REJECT</literal></term>
<listitem>
<para>
The server is running but is in a state that disallows connections
(startup, shutdown, or crash recovery).
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQpingParams-PQPING_NO_RESPONSE">
<term><literal>PQPING_NO_RESPONSE</literal></term>
<listitem>
<para>
The server could not be contacted. This might indicate that the
server is not running, or that there is something wrong with the
given connection parameters (for example, wrong port number), or
that there is a network connectivity problem (for example, a
firewall blocking the connection request).
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQpingParams-PQPING_NO_ATTEMPT">
<term><literal>PQPING_NO_ATTEMPT</literal></term>
<listitem>
<para>
No attempt was made to contact the server, because the supplied
parameters were obviously incorrect or there was some client-side
problem (for example, out of memory).
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-PQping">
<term><function>PQping</function><indexterm><primary>PQping</primary></indexterm></term>
<listitem>
<para>
<xref linkend="libpq-PQping"/> reports the status of the
server. It accepts connection parameters identical to those of
<xref linkend="libpq-PQconnectdb"/>, described above. It is not
necessary to supply correct user name, password, or database name
values to obtain the server status; however, if incorrect values
are provided, the server will log a failed connection attempt.
<synopsis>
PGPing PQping(const char *conninfo);
</synopsis>
</para>
<para>
The return values are the same as for <xref linkend="libpq-PQpingParams"/>.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-pqsetsslkeypasshook-openssl">
<term><function>PQsetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQsetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
<listitem>
<para>
<function>PQsetSSLKeyPassHook_OpenSSL</function> lets an application override
<application>libpq</application>'s <link linkend="libpq-ssl-clientcert">default
handling of encrypted client certificate key files</link> using
<xref linkend="libpq-connect-sslpassword"/> or interactive prompting.
<synopsis>
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook);
</synopsis>
The application passes a pointer to a callback function with signature:
<programlisting>
int callback_fn(char *buf, int size, PGconn *conn);
</programlisting>
which <application>libpq</application> will then call
<emphasis>instead of</emphasis> its default
<function>PQdefaultSSLKeyPassHook_OpenSSL</function> handler. The
callback should determine the password for the key and copy it to
result-buffer <parameter>buf</parameter> of size
<parameter>size</parameter>. The string in <parameter>buf</parameter>
must be null-terminated. The callback must return the length of the
password stored in <parameter>buf</parameter> excluding the null
terminator. On failure, the callback should set
<literal>buf[0] = '\0'</literal> and return 0. See
<function>PQdefaultSSLKeyPassHook_OpenSSL</function> in
<application>libpq</application>'s source code for an example.
</para>
<para>
If the user specified an explicit key location,
its path will be in <literal>conn->sslkey</literal> when the callback
is invoked. This will be empty if the default key path is being used.
For keys that are engine specifiers, it is up to engine implementations
whether they use the OpenSSL password callback or define their own handling.
</para>
<para>
The app callback may choose to delegate unhandled cases to
<function>PQdefaultSSLKeyPassHook_OpenSSL</function>,
or call it first and try something else if it returns 0, or completely override it.
</para>
<para>
The callback <emphasis>must not</emphasis> escape normal flow control with exceptions,
<function>longjmp(...)</function>, etc. It must return normally.
</para>
</listitem>
</varlistentry>
<varlistentry id="libpq-pqgetsslkeypasshook-openssl">
<term><function>PQgetSSLKeyPassHook_OpenSSL</function><indexterm><primary>PQgetSSLKeyPassHook_OpenSSL</primary></indexterm></term>
<listitem>
<para>
<function>PQgetSSLKeyPassHook_OpenSSL</function> returns the current
client certificate key password hook, or <literal>NULL</literal>
if none has been set.
<synopsis>
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void);
</synopsis>
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
<sect2 id="libpq-connstring">
<title>Connection Strings</title>
<indexterm zone="libpq-connstring">
<primary><literal>conninfo</literal></primary>
</indexterm>
<indexterm zone="libpq-connstring">
<primary><literal>URI</literal></primary>
</indexterm>
<para>
Several <application>libpq</application> functions parse a user-specified string to obtain
connection parameters. There are two accepted formats for these strings:
plain keyword/value strings
and URIs. URIs generally follow
<ulink url="https://tools.ietf.org/html/rfc3986">RFC
3986</ulink>, except that multi-host connection strings are allowed
as further described below.
</para>
<sect3>
<title>Keyword/Value Connection Strings</title>
<para>
In the keyword/value format, each parameter setting is in the form
<replaceable>keyword</replaceable> <literal>=</literal>
<replaceable>value</replaceable>, with space(s) between settings.
Spaces around a setting's equal sign are
optional. To write an empty value, or a value containing spaces, surround it
with single quotes, for example <literal>keyword = 'a value'</literal>.
Single quotes and backslashes within
a value must be escaped with a backslash, i.e., <literal>\'</literal> and
<literal>\\</literal>.
</para>
<para>
Example:
<programlisting>
host=localhost port=5432 dbname=mydb connect_timeout=10
</programlisting>
</para>
<para>
The recognized parameter key words are listed in <xref
linkend="libpq-paramkeywords"/>.
</para>
</sect3>
<sect3>
<title>Connection URIs</title>
<para>
The general form for a connection <acronym>URI</acronym> is:
<synopsis>
postgresql://<optional><replaceable>userspec</replaceable>@</optional><optional><replaceable>hostspec</replaceable></optional><optional>/<replaceable>dbname</replaceable></optional><optional>?<replaceable>paramspec</replaceable></optional>
<phrase>where <replaceable>userspec</replaceable> is:</phrase>
<replaceable>user</replaceable><optional>:<replaceable>password</replaceable></optional>
<phrase>and <replaceable>hostspec</replaceable> is:</phrase>
<optional><replaceable>host</replaceable></optional><optional>:<replaceable>port</replaceable></optional><optional>,...</optional>
<phrase>and <replaceable>paramspec</replaceable> is:</phrase>
<replaceable>name</replaceable>=<replaceable>value</replaceable><optional>&...</optional>
</synopsis>
</para>
<para>
The <acronym>URI</acronym> scheme designator can be either
<literal>postgresql://</literal> or <literal>postgres://</literal>. Each
of the remaining <acronym>URI</acronym> parts is optional. The
following examples illustrate valid <acronym>URI</acronym> syntax:
<programlisting>
postgresql://
postgresql://localhost
postgresql://localhost:5433
postgresql://localhost/mydb
postgresql://user@localhost
postgresql://user:secret@localhost
postgresql://other@localhost/otherdb?connect_timeout=10&application_name=myapp
postgresql://host1:123,host2:456/somedb?target_session_attrs=any&application_name=myapp
</programlisting>
Values that would normally appear in the hierarchical part of
the <acronym>URI</acronym> can alternatively be given as named
parameters. For example:
<programlisting>
postgresql:///mydb?host=localhost&port=5433
</programlisting>
All named parameters must match key words listed in
<xref linkend="libpq-paramkeywords"/>, except that for compatibility
with JDBC connection <acronym>URI</acronym>s, instances
of <literal>ssl=true</literal> are translated into
<literal>sslmode=require</literal>.
</para>
<para>
The connection <acronym>URI</acronym> needs to be encoded with <ulink
url="https://tools.ietf.org/html/rfc3986#section-2.1">percent-encoding</ulink>
if it includes symbols with special meaning in any of its parts. Here is
an example where the equal sign (<literal>=</literal>) is replaced with
<literal>%3D</literal> and the space character with
<literal>%20</literal>:
<programlisting>
postgresql://user@localhost:5433/mydb?options=-c%20synchronous_commit%3Doff
</programlisting>
</para>
<para>
The host part may be either a host name or an IP address. To specify an
IPv6 address, enclose it in square brackets:
<synopsis>
postgresql://[2001:db8::1234]/database
</synopsis>
</para>
<para>
The host part is interpreted as described for the parameter <xref
linkend="libpq-connect-host"/>. In particular, a Unix-domain socket
connection is chosen if the host part is either empty or looks like an
absolute path name,
otherwise a TCP/IP connection is initiated. Note, however, that the
slash is a reserved character in the hierarchical part of the URI. So, to
specify a non-standard Unix-domain socket directory, either omit the host
part of the URI and specify the host as a named parameter, or
percent-encode the path in the host part of the URI:
<programlisting>
postgresql:///dbname?host=/var/lib/postgresql
postgresql://%2Fvar%2Flib%2Fpostgresql/dbname
</programlisting>
</para>
<para>
It is possible to specify multiple host components, each with an optional
port component, in a single URI. A URI of the form
<literal>postgresql://host1:port1,host2:port2,host3:port3/</literal>
is equivalent to a connection string of the form
<literal>host=host1,host2,host3 port=port1,port2,port3</literal>.
As further described below, each
host will be tried in turn until a connection is successfully established.
</para>
</sect3>
<sect3 id="libpq-multiple-hosts">