]> begriffs open source - ai-pg/blob - full-docs/txt/libpq-copy.txt
Convert HTML docs to more streamlined TXT
[ai-pg] / full-docs / txt / libpq-copy.txt
1
2 32.10. Functions Associated with the COPY Command #
3
4    32.10.1. Functions for Sending COPY Data
5    32.10.2. Functions for Receiving COPY Data
6    32.10.3. Obsolete Functions for COPY
7
8    The COPY command in PostgreSQL has options to read from or write to the
9    network connection used by libpq. The functions described in this
10    section allow applications to take advantage of this capability by
11    supplying or consuming copied data.
12
13    The overall process is that the application first issues the SQL COPY
14    command via PQexec or one of the equivalent functions. The response to
15    this (if there is no error in the command) will be a PGresult object
16    bearing a status code of PGRES_COPY_OUT or PGRES_COPY_IN (depending on
17    the specified copy direction). The application should then use the
18    functions of this section to receive or transmit data rows. When the
19    data transfer is complete, another PGresult object is returned to
20    indicate success or failure of the transfer. Its status will be
21    PGRES_COMMAND_OK for success or PGRES_FATAL_ERROR if some problem was
22    encountered. At this point further SQL commands can be issued via
23    PQexec. (It is not possible to execute other SQL commands using the
24    same connection while the COPY operation is in progress.)
25
26    If a COPY command is issued via PQexec in a string that could contain
27    additional commands, the application must continue fetching results via
28    PQgetResult after completing the COPY sequence. Only when PQgetResult
29    returns NULL is it certain that the PQexec command string is done and
30    it is safe to issue more commands.
31
32    The functions of this section should be executed only after obtaining a
33    result status of PGRES_COPY_OUT or PGRES_COPY_IN from PQexec or
34    PQgetResult.
35
36    A PGresult object bearing one of these status values carries some
37    additional data about the COPY operation that is starting. This
38    additional data is available using functions that are also used in
39    connection with query results:
40
41    PQnfields #
42           Returns the number of columns (fields) to be copied.
43
44    PQbinaryTuples #
45           0 indicates the overall copy format is textual (rows separated
46           by newlines, columns separated by separator characters, etc.). 1
47           indicates the overall copy format is binary. See COPY for more
48           information.
49
50    PQfformat #
51           Returns the format code (0 for text, 1 for binary) associated
52           with each column of the copy operation. The per-column format
53           codes will always be zero when the overall copy format is
54           textual, but the binary format can support both text and binary
55           columns. (However, as of the current implementation of COPY,
56           only binary columns appear in a binary copy; so the per-column
57           formats always match the overall format at present.)
58
59 32.10.1. Functions for Sending COPY Data #
60
61    These functions are used to send data during COPY FROM STDIN. They will
62    fail if called when the connection is not in COPY_IN state.
63
64    PQputCopyData #
65           Sends data to the server during COPY_IN state.
66
67 int PQputCopyData(PGconn *conn,
68                   const char *buffer,
69                   int nbytes);
70
71           Transmits the COPY data in the specified buffer, of length
72           nbytes, to the server. The result is 1 if the data was queued,
73           zero if it was not queued because of full buffers (this will
74           only happen in nonblocking mode), or -1 if an error occurred.
75           (Use PQerrorMessage to retrieve details if the return value is
76           -1. If the value is zero, wait for write-ready and try again.)
77
78           The application can divide the COPY data stream into buffer
79           loads of any convenient size. Buffer-load boundaries have no
80           semantic significance when sending. The contents of the data
81           stream must match the data format expected by the COPY command;
82           see COPY for details.
83
84    PQputCopyEnd #
85           Sends end-of-data indication to the server during COPY_IN state.
86
87 int PQputCopyEnd(PGconn *conn,
88                  const char *errormsg);
89
90           Ends the COPY_IN operation successfully if errormsg is NULL. If
91           errormsg is not NULL then the COPY is forced to fail, with the
92           string pointed to by errormsg used as the error message. (One
93           should not assume that this exact error message will come back
94           from the server, however, as the server might have already
95           failed the COPY for its own reasons.)
96
97           The result is 1 if the termination message was sent; or in
98           nonblocking mode, this may only indicate that the termination
99           message was successfully queued. (In nonblocking mode, to be
100           certain that the data has been sent, you should next wait for
101           write-ready and call PQflush, repeating until it returns zero.)
102           Zero indicates that the function could not queue the termination
103           message because of full buffers; this will only happen in
104           nonblocking mode. (In this case, wait for write-ready and try
105           the PQputCopyEnd call again.) If a hard error occurs, -1 is
106           returned; you can use PQerrorMessage to retrieve details.
107
108           After successfully calling PQputCopyEnd, call PQgetResult to
109           obtain the final result status of the COPY command. One can wait
110           for this result to be available in the usual way. Then return to
111           normal operation.
112
113 32.10.2. Functions for Receiving COPY Data #
114
115    These functions are used to receive data during COPY TO STDOUT. They
116    will fail if called when the connection is not in COPY_OUT state.
117
118    PQgetCopyData #
119           Receives data from the server during COPY_OUT state.
120
121 int PQgetCopyData(PGconn *conn,
122                   char **buffer,
123                   int async);
124
125           Attempts to obtain another row of data from the server during a
126           COPY. Data is always returned one data row at a time; if only a
127           partial row is available, it is not returned. Successful return
128           of a data row involves allocating a chunk of memory to hold the
129           data. The buffer parameter must be non-NULL. *buffer is set to
130           point to the allocated memory, or to NULL in cases where no
131           buffer is returned. A non-NULL result buffer should be freed
132           using PQfreemem when no longer needed.
133
134           When a row is successfully returned, the return value is the
135           number of data bytes in the row (this will always be greater
136           than zero). The returned string is always null-terminated,
137           though this is probably only useful for textual COPY. A result
138           of zero indicates that the COPY is still in progress, but no row
139           is yet available (this is only possible when async is true). A
140           result of -1 indicates that the COPY is done. A result of -2
141           indicates that an error occurred (consult PQerrorMessage for the
142           reason).
143
144           When async is true (not zero), PQgetCopyData will not block
145           waiting for input; it will return zero if the COPY is still in
146           progress but no complete row is available. (In this case wait
147           for read-ready and then call PQconsumeInput before calling
148           PQgetCopyData again.) When async is false (zero), PQgetCopyData
149           will block until data is available or the operation completes.
150
151           After PQgetCopyData returns -1, call PQgetResult to obtain the
152           final result status of the COPY command. One can wait for this
153           result to be available in the usual way. Then return to normal
154           operation.
155
156 32.10.3. Obsolete Functions for COPY #
157
158    These functions represent older methods of handling COPY. Although they
159    still work, they are deprecated due to poor error handling,
160    inconvenient methods of detecting end-of-data, and lack of support for
161    binary or nonblocking transfers.
162
163    PQgetline #
164           Reads a newline-terminated line of characters (transmitted by
165           the server) into a buffer string of size length.
166
167 int PQgetline(PGconn *conn,
168               char *buffer,
169               int length);
170
171           This function copies up to length-1 characters into the buffer
172           and converts the terminating newline into a zero byte. PQgetline
173           returns EOF at the end of input, 0 if the entire line has been
174           read, and 1 if the buffer is full but the terminating newline
175           has not yet been read.
176
177           Note that the application must check to see if a new line
178           consists of the two characters \., which indicates that the
179           server has finished sending the results of the COPY command. If
180           the application might receive lines that are more than length-1
181           characters long, care is needed to be sure it recognizes the \.
182           line correctly (and does not, for example, mistake the end of a
183           long data line for a terminator line).
184
185    PQgetlineAsync #
186           Reads a row of COPY data (transmitted by the server) into a
187           buffer without blocking.
188
189 int PQgetlineAsync(PGconn *conn,
190                    char *buffer,
191                    int bufsize);
192
193           This function is similar to PQgetline, but it can be used by
194           applications that must read COPY data asynchronously, that is,
195           without blocking. Having issued the COPY command and gotten a
196           PGRES_COPY_OUT response, the application should call
197           PQconsumeInput and PQgetlineAsync until the end-of-data signal
198           is detected.
199
200           Unlike PQgetline, this function takes responsibility for
201           detecting end-of-data.
202
203           On each call, PQgetlineAsync will return data if a complete data
204           row is available in libpq's input buffer. Otherwise, no data is
205           returned until the rest of the row arrives. The function returns
206           -1 if the end-of-copy-data marker has been recognized, or 0 if
207           no data is available, or a positive number giving the number of
208           bytes of data returned. If -1 is returned, the caller must next
209           call PQendcopy, and then return to normal processing.
210
211           The data returned will not extend beyond a data-row boundary. If
212           possible a whole row will be returned at one time. But if the
213           buffer offered by the caller is too small to hold a row sent by
214           the server, then a partial data row will be returned. With
215           textual data this can be detected by testing whether the last
216           returned byte is \n or not. (In a binary COPY, actual parsing of
217           the COPY data format will be needed to make the equivalent
218           determination.) The returned string is not null-terminated. (If
219           you want to add a terminating null, be sure to pass a bufsize
220           one smaller than the room actually available.)
221
222    PQputline #
223           Sends a null-terminated string to the server. Returns 0 if OK
224           and EOF if unable to send the string.
225
226 int PQputline(PGconn *conn,
227               const char *string);
228
229           The COPY data stream sent by a series of calls to PQputline has
230           the same format as that returned by PQgetlineAsync, except that
231           applications are not obliged to send exactly one data row per
232           PQputline call; it is okay to send a partial line or multiple
233           lines per call.
234
235 Note
236
237           Before PostgreSQL protocol 3.0, it was necessary for the
238           application to explicitly send the two characters \. as a final
239           line to indicate to the server that it had finished sending COPY
240           data. While this still works, it is deprecated and the special
241           meaning of \. can be expected to be removed in a future release.
242           (It already will misbehave in CSV mode.) It is sufficient to
243           call PQendcopy after having sent the actual data.
244
245    PQputnbytes #
246           Sends a non-null-terminated string to the server. Returns 0 if
247           OK and EOF if unable to send the string.
248
249 int PQputnbytes(PGconn *conn,
250                 const char *buffer,
251                 int nbytes);
252
253           This is exactly like PQputline, except that the data buffer need
254           not be null-terminated since the number of bytes to send is
255           specified directly. Use this procedure when sending binary data.
256
257    PQendcopy #
258           Synchronizes with the server.
259
260 int PQendcopy(PGconn *conn);
261
262           This function waits until the server has finished the copying.
263           It should either be issued when the last string has been sent to
264           the server using PQputline or when the last string has been
265           received from the server using PQgetline. It must be issued or
266           the server will get “out of sync” with the client. Upon return
267           from this function, the server is ready to receive the next SQL
268           command. The return value is 0 on successful completion, nonzero
269           otherwise. (Use PQerrorMessage to retrieve details if the return
270           value is nonzero.)
271
272           When using PQgetResult, the application should respond to a
273           PGRES_COPY_OUT result by executing PQgetline repeatedly,
274           followed by PQendcopy after the terminator line is seen. It
275           should then return to the PQgetResult loop until PQgetResult
276           returns a null pointer. Similarly a PGRES_COPY_IN result is
277           processed by a series of PQputline calls followed by PQendcopy,
278           then return to the PQgetResult loop. This arrangement will
279           ensure that a COPY command embedded in a series of SQL commands
280           will be executed correctly.
281
282           Older applications are likely to submit a COPY via PQexec and
283           assume that the transaction is done after PQendcopy. This will
284           work correctly only if the COPY is the only SQL command in the
285           command string.