1 /*-------------------------------------------------------------------------
4 * Implements the COPY utility command
6 * Portions Copyright (c) 1996-2011, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/commands/copy.c
13 *-------------------------------------------------------------------------
20 #include <netinet/in.h>
21 #include <arpa/inet.h>
23 #include "access/heapam.h"
24 #include "access/sysattr.h"
25 #include "access/xact.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_type.h"
28 #include "commands/copy.h"
29 #include "commands/defrem.h"
30 #include "commands/trigger.h"
31 #include "executor/executor.h"
32 #include "libpq/libpq.h"
33 #include "libpq/pqformat.h"
34 #include "mb/pg_wchar.h"
35 #include "miscadmin.h"
36 #include "optimizer/planner.h"
37 #include "parser/parse_relation.h"
38 #include "rewrite/rewriteHandler.h"
39 #include "storage/fd.h"
40 #include "tcop/tcopprot.h"
41 #include "utils/acl.h"
42 #include "utils/builtins.h"
43 #include "utils/lsyscache.h"
44 #include "utils/memutils.h"
45 #include "utils/snapmgr.h"
48 #define ISOCTAL(c) (((c) >= '0') && ((c) <= '7'))
49 #define OCTVALUE(c) ((c) - '0')
52 * Represents the different source/dest cases we need to worry about at
57 COPY_FILE, /* to/from file */
58 COPY_OLD_FE, /* to/from frontend (2.0 protocol) */
59 COPY_NEW_FE /* to/from frontend (3.0 protocol) */
63 * Represents the end-of-line terminator type of the input
74 * This struct contains all the state variables used throughout a COPY
75 * operation. For simplicity, we use the same struct for all variants of COPY,
76 * even though some fields are used in only some cases.
78 * Multi-byte encodings: all supported client-side encodings encode multi-byte
79 * characters by having the first byte's high bit set. Subsequent bytes of the
80 * character can have the high bit not set. When scanning data in such an
81 * encoding to look for a match to a single-byte (ie ASCII) character, we must
82 * use the full pg_encoding_mblen() machinery to skip over multibyte
83 * characters, else we might find a false match to a trailing byte. In
84 * supported server encodings, there is no possibility of a false match, and
85 * it's faster to make useless comparisons to trailing bytes than it is to
86 * invoke pg_encoding_mblen() to skip over them. encoding_embeds_ascii is TRUE
87 * when we have to do it the hard way.
89 typedef struct CopyStateData
91 /* low-level state data */
92 CopyDest copy_dest; /* type of copy source/destination */
93 FILE *copy_file; /* used if copy_dest == COPY_FILE */
94 StringInfo fe_msgbuf; /* used for all dests during COPY TO, only for
95 * dest == COPY_NEW_FE in COPY FROM */
96 bool fe_eof; /* true if detected end of copy data */
97 EolType eol_type; /* EOL type of input */
98 int file_encoding; /* file or remote side's character encoding */
99 bool need_transcoding; /* file encoding diff from server? */
100 bool encoding_embeds_ascii; /* ASCII can be non-first byte? */
102 /* parameters from the COPY command */
103 Relation rel; /* relation to copy to or from */
104 QueryDesc *queryDesc; /* executable query to copy from */
105 List *attnumlist; /* integer list of attnums to copy */
106 char *filename; /* filename, or NULL for STDIN/STDOUT */
107 bool binary; /* binary format? */
108 bool oids; /* include OIDs? */
109 bool csv_mode; /* Comma Separated Value format? */
110 bool header_line; /* CSV header line? */
111 char *null_print; /* NULL marker string (server encoding!) */
112 int null_print_len; /* length of same */
113 char *null_print_client; /* same converted to file encoding */
114 char *delim; /* column delimiter (must be 1 byte) */
115 char *quote; /* CSV quote char (must be 1 byte) */
116 char *escape; /* CSV escape char (must be 1 byte) */
117 List *force_quote; /* list of column names */
118 bool force_quote_all; /* FORCE QUOTE *? */
119 bool *force_quote_flags; /* per-column CSV FQ flags */
120 List *force_notnull; /* list of column names */
121 bool *force_notnull_flags; /* per-column CSV FNN flags */
123 /* these are just for error messages, see CopyFromErrorCallback */
124 const char *cur_relname; /* table name for error messages */
125 int cur_lineno; /* line number for error messages */
126 const char *cur_attname; /* current att for error messages */
127 const char *cur_attval; /* current att value for error messages */
130 * Working state for COPY TO/FROM
132 MemoryContext copycontext; /* per-copy execution context */
135 * Working state for COPY TO
137 FmgrInfo *out_functions; /* lookup info for output functions */
138 MemoryContext rowcontext; /* per-row evaluation context */
141 * Working state for COPY FROM
143 AttrNumber num_defaults;
145 FmgrInfo oid_in_function;
147 FmgrInfo *in_functions; /* array of input functions for each attrs */
148 Oid *typioparams; /* array of element types for in_functions */
149 int *defmap; /* array of default att numbers */
150 ExprState **defexprs; /* array of default att expressions */
153 * These variables are used to reduce overhead in textual COPY FROM.
155 * attribute_buf holds the separated, de-escaped text for each field of
156 * the current line. The CopyReadAttributes functions return arrays of
157 * pointers into this buffer. We avoid palloc/pfree overhead by re-using
158 * the buffer on each cycle.
160 StringInfoData attribute_buf;
162 /* field raw data pointers found by COPY FROM */
168 * Similarly, line_buf holds the whole input line being processed. The
169 * input cycle is first to read the whole line into line_buf, convert it
170 * to server encoding there, and then extract the individual attribute
171 * fields into attribute_buf. line_buf is preserved unmodified so that we
172 * can display it in error messages if appropriate.
174 StringInfoData line_buf;
175 bool line_buf_converted; /* converted to server encoding? */
178 * Finally, raw_buf holds raw data read from the data source (file or
179 * client connection). CopyReadLine parses this data sufficiently to
180 * locate line boundaries, then transfers the data to line_buf and
181 * converts it. Note: we guarantee that there is a \0 at
182 * raw_buf[raw_buf_len].
184 #define RAW_BUF_SIZE 65536 /* we palloc RAW_BUF_SIZE+1 bytes */
186 int raw_buf_index; /* next byte to process */
187 int raw_buf_len; /* total # of bytes stored */
190 /* DestReceiver for COPY (SELECT) TO */
193 DestReceiver pub; /* publicly-known function pointers */
194 CopyState cstate; /* CopyStateData for the command */
195 uint64 processed; /* # of tuples processed */
200 * These macros centralize code used to process line_buf and raw_buf buffers.
201 * They are macros because they often do continue/break control and to avoid
202 * function call overhead in tight COPY loops.
204 * We must use "if (1)" because the usual "do {...} while(0)" wrapper would
205 * prevent the continue/break processing from working. We end the "if (1)"
206 * with "else ((void) 0)" to ensure the "if" does not unintentionally match
207 * any "else" in the calling code, and to avoid any compiler warnings about
208 * empty statements. See http://www.cit.gu.edu.au/~anthony/info/C/C.macros.
212 * This keeps the character read at the top of the loop in the buffer
213 * even if there is more than one read-ahead.
215 #define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen) \
218 if (raw_buf_ptr + (extralen) >= copy_buf_len && !hit_eof) \
220 raw_buf_ptr = prev_raw_ptr; /* undo fetch */ \
226 /* This consumes the remainder of the buffer and breaks */
227 #define IF_NEED_REFILL_AND_EOF_BREAK(extralen) \
230 if (raw_buf_ptr + (extralen) >= copy_buf_len && hit_eof) \
233 raw_buf_ptr = copy_buf_len; /* consume the partial character */ \
234 /* backslash just before EOF, treat as data char */ \
241 * Transfer any approved data to line_buf; must do this to be sure
242 * there is some room in raw_buf.
244 #define REFILL_LINEBUF \
247 if (raw_buf_ptr > cstate->raw_buf_index) \
249 appendBinaryStringInfo(&cstate->line_buf, \
250 cstate->raw_buf + cstate->raw_buf_index, \
251 raw_buf_ptr - cstate->raw_buf_index); \
252 cstate->raw_buf_index = raw_buf_ptr; \
256 /* Undo any read-ahead and jump out of the block. */
257 #define NO_END_OF_COPY_GOTO \
260 raw_buf_ptr = prev_raw_ptr + 1; \
261 goto not_end_of_copy; \
264 static const char BinarySignature[11] = "PGCOPY\n\377\r\n\0";
267 /* non-export function prototypes */
268 static CopyState BeginCopy(bool is_from, Relation rel, Node *raw_query,
269 const char *queryString, List *attnamelist, List *options);
270 static void EndCopy(CopyState cstate);
271 static CopyState BeginCopyTo(Relation rel, Node *query, const char *queryString,
272 const char *filename, List *attnamelist, List *options);
273 static void EndCopyTo(CopyState cstate);
274 static uint64 DoCopyTo(CopyState cstate);
275 static uint64 CopyTo(CopyState cstate);
276 static void CopyOneRowTo(CopyState cstate, Oid tupleOid,
277 Datum *values, bool *nulls);
278 static uint64 CopyFrom(CopyState cstate);
279 static bool CopyReadLine(CopyState cstate);
280 static bool CopyReadLineText(CopyState cstate);
281 static int CopyReadAttributesText(CopyState cstate);
282 static int CopyReadAttributesCSV(CopyState cstate);
283 static Datum CopyReadBinaryAttribute(CopyState cstate,
284 int column_no, FmgrInfo *flinfo,
285 Oid typioparam, int32 typmod,
287 static void CopyAttributeOutText(CopyState cstate, char *string);
288 static void CopyAttributeOutCSV(CopyState cstate, char *string,
289 bool use_quote, bool single_attr);
290 static List *CopyGetAttnums(TupleDesc tupDesc, Relation rel,
292 static char *limit_printout_length(const char *str);
294 /* Low-level communications functions */
295 static void SendCopyBegin(CopyState cstate);
296 static void ReceiveCopyBegin(CopyState cstate);
297 static void SendCopyEnd(CopyState cstate);
298 static void CopySendData(CopyState cstate, void *databuf, int datasize);
299 static void CopySendString(CopyState cstate, const char *str);
300 static void CopySendChar(CopyState cstate, char c);
301 static void CopySendEndOfRow(CopyState cstate);
302 static int CopyGetData(CopyState cstate, void *databuf,
303 int minread, int maxread);
304 static void CopySendInt32(CopyState cstate, int32 val);
305 static bool CopyGetInt32(CopyState cstate, int32 *val);
306 static void CopySendInt16(CopyState cstate, int16 val);
307 static bool CopyGetInt16(CopyState cstate, int16 *val);
311 * Send copy start/stop messages for frontend copies. These have changed
312 * in past protocol redesigns.
315 SendCopyBegin(CopyState cstate)
317 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
321 int natts = list_length(cstate->attnumlist);
322 int16 format = (cstate->binary ? 1 : 0);
325 pq_beginmessage(&buf, 'H');
326 pq_sendbyte(&buf, format); /* overall format */
327 pq_sendint(&buf, natts, 2);
328 for (i = 0; i < natts; i++)
329 pq_sendint(&buf, format, 2); /* per-column formats */
331 cstate->copy_dest = COPY_NEW_FE;
333 else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
338 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
339 errmsg("COPY BINARY is not supported to stdout or from stdin")));
340 pq_putemptymessage('H');
341 /* grottiness needed for old COPY OUT protocol */
343 cstate->copy_dest = COPY_OLD_FE;
350 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
351 errmsg("COPY BINARY is not supported to stdout or from stdin")));
352 pq_putemptymessage('B');
353 /* grottiness needed for old COPY OUT protocol */
355 cstate->copy_dest = COPY_OLD_FE;
360 ReceiveCopyBegin(CopyState cstate)
362 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
366 int natts = list_length(cstate->attnumlist);
367 int16 format = (cstate->binary ? 1 : 0);
370 pq_beginmessage(&buf, 'G');
371 pq_sendbyte(&buf, format); /* overall format */
372 pq_sendint(&buf, natts, 2);
373 for (i = 0; i < natts; i++)
374 pq_sendint(&buf, format, 2); /* per-column formats */
376 cstate->copy_dest = COPY_NEW_FE;
377 cstate->fe_msgbuf = makeStringInfo();
379 else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
384 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
385 errmsg("COPY BINARY is not supported to stdout or from stdin")));
386 pq_putemptymessage('G');
387 cstate->copy_dest = COPY_OLD_FE;
394 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
395 errmsg("COPY BINARY is not supported to stdout or from stdin")));
396 pq_putemptymessage('D');
397 cstate->copy_dest = COPY_OLD_FE;
399 /* We *must* flush here to ensure FE knows it can send. */
404 SendCopyEnd(CopyState cstate)
406 if (cstate->copy_dest == COPY_NEW_FE)
408 /* Shouldn't have any unsent data */
409 Assert(cstate->fe_msgbuf->len == 0);
410 /* Send Copy Done message */
411 pq_putemptymessage('c');
415 CopySendData(cstate, "\\.", 2);
416 /* Need to flush out the trailer (this also appends a newline) */
417 CopySendEndOfRow(cstate);
418 pq_endcopyout(false);
423 * CopySendData sends output data to the destination (file or frontend)
424 * CopySendString does the same for null-terminated strings
425 * CopySendChar does the same for single characters
426 * CopySendEndOfRow does the appropriate thing at end of each data row
427 * (data is not actually flushed except by CopySendEndOfRow)
429 * NB: no data conversion is applied by these functions
433 CopySendData(CopyState cstate, void *databuf, int datasize)
435 appendBinaryStringInfo(cstate->fe_msgbuf, (char *) databuf, datasize);
439 CopySendString(CopyState cstate, const char *str)
441 appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
445 CopySendChar(CopyState cstate, char c)
447 appendStringInfoCharMacro(cstate->fe_msgbuf, c);
451 CopySendEndOfRow(CopyState cstate)
453 StringInfo fe_msgbuf = cstate->fe_msgbuf;
455 switch (cstate->copy_dest)
460 /* Default line termination depends on platform */
462 CopySendChar(cstate, '\n');
464 CopySendString(cstate, "\r\n");
468 (void) fwrite(fe_msgbuf->data, fe_msgbuf->len,
469 1, cstate->copy_file);
470 if (ferror(cstate->copy_file))
472 (errcode_for_file_access(),
473 errmsg("could not write to COPY file: %m")));
476 /* The FE/BE protocol uses \n as newline for all platforms */
478 CopySendChar(cstate, '\n');
480 if (pq_putbytes(fe_msgbuf->data, fe_msgbuf->len))
482 /* no hope of recovering connection sync, so FATAL */
484 (errcode(ERRCODE_CONNECTION_FAILURE),
485 errmsg("connection lost during COPY to stdout")));
489 /* The FE/BE protocol uses \n as newline for all platforms */
491 CopySendChar(cstate, '\n');
493 /* Dump the accumulated row as one CopyData message */
494 (void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
498 resetStringInfo(fe_msgbuf);
502 * CopyGetData reads data from the source (file or frontend)
504 * We attempt to read at least minread, and at most maxread, bytes from
505 * the source. The actual number of bytes read is returned; if this is
506 * less than minread, EOF was detected.
508 * Note: when copying from the frontend, we expect a proper EOF mark per
509 * protocol; if the frontend simply drops the connection, we raise error.
510 * It seems unwise to allow the COPY IN to complete normally in that case.
512 * NB: no data conversion is applied here.
515 CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
519 switch (cstate->copy_dest)
522 bytesread = fread(databuf, 1, maxread, cstate->copy_file);
523 if (ferror(cstate->copy_file))
525 (errcode_for_file_access(),
526 errmsg("could not read from COPY file: %m")));
531 * We cannot read more than minread bytes (which in practice is 1)
532 * because old protocol doesn't have any clear way of separating
533 * the COPY stream from following data. This is slow, but not any
534 * slower than the code path was originally, and we don't care
535 * much anymore about the performance of old protocol.
537 if (pq_getbytes((char *) databuf, minread))
539 /* Only a \. terminator is legal EOF in old protocol */
541 (errcode(ERRCODE_CONNECTION_FAILURE),
542 errmsg("unexpected EOF on client connection")));
547 while (maxread > 0 && bytesread < minread && !cstate->fe_eof)
551 while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
553 /* Try to receive another message */
557 mtype = pq_getbyte();
560 (errcode(ERRCODE_CONNECTION_FAILURE),
561 errmsg("unexpected EOF on client connection")));
562 if (pq_getmessage(cstate->fe_msgbuf, 0))
564 (errcode(ERRCODE_CONNECTION_FAILURE),
565 errmsg("unexpected EOF on client connection")));
568 case 'd': /* CopyData */
570 case 'c': /* CopyDone */
571 /* COPY IN correctly terminated by frontend */
572 cstate->fe_eof = true;
574 case 'f': /* CopyFail */
576 (errcode(ERRCODE_QUERY_CANCELED),
577 errmsg("COPY from stdin failed: %s",
578 pq_getmsgstring(cstate->fe_msgbuf))));
580 case 'H': /* Flush */
584 * Ignore Flush/Sync for the convenience of client
585 * libraries (such as libpq) that may send those
586 * without noticing that the command they just
592 (errcode(ERRCODE_PROTOCOL_VIOLATION),
593 errmsg("unexpected message type 0x%02X during COPY from stdin",
598 avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
601 pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
602 databuf = (void *) ((char *) databuf + avail);
614 * These functions do apply some data conversion
618 * CopySendInt32 sends an int32 in network byte order
621 CopySendInt32(CopyState cstate, int32 val)
625 buf = htonl((uint32) val);
626 CopySendData(cstate, &buf, sizeof(buf));
630 * CopyGetInt32 reads an int32 that appears in network byte order
632 * Returns true if OK, false if EOF
635 CopyGetInt32(CopyState cstate, int32 *val)
639 if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
641 *val = 0; /* suppress compiler warning */
644 *val = (int32) ntohl(buf);
649 * CopySendInt16 sends an int16 in network byte order
652 CopySendInt16(CopyState cstate, int16 val)
656 buf = htons((uint16) val);
657 CopySendData(cstate, &buf, sizeof(buf));
661 * CopyGetInt16 reads an int16 that appears in network byte order
664 CopyGetInt16(CopyState cstate, int16 *val)
668 if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
670 *val = 0; /* suppress compiler warning */
673 *val = (int16) ntohs(buf);
679 * CopyLoadRawBuf loads some more data into raw_buf
681 * Returns TRUE if able to obtain at least one more byte, else FALSE.
683 * If raw_buf_index < raw_buf_len, the unprocessed bytes are transferred
684 * down to the start of the buffer and then we load more data after that.
685 * This case is used only when a frontend multibyte character crosses a
686 * bufferload boundary.
689 CopyLoadRawBuf(CopyState cstate)
694 if (cstate->raw_buf_index < cstate->raw_buf_len)
696 /* Copy down the unprocessed data */
697 nbytes = cstate->raw_buf_len - cstate->raw_buf_index;
698 memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
702 nbytes = 0; /* no data need be saved */
704 inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
705 1, RAW_BUF_SIZE - nbytes);
707 cstate->raw_buf[nbytes] = '\0';
708 cstate->raw_buf_index = 0;
709 cstate->raw_buf_len = nbytes;
710 return (inbytes > 0);
715 * DoCopy executes the SQL COPY statement
717 * Either unload or reload contents of table <relation>, depending on <from>.
718 * (<from> = TRUE means we are inserting into the table.) In the "TO" case
719 * we also support copying the output of an arbitrary SELECT query.
721 * If <pipe> is false, transfer is between the table and the file named
722 * <filename>. Otherwise, transfer is between the table and our regular
723 * input/output stream. The latter could be either stdin/stdout or a
724 * socket, depending on whether we're running under Postmaster control.
726 * Do not allow a Postgres user without superuser privilege to read from
727 * or write to a file.
729 * Do not allow the copy if user doesn't have proper permission to access
730 * the table or the specifically requested columns.
733 DoCopy(const CopyStmt *stmt, const char *queryString)
736 bool is_from = stmt->is_from;
737 bool pipe = (stmt->filename == NULL);
741 /* Disallow file COPY except to superusers. */
742 if (!pipe && !superuser())
744 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
745 errmsg("must be superuser to COPY to or from a file"),
746 errhint("Anyone can COPY to stdout or from stdin. "
747 "psql's \\copy command also works for anyone.")));
752 AclMode required_access = (is_from ? ACL_INSERT : ACL_SELECT);
757 Assert(!stmt->query);
759 /* Open and lock the relation, using the appropriate lock type. */
760 rel = heap_openrv(stmt->relation,
761 (is_from ? RowExclusiveLock : AccessShareLock));
763 rte = makeNode(RangeTblEntry);
764 rte->rtekind = RTE_RELATION;
765 rte->relid = RelationGetRelid(rel);
766 rte->requiredPerms = required_access;
768 tupDesc = RelationGetDescr(rel);
769 attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
770 foreach(cur, attnums)
772 int attno = lfirst_int(cur) -
773 FirstLowInvalidHeapAttributeNumber;
776 rte->modifiedCols = bms_add_member(rte->modifiedCols, attno);
778 rte->selectedCols = bms_add_member(rte->selectedCols, attno);
780 ExecCheckRTPerms(list_make1(rte), true);
791 /* check read-only transaction */
792 if (XactReadOnly && rel->rd_backend != MyBackendId)
793 PreventCommandIfReadOnly("COPY FROM");
795 cstate = BeginCopyFrom(rel, stmt->filename,
796 stmt->attlist, stmt->options);
797 processed = CopyFrom(cstate); /* copy from file to database */
802 cstate = BeginCopyTo(rel, stmt->query, queryString, stmt->filename,
803 stmt->attlist, stmt->options);
804 processed = DoCopyTo(cstate); /* copy from database to file */
809 * Close the relation. If reading, we can release the AccessShareLock we
810 * got; if writing, we should hold the lock until end of transaction to
811 * ensure that updates will be committed before lock is released.
814 heap_close(rel, (is_from ? NoLock : AccessShareLock));
820 * Process the statement option list for COPY.
822 * Scan the options list (a list of DefElem) and transpose the information
823 * into cstate, applying appropriate error checking.
825 * cstate is assumed to be filled with zeroes initially.
827 * This is exported so that external users of the COPY API can sanity-check
828 * a list of options. In that usage, cstate should be passed as NULL
829 * (since external users don't know sizeof(CopyStateData)) and the collected
830 * data is just leaked until CurrentMemoryContext is reset.
832 * Note that additional checking, such as whether column names listed in FORCE
833 * QUOTE actually exist, has to be applied later. This just checks for
834 * self-consistency of the options list.
837 ProcessCopyOptions(CopyState cstate,
841 bool format_specified = false;
844 /* Support external use for option sanity checking */
846 cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
848 cstate->file_encoding = -1;
850 /* Extract options from the statement node tree */
851 foreach(option, options)
853 DefElem *defel = (DefElem *) lfirst(option);
855 if (strcmp(defel->defname, "format") == 0)
857 char *fmt = defGetString(defel);
859 if (format_specified)
861 (errcode(ERRCODE_SYNTAX_ERROR),
862 errmsg("conflicting or redundant options")));
863 format_specified = true;
864 if (strcmp(fmt, "text") == 0)
865 /* default format */ ;
866 else if (strcmp(fmt, "csv") == 0)
867 cstate->csv_mode = true;
868 else if (strcmp(fmt, "binary") == 0)
869 cstate->binary = true;
872 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
873 errmsg("COPY format \"%s\" not recognized", fmt)));
875 else if (strcmp(defel->defname, "oids") == 0)
879 (errcode(ERRCODE_SYNTAX_ERROR),
880 errmsg("conflicting or redundant options")));
881 cstate->oids = defGetBoolean(defel);
883 else if (strcmp(defel->defname, "delimiter") == 0)
887 (errcode(ERRCODE_SYNTAX_ERROR),
888 errmsg("conflicting or redundant options")));
889 cstate->delim = defGetString(defel);
891 else if (strcmp(defel->defname, "null") == 0)
893 if (cstate->null_print)
895 (errcode(ERRCODE_SYNTAX_ERROR),
896 errmsg("conflicting or redundant options")));
897 cstate->null_print = defGetString(defel);
899 else if (strcmp(defel->defname, "header") == 0)
901 if (cstate->header_line)
903 (errcode(ERRCODE_SYNTAX_ERROR),
904 errmsg("conflicting or redundant options")));
905 cstate->header_line = defGetBoolean(defel);
907 else if (strcmp(defel->defname, "quote") == 0)
911 (errcode(ERRCODE_SYNTAX_ERROR),
912 errmsg("conflicting or redundant options")));
913 cstate->quote = defGetString(defel);
915 else if (strcmp(defel->defname, "escape") == 0)
919 (errcode(ERRCODE_SYNTAX_ERROR),
920 errmsg("conflicting or redundant options")));
921 cstate->escape = defGetString(defel);
923 else if (strcmp(defel->defname, "force_quote") == 0)
925 if (cstate->force_quote || cstate->force_quote_all)
927 (errcode(ERRCODE_SYNTAX_ERROR),
928 errmsg("conflicting or redundant options")));
929 if (defel->arg && IsA(defel->arg, A_Star))
930 cstate->force_quote_all = true;
931 else if (defel->arg && IsA(defel->arg, List))
932 cstate->force_quote = (List *) defel->arg;
935 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
936 errmsg("argument to option \"%s\" must be a list of column names",
939 else if (strcmp(defel->defname, "force_not_null") == 0)
941 if (cstate->force_notnull)
943 (errcode(ERRCODE_SYNTAX_ERROR),
944 errmsg("conflicting or redundant options")));
945 if (defel->arg && IsA(defel->arg, List))
946 cstate->force_notnull = (List *) defel->arg;
949 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
950 errmsg("argument to option \"%s\" must be a list of column names",
953 else if (strcmp(defel->defname, "encoding") == 0)
955 if (cstate->file_encoding >= 0)
957 (errcode(ERRCODE_SYNTAX_ERROR),
958 errmsg("conflicting or redundant options")));
959 cstate->file_encoding = pg_char_to_encoding(defGetString(defel));
960 if (cstate->file_encoding < 0)
962 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
963 errmsg("argument to option \"%s\" must be a valid encoding name",
968 (errcode(ERRCODE_SYNTAX_ERROR),
969 errmsg("option \"%s\" not recognized",
974 * Check for incompatible options (must do these two before inserting
977 if (cstate->binary && cstate->delim)
979 (errcode(ERRCODE_SYNTAX_ERROR),
980 errmsg("cannot specify DELIMITER in BINARY mode")));
982 if (cstate->binary && cstate->null_print)
984 (errcode(ERRCODE_SYNTAX_ERROR),
985 errmsg("cannot specify NULL in BINARY mode")));
987 /* Set defaults for omitted options */
989 cstate->delim = cstate->csv_mode ? "," : "\t";
991 if (!cstate->null_print)
992 cstate->null_print = cstate->csv_mode ? "" : "\\N";
993 cstate->null_print_len = strlen(cstate->null_print);
995 if (cstate->csv_mode)
998 cstate->quote = "\"";
1000 cstate->escape = cstate->quote;
1003 /* Only single-byte delimiter strings are supported. */
1004 if (strlen(cstate->delim) != 1)
1006 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1007 errmsg("COPY delimiter must be a single one-byte character")));
1009 /* Disallow end-of-line characters */
1010 if (strchr(cstate->delim, '\r') != NULL ||
1011 strchr(cstate->delim, '\n') != NULL)
1013 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1014 errmsg("COPY delimiter cannot be newline or carriage return")));
1016 if (strchr(cstate->null_print, '\r') != NULL ||
1017 strchr(cstate->null_print, '\n') != NULL)
1019 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1020 errmsg("COPY null representation cannot use newline or carriage return")));
1023 * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
1024 * backslash because it would be ambiguous. We can't allow the other
1025 * cases because data characters matching the delimiter must be
1026 * backslashed, and certain backslash combinations are interpreted
1027 * non-literally by COPY IN. Disallowing all lower case ASCII letters is
1028 * more than strictly necessary, but seems best for consistency and
1029 * future-proofing. Likewise we disallow all digits though only octal
1030 * digits are actually dangerous.
1032 if (!cstate->csv_mode &&
1033 strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
1034 cstate->delim[0]) != NULL)
1036 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1037 errmsg("COPY delimiter cannot be \"%s\"", cstate->delim)));
1040 if (!cstate->csv_mode && cstate->header_line)
1042 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1043 errmsg("COPY HEADER available only in CSV mode")));
1046 if (!cstate->csv_mode && cstate->quote != NULL)
1048 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1049 errmsg("COPY quote available only in CSV mode")));
1051 if (cstate->csv_mode && strlen(cstate->quote) != 1)
1053 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1054 errmsg("COPY quote must be a single one-byte character")));
1056 if (cstate->csv_mode && cstate->delim[0] == cstate->quote[0])
1058 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1059 errmsg("COPY delimiter and quote must be different")));
1062 if (!cstate->csv_mode && cstate->escape != NULL)
1064 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1065 errmsg("COPY escape available only in CSV mode")));
1067 if (cstate->csv_mode && strlen(cstate->escape) != 1)
1069 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1070 errmsg("COPY escape must be a single one-byte character")));
1072 /* Check force_quote */
1073 if (!cstate->csv_mode && (cstate->force_quote || cstate->force_quote_all))
1075 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1076 errmsg("COPY force quote available only in CSV mode")));
1077 if ((cstate->force_quote || cstate->force_quote_all) && is_from)
1079 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1080 errmsg("COPY force quote only available using COPY TO")));
1082 /* Check force_notnull */
1083 if (!cstate->csv_mode && cstate->force_notnull != NIL)
1085 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1086 errmsg("COPY force not null available only in CSV mode")));
1087 if (cstate->force_notnull != NIL && !is_from)
1089 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1090 errmsg("COPY force not null only available using COPY FROM")));
1092 /* Don't allow the delimiter to appear in the null string. */
1093 if (strchr(cstate->null_print, cstate->delim[0]) != NULL)
1095 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1096 errmsg("COPY delimiter must not appear in the NULL specification")));
1098 /* Don't allow the CSV quote char to appear in the null string. */
1099 if (cstate->csv_mode &&
1100 strchr(cstate->null_print, cstate->quote[0]) != NULL)
1102 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1103 errmsg("CSV quote character must not appear in the NULL specification")));
1107 * Common setup routines used by BeginCopyFrom and BeginCopyTo.
1109 * Iff <binary>, unload or reload in the binary format, as opposed to the
1110 * more wasteful but more robust and portable text format.
1112 * Iff <oids>, unload or reload the format that includes OID information.
1113 * On input, we accept OIDs whether or not the table has an OID column,
1114 * but silently drop them if it does not. On output, we report an error
1115 * if the user asks for OIDs in a table that has none (not providing an
1116 * OID column might seem friendlier, but could seriously confuse programs).
1118 * If in the text format, delimit columns with delimiter <delim> and print
1119 * NULL values as <null_print>.
1122 BeginCopy(bool is_from,
1125 const char *queryString,
1132 MemoryContext oldcontext;
1134 /* Allocate workspace and zero all fields */
1135 cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1138 * We allocate everything used by a cstate in a new memory context.
1139 * This avoids memory leaks during repeated use of COPY in a query.
1141 cstate->copycontext = AllocSetContextCreate(CurrentMemoryContext,
1143 ALLOCSET_DEFAULT_MINSIZE,
1144 ALLOCSET_DEFAULT_INITSIZE,
1145 ALLOCSET_DEFAULT_MAXSIZE);
1147 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1149 /* Extract options from the statement node tree */
1150 ProcessCopyOptions(cstate, is_from, options);
1152 /* Process the source/target relation or query */
1159 tupDesc = RelationGetDescr(cstate->rel);
1161 /* Don't allow COPY w/ OIDs to or from a table without them */
1162 if (cstate->oids && !cstate->rel->rd_rel->relhasoids)
1164 (errcode(ERRCODE_UNDEFINED_COLUMN),
1165 errmsg("table \"%s\" does not have OIDs",
1166 RelationGetRelationName(cstate->rel))));
1178 /* Don't allow COPY w/ OIDs from a select */
1181 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1182 errmsg("COPY (SELECT) WITH OIDS is not supported")));
1185 * Run parse analysis and rewrite. Note this also acquires sufficient
1186 * locks on the source table(s).
1188 * Because the parser and planner tend to scribble on their input, we
1189 * make a preliminary copy of the source querytree. This prevents
1190 * problems in the case that the COPY is in a portal or plpgsql
1191 * function and is executed repeatedly. (See also the same hack in
1192 * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
1194 rewritten = pg_analyze_and_rewrite((Node *) copyObject(raw_query),
1195 queryString, NULL, 0);
1197 /* We don't expect more or less than one result query */
1198 if (list_length(rewritten) != 1)
1199 elog(ERROR, "unexpected rewrite result");
1201 query = (Query *) linitial(rewritten);
1202 Assert(query->commandType == CMD_SELECT);
1203 Assert(query->utilityStmt == NULL);
1205 /* Query mustn't use INTO, either */
1206 if (query->intoClause)
1208 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1209 errmsg("COPY (SELECT INTO) is not supported")));
1211 /* plan the query */
1212 plan = planner(query, 0, NULL);
1215 * Use a snapshot with an updated command ID to ensure this query sees
1216 * results of any previously executed queries.
1218 PushUpdatedSnapshot(GetActiveSnapshot());
1220 /* Create dest receiver for COPY OUT */
1221 dest = CreateDestReceiver(DestCopyOut);
1222 ((DR_copy *) dest)->cstate = cstate;
1224 /* Create a QueryDesc requesting no output */
1225 cstate->queryDesc = CreateQueryDesc(plan, queryString,
1226 GetActiveSnapshot(),
1231 * Call ExecutorStart to prepare the plan for execution.
1233 * ExecutorStart computes a result tupdesc for us
1235 ExecutorStart(cstate->queryDesc, 0);
1237 tupDesc = cstate->queryDesc->tupDesc;
1240 /* Generate or convert list of attributes to process */
1241 cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1243 num_phys_attrs = tupDesc->natts;
1245 /* Convert FORCE QUOTE name list to per-column flags, check validity */
1246 cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1247 if (cstate->force_quote_all)
1251 for (i = 0; i < num_phys_attrs; i++)
1252 cstate->force_quote_flags[i] = true;
1254 else if (cstate->force_quote)
1259 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_quote);
1261 foreach(cur, attnums)
1263 int attnum = lfirst_int(cur);
1265 if (!list_member_int(cstate->attnumlist, attnum))
1267 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1268 errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
1269 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1270 cstate->force_quote_flags[attnum - 1] = true;
1274 /* Convert FORCE NOT NULL name list to per-column flags, check validity */
1275 cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1276 if (cstate->force_notnull)
1281 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_notnull);
1283 foreach(cur, attnums)
1285 int attnum = lfirst_int(cur);
1287 if (!list_member_int(cstate->attnumlist, attnum))
1289 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1290 errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
1291 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1292 cstate->force_notnull_flags[attnum - 1] = true;
1296 /* Use client encoding when ENCODING option is not specified. */
1297 if (cstate->file_encoding < 0)
1298 cstate->file_encoding = pg_get_client_encoding();
1301 * Set up encoding conversion info. Even if the file and server
1302 * encodings are the same, we must apply pg_any_to_server() to validate
1303 * data in multibyte encodings.
1305 cstate->need_transcoding =
1306 (cstate->file_encoding != GetDatabaseEncoding() ||
1307 pg_database_encoding_max_length() > 1);
1308 /* See Multibyte encoding comment above */
1309 cstate->encoding_embeds_ascii = PG_ENCODING_IS_CLIENT_ONLY(cstate->file_encoding);
1311 cstate->copy_dest = COPY_FILE; /* default */
1313 MemoryContextSwitchTo(oldcontext);
1319 * Release resources allocated in a cstate for COPY TO/FROM.
1322 EndCopy(CopyState cstate)
1324 if (cstate->filename != NULL && FreeFile(cstate->copy_file))
1326 (errcode_for_file_access(),
1327 errmsg("could not close file \"%s\": %m",
1328 cstate->filename)));
1330 MemoryContextDelete(cstate->copycontext);
1335 * Setup CopyState to read tuples from a table or a query for COPY TO.
1338 BeginCopyTo(Relation rel,
1340 const char *queryString,
1341 const char *filename,
1346 bool pipe = (filename == NULL);
1347 MemoryContext oldcontext;
1349 if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
1351 if (rel->rd_rel->relkind == RELKIND_VIEW)
1353 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1354 errmsg("cannot copy from view \"%s\"",
1355 RelationGetRelationName(rel)),
1356 errhint("Try the COPY (SELECT ...) TO variant.")));
1357 else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1359 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1360 errmsg("cannot copy from foreign table \"%s\"",
1361 RelationGetRelationName(rel)),
1362 errhint("Try the COPY (SELECT ...) TO variant.")));
1363 else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
1365 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1366 errmsg("cannot copy from sequence \"%s\"",
1367 RelationGetRelationName(rel))));
1370 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1371 errmsg("cannot copy from non-table relation \"%s\"",
1372 RelationGetRelationName(rel))));
1375 cstate = BeginCopy(false, rel, query, queryString, attnamelist, options);
1376 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1380 if (whereToSendOutput != DestRemote)
1381 cstate->copy_file = stdout;
1385 mode_t oumask; /* Pre-existing umask value */
1389 * Prevent write to relative path ... too easy to shoot oneself in the
1390 * foot by overwriting a database file ...
1392 if (!is_absolute_path(filename))
1394 (errcode(ERRCODE_INVALID_NAME),
1395 errmsg("relative path not allowed for COPY to file")));
1397 cstate->filename = pstrdup(filename);
1398 oumask = umask(S_IWGRP | S_IWOTH);
1399 cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
1402 if (cstate->copy_file == NULL)
1404 (errcode_for_file_access(),
1405 errmsg("could not open file \"%s\" for writing: %m",
1406 cstate->filename)));
1408 fstat(fileno(cstate->copy_file), &st);
1409 if (S_ISDIR(st.st_mode))
1411 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1412 errmsg("\"%s\" is a directory", cstate->filename)));
1415 MemoryContextSwitchTo(oldcontext);
1421 * This intermediate routine exists mainly to localize the effects of setjmp
1422 * so we don't need to plaster a lot of variables with "volatile".
1425 DoCopyTo(CopyState cstate)
1427 bool pipe = (cstate->filename == NULL);
1428 bool fe_copy = (pipe && whereToSendOutput == DestRemote);
1434 SendCopyBegin(cstate);
1436 processed = CopyTo(cstate);
1439 SendCopyEnd(cstate);
1444 * Make sure we turn off old-style COPY OUT mode upon error. It is
1445 * okay to do this in all cases, since it does nothing if the mode is
1448 pq_endcopyout(true);
1457 * Clean up storage and release resources for COPY TO.
1460 EndCopyTo(CopyState cstate)
1462 if (cstate->queryDesc != NULL)
1464 /* Close down the query and free resources. */
1465 ExecutorEnd(cstate->queryDesc);
1466 FreeQueryDesc(cstate->queryDesc);
1467 PopActiveSnapshot();
1470 /* Clean up storage */
1475 * Copy from relation or query TO file.
1478 CopyTo(CopyState cstate)
1482 Form_pg_attribute *attr;
1487 tupDesc = RelationGetDescr(cstate->rel);
1489 tupDesc = cstate->queryDesc->tupDesc;
1490 attr = tupDesc->attrs;
1491 num_phys_attrs = tupDesc->natts;
1492 cstate->null_print_client = cstate->null_print; /* default */
1494 /* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
1495 cstate->fe_msgbuf = makeStringInfo();
1497 /* Get info about the columns we need to process. */
1498 cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1499 foreach(cur, cstate->attnumlist)
1501 int attnum = lfirst_int(cur);
1506 getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
1510 getTypeOutputInfo(attr[attnum - 1]->atttypid,
1513 fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
1517 * Create a temporary memory context that we can reset once per row to
1518 * recover palloc'd memory. This avoids any problems with leaks inside
1519 * datatype output routines, and should be faster than retail pfree's
1520 * anyway. (We don't need a whole econtext as CopyFrom does.)
1522 cstate->rowcontext = AllocSetContextCreate(CurrentMemoryContext,
1524 ALLOCSET_DEFAULT_MINSIZE,
1525 ALLOCSET_DEFAULT_INITSIZE,
1526 ALLOCSET_DEFAULT_MAXSIZE);
1530 /* Generate header for a binary copy */
1534 CopySendData(cstate, (char *) BinarySignature, 11);
1539 CopySendInt32(cstate, tmp);
1540 /* No header extension */
1542 CopySendInt32(cstate, tmp);
1547 * For non-binary copy, we need to convert null_print to file
1548 * encoding, because it will be sent directly with CopySendString.
1550 if (cstate->need_transcoding)
1551 cstate->null_print_client = pg_server_to_any(cstate->null_print,
1552 cstate->null_print_len,
1553 cstate->file_encoding);
1555 /* if a header has been requested send the line */
1556 if (cstate->header_line)
1558 bool hdr_delim = false;
1560 foreach(cur, cstate->attnumlist)
1562 int attnum = lfirst_int(cur);
1566 CopySendChar(cstate, cstate->delim[0]);
1569 colname = NameStr(attr[attnum - 1]->attname);
1571 CopyAttributeOutCSV(cstate, colname, false,
1572 list_length(cstate->attnumlist) == 1);
1575 CopySendEndOfRow(cstate);
1583 HeapScanDesc scandesc;
1586 values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
1587 nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
1589 scandesc = heap_beginscan(cstate->rel, GetActiveSnapshot(), 0, NULL);
1592 while ((tuple = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
1594 CHECK_FOR_INTERRUPTS();
1596 /* Deconstruct the tuple ... faster than repeated heap_getattr */
1597 heap_deform_tuple(tuple, tupDesc, values, nulls);
1599 /* Format and send the data */
1600 CopyOneRowTo(cstate, HeapTupleGetOid(tuple), values, nulls);
1604 heap_endscan(scandesc);
1611 /* run the plan --- the dest receiver will send tuples */
1612 ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L);
1613 processed = ((DR_copy *) cstate->queryDesc->dest)->processed;
1618 /* Generate trailer for a binary copy */
1619 CopySendInt16(cstate, -1);
1620 /* Need to flush out the trailer */
1621 CopySendEndOfRow(cstate);
1624 MemoryContextDelete(cstate->rowcontext);
1630 * Emit one row during CopyTo().
1633 CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
1635 bool need_delim = false;
1636 FmgrInfo *out_functions = cstate->out_functions;
1637 MemoryContext oldcontext;
1641 MemoryContextReset(cstate->rowcontext);
1642 oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
1646 /* Binary per-tuple header */
1647 CopySendInt16(cstate, list_length(cstate->attnumlist));
1648 /* Send OID if wanted --- note attnumlist doesn't include it */
1651 /* Hack --- assume Oid is same size as int32 */
1652 CopySendInt32(cstate, sizeof(int32));
1653 CopySendInt32(cstate, tupleOid);
1658 /* Text format has no per-tuple header, but send OID if wanted */
1659 /* Assume digits don't need any quoting or encoding conversion */
1662 string = DatumGetCString(DirectFunctionCall1(oidout,
1663 ObjectIdGetDatum(tupleOid)));
1664 CopySendString(cstate, string);
1669 foreach(cur, cstate->attnumlist)
1671 int attnum = lfirst_int(cur);
1672 Datum value = values[attnum - 1];
1673 bool isnull = nulls[attnum - 1];
1675 if (!cstate->binary)
1678 CopySendChar(cstate, cstate->delim[0]);
1684 if (!cstate->binary)
1685 CopySendString(cstate, cstate->null_print_client);
1687 CopySendInt32(cstate, -1);
1691 if (!cstate->binary)
1693 string = OutputFunctionCall(&out_functions[attnum - 1],
1695 if (cstate->csv_mode)
1696 CopyAttributeOutCSV(cstate, string,
1697 cstate->force_quote_flags[attnum - 1],
1698 list_length(cstate->attnumlist) == 1);
1700 CopyAttributeOutText(cstate, string);
1706 outputbytes = SendFunctionCall(&out_functions[attnum - 1],
1708 CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
1709 CopySendData(cstate, VARDATA(outputbytes),
1710 VARSIZE(outputbytes) - VARHDRSZ);
1715 CopySendEndOfRow(cstate);
1717 MemoryContextSwitchTo(oldcontext);
1722 * error context callback for COPY FROM
1724 * The argument for the error context must be CopyState.
1727 CopyFromErrorCallback(void *arg)
1729 CopyState cstate = (CopyState) arg;
1733 /* can't usefully display the data */
1734 if (cstate->cur_attname)
1735 errcontext("COPY %s, line %d, column %s",
1736 cstate->cur_relname, cstate->cur_lineno,
1737 cstate->cur_attname);
1739 errcontext("COPY %s, line %d",
1740 cstate->cur_relname, cstate->cur_lineno);
1744 if (cstate->cur_attname && cstate->cur_attval)
1746 /* error is relevant to a particular column */
1749 attval = limit_printout_length(cstate->cur_attval);
1750 errcontext("COPY %s, line %d, column %s: \"%s\"",
1751 cstate->cur_relname, cstate->cur_lineno,
1752 cstate->cur_attname, attval);
1755 else if (cstate->cur_attname)
1757 /* error is relevant to a particular column, value is NULL */
1758 errcontext("COPY %s, line %d, column %s: null input",
1759 cstate->cur_relname, cstate->cur_lineno,
1760 cstate->cur_attname);
1764 /* error is relevant to a particular line */
1765 if (cstate->line_buf_converted || !cstate->need_transcoding)
1769 lineval = limit_printout_length(cstate->line_buf.data);
1770 errcontext("COPY %s, line %d: \"%s\"",
1771 cstate->cur_relname, cstate->cur_lineno, lineval);
1777 * Here, the line buffer is still in a foreign encoding, and
1778 * indeed it's quite likely that the error is precisely a
1779 * failure to do encoding conversion (ie, bad data). We dare
1780 * not try to convert it, and at present there's no way to
1781 * regurgitate it without conversion. So we have to punt and
1782 * just report the line number.
1784 errcontext("COPY %s, line %d",
1785 cstate->cur_relname, cstate->cur_lineno);
1792 * Make sure we don't print an unreasonable amount of COPY data in a message.
1794 * It would seem a lot easier to just use the sprintf "precision" limit to
1795 * truncate the string. However, some versions of glibc have a bug/misfeature
1796 * that vsnprintf will always fail (return -1) if it is asked to truncate
1797 * a string that contains invalid byte sequences for the current encoding.
1798 * So, do our own truncation. We return a pstrdup'd copy of the input.
1801 limit_printout_length(const char *str)
1803 #define MAX_COPY_DATA_DISPLAY 100
1805 int slen = strlen(str);
1809 /* Fast path if definitely okay */
1810 if (slen <= MAX_COPY_DATA_DISPLAY)
1811 return pstrdup(str);
1813 /* Apply encoding-dependent truncation */
1814 len = pg_mbcliplen(str, slen, MAX_COPY_DATA_DISPLAY);
1817 * Truncate, and add "..." to show we truncated the input.
1819 res = (char *) palloc(len + 4);
1820 memcpy(res, str, len);
1821 strcpy(res + len, "...");
1827 * Copy FROM file to relation.
1830 CopyFrom(CopyState cstate)
1836 ResultRelInfo *resultRelInfo;
1837 EState *estate = CreateExecutorState(); /* for ExecConstraints() */
1838 ExprContext *econtext;
1839 TupleTableSlot *slot;
1840 MemoryContext oldcontext = CurrentMemoryContext;
1841 ErrorContextCallback errcontext;
1842 CommandId mycid = GetCurrentCommandId(true);
1843 int hi_options = 0; /* start with default heap_insert options */
1844 BulkInsertState bistate;
1845 uint64 processed = 0;
1847 Assert(cstate->rel);
1849 if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
1851 if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
1853 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1854 errmsg("cannot copy to view \"%s\"",
1855 RelationGetRelationName(cstate->rel))));
1856 else if (cstate->rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1858 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1859 errmsg("cannot copy to foreign table \"%s\"",
1860 RelationGetRelationName(cstate->rel))));
1861 else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
1863 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1864 errmsg("cannot copy to sequence \"%s\"",
1865 RelationGetRelationName(cstate->rel))));
1868 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1869 errmsg("cannot copy to non-table relation \"%s\"",
1870 RelationGetRelationName(cstate->rel))));
1873 tupDesc = RelationGetDescr(cstate->rel);
1876 * Check to see if we can avoid writing WAL
1878 * If archive logging/streaming is not enabled *and* either
1879 * - table was created in same transaction as this COPY
1880 * - data is being written to relfilenode created in this transaction
1881 * then we can skip writing WAL. It's safe because if the transaction
1882 * doesn't commit, we'll discard the table (or the new relfilenode file).
1883 * If it does commit, we'll have done the heap_sync at the bottom of this
1886 * As mentioned in comments in utils/rel.h, the in-same-transaction test
1887 * is not completely reliable, since in rare cases rd_createSubid or
1888 * rd_newRelfilenodeSubid can be cleared before the end of the transaction.
1889 * However this is OK since at worst we will fail to make the optimization.
1891 * Also, if the target file is new-in-transaction, we assume that checking
1892 * FSM for free space is a waste of time, even if we must use WAL because
1893 * of archiving. This could possibly be wrong, but it's unlikely.
1895 * The comments for heap_insert and RelationGetBufferForTuple specify that
1896 * skipping WAL logging is only safe if we ensure that our tuples do not
1897 * go into pages containing tuples from any other transactions --- but this
1898 * must be the case if we have a new table or new relfilenode, so we need
1899 * no additional work to enforce that.
1902 if (cstate->rel->rd_createSubid != InvalidSubTransactionId ||
1903 cstate->rel->rd_newRelfilenodeSubid != InvalidSubTransactionId)
1905 hi_options |= HEAP_INSERT_SKIP_FSM;
1906 if (!XLogIsNeeded())
1907 hi_options |= HEAP_INSERT_SKIP_WAL;
1911 * We need a ResultRelInfo so we can use the regular executor's
1912 * index-entry-making machinery. (There used to be a huge amount of code
1913 * here that basically duplicated execUtils.c ...)
1915 resultRelInfo = makeNode(ResultRelInfo);
1916 resultRelInfo->ri_RangeTableIndex = 1; /* dummy */
1917 resultRelInfo->ri_RelationDesc = cstate->rel;
1918 resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
1919 if (resultRelInfo->ri_TrigDesc)
1921 resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
1922 palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
1923 resultRelInfo->ri_TrigWhenExprs = (List **)
1924 palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(List *));
1926 resultRelInfo->ri_TrigInstrument = NULL;
1928 ExecOpenIndices(resultRelInfo);
1930 estate->es_result_relations = resultRelInfo;
1931 estate->es_num_result_relations = 1;
1932 estate->es_result_relation_info = resultRelInfo;
1934 /* Set up a tuple slot too */
1935 slot = ExecInitExtraTupleSlot(estate);
1936 ExecSetSlotDescriptor(slot, tupDesc);
1938 /* Prepare to catch AFTER triggers. */
1939 AfterTriggerBeginQuery();
1942 * Check BEFORE STATEMENT insertion triggers. It's debateable whether we
1943 * should do this for COPY, since it's not really an "INSERT" statement as
1944 * such. However, executing these triggers maintains consistency with the
1945 * EACH ROW triggers that we already fire on COPY.
1947 ExecBSInsertTriggers(estate, resultRelInfo);
1949 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
1950 nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
1952 bistate = GetBulkInsertState();
1953 econtext = GetPerTupleExprContext(estate);
1955 /* Set up callback to identify error line number */
1956 errcontext.callback = CopyFromErrorCallback;
1957 errcontext.arg = (void *) cstate;
1958 errcontext.previous = error_context_stack;
1959 error_context_stack = &errcontext;
1964 Oid loaded_oid = InvalidOid;
1966 CHECK_FOR_INTERRUPTS();
1968 /* Reset the per-tuple exprcontext */
1969 ResetPerTupleExprContext(estate);
1971 /* Switch into its memory context */
1972 MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
1974 if (!NextCopyFrom(cstate, econtext, values, nulls, &loaded_oid))
1977 /* And now we can form the input tuple. */
1978 tuple = heap_form_tuple(tupDesc, values, nulls);
1980 if (loaded_oid != InvalidOid)
1981 HeapTupleSetOid(tuple, loaded_oid);
1983 /* Triggers and stuff need to be invoked in query context. */
1984 MemoryContextSwitchTo(oldcontext);
1988 /* BEFORE ROW INSERT Triggers */
1989 if (resultRelInfo->ri_TrigDesc &&
1990 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
1994 newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1996 if (newtuple == NULL) /* "do nothing" */
1998 else if (newtuple != tuple) /* modified by Trigger(s) */
2000 heap_freetuple(tuple);
2007 List *recheckIndexes = NIL;
2009 /* Place tuple in tuple slot */
2010 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2012 /* Check the constraints of the tuple */
2013 if (cstate->rel->rd_att->constr)
2014 ExecConstraints(resultRelInfo, slot, estate);
2016 /* OK, store the tuple and create index entries for it */
2017 heap_insert(cstate->rel, tuple, mycid, hi_options, bistate);
2019 if (resultRelInfo->ri_NumIndices > 0)
2020 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
2023 /* AFTER ROW INSERT Triggers */
2024 ExecARInsertTriggers(estate, resultRelInfo, tuple,
2027 list_free(recheckIndexes);
2030 * We count only tuples not suppressed by a BEFORE INSERT trigger;
2031 * this is the same definition used by execMain.c for counting
2032 * tuples inserted by an INSERT command.
2038 /* Done, clean up */
2039 error_context_stack = errcontext.previous;
2041 FreeBulkInsertState(bistate);
2043 MemoryContextSwitchTo(oldcontext);
2045 /* Execute AFTER STATEMENT insertion triggers */
2046 ExecASInsertTriggers(estate, resultRelInfo);
2048 /* Handle queued AFTER triggers */
2049 AfterTriggerEndQuery(estate);
2054 ExecResetTupleTable(estate->es_tupleTable, false);
2056 ExecCloseIndices(resultRelInfo);
2058 FreeExecutorState(estate);
2061 * If we skipped writing WAL, then we need to sync the heap (but not
2062 * indexes since those use WAL anyway)
2064 if (hi_options & HEAP_INSERT_SKIP_WAL)
2065 heap_sync(cstate->rel);
2071 * Setup to read tuples from a file for COPY FROM.
2073 * 'rel': Used as a template for the tuples
2074 * 'filename': Name of server-local file to read
2075 * 'attnamelist': List of char *, columns to include. NIL selects all cols.
2076 * 'options': List of DefElem. See copy_opt_item in gram.y for selections.
2078 * Returns a CopyState, to be passed to NextCopyFrom and related functions.
2081 BeginCopyFrom(Relation rel,
2082 const char *filename,
2087 bool pipe = (filename == NULL);
2089 Form_pg_attribute *attr;
2090 AttrNumber num_phys_attrs,
2092 FmgrInfo *in_functions;
2097 ExprState **defexprs;
2098 MemoryContext oldcontext;
2100 cstate = BeginCopy(true, rel, NULL, NULL, attnamelist, options);
2101 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
2103 /* Initialize state variables */
2104 cstate->fe_eof = false;
2105 cstate->eol_type = EOL_UNKNOWN;
2106 cstate->cur_relname = RelationGetRelationName(cstate->rel);
2107 cstate->cur_lineno = 0;
2108 cstate->cur_attname = NULL;
2109 cstate->cur_attval = NULL;
2111 /* Set up variables to avoid per-attribute overhead. */
2112 initStringInfo(&cstate->attribute_buf);
2113 initStringInfo(&cstate->line_buf);
2114 cstate->line_buf_converted = false;
2115 cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
2116 cstate->raw_buf_index = cstate->raw_buf_len = 0;
2118 tupDesc = RelationGetDescr(cstate->rel);
2119 attr = tupDesc->attrs;
2120 num_phys_attrs = tupDesc->natts;
2124 * Pick up the required catalog information for each attribute in the
2125 * relation, including the input function, the element type (to pass to
2126 * the input function), and info about defaults and constraints. (Which
2127 * input function we use depends on text/binary format choice.)
2129 in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2130 typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
2131 defmap = (int *) palloc(num_phys_attrs * sizeof(int));
2132 defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
2134 for (attnum = 1; attnum <= num_phys_attrs; attnum++)
2136 /* We don't need info for dropped attributes */
2137 if (attr[attnum - 1]->attisdropped)
2140 /* Fetch the input function and typioparam info */
2142 getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
2143 &in_func_oid, &typioparams[attnum - 1]);
2145 getTypeInputInfo(attr[attnum - 1]->atttypid,
2146 &in_func_oid, &typioparams[attnum - 1]);
2147 fmgr_info(in_func_oid, &in_functions[attnum - 1]);
2149 /* Get default info if needed */
2150 if (!list_member_int(cstate->attnumlist, attnum))
2152 /* attribute is NOT to be copied from input */
2153 /* use default value if one exists */
2154 Node *defexpr = build_column_default(cstate->rel, attnum);
2156 if (defexpr != NULL)
2158 /* Initialize expressions in copycontext. */
2159 defexprs[num_defaults] = ExecInitExpr(
2160 expression_planner((Expr *) defexpr), NULL);
2161 defmap[num_defaults] = attnum - 1;
2167 /* We keep those variables in cstate. */
2168 cstate->in_functions = in_functions;
2169 cstate->typioparams = typioparams;
2170 cstate->defmap = defmap;
2171 cstate->defexprs = defexprs;
2172 cstate->num_defaults = num_defaults;
2176 if (whereToSendOutput == DestRemote)
2177 ReceiveCopyBegin(cstate);
2179 cstate->copy_file = stdin;
2185 cstate->filename = pstrdup(filename);
2186 cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
2188 if (cstate->copy_file == NULL)
2190 (errcode_for_file_access(),
2191 errmsg("could not open file \"%s\" for reading: %m",
2192 cstate->filename)));
2194 fstat(fileno(cstate->copy_file), &st);
2195 if (S_ISDIR(st.st_mode))
2197 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2198 errmsg("\"%s\" is a directory", cstate->filename)));
2201 if (!cstate->binary)
2203 /* must rely on user to tell us... */
2204 cstate->file_has_oids = cstate->oids;
2208 /* Read and verify binary header */
2213 if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
2214 memcmp(readSig, BinarySignature, 11) != 0)
2216 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2217 errmsg("COPY file signature not recognized")));
2219 if (!CopyGetInt32(cstate, &tmp))
2221 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2222 errmsg("invalid COPY file header (missing flags)")));
2223 cstate->file_has_oids = (tmp & (1 << 16)) != 0;
2225 if ((tmp >> 16) != 0)
2227 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2228 errmsg("unrecognized critical flags in COPY file header")));
2229 /* Header extension length */
2230 if (!CopyGetInt32(cstate, &tmp) ||
2233 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2234 errmsg("invalid COPY file header (missing length)")));
2235 /* Skip extension header, if present */
2238 if (CopyGetData(cstate, readSig, 1, 1) != 1)
2240 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2241 errmsg("invalid COPY file header (wrong length)")));
2245 if (cstate->file_has_oids && cstate->binary)
2247 getTypeBinaryInputInfo(OIDOID,
2248 &in_func_oid, &cstate->oid_typioparam);
2249 fmgr_info(in_func_oid, &cstate->oid_in_function);
2252 /* create workspace for CopyReadAttributes results */
2253 if (!cstate->binary)
2255 AttrNumber attr_count = list_length(cstate->attnumlist);
2256 int nfields = cstate->file_has_oids ? (attr_count + 1) : attr_count;
2258 cstate->max_fields = nfields;
2259 cstate->raw_fields = (char **) palloc(nfields * sizeof(char *));
2262 MemoryContextSwitchTo(oldcontext);
2268 * Read raw fields in the next line for COPY FROM in text or csv mode.
2269 * Return false if no more lines.
2271 * An internal temporary buffer is returned via 'fields'. It is valid until
2272 * the next call of the function. Since the function returns all raw fields
2273 * in the input file, 'nfields' could be different from the number of columns
2276 * NOTE: force_not_null option are not applied to the returned fields.
2279 NextCopyFromRawFields(CopyState cstate, char ***fields, int *nfields)
2284 /* only available for text or csv input */
2285 Assert(!cstate->binary);
2287 /* on input just throw the header line away */
2288 if (cstate->cur_lineno == 0 && cstate->header_line)
2290 cstate->cur_lineno++;
2291 if (CopyReadLine(cstate))
2292 return false; /* done */
2295 cstate->cur_lineno++;
2297 /* Actually read the line into memory here */
2298 done = CopyReadLine(cstate);
2301 * EOF at start of line means we're done. If we see EOF after
2302 * some characters, we act as though it was newline followed by
2303 * EOF, ie, process the line and then exit loop on next iteration.
2305 if (done && cstate->line_buf.len == 0)
2308 /* Parse the line into de-escaped field values */
2309 if (cstate->csv_mode)
2310 fldct = CopyReadAttributesCSV(cstate);
2312 fldct = CopyReadAttributesText(cstate);
2314 *fields = cstate->raw_fields;
2320 * Read next tuple from file for COPY FROM. Return false if no more tuples.
2322 * 'econtext' is used to evaluate default expression for each columns not
2323 * read from the file. It can be NULL when no default values are used, i.e.
2324 * when all columns are read from the file.
2326 * 'values' and 'nulls' arrays must be the same length as columns of the
2327 * relation passed to BeginCopyFrom. This function fills the arrays.
2328 * Oid of the tuple is returned with 'tupleOid' separately.
2331 NextCopyFrom(CopyState cstate, ExprContext *econtext,
2332 Datum *values, bool *nulls, Oid *tupleOid)
2335 Form_pg_attribute *attr;
2336 AttrNumber num_phys_attrs,
2338 num_defaults = cstate->num_defaults;
2339 FmgrInfo *in_functions = cstate->in_functions;
2340 Oid *typioparams = cstate->typioparams;
2344 bool file_has_oids = cstate->file_has_oids;
2345 int *defmap = cstate->defmap;
2346 ExprState **defexprs = cstate->defexprs;
2348 tupDesc = RelationGetDescr(cstate->rel);
2349 attr = tupDesc->attrs;
2350 num_phys_attrs = tupDesc->natts;
2351 attr_count = list_length(cstate->attnumlist);
2352 nfields = file_has_oids ? (attr_count + 1) : attr_count;
2354 /* Initialize all values for row to NULL */
2355 MemSet(values, 0, num_phys_attrs * sizeof(Datum));
2356 MemSet(nulls, true, num_phys_attrs * sizeof(bool));
2358 if (!cstate->binary)
2360 char **field_strings;
2366 /* read raw fields in the next line */
2367 if (!NextCopyFromRawFields(cstate, &field_strings, &fldct))
2370 /* check for overflowing fields */
2371 if (nfields > 0 && fldct > nfields)
2373 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2374 errmsg("extra data after last expected column")));
2378 /* Read the OID field if present */
2381 if (fieldno >= fldct)
2383 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2384 errmsg("missing data for OID column")));
2385 string = field_strings[fieldno++];
2389 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2390 errmsg("null OID in COPY data")));
2391 else if (cstate->oids && tupleOid != NULL)
2393 cstate->cur_attname = "oid";
2394 cstate->cur_attval = string;
2395 *tupleOid = DatumGetObjectId(DirectFunctionCall1(oidin,
2396 CStringGetDatum(string)));
2397 if (*tupleOid == InvalidOid)
2399 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2400 errmsg("invalid OID in COPY data")));
2401 cstate->cur_attname = NULL;
2402 cstate->cur_attval = NULL;
2406 /* Loop to read the user attributes on the line. */
2407 foreach(cur, cstate->attnumlist)
2409 int attnum = lfirst_int(cur);
2412 if (fieldno >= fldct)
2414 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2415 errmsg("missing data for column \"%s\"",
2416 NameStr(attr[m]->attname))));
2417 string = field_strings[fieldno++];
2419 if (cstate->csv_mode && string == NULL &&
2420 cstate->force_notnull_flags[m])
2422 /* Go ahead and read the NULL string */
2423 string = cstate->null_print;
2426 cstate->cur_attname = NameStr(attr[m]->attname);
2427 cstate->cur_attval = string;
2428 values[m] = InputFunctionCall(&in_functions[m],
2431 attr[m]->atttypmod);
2434 cstate->cur_attname = NULL;
2435 cstate->cur_attval = NULL;
2438 Assert(fieldno == nfields);
2446 cstate->cur_lineno++;
2448 if (!CopyGetInt16(cstate, &fld_count))
2450 /* EOF detected (end of file, or protocol-level EOF) */
2454 if (fld_count == -1)
2457 * Received EOF marker. In a V3-protocol copy, wait for
2458 * the protocol-level EOF, and complain if it doesn't come
2459 * immediately. This ensures that we correctly handle
2460 * CopyFail, if client chooses to send that now.
2462 * Note that we MUST NOT try to read more data in an
2463 * old-protocol copy, since there is no protocol-level EOF
2464 * marker then. We could go either way for copy from file,
2465 * but choose to throw error if there's data after the EOF
2466 * marker, for consistency with the new-protocol case.
2470 if (cstate->copy_dest != COPY_OLD_FE &&
2471 CopyGetData(cstate, &dummy, 1, 1) > 0)
2473 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2474 errmsg("received copy data after EOF marker")));
2478 if (fld_count != attr_count)
2480 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2481 errmsg("row field count is %d, expected %d",
2482 (int) fld_count, attr_count)));
2488 cstate->cur_attname = "oid";
2490 DatumGetObjectId(CopyReadBinaryAttribute(cstate,
2492 &cstate->oid_in_function,
2493 cstate->oid_typioparam,
2496 if (isnull || loaded_oid == InvalidOid)
2498 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2499 errmsg("invalid OID in COPY data")));
2500 cstate->cur_attname = NULL;
2501 if (cstate->oids && tupleOid != NULL)
2502 *tupleOid = loaded_oid;
2506 foreach(cur, cstate->attnumlist)
2508 int attnum = lfirst_int(cur);
2511 cstate->cur_attname = NameStr(attr[m]->attname);
2513 values[m] = CopyReadBinaryAttribute(cstate,
2519 cstate->cur_attname = NULL;
2524 * Now compute and insert any defaults available for the columns not
2525 * provided by the input data. Anything not processed here or above
2528 for (i = 0; i < num_defaults; i++)
2531 * The caller must supply econtext and have switched into the
2532 * per-tuple memory context in it.
2534 Assert(econtext != NULL);
2535 Assert(CurrentMemoryContext == econtext->ecxt_per_tuple_memory);
2537 values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
2538 &nulls[defmap[i]], NULL);
2545 * Clean up storage and release resources for COPY FROM.
2548 EndCopyFrom(CopyState cstate)
2550 /* No COPY FROM related resources except memory. */
2556 * Read the next input line and stash it in line_buf, with conversion to
2559 * Result is true if read was terminated by EOF, false if terminated
2560 * by newline. The terminating newline or EOF marker is not included
2561 * in the final value of line_buf.
2564 CopyReadLine(CopyState cstate)
2568 resetStringInfo(&cstate->line_buf);
2570 /* Mark that encoding conversion hasn't occurred yet */
2571 cstate->line_buf_converted = false;
2573 /* Parse data and transfer into line_buf */
2574 result = CopyReadLineText(cstate);
2579 * Reached EOF. In protocol version 3, we should ignore anything
2580 * after \. up to the protocol end of copy data. (XXX maybe better
2581 * not to treat \. as special?)
2583 if (cstate->copy_dest == COPY_NEW_FE)
2587 cstate->raw_buf_index = cstate->raw_buf_len;
2588 } while (CopyLoadRawBuf(cstate));
2594 * If we didn't hit EOF, then we must have transferred the EOL marker
2595 * to line_buf along with the data. Get rid of it.
2597 switch (cstate->eol_type)
2600 Assert(cstate->line_buf.len >= 1);
2601 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
2602 cstate->line_buf.len--;
2603 cstate->line_buf.data[cstate->line_buf.len] = '\0';
2606 Assert(cstate->line_buf.len >= 1);
2607 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\r');
2608 cstate->line_buf.len--;
2609 cstate->line_buf.data[cstate->line_buf.len] = '\0';
2612 Assert(cstate->line_buf.len >= 2);
2613 Assert(cstate->line_buf.data[cstate->line_buf.len - 2] == '\r');
2614 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
2615 cstate->line_buf.len -= 2;
2616 cstate->line_buf.data[cstate->line_buf.len] = '\0';
2619 /* shouldn't get here */
2625 /* Done reading the line. Convert it to server encoding. */
2626 if (cstate->need_transcoding)
2630 cvt = pg_any_to_server(cstate->line_buf.data,
2631 cstate->line_buf.len,
2632 cstate->file_encoding);
2633 if (cvt != cstate->line_buf.data)
2635 /* transfer converted data back to line_buf */
2636 resetStringInfo(&cstate->line_buf);
2637 appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
2642 /* Now it's safe to use the buffer in error messages */
2643 cstate->line_buf_converted = true;
2649 * CopyReadLineText - inner loop of CopyReadLine for text mode
2652 CopyReadLineText(CopyState cstate)
2657 bool need_data = false;
2658 bool hit_eof = false;
2659 bool result = false;
2663 bool first_char_in_line = true;
2664 bool in_quote = false,
2665 last_was_esc = false;
2667 char escapec = '\0';
2669 if (cstate->csv_mode)
2671 quotec = cstate->quote[0];
2672 escapec = cstate->escape[0];
2673 /* ignore special escape processing if it's the same as quotec */
2674 if (quotec == escapec)
2678 mblen_str[1] = '\0';
2681 * The objective of this loop is to transfer the entire next input line
2682 * into line_buf. Hence, we only care for detecting newlines (\r and/or
2683 * \n) and the end-of-copy marker (\.).
2685 * In CSV mode, \r and \n inside a quoted field are just part of the data
2686 * value and are put in line_buf. We keep just enough state to know if we
2687 * are currently in a quoted field or not.
2689 * These four characters, and the CSV escape and quote characters, are
2690 * assumed the same in frontend and backend encodings.
2692 * For speed, we try to move data from raw_buf to line_buf in chunks
2693 * rather than one character at a time. raw_buf_ptr points to the next
2694 * character to examine; any characters from raw_buf_index to raw_buf_ptr
2695 * have been determined to be part of the line, but not yet transferred to
2698 * For a little extra speed within the loop, we copy raw_buf and
2699 * raw_buf_len into local variables.
2701 copy_raw_buf = cstate->raw_buf;
2702 raw_buf_ptr = cstate->raw_buf_index;
2703 copy_buf_len = cstate->raw_buf_len;
2711 * Load more data if needed. Ideally we would just force four bytes
2712 * of read-ahead and avoid the many calls to
2713 * IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(), but the COPY_OLD_FE protocol
2714 * does not allow us to read too far ahead or we might read into the
2715 * next data, so we read-ahead only as far we know we can. One
2716 * optimization would be to read-ahead four byte here if
2717 * cstate->copy_dest != COPY_OLD_FE, but it hardly seems worth it,
2718 * considering the size of the buffer.
2720 if (raw_buf_ptr >= copy_buf_len || need_data)
2725 * Try to read some more data. This will certainly reset
2726 * raw_buf_index to zero, and raw_buf_ptr must go with it.
2728 if (!CopyLoadRawBuf(cstate))
2731 copy_buf_len = cstate->raw_buf_len;
2734 * If we are completely out of data, break out of the loop,
2737 if (copy_buf_len <= 0)
2745 /* OK to fetch a character */
2746 prev_raw_ptr = raw_buf_ptr;
2747 c = copy_raw_buf[raw_buf_ptr++];
2749 if (cstate->csv_mode)
2752 * If character is '\\' or '\r', we may need to look ahead below.
2753 * Force fetch of the next character if we don't already have it.
2754 * We need to do this before changing CSV state, in case one of
2755 * these characters is also the quote or escape character.
2757 * Note: old-protocol does not like forced prefetch, but it's OK
2758 * here since we cannot validly be at EOF.
2760 if (c == '\\' || c == '\r')
2762 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2766 * Dealing with quotes and escapes here is mildly tricky. If the
2767 * quote char is also the escape char, there's no problem - we
2768 * just use the char as a toggle. If they are different, we need
2769 * to ensure that we only take account of an escape inside a
2770 * quoted field and immediately preceding a quote char, and not
2771 * the second in a escape-escape sequence.
2773 if (in_quote && c == escapec)
2774 last_was_esc = !last_was_esc;
2775 if (c == quotec && !last_was_esc)
2776 in_quote = !in_quote;
2778 last_was_esc = false;
2781 * Updating the line count for embedded CR and/or LF chars is
2782 * necessarily a little fragile - this test is probably about the
2783 * best we can do. (XXX it's arguable whether we should do this
2784 * at all --- is cur_lineno a physical or logical count?)
2786 if (in_quote && c == (cstate->eol_type == EOL_NL ? '\n' : '\r'))
2787 cstate->cur_lineno++;
2791 if (c == '\r' && (!cstate->csv_mode || !in_quote))
2793 /* Check for \r\n on first line, _and_ handle \r\n. */
2794 if (cstate->eol_type == EOL_UNKNOWN ||
2795 cstate->eol_type == EOL_CRNL)
2798 * If need more data, go back to loop top to load it.
2800 * Note that if we are at EOF, c will wind up as '\0' because
2801 * of the guaranteed pad of raw_buf.
2803 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2806 c = copy_raw_buf[raw_buf_ptr];
2810 raw_buf_ptr++; /* eat newline */
2811 cstate->eol_type = EOL_CRNL; /* in case not set yet */
2815 /* found \r, but no \n */
2816 if (cstate->eol_type == EOL_CRNL)
2818 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2820 errmsg("literal carriage return found in data") :
2821 errmsg("unquoted carriage return found in data"),
2823 errhint("Use \"\\r\" to represent carriage return.") :
2824 errhint("Use quoted CSV field to represent carriage return.")));
2827 * if we got here, it is the first line and we didn't find
2828 * \n, so don't consume the peeked character
2830 cstate->eol_type = EOL_CR;
2833 else if (cstate->eol_type == EOL_NL)
2835 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2837 errmsg("literal carriage return found in data") :
2838 errmsg("unquoted carriage return found in data"),
2840 errhint("Use \"\\r\" to represent carriage return.") :
2841 errhint("Use quoted CSV field to represent carriage return.")));
2842 /* If reach here, we have found the line terminator */
2847 if (c == '\n' && (!cstate->csv_mode || !in_quote))
2849 if (cstate->eol_type == EOL_CR || cstate->eol_type == EOL_CRNL)
2851 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2853 errmsg("literal newline found in data") :
2854 errmsg("unquoted newline found in data"),
2856 errhint("Use \"\\n\" to represent newline.") :
2857 errhint("Use quoted CSV field to represent newline.")));
2858 cstate->eol_type = EOL_NL; /* in case not set yet */
2859 /* If reach here, we have found the line terminator */
2864 * In CSV mode, we only recognize \. alone on a line. This is because
2865 * \. is a valid CSV data value.
2867 if (c == '\\' && (!cstate->csv_mode || first_char_in_line))
2871 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2872 IF_NEED_REFILL_AND_EOF_BREAK(0);
2875 * get next character
2876 * Note: we do not change c so if it isn't \., we can fall
2877 * through and continue processing for file encoding.
2880 c2 = copy_raw_buf[raw_buf_ptr];
2884 raw_buf_ptr++; /* consume the '.' */
2887 * Note: if we loop back for more data here, it does not
2888 * matter that the CSV state change checks are re-executed; we
2889 * will come back here with no important state changed.
2891 if (cstate->eol_type == EOL_CRNL)
2893 /* Get the next character */
2894 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2895 /* if hit_eof, c2 will become '\0' */
2896 c2 = copy_raw_buf[raw_buf_ptr++];
2900 if (!cstate->csv_mode)
2902 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2903 errmsg("end-of-copy marker does not match previous newline style")));
2905 NO_END_OF_COPY_GOTO;
2907 else if (c2 != '\r')
2909 if (!cstate->csv_mode)
2911 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2912 errmsg("end-of-copy marker corrupt")));
2914 NO_END_OF_COPY_GOTO;
2918 /* Get the next character */
2919 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2920 /* if hit_eof, c2 will become '\0' */
2921 c2 = copy_raw_buf[raw_buf_ptr++];
2923 if (c2 != '\r' && c2 != '\n')
2925 if (!cstate->csv_mode)
2927 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2928 errmsg("end-of-copy marker corrupt")));
2930 NO_END_OF_COPY_GOTO;
2933 if ((cstate->eol_type == EOL_NL && c2 != '\n') ||
2934 (cstate->eol_type == EOL_CRNL && c2 != '\n') ||
2935 (cstate->eol_type == EOL_CR && c2 != '\r'))
2938 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2939 errmsg("end-of-copy marker does not match previous newline style")));
2943 * Transfer only the data before the \. into line_buf, then
2944 * discard the data and the \. sequence.
2946 if (prev_raw_ptr > cstate->raw_buf_index)
2947 appendBinaryStringInfo(&cstate->line_buf,
2948 cstate->raw_buf + cstate->raw_buf_index,
2949 prev_raw_ptr - cstate->raw_buf_index);
2950 cstate->raw_buf_index = raw_buf_ptr;
2951 result = true; /* report EOF */
2954 else if (!cstate->csv_mode)
2957 * If we are here, it means we found a backslash followed by
2958 * something other than a period. In non-CSV mode, anything
2959 * after a backslash is special, so we skip over that second
2960 * character too. If we didn't do that \\. would be
2961 * considered an eof-of copy, while in non-CSV mode it is a
2962 * literal backslash followed by a period. In CSV mode,
2963 * backslashes are not special, so we want to process the
2964 * character after the backslash just like a normal character,
2965 * so we don't increment in those cases.
2971 * This label is for CSV cases where \. appears at the start of a
2972 * line, but there is more text after it, meaning it was a data value.
2973 * We are more strict for \. in CSV mode because \. could be a data
2974 * value, while in non-CSV mode, \. cannot be a data value.
2979 * Process all bytes of a multi-byte character as a group.
2981 * We only support multi-byte sequences where the first byte has the
2982 * high-bit set, so as an optimization we can avoid this block
2983 * entirely if it is not set.
2985 if (cstate->encoding_embeds_ascii && IS_HIGHBIT_SET(c))
2990 /* All our encodings only read the first byte to get the length */
2991 mblen = pg_encoding_mblen(cstate->file_encoding, mblen_str);
2992 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(mblen - 1);
2993 IF_NEED_REFILL_AND_EOF_BREAK(mblen - 1);
2994 raw_buf_ptr += mblen - 1;
2996 first_char_in_line = false;
2997 } /* end of outer loop */
3000 * Transfer any still-uncopied data to line_buf.
3008 * Return decimal value for a hexadecimal digit
3011 GetDecimalFromHex(char hex)
3013 if (isdigit((unsigned char) hex))
3016 return tolower((unsigned char) hex) - 'a' + 10;
3020 * Parse the current line into separate attributes (fields),
3021 * performing de-escaping as needed.
3023 * The input is in line_buf. We use attribute_buf to hold the result
3024 * strings. cstate->raw_fields[k] is set to point to the k'th attribute
3025 * string, or NULL when the input matches the null marker string.
3026 * This array is expanded as necessary.
3028 * (Note that the caller cannot check for nulls since the returned
3029 * string would be the post-de-escaping equivalent, which may look
3030 * the same as some valid data string.)
3032 * delim is the column delimiter string (must be just one byte for now).
3033 * null_print is the null marker string. Note that this is compared to
3034 * the pre-de-escaped input string.
3036 * The return value is the number of fields actually read.
3039 CopyReadAttributesText(CopyState cstate)
3041 char delimc = cstate->delim[0];
3048 * We need a special case for zero-column tables: check that the input
3049 * line is empty, and return.
3051 if (cstate->max_fields <= 0)
3053 if (cstate->line_buf.len != 0)
3055 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3056 errmsg("extra data after last expected column")));
3060 resetStringInfo(&cstate->attribute_buf);
3063 * The de-escaped attributes will certainly not be longer than the input
3064 * data line, so we can just force attribute_buf to be large enough and
3065 * then transfer data without any checks for enough space. We need to do
3066 * it this way because enlarging attribute_buf mid-stream would invalidate
3067 * pointers already stored into cstate->raw_fields[].
3069 if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
3070 enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
3071 output_ptr = cstate->attribute_buf.data;
3073 /* set pointer variables for loop */
3074 cur_ptr = cstate->line_buf.data;
3075 line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
3077 /* Outer loop iterates over fields */
3081 bool found_delim = false;
3085 bool saw_non_ascii = false;
3087 /* Make sure there is enough space for the next value */
3088 if (fieldno >= cstate->max_fields)
3090 cstate->max_fields *= 2;
3091 cstate->raw_fields =
3092 repalloc(cstate->raw_fields, cstate->max_fields*sizeof(char *));
3095 /* Remember start of field on both input and output sides */
3096 start_ptr = cur_ptr;
3097 cstate->raw_fields[fieldno] = output_ptr;
3099 /* Scan data for field */
3105 if (cur_ptr >= line_end_ptr)
3115 if (cur_ptr >= line_end_ptr)
3133 if (cur_ptr < line_end_ptr)
3139 val = (val << 3) + OCTVALUE(c);
3140 if (cur_ptr < line_end_ptr)
3146 val = (val << 3) + OCTVALUE(c);
3152 if (c == '\0' || IS_HIGHBIT_SET(c))
3153 saw_non_ascii = true;
3158 if (cur_ptr < line_end_ptr)
3160 char hexchar = *cur_ptr;
3162 if (isxdigit((unsigned char) hexchar))
3164 int val = GetDecimalFromHex(hexchar);
3167 if (cur_ptr < line_end_ptr)
3170 if (isxdigit((unsigned char) hexchar))
3173 val = (val << 4) + GetDecimalFromHex(hexchar);
3177 if (c == '\0' || IS_HIGHBIT_SET(c))
3178 saw_non_ascii = true;
3202 * in all other cases, take the char after '\'
3208 /* Add c to output string */
3212 /* Terminate attribute value in output area */
3213 *output_ptr++ = '\0';
3216 * If we de-escaped a non-7-bit-ASCII char, make sure we still have
3217 * valid data for the db encoding. Avoid calling strlen here for the
3218 * sake of efficiency.
3222 char *fld = cstate->raw_fields[fieldno];
3224 pg_verifymbstr(fld, output_ptr - (fld + 1), false);
3227 /* Check whether raw input matched null marker */
3228 input_len = end_ptr - start_ptr;
3229 if (input_len == cstate->null_print_len &&
3230 strncmp(start_ptr, cstate->null_print, input_len) == 0)
3231 cstate->raw_fields[fieldno] = NULL;
3234 /* Done if we hit EOL instead of a delim */
3239 /* Clean up state of attribute_buf */
3241 Assert(*output_ptr == '\0');
3242 cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
3248 * Parse the current line into separate attributes (fields),
3249 * performing de-escaping as needed. This has exactly the same API as
3250 * CopyReadAttributesText, except we parse the fields according to
3251 * "standard" (i.e. common) CSV usage.
3254 CopyReadAttributesCSV(CopyState cstate)
3256 char delimc = cstate->delim[0];
3257 char quotec = cstate->quote[0];
3258 char escapec = cstate->escape[0];
3265 * We need a special case for zero-column tables: check that the input
3266 * line is empty, and return.
3268 if (cstate->max_fields <= 0)
3270 if (cstate->line_buf.len != 0)
3272 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3273 errmsg("extra data after last expected column")));
3277 resetStringInfo(&cstate->attribute_buf);
3280 * The de-escaped attributes will certainly not be longer than the input
3281 * data line, so we can just force attribute_buf to be large enough and
3282 * then transfer data without any checks for enough space. We need to do
3283 * it this way because enlarging attribute_buf mid-stream would invalidate
3284 * pointers already stored into cstate->raw_fields[].
3286 if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
3287 enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
3288 output_ptr = cstate->attribute_buf.data;
3290 /* set pointer variables for loop */
3291 cur_ptr = cstate->line_buf.data;
3292 line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
3294 /* Outer loop iterates over fields */
3298 bool found_delim = false;
3299 bool saw_quote = false;
3304 /* Make sure there is enough space for the next value */
3305 if (fieldno >= cstate->max_fields)
3307 cstate->max_fields *= 2;
3308 cstate->raw_fields =
3309 repalloc(cstate->raw_fields, cstate->max_fields*sizeof(char *));
3312 /* Remember start of field on both input and output sides */
3313 start_ptr = cur_ptr;
3314 cstate->raw_fields[fieldno] = output_ptr;
3317 * Scan data for field,
3319 * The loop starts in "not quote" mode and then toggles between that
3320 * and "in quote" mode. The loop exits normally if it is in "not
3321 * quote" mode and a delimiter or line end is seen.
3331 if (cur_ptr >= line_end_ptr)
3334 /* unquoted field delimiter */
3340 /* start of quoted field (or part of field) */
3346 /* Add c to output string */
3354 if (cur_ptr >= line_end_ptr)
3356 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3357 errmsg("unterminated CSV quoted field")));
3361 /* escape within a quoted field */
3365 * peek at the next char if available, and escape it if it
3366 * is an escape char or a quote char
3368 if (cur_ptr < line_end_ptr)
3370 char nextc = *cur_ptr;
3372 if (nextc == escapec || nextc == quotec)
3374 *output_ptr++ = nextc;
3382 * end of quoted field. Must do this test after testing for
3383 * escape in case quote char and escape char are the same
3384 * (which is the common case).
3389 /* Add c to output string */
3395 /* Terminate attribute value in output area */
3396 *output_ptr++ = '\0';
3398 /* Check whether raw input matched null marker */
3399 input_len = end_ptr - start_ptr;
3400 if (!saw_quote && input_len == cstate->null_print_len &&
3401 strncmp(start_ptr, cstate->null_print, input_len) == 0)
3402 cstate->raw_fields[fieldno] = NULL;
3405 /* Done if we hit EOL instead of a delim */
3410 /* Clean up state of attribute_buf */
3412 Assert(*output_ptr == '\0');
3413 cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
3420 * Read a binary attribute
3423 CopyReadBinaryAttribute(CopyState cstate,
3424 int column_no, FmgrInfo *flinfo,
3425 Oid typioparam, int32 typmod,
3431 if (!CopyGetInt32(cstate, &fld_size))
3433 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3434 errmsg("unexpected EOF in COPY data")));
3438 return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
3442 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3443 errmsg("invalid field size")));
3445 /* reset attribute_buf to empty, and load raw data in it */
3446 resetStringInfo(&cstate->attribute_buf);
3448 enlargeStringInfo(&cstate->attribute_buf, fld_size);
3449 if (CopyGetData(cstate, cstate->attribute_buf.data,
3450 fld_size, fld_size) != fld_size)
3452 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3453 errmsg("unexpected EOF in COPY data")));
3455 cstate->attribute_buf.len = fld_size;
3456 cstate->attribute_buf.data[fld_size] = '\0';
3458 /* Call the column type's binary input converter */
3459 result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
3460 typioparam, typmod);
3462 /* Trouble if it didn't eat the whole buffer */
3463 if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
3465 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
3466 errmsg("incorrect binary data format")));
3473 * Send text representation of one attribute, with conversion and escaping
3475 #define DUMPSOFAR() \
3478 CopySendData(cstate, start, ptr - start); \
3482 CopyAttributeOutText(CopyState cstate, char *string)
3487 char delimc = cstate->delim[0];
3489 if (cstate->need_transcoding)
3490 ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
3495 * We have to grovel through the string searching for control characters
3496 * and instances of the delimiter character. In most cases, though, these
3497 * are infrequent. To avoid overhead from calling CopySendData once per
3498 * character, we dump out all characters between escaped characters in a
3499 * single call. The loop invariant is that the data from "start" to "ptr"
3500 * can be sent literally, but hasn't yet been.
3502 * We can skip pg_encoding_mblen() overhead when encoding is safe, because
3503 * in valid backend encodings, extra bytes of a multibyte character never
3504 * look like ASCII. This loop is sufficiently performance-critical that
3505 * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
3506 * of the normal safe-encoding path.
3508 if (cstate->encoding_embeds_ascii)
3511 while ((c = *ptr) != '\0')
3513 if ((unsigned char) c < (unsigned char) 0x20)
3516 * \r and \n must be escaped, the others are traditional. We
3517 * prefer to dump these using the C-like notation, rather than
3518 * a backslash and the literal character, because it makes the
3519 * dump file a bit more proof against Microsoftish data
3543 /* If it's the delimiter, must backslash it */
3546 /* All ASCII control chars are length 1 */
3548 continue; /* fall to end of loop */
3550 /* if we get here, we need to convert the control char */
3552 CopySendChar(cstate, '\\');
3553 CopySendChar(cstate, c);
3554 start = ++ptr; /* do not include char in next run */
3556 else if (c == '\\' || c == delimc)
3559 CopySendChar(cstate, '\\');
3560 start = ptr++; /* we include char in next run */
3562 else if (IS_HIGHBIT_SET(c))
3563 ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
3571 while ((c = *ptr) != '\0')
3573 if ((unsigned char) c < (unsigned char) 0x20)
3576 * \r and \n must be escaped, the others are traditional. We
3577 * prefer to dump these using the C-like notation, rather than
3578 * a backslash and the literal character, because it makes the
3579 * dump file a bit more proof against Microsoftish data
3603 /* If it's the delimiter, must backslash it */
3606 /* All ASCII control chars are length 1 */
3608 continue; /* fall to end of loop */
3610 /* if we get here, we need to convert the control char */
3612 CopySendChar(cstate, '\\');
3613 CopySendChar(cstate, c);
3614 start = ++ptr; /* do not include char in next run */
3616 else if (c == '\\' || c == delimc)
3619 CopySendChar(cstate, '\\');
3620 start = ptr++; /* we include char in next run */
3631 * Send text representation of one attribute, with conversion and
3632 * CSV-style escaping
3635 CopyAttributeOutCSV(CopyState cstate, char *string,
3636 bool use_quote, bool single_attr)
3641 char delimc = cstate->delim[0];
3642 char quotec = cstate->quote[0];
3643 char escapec = cstate->escape[0];
3645 /* force quoting if it matches null_print (before conversion!) */
3646 if (!use_quote && strcmp(string, cstate->null_print) == 0)
3649 if (cstate->need_transcoding)
3650 ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
3655 * Make a preliminary pass to discover if it needs quoting
3660 * Because '\.' can be a data value, quote it if it appears alone on a
3661 * line so it is not interpreted as the end-of-data marker.
3663 if (single_attr && strcmp(ptr, "\\.") == 0)
3669 while ((c = *tptr) != '\0')
3671 if (c == delimc || c == quotec || c == '\n' || c == '\r')
3676 if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
3677 tptr += pg_encoding_mblen(cstate->file_encoding, tptr);
3686 CopySendChar(cstate, quotec);
3689 * We adopt the same optimization strategy as in CopyAttributeOutText
3692 while ((c = *ptr) != '\0')
3694 if (c == quotec || c == escapec)
3697 CopySendChar(cstate, escapec);
3698 start = ptr; /* we include char in next run */
3700 if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
3701 ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
3707 CopySendChar(cstate, quotec);
3711 /* If it doesn't need quoting, we can just dump it as-is */
3712 CopySendString(cstate, ptr);
3717 * CopyGetAttnums - build an integer list of attnums to be copied
3719 * The input attnamelist is either the user-specified column list,
3720 * or NIL if there was none (in which case we want all the non-dropped
3723 * rel can be NULL ... it's only used for error reports.
3726 CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
3728 List *attnums = NIL;
3730 if (attnamelist == NIL)
3732 /* Generate default column list */
3733 Form_pg_attribute *attr = tupDesc->attrs;
3734 int attr_count = tupDesc->natts;
3737 for (i = 0; i < attr_count; i++)
3739 if (attr[i]->attisdropped)
3741 attnums = lappend_int(attnums, i + 1);
3746 /* Validate the user-supplied list and extract attnums */
3749 foreach(l, attnamelist)
3751 char *name = strVal(lfirst(l));
3755 /* Lookup column name */
3756 attnum = InvalidAttrNumber;
3757 for (i = 0; i < tupDesc->natts; i++)
3759 if (tupDesc->attrs[i]->attisdropped)
3761 if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
3763 attnum = tupDesc->attrs[i]->attnum;
3767 if (attnum == InvalidAttrNumber)
3771 (errcode(ERRCODE_UNDEFINED_COLUMN),
3772 errmsg("column \"%s\" of relation \"%s\" does not exist",
3773 name, RelationGetRelationName(rel))));
3776 (errcode(ERRCODE_UNDEFINED_COLUMN),
3777 errmsg("column \"%s\" does not exist",
3780 /* Check for duplicates */
3781 if (list_member_int(attnums, attnum))
3783 (errcode(ERRCODE_DUPLICATE_COLUMN),
3784 errmsg("column \"%s\" specified more than once",
3786 attnums = lappend_int(attnums, attnum);
3795 * copy_dest_startup --- executor startup
3798 copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
3804 * copy_dest_receive --- receive one tuple
3807 copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
3809 DR_copy *myState = (DR_copy *) self;
3810 CopyState cstate = myState->cstate;
3812 /* Make sure the tuple is fully deconstructed */
3813 slot_getallattrs(slot);
3815 /* And send the data */
3816 CopyOneRowTo(cstate, InvalidOid, slot->tts_values, slot->tts_isnull);
3817 myState->processed++;
3821 * copy_dest_shutdown --- executor end
3824 copy_dest_shutdown(DestReceiver *self)
3830 * copy_dest_destroy --- release DestReceiver object
3833 copy_dest_destroy(DestReceiver *self)
3839 * CreateCopyDestReceiver -- create a suitable DestReceiver object
3842 CreateCopyDestReceiver(void)
3844 DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
3846 self->pub.receiveSlot = copy_dest_receive;
3847 self->pub.rStartup = copy_dest_startup;
3848 self->pub.rShutdown = copy_dest_shutdown;
3849 self->pub.rDestroy = copy_dest_destroy;
3850 self->pub.mydest = DestCopyOut;
3852 self->cstate = NULL; /* will be set later */
3853 self->processed = 0;
3855 return (DestReceiver *) self;