1 /*-------------------------------------------------------------------------
4 * Implements the COPY utility command
6 * Portions Copyright (c) 1996-2014, 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/htup_details.h"
25 #include "access/sysattr.h"
26 #include "access/xact.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_type.h"
29 #include "commands/copy.h"
30 #include "commands/defrem.h"
31 #include "commands/trigger.h"
32 #include "executor/executor.h"
33 #include "libpq/libpq.h"
34 #include "libpq/pqformat.h"
35 #include "mb/pg_wchar.h"
36 #include "miscadmin.h"
37 #include "optimizer/clauses.h"
38 #include "optimizer/planner.h"
39 #include "parser/parse_relation.h"
40 #include "rewrite/rewriteHandler.h"
41 #include "storage/fd.h"
42 #include "tcop/tcopprot.h"
43 #include "utils/acl.h"
44 #include "utils/builtins.h"
45 #include "utils/lsyscache.h"
46 #include "utils/memutils.h"
47 #include "utils/portal.h"
48 #include "utils/rel.h"
49 #include "utils/snapmgr.h"
52 #define ISOCTAL(c) (((c) >= '0') && ((c) <= '7'))
53 #define OCTVALUE(c) ((c) - '0')
56 * Represents the different source/dest cases we need to worry about at
61 COPY_FILE, /* to/from file (or a piped program) */
62 COPY_OLD_FE, /* to/from frontend (2.0 protocol) */
63 COPY_NEW_FE /* to/from frontend (3.0 protocol) */
67 * Represents the end-of-line terminator type of the input
78 * This struct contains all the state variables used throughout a COPY
79 * operation. For simplicity, we use the same struct for all variants of COPY,
80 * even though some fields are used in only some cases.
82 * Multi-byte encodings: all supported client-side encodings encode multi-byte
83 * characters by having the first byte's high bit set. Subsequent bytes of the
84 * character can have the high bit not set. When scanning data in such an
85 * encoding to look for a match to a single-byte (ie ASCII) character, we must
86 * use the full pg_encoding_mblen() machinery to skip over multibyte
87 * characters, else we might find a false match to a trailing byte. In
88 * supported server encodings, there is no possibility of a false match, and
89 * it's faster to make useless comparisons to trailing bytes than it is to
90 * invoke pg_encoding_mblen() to skip over them. encoding_embeds_ascii is TRUE
91 * when we have to do it the hard way.
93 typedef struct CopyStateData
95 /* low-level state data */
96 CopyDest copy_dest; /* type of copy source/destination */
97 FILE *copy_file; /* used if copy_dest == COPY_FILE */
98 StringInfo fe_msgbuf; /* used for all dests during COPY TO, only for
99 * dest == COPY_NEW_FE in COPY FROM */
100 bool fe_eof; /* true if detected end of copy data */
101 EolType eol_type; /* EOL type of input */
102 int file_encoding; /* file or remote side's character encoding */
103 bool need_transcoding; /* file encoding diff from server? */
104 bool encoding_embeds_ascii; /* ASCII can be non-first byte? */
106 /* parameters from the COPY command */
107 Relation rel; /* relation to copy to or from */
108 QueryDesc *queryDesc; /* executable query to copy from */
109 List *attnumlist; /* integer list of attnums to copy */
110 char *filename; /* filename, or NULL for STDIN/STDOUT */
111 bool is_program; /* is 'filename' a program to popen? */
112 bool binary; /* binary format? */
113 bool oids; /* include OIDs? */
114 bool freeze; /* freeze rows on loading? */
115 bool csv_mode; /* Comma Separated Value format? */
116 bool header_line; /* CSV header line? */
117 char *null_print; /* NULL marker string (server encoding!) */
118 int null_print_len; /* length of same */
119 char *null_print_client; /* same converted to file encoding */
120 char *delim; /* column delimiter (must be 1 byte) */
121 char *quote; /* CSV quote char (must be 1 byte) */
122 char *escape; /* CSV escape char (must be 1 byte) */
123 List *force_quote; /* list of column names */
124 bool force_quote_all; /* FORCE QUOTE *? */
125 bool *force_quote_flags; /* per-column CSV FQ flags */
126 List *force_notnull; /* list of column names */
127 bool *force_notnull_flags; /* per-column CSV FNN flags */
128 List *force_null; /* list of column names */
129 bool *force_null_flags; /* per-column CSV FN flags */
130 bool convert_selectively; /* do selective binary conversion? */
131 List *convert_select; /* list of column names (can be NIL) */
132 bool *convert_select_flags; /* per-column CSV/TEXT CS flags */
134 /* these are just for error messages, see CopyFromErrorCallback */
135 const char *cur_relname; /* table name for error messages */
136 int cur_lineno; /* line number for error messages */
137 const char *cur_attname; /* current att for error messages */
138 const char *cur_attval; /* current att value for error messages */
141 * Working state for COPY TO/FROM
143 MemoryContext copycontext; /* per-copy execution context */
146 * Working state for COPY TO
148 FmgrInfo *out_functions; /* lookup info for output functions */
149 MemoryContext rowcontext; /* per-row evaluation context */
152 * Working state for COPY FROM
154 AttrNumber num_defaults;
156 FmgrInfo oid_in_function;
158 FmgrInfo *in_functions; /* array of input functions for each attrs */
159 Oid *typioparams; /* array of element types for in_functions */
160 int *defmap; /* array of default att numbers */
161 ExprState **defexprs; /* array of default att expressions */
162 bool volatile_defexprs; /* is any of defexprs volatile? */
165 * These variables are used to reduce overhead in textual COPY FROM.
167 * attribute_buf holds the separated, de-escaped text for each field of
168 * the current line. The CopyReadAttributes functions return arrays of
169 * pointers into this buffer. We avoid palloc/pfree overhead by re-using
170 * the buffer on each cycle.
172 StringInfoData attribute_buf;
174 /* field raw data pointers found by COPY FROM */
180 * Similarly, line_buf holds the whole input line being processed. The
181 * input cycle is first to read the whole line into line_buf, convert it
182 * to server encoding there, and then extract the individual attribute
183 * fields into attribute_buf. line_buf is preserved unmodified so that we
184 * can display it in error messages if appropriate.
186 StringInfoData line_buf;
187 bool line_buf_converted; /* converted to server encoding? */
188 bool line_buf_valid; /* contains the row being processed? */
191 * Finally, raw_buf holds raw data read from the data source (file or
192 * client connection). CopyReadLine parses this data sufficiently to
193 * locate line boundaries, then transfers the data to line_buf and
194 * converts it. Note: we guarantee that there is a \0 at
195 * raw_buf[raw_buf_len].
197 #define RAW_BUF_SIZE 65536 /* we palloc RAW_BUF_SIZE+1 bytes */
199 int raw_buf_index; /* next byte to process */
200 int raw_buf_len; /* total # of bytes stored */
203 /* DestReceiver for COPY (SELECT) TO */
206 DestReceiver pub; /* publicly-known function pointers */
207 CopyState cstate; /* CopyStateData for the command */
208 uint64 processed; /* # of tuples processed */
213 * These macros centralize code used to process line_buf and raw_buf buffers.
214 * They are macros because they often do continue/break control and to avoid
215 * function call overhead in tight COPY loops.
217 * We must use "if (1)" because the usual "do {...} while(0)" wrapper would
218 * prevent the continue/break processing from working. We end the "if (1)"
219 * with "else ((void) 0)" to ensure the "if" does not unintentionally match
220 * any "else" in the calling code, and to avoid any compiler warnings about
221 * empty statements. See http://www.cit.gu.edu.au/~anthony/info/C/C.macros.
225 * This keeps the character read at the top of the loop in the buffer
226 * even if there is more than one read-ahead.
228 #define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen) \
231 if (raw_buf_ptr + (extralen) >= copy_buf_len && !hit_eof) \
233 raw_buf_ptr = prev_raw_ptr; /* undo fetch */ \
239 /* This consumes the remainder of the buffer and breaks */
240 #define IF_NEED_REFILL_AND_EOF_BREAK(extralen) \
243 if (raw_buf_ptr + (extralen) >= copy_buf_len && hit_eof) \
246 raw_buf_ptr = copy_buf_len; /* consume the partial character */ \
247 /* backslash just before EOF, treat as data char */ \
254 * Transfer any approved data to line_buf; must do this to be sure
255 * there is some room in raw_buf.
257 #define REFILL_LINEBUF \
260 if (raw_buf_ptr > cstate->raw_buf_index) \
262 appendBinaryStringInfo(&cstate->line_buf, \
263 cstate->raw_buf + cstate->raw_buf_index, \
264 raw_buf_ptr - cstate->raw_buf_index); \
265 cstate->raw_buf_index = raw_buf_ptr; \
269 /* Undo any read-ahead and jump out of the block. */
270 #define NO_END_OF_COPY_GOTO \
273 raw_buf_ptr = prev_raw_ptr + 1; \
274 goto not_end_of_copy; \
277 static const char BinarySignature[11] = "PGCOPY\n\377\r\n\0";
280 /* non-export function prototypes */
281 static CopyState BeginCopy(bool is_from, Relation rel, Node *raw_query,
282 const char *queryString, List *attnamelist, List *options);
283 static void EndCopy(CopyState cstate);
284 static void ClosePipeToProgram(CopyState cstate);
285 static CopyState BeginCopyTo(Relation rel, Node *query, const char *queryString,
286 const char *filename, bool is_program, List *attnamelist,
288 static void EndCopyTo(CopyState cstate);
289 static uint64 DoCopyTo(CopyState cstate);
290 static uint64 CopyTo(CopyState cstate);
291 static void CopyOneRowTo(CopyState cstate, Oid tupleOid,
292 Datum *values, bool *nulls);
293 static uint64 CopyFrom(CopyState cstate);
294 static void CopyFromInsertBatch(CopyState cstate, EState *estate,
295 CommandId mycid, int hi_options,
296 ResultRelInfo *resultRelInfo, TupleTableSlot *myslot,
297 BulkInsertState bistate,
298 int nBufferedTuples, HeapTuple *bufferedTuples,
299 int firstBufferedLineNo);
300 static bool CopyReadLine(CopyState cstate);
301 static bool CopyReadLineText(CopyState cstate);
302 static int CopyReadAttributesText(CopyState cstate);
303 static int CopyReadAttributesCSV(CopyState cstate);
304 static Datum CopyReadBinaryAttribute(CopyState cstate,
305 int column_no, FmgrInfo *flinfo,
306 Oid typioparam, int32 typmod,
308 static void CopyAttributeOutText(CopyState cstate, char *string);
309 static void CopyAttributeOutCSV(CopyState cstate, char *string,
310 bool use_quote, bool single_attr);
311 static List *CopyGetAttnums(TupleDesc tupDesc, Relation rel,
313 static char *limit_printout_length(const char *str);
315 /* Low-level communications functions */
316 static void SendCopyBegin(CopyState cstate);
317 static void ReceiveCopyBegin(CopyState cstate);
318 static void SendCopyEnd(CopyState cstate);
319 static void CopySendData(CopyState cstate, const void *databuf, int datasize);
320 static void CopySendString(CopyState cstate, const char *str);
321 static void CopySendChar(CopyState cstate, char c);
322 static void CopySendEndOfRow(CopyState cstate);
323 static int CopyGetData(CopyState cstate, void *databuf,
324 int minread, int maxread);
325 static void CopySendInt32(CopyState cstate, int32 val);
326 static bool CopyGetInt32(CopyState cstate, int32 *val);
327 static void CopySendInt16(CopyState cstate, int16 val);
328 static bool CopyGetInt16(CopyState cstate, int16 *val);
332 * Send copy start/stop messages for frontend copies. These have changed
333 * in past protocol redesigns.
336 SendCopyBegin(CopyState cstate)
338 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
342 int natts = list_length(cstate->attnumlist);
343 int16 format = (cstate->binary ? 1 : 0);
346 pq_beginmessage(&buf, 'H');
347 pq_sendbyte(&buf, format); /* overall format */
348 pq_sendint(&buf, natts, 2);
349 for (i = 0; i < natts; i++)
350 pq_sendint(&buf, format, 2); /* per-column formats */
352 cstate->copy_dest = COPY_NEW_FE;
354 else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
359 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
360 errmsg("COPY BINARY is not supported to stdout or from stdin")));
361 pq_putemptymessage('H');
362 /* grottiness needed for old COPY OUT protocol */
364 cstate->copy_dest = COPY_OLD_FE;
371 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
372 errmsg("COPY BINARY is not supported to stdout or from stdin")));
373 pq_putemptymessage('B');
374 /* grottiness needed for old COPY OUT protocol */
376 cstate->copy_dest = COPY_OLD_FE;
381 ReceiveCopyBegin(CopyState cstate)
383 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
387 int natts = list_length(cstate->attnumlist);
388 int16 format = (cstate->binary ? 1 : 0);
391 pq_beginmessage(&buf, 'G');
392 pq_sendbyte(&buf, format); /* overall format */
393 pq_sendint(&buf, natts, 2);
394 for (i = 0; i < natts; i++)
395 pq_sendint(&buf, format, 2); /* per-column formats */
397 cstate->copy_dest = COPY_NEW_FE;
398 cstate->fe_msgbuf = makeStringInfo();
400 else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
405 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
406 errmsg("COPY BINARY is not supported to stdout or from stdin")));
407 pq_putemptymessage('G');
408 cstate->copy_dest = COPY_OLD_FE;
415 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
416 errmsg("COPY BINARY is not supported to stdout or from stdin")));
417 pq_putemptymessage('D');
418 cstate->copy_dest = COPY_OLD_FE;
420 /* We *must* flush here to ensure FE knows it can send. */
425 SendCopyEnd(CopyState cstate)
427 if (cstate->copy_dest == COPY_NEW_FE)
429 /* Shouldn't have any unsent data */
430 Assert(cstate->fe_msgbuf->len == 0);
431 /* Send Copy Done message */
432 pq_putemptymessage('c');
436 CopySendData(cstate, "\\.", 2);
437 /* Need to flush out the trailer (this also appends a newline) */
438 CopySendEndOfRow(cstate);
439 pq_endcopyout(false);
444 * CopySendData sends output data to the destination (file or frontend)
445 * CopySendString does the same for null-terminated strings
446 * CopySendChar does the same for single characters
447 * CopySendEndOfRow does the appropriate thing at end of each data row
448 * (data is not actually flushed except by CopySendEndOfRow)
450 * NB: no data conversion is applied by these functions
454 CopySendData(CopyState cstate, const void *databuf, int datasize)
456 appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
460 CopySendString(CopyState cstate, const char *str)
462 appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
466 CopySendChar(CopyState cstate, char c)
468 appendStringInfoCharMacro(cstate->fe_msgbuf, c);
472 CopySendEndOfRow(CopyState cstate)
474 StringInfo fe_msgbuf = cstate->fe_msgbuf;
476 switch (cstate->copy_dest)
481 /* Default line termination depends on platform */
483 CopySendChar(cstate, '\n');
485 CopySendString(cstate, "\r\n");
489 if (fwrite(fe_msgbuf->data, fe_msgbuf->len, 1,
490 cstate->copy_file) != 1 ||
491 ferror(cstate->copy_file))
493 if (cstate->is_program)
498 * The pipe will be closed automatically on error at
499 * the end of transaction, but we might get a better
500 * error message from the subprocess' exit code than
503 ClosePipeToProgram(cstate);
506 * If ClosePipeToProgram() didn't throw an error, the
507 * program terminated normally, but closed the pipe
508 * first. Restore errno, and throw an error.
513 (errcode_for_file_access(),
514 errmsg("could not write to COPY program: %m")));
518 (errcode_for_file_access(),
519 errmsg("could not write to COPY file: %m")));
523 /* The FE/BE protocol uses \n as newline for all platforms */
525 CopySendChar(cstate, '\n');
527 if (pq_putbytes(fe_msgbuf->data, fe_msgbuf->len))
529 /* no hope of recovering connection sync, so FATAL */
531 (errcode(ERRCODE_CONNECTION_FAILURE),
532 errmsg("connection lost during COPY to stdout")));
536 /* The FE/BE protocol uses \n as newline for all platforms */
538 CopySendChar(cstate, '\n');
540 /* Dump the accumulated row as one CopyData message */
541 (void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
545 resetStringInfo(fe_msgbuf);
549 * CopyGetData reads data from the source (file or frontend)
551 * We attempt to read at least minread, and at most maxread, bytes from
552 * the source. The actual number of bytes read is returned; if this is
553 * less than minread, EOF was detected.
555 * Note: when copying from the frontend, we expect a proper EOF mark per
556 * protocol; if the frontend simply drops the connection, we raise error.
557 * It seems unwise to allow the COPY IN to complete normally in that case.
559 * NB: no data conversion is applied here.
562 CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
566 switch (cstate->copy_dest)
569 bytesread = fread(databuf, 1, maxread, cstate->copy_file);
570 if (ferror(cstate->copy_file))
572 (errcode_for_file_access(),
573 errmsg("could not read from COPY file: %m")));
578 * We cannot read more than minread bytes (which in practice is 1)
579 * because old protocol doesn't have any clear way of separating
580 * the COPY stream from following data. This is slow, but not any
581 * slower than the code path was originally, and we don't care
582 * much anymore about the performance of old protocol.
584 if (pq_getbytes((char *) databuf, minread))
586 /* Only a \. terminator is legal EOF in old protocol */
588 (errcode(ERRCODE_CONNECTION_FAILURE),
589 errmsg("unexpected EOF on client connection with an open transaction")));
594 while (maxread > 0 && bytesread < minread && !cstate->fe_eof)
598 while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
600 /* Try to receive another message */
604 mtype = pq_getbyte();
607 (errcode(ERRCODE_CONNECTION_FAILURE),
608 errmsg("unexpected EOF on client connection with an open transaction")));
609 if (pq_getmessage(cstate->fe_msgbuf, 0))
611 (errcode(ERRCODE_CONNECTION_FAILURE),
612 errmsg("unexpected EOF on client connection with an open transaction")));
615 case 'd': /* CopyData */
617 case 'c': /* CopyDone */
618 /* COPY IN correctly terminated by frontend */
619 cstate->fe_eof = true;
621 case 'f': /* CopyFail */
623 (errcode(ERRCODE_QUERY_CANCELED),
624 errmsg("COPY from stdin failed: %s",
625 pq_getmsgstring(cstate->fe_msgbuf))));
627 case 'H': /* Flush */
631 * Ignore Flush/Sync for the convenience of client
632 * libraries (such as libpq) that may send those
633 * without noticing that the command they just
639 (errcode(ERRCODE_PROTOCOL_VIOLATION),
640 errmsg("unexpected message type 0x%02X during COPY from stdin",
645 avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
648 pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
649 databuf = (void *) ((char *) databuf + avail);
661 * These functions do apply some data conversion
665 * CopySendInt32 sends an int32 in network byte order
668 CopySendInt32(CopyState cstate, int32 val)
672 buf = htonl((uint32) val);
673 CopySendData(cstate, &buf, sizeof(buf));
677 * CopyGetInt32 reads an int32 that appears in network byte order
679 * Returns true if OK, false if EOF
682 CopyGetInt32(CopyState cstate, int32 *val)
686 if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
688 *val = 0; /* suppress compiler warning */
691 *val = (int32) ntohl(buf);
696 * CopySendInt16 sends an int16 in network byte order
699 CopySendInt16(CopyState cstate, int16 val)
703 buf = htons((uint16) val);
704 CopySendData(cstate, &buf, sizeof(buf));
708 * CopyGetInt16 reads an int16 that appears in network byte order
711 CopyGetInt16(CopyState cstate, int16 *val)
715 if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
717 *val = 0; /* suppress compiler warning */
720 *val = (int16) ntohs(buf);
726 * CopyLoadRawBuf loads some more data into raw_buf
728 * Returns TRUE if able to obtain at least one more byte, else FALSE.
730 * If raw_buf_index < raw_buf_len, the unprocessed bytes are transferred
731 * down to the start of the buffer and then we load more data after that.
732 * This case is used only when a frontend multibyte character crosses a
733 * bufferload boundary.
736 CopyLoadRawBuf(CopyState cstate)
741 if (cstate->raw_buf_index < cstate->raw_buf_len)
743 /* Copy down the unprocessed data */
744 nbytes = cstate->raw_buf_len - cstate->raw_buf_index;
745 memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
749 nbytes = 0; /* no data need be saved */
751 inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
752 1, RAW_BUF_SIZE - nbytes);
754 cstate->raw_buf[nbytes] = '\0';
755 cstate->raw_buf_index = 0;
756 cstate->raw_buf_len = nbytes;
757 return (inbytes > 0);
762 * DoCopy executes the SQL COPY statement
764 * Either unload or reload contents of table <relation>, depending on <from>.
765 * (<from> = TRUE means we are inserting into the table.) In the "TO" case
766 * we also support copying the output of an arbitrary SELECT query.
768 * If <pipe> is false, transfer is between the table and the file named
769 * <filename>. Otherwise, transfer is between the table and our regular
770 * input/output stream. The latter could be either stdin/stdout or a
771 * socket, depending on whether we're running under Postmaster control.
773 * Do not allow a Postgres user without superuser privilege to read from
774 * or write to a file.
776 * Do not allow the copy if user doesn't have proper permission to access
777 * the table or the specifically requested columns.
780 DoCopy(const CopyStmt *stmt, const char *queryString, uint64 *processed)
783 bool is_from = stmt->is_from;
784 bool pipe = (stmt->filename == NULL);
788 /* Disallow COPY to/from file or program except to superusers. */
789 if (!pipe && !superuser())
791 if (stmt->is_program)
793 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
794 errmsg("must be superuser to COPY to or from an external program"),
795 errhint("Anyone can COPY to stdout or from stdin. "
796 "psql's \\copy command also works for anyone.")));
799 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
800 errmsg("must be superuser to COPY to or from a file"),
801 errhint("Anyone can COPY to stdout or from stdin. "
802 "psql's \\copy command also works for anyone.")));
808 AclMode required_access = (is_from ? ACL_INSERT : ACL_SELECT);
813 Assert(!stmt->query);
815 /* Open and lock the relation, using the appropriate lock type. */
816 rel = heap_openrv(stmt->relation,
817 (is_from ? RowExclusiveLock : AccessShareLock));
819 relid = RelationGetRelid(rel);
821 rte = makeNode(RangeTblEntry);
822 rte->rtekind = RTE_RELATION;
823 rte->relid = RelationGetRelid(rel);
824 rte->relkind = rel->rd_rel->relkind;
825 rte->requiredPerms = required_access;
827 tupDesc = RelationGetDescr(rel);
828 attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
829 foreach(cur, attnums)
831 int attno = lfirst_int(cur) -
832 FirstLowInvalidHeapAttributeNumber;
835 rte->modifiedCols = bms_add_member(rte->modifiedCols, attno);
837 rte->selectedCols = bms_add_member(rte->selectedCols, attno);
839 ExecCheckRTPerms(list_make1(rte), true);
853 /* check read-only transaction */
854 if (XactReadOnly && !rel->rd_islocaltemp)
855 PreventCommandIfReadOnly("COPY FROM");
857 cstate = BeginCopyFrom(rel, stmt->filename, stmt->is_program,
858 stmt->attlist, stmt->options);
859 *processed = CopyFrom(cstate); /* copy from file to database */
864 cstate = BeginCopyTo(rel, stmt->query, queryString,
865 stmt->filename, stmt->is_program,
866 stmt->attlist, stmt->options);
867 *processed = DoCopyTo(cstate); /* copy from database to file */
872 * Close the relation. If reading, we can release the AccessShareLock we
873 * got; if writing, we should hold the lock until end of transaction to
874 * ensure that updates will be committed before lock is released.
877 heap_close(rel, (is_from ? NoLock : AccessShareLock));
883 * Process the statement option list for COPY.
885 * Scan the options list (a list of DefElem) and transpose the information
886 * into cstate, applying appropriate error checking.
888 * cstate is assumed to be filled with zeroes initially.
890 * This is exported so that external users of the COPY API can sanity-check
891 * a list of options. In that usage, cstate should be passed as NULL
892 * (since external users don't know sizeof(CopyStateData)) and the collected
893 * data is just leaked until CurrentMemoryContext is reset.
895 * Note that additional checking, such as whether column names listed in FORCE
896 * QUOTE actually exist, has to be applied later. This just checks for
897 * self-consistency of the options list.
900 ProcessCopyOptions(CopyState cstate,
904 bool format_specified = false;
907 /* Support external use for option sanity checking */
909 cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
911 cstate->file_encoding = -1;
913 /* Extract options from the statement node tree */
914 foreach(option, options)
916 DefElem *defel = (DefElem *) lfirst(option);
918 if (strcmp(defel->defname, "format") == 0)
920 char *fmt = defGetString(defel);
922 if (format_specified)
924 (errcode(ERRCODE_SYNTAX_ERROR),
925 errmsg("conflicting or redundant options")));
926 format_specified = true;
927 if (strcmp(fmt, "text") == 0)
928 /* default format */ ;
929 else if (strcmp(fmt, "csv") == 0)
930 cstate->csv_mode = true;
931 else if (strcmp(fmt, "binary") == 0)
932 cstate->binary = true;
935 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
936 errmsg("COPY format \"%s\" not recognized", fmt)));
938 else if (strcmp(defel->defname, "oids") == 0)
942 (errcode(ERRCODE_SYNTAX_ERROR),
943 errmsg("conflicting or redundant options")));
944 cstate->oids = defGetBoolean(defel);
946 else if (strcmp(defel->defname, "freeze") == 0)
950 (errcode(ERRCODE_SYNTAX_ERROR),
951 errmsg("conflicting or redundant options")));
952 cstate->freeze = defGetBoolean(defel);
954 else if (strcmp(defel->defname, "delimiter") == 0)
958 (errcode(ERRCODE_SYNTAX_ERROR),
959 errmsg("conflicting or redundant options")));
960 cstate->delim = defGetString(defel);
962 else if (strcmp(defel->defname, "null") == 0)
964 if (cstate->null_print)
966 (errcode(ERRCODE_SYNTAX_ERROR),
967 errmsg("conflicting or redundant options")));
968 cstate->null_print = defGetString(defel);
970 else if (strcmp(defel->defname, "header") == 0)
972 if (cstate->header_line)
974 (errcode(ERRCODE_SYNTAX_ERROR),
975 errmsg("conflicting or redundant options")));
976 cstate->header_line = defGetBoolean(defel);
978 else if (strcmp(defel->defname, "quote") == 0)
982 (errcode(ERRCODE_SYNTAX_ERROR),
983 errmsg("conflicting or redundant options")));
984 cstate->quote = defGetString(defel);
986 else if (strcmp(defel->defname, "escape") == 0)
990 (errcode(ERRCODE_SYNTAX_ERROR),
991 errmsg("conflicting or redundant options")));
992 cstate->escape = defGetString(defel);
994 else if (strcmp(defel->defname, "force_quote") == 0)
996 if (cstate->force_quote || cstate->force_quote_all)
998 (errcode(ERRCODE_SYNTAX_ERROR),
999 errmsg("conflicting or redundant options")));
1000 if (defel->arg && IsA(defel->arg, A_Star))
1001 cstate->force_quote_all = true;
1002 else if (defel->arg && IsA(defel->arg, List))
1003 cstate->force_quote = (List *) defel->arg;
1006 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1007 errmsg("argument to option \"%s\" must be a list of column names",
1010 else if (strcmp(defel->defname, "force_not_null") == 0)
1012 if (cstate->force_notnull)
1014 (errcode(ERRCODE_SYNTAX_ERROR),
1015 errmsg("conflicting or redundant options")));
1016 if (defel->arg && IsA(defel->arg, List))
1017 cstate->force_notnull = (List *) defel->arg;
1020 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1021 errmsg("argument to option \"%s\" must be a list of column names",
1024 else if (strcmp(defel->defname, "force_null") == 0)
1026 if (cstate->force_null)
1028 (errcode(ERRCODE_SYNTAX_ERROR),
1029 errmsg("conflicting or redundant options")));
1030 if (defel->arg && IsA(defel->arg, List))
1031 cstate->force_null = (List *) defel->arg;
1034 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1035 errmsg("argument to option \"%s\" must be a list of column names",
1038 else if (strcmp(defel->defname, "convert_selectively") == 0)
1041 * Undocumented, not-accessible-from-SQL option: convert only the
1042 * named columns to binary form, storing the rest as NULLs. It's
1043 * allowed for the column list to be NIL.
1045 if (cstate->convert_selectively)
1047 (errcode(ERRCODE_SYNTAX_ERROR),
1048 errmsg("conflicting or redundant options")));
1049 cstate->convert_selectively = true;
1050 if (defel->arg == NULL || IsA(defel->arg, List))
1051 cstate->convert_select = (List *) defel->arg;
1054 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1055 errmsg("argument to option \"%s\" must be a list of column names",
1058 else if (strcmp(defel->defname, "encoding") == 0)
1060 if (cstate->file_encoding >= 0)
1062 (errcode(ERRCODE_SYNTAX_ERROR),
1063 errmsg("conflicting or redundant options")));
1064 cstate->file_encoding = pg_char_to_encoding(defGetString(defel));
1065 if (cstate->file_encoding < 0)
1067 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1068 errmsg("argument to option \"%s\" must be a valid encoding name",
1073 (errcode(ERRCODE_SYNTAX_ERROR),
1074 errmsg("option \"%s\" not recognized",
1079 * Check for incompatible options (must do these two before inserting
1082 if (cstate->binary && cstate->delim)
1084 (errcode(ERRCODE_SYNTAX_ERROR),
1085 errmsg("cannot specify DELIMITER in BINARY mode")));
1087 if (cstate->binary && cstate->null_print)
1089 (errcode(ERRCODE_SYNTAX_ERROR),
1090 errmsg("cannot specify NULL in BINARY mode")));
1092 /* Set defaults for omitted options */
1094 cstate->delim = cstate->csv_mode ? "," : "\t";
1096 if (!cstate->null_print)
1097 cstate->null_print = cstate->csv_mode ? "" : "\\N";
1098 cstate->null_print_len = strlen(cstate->null_print);
1100 if (cstate->csv_mode)
1103 cstate->quote = "\"";
1104 if (!cstate->escape)
1105 cstate->escape = cstate->quote;
1108 /* Only single-byte delimiter strings are supported. */
1109 if (strlen(cstate->delim) != 1)
1111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1112 errmsg("COPY delimiter must be a single one-byte character")));
1114 /* Disallow end-of-line characters */
1115 if (strchr(cstate->delim, '\r') != NULL ||
1116 strchr(cstate->delim, '\n') != NULL)
1118 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1119 errmsg("COPY delimiter cannot be newline or carriage return")));
1121 if (strchr(cstate->null_print, '\r') != NULL ||
1122 strchr(cstate->null_print, '\n') != NULL)
1124 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1125 errmsg("COPY null representation cannot use newline or carriage return")));
1128 * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
1129 * backslash because it would be ambiguous. We can't allow the other
1130 * cases because data characters matching the delimiter must be
1131 * backslashed, and certain backslash combinations are interpreted
1132 * non-literally by COPY IN. Disallowing all lower case ASCII letters is
1133 * more than strictly necessary, but seems best for consistency and
1134 * future-proofing. Likewise we disallow all digits though only octal
1135 * digits are actually dangerous.
1137 if (!cstate->csv_mode &&
1138 strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
1139 cstate->delim[0]) != NULL)
1141 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1142 errmsg("COPY delimiter cannot be \"%s\"", cstate->delim)));
1145 if (!cstate->csv_mode && cstate->header_line)
1147 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1148 errmsg("COPY HEADER available only in CSV mode")));
1151 if (!cstate->csv_mode && cstate->quote != NULL)
1153 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1154 errmsg("COPY quote available only in CSV mode")));
1156 if (cstate->csv_mode && strlen(cstate->quote) != 1)
1158 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1159 errmsg("COPY quote must be a single one-byte character")));
1161 if (cstate->csv_mode && cstate->delim[0] == cstate->quote[0])
1163 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1164 errmsg("COPY delimiter and quote must be different")));
1167 if (!cstate->csv_mode && cstate->escape != NULL)
1169 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1170 errmsg("COPY escape available only in CSV mode")));
1172 if (cstate->csv_mode && strlen(cstate->escape) != 1)
1174 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1175 errmsg("COPY escape must be a single one-byte character")));
1177 /* Check force_quote */
1178 if (!cstate->csv_mode && (cstate->force_quote || cstate->force_quote_all))
1180 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1181 errmsg("COPY force quote available only in CSV mode")));
1182 if ((cstate->force_quote || cstate->force_quote_all) && is_from)
1184 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1185 errmsg("COPY force quote only available using COPY TO")));
1187 /* Check force_notnull */
1188 if (!cstate->csv_mode && cstate->force_notnull != NIL)
1190 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1191 errmsg("COPY force not null available only in CSV mode")));
1192 if (cstate->force_notnull != NIL && !is_from)
1194 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1195 errmsg("COPY force not null only available using COPY FROM")));
1197 /* Check force_null */
1198 if (!cstate->csv_mode && cstate->force_null != NIL)
1200 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1201 errmsg("COPY force null available only in CSV mode")));
1203 if (cstate->force_null != NIL && !is_from)
1205 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1206 errmsg("COPY force null only available using COPY FROM")));
1208 /* Don't allow the delimiter to appear in the null string. */
1209 if (strchr(cstate->null_print, cstate->delim[0]) != NULL)
1211 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1212 errmsg("COPY delimiter must not appear in the NULL specification")));
1214 /* Don't allow the CSV quote char to appear in the null string. */
1215 if (cstate->csv_mode &&
1216 strchr(cstate->null_print, cstate->quote[0]) != NULL)
1218 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1219 errmsg("CSV quote character must not appear in the NULL specification")));
1223 * Common setup routines used by BeginCopyFrom and BeginCopyTo.
1225 * Iff <binary>, unload or reload in the binary format, as opposed to the
1226 * more wasteful but more robust and portable text format.
1228 * Iff <oids>, unload or reload the format that includes OID information.
1229 * On input, we accept OIDs whether or not the table has an OID column,
1230 * but silently drop them if it does not. On output, we report an error
1231 * if the user asks for OIDs in a table that has none (not providing an
1232 * OID column might seem friendlier, but could seriously confuse programs).
1234 * If in the text format, delimit columns with delimiter <delim> and print
1235 * NULL values as <null_print>.
1238 BeginCopy(bool is_from,
1241 const char *queryString,
1248 MemoryContext oldcontext;
1250 /* Allocate workspace and zero all fields */
1251 cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1254 * We allocate everything used by a cstate in a new memory context. This
1255 * avoids memory leaks during repeated use of COPY in a query.
1257 cstate->copycontext = AllocSetContextCreate(CurrentMemoryContext,
1259 ALLOCSET_DEFAULT_MINSIZE,
1260 ALLOCSET_DEFAULT_INITSIZE,
1261 ALLOCSET_DEFAULT_MAXSIZE);
1263 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1265 /* Extract options from the statement node tree */
1266 ProcessCopyOptions(cstate, is_from, options);
1268 /* Process the source/target relation or query */
1275 tupDesc = RelationGetDescr(cstate->rel);
1277 /* Don't allow COPY w/ OIDs to or from a table without them */
1278 if (cstate->oids && !cstate->rel->rd_rel->relhasoids)
1280 (errcode(ERRCODE_UNDEFINED_COLUMN),
1281 errmsg("table \"%s\" does not have OIDs",
1282 RelationGetRelationName(cstate->rel))));
1294 /* Don't allow COPY w/ OIDs from a select */
1297 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1298 errmsg("COPY (SELECT) WITH OIDS is not supported")));
1301 * Run parse analysis and rewrite. Note this also acquires sufficient
1302 * locks on the source table(s).
1304 * Because the parser and planner tend to scribble on their input, we
1305 * make a preliminary copy of the source querytree. This prevents
1306 * problems in the case that the COPY is in a portal or plpgsql
1307 * function and is executed repeatedly. (See also the same hack in
1308 * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
1310 rewritten = pg_analyze_and_rewrite((Node *) copyObject(raw_query),
1311 queryString, NULL, 0);
1313 /* We don't expect more or less than one result query */
1314 if (list_length(rewritten) != 1)
1315 elog(ERROR, "unexpected rewrite result");
1317 query = (Query *) linitial(rewritten);
1319 /* The grammar allows SELECT INTO, but we don't support that */
1320 if (query->utilityStmt != NULL &&
1321 IsA(query->utilityStmt, CreateTableAsStmt))
1323 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1324 errmsg("COPY (SELECT INTO) is not supported")));
1326 Assert(query->commandType == CMD_SELECT);
1327 Assert(query->utilityStmt == NULL);
1329 /* plan the query */
1330 plan = planner(query, 0, NULL);
1333 * Use a snapshot with an updated command ID to ensure this query sees
1334 * results of any previously executed queries.
1336 PushCopiedSnapshot(GetActiveSnapshot());
1337 UpdateActiveSnapshotCommandId();
1339 /* Create dest receiver for COPY OUT */
1340 dest = CreateDestReceiver(DestCopyOut);
1341 ((DR_copy *) dest)->cstate = cstate;
1343 /* Create a QueryDesc requesting no output */
1344 cstate->queryDesc = CreateQueryDesc(plan, queryString,
1345 GetActiveSnapshot(),
1350 * Call ExecutorStart to prepare the plan for execution.
1352 * ExecutorStart computes a result tupdesc for us
1354 ExecutorStart(cstate->queryDesc, 0);
1356 tupDesc = cstate->queryDesc->tupDesc;
1359 /* Generate or convert list of attributes to process */
1360 cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1362 num_phys_attrs = tupDesc->natts;
1364 /* Convert FORCE QUOTE name list to per-column flags, check validity */
1365 cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1366 if (cstate->force_quote_all)
1370 for (i = 0; i < num_phys_attrs; i++)
1371 cstate->force_quote_flags[i] = true;
1373 else if (cstate->force_quote)
1378 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_quote);
1380 foreach(cur, attnums)
1382 int attnum = lfirst_int(cur);
1384 if (!list_member_int(cstate->attnumlist, attnum))
1386 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1387 errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
1388 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1389 cstate->force_quote_flags[attnum - 1] = true;
1393 /* Convert FORCE NOT NULL name list to per-column flags, check validity */
1394 cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1395 if (cstate->force_notnull)
1400 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_notnull);
1402 foreach(cur, attnums)
1404 int attnum = lfirst_int(cur);
1406 if (!list_member_int(cstate->attnumlist, attnum))
1408 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1409 errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
1410 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1411 cstate->force_notnull_flags[attnum - 1] = true;
1415 /* Convert FORCE NULL name list to per-column flags, check validity */
1416 cstate->force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1417 if (cstate->force_null)
1422 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_null);
1424 foreach(cur, attnums)
1426 int attnum = lfirst_int(cur);
1428 if (!list_member_int(cstate->attnumlist, attnum))
1430 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1431 errmsg("FORCE NULL column \"%s\" not referenced by COPY",
1432 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1433 cstate->force_null_flags[attnum - 1] = true;
1437 /* Convert convert_selectively name list to per-column flags */
1438 if (cstate->convert_selectively)
1443 cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1445 attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->convert_select);
1447 foreach(cur, attnums)
1449 int attnum = lfirst_int(cur);
1451 if (!list_member_int(cstate->attnumlist, attnum))
1453 (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1454 errmsg_internal("selected column \"%s\" not referenced by COPY",
1455 NameStr(tupDesc->attrs[attnum - 1]->attname))));
1456 cstate->convert_select_flags[attnum - 1] = true;
1460 /* Use client encoding when ENCODING option is not specified. */
1461 if (cstate->file_encoding < 0)
1462 cstate->file_encoding = pg_get_client_encoding();
1465 * Set up encoding conversion info. Even if the file and server encodings
1466 * are the same, we must apply pg_any_to_server() to validate data in
1467 * multibyte encodings.
1469 cstate->need_transcoding =
1470 (cstate->file_encoding != GetDatabaseEncoding() ||
1471 pg_database_encoding_max_length() > 1);
1472 /* See Multibyte encoding comment above */
1473 cstate->encoding_embeds_ascii = PG_ENCODING_IS_CLIENT_ONLY(cstate->file_encoding);
1475 cstate->copy_dest = COPY_FILE; /* default */
1477 MemoryContextSwitchTo(oldcontext);
1483 * Closes the pipe to an external program, checking the pclose() return code.
1486 ClosePipeToProgram(CopyState cstate)
1490 Assert(cstate->is_program);
1492 pclose_rc = ClosePipeStream(cstate->copy_file);
1493 if (pclose_rc == -1)
1495 (errmsg("could not close pipe to external command: %m")));
1496 else if (pclose_rc != 0)
1498 (errmsg("program \"%s\" failed",
1500 errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1504 * Release resources allocated in a cstate for COPY TO/FROM.
1507 EndCopy(CopyState cstate)
1509 if (cstate->is_program)
1511 ClosePipeToProgram(cstate);
1515 if (cstate->filename != NULL && FreeFile(cstate->copy_file))
1517 (errcode_for_file_access(),
1518 errmsg("could not close file \"%s\": %m",
1519 cstate->filename)));
1522 MemoryContextDelete(cstate->copycontext);
1527 * Setup CopyState to read tuples from a table or a query for COPY TO.
1530 BeginCopyTo(Relation rel,
1532 const char *queryString,
1533 const char *filename,
1539 bool pipe = (filename == NULL);
1540 MemoryContext oldcontext;
1542 if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
1544 if (rel->rd_rel->relkind == RELKIND_VIEW)
1546 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1547 errmsg("cannot copy from view \"%s\"",
1548 RelationGetRelationName(rel)),
1549 errhint("Try the COPY (SELECT ...) TO variant.")));
1550 else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
1552 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1553 errmsg("cannot copy from materialized view \"%s\"",
1554 RelationGetRelationName(rel)),
1555 errhint("Try the COPY (SELECT ...) TO variant.")));
1556 else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1558 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1559 errmsg("cannot copy from foreign table \"%s\"",
1560 RelationGetRelationName(rel)),
1561 errhint("Try the COPY (SELECT ...) TO variant.")));
1562 else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
1564 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1565 errmsg("cannot copy from sequence \"%s\"",
1566 RelationGetRelationName(rel))));
1569 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1570 errmsg("cannot copy from non-table relation \"%s\"",
1571 RelationGetRelationName(rel))));
1574 cstate = BeginCopy(false, rel, query, queryString, attnamelist, options);
1575 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1579 Assert(!is_program); /* the grammar does not allow this */
1580 if (whereToSendOutput != DestRemote)
1581 cstate->copy_file = stdout;
1585 cstate->filename = pstrdup(filename);
1586 cstate->is_program = is_program;
1590 cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
1591 if (cstate->copy_file == NULL)
1593 (errmsg("could not execute command \"%s\": %m",
1594 cstate->filename)));
1598 mode_t oumask; /* Pre-existing umask value */
1602 * Prevent write to relative path ... too easy to shoot oneself in
1603 * the foot by overwriting a database file ...
1605 if (!is_absolute_path(filename))
1607 (errcode(ERRCODE_INVALID_NAME),
1608 errmsg("relative path not allowed for COPY to file")));
1610 oumask = umask(S_IWGRP | S_IWOTH);
1611 cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
1613 if (cstate->copy_file == NULL)
1615 (errcode_for_file_access(),
1616 errmsg("could not open file \"%s\" for writing: %m",
1617 cstate->filename)));
1619 fstat(fileno(cstate->copy_file), &st);
1620 if (S_ISDIR(st.st_mode))
1622 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1623 errmsg("\"%s\" is a directory", cstate->filename)));
1627 MemoryContextSwitchTo(oldcontext);
1633 * This intermediate routine exists mainly to localize the effects of setjmp
1634 * so we don't need to plaster a lot of variables with "volatile".
1637 DoCopyTo(CopyState cstate)
1639 bool pipe = (cstate->filename == NULL);
1640 bool fe_copy = (pipe && whereToSendOutput == DestRemote);
1646 SendCopyBegin(cstate);
1648 processed = CopyTo(cstate);
1651 SendCopyEnd(cstate);
1656 * Make sure we turn off old-style COPY OUT mode upon error. It is
1657 * okay to do this in all cases, since it does nothing if the mode is
1660 pq_endcopyout(true);
1669 * Clean up storage and release resources for COPY TO.
1672 EndCopyTo(CopyState cstate)
1674 if (cstate->queryDesc != NULL)
1676 /* Close down the query and free resources. */
1677 ExecutorFinish(cstate->queryDesc);
1678 ExecutorEnd(cstate->queryDesc);
1679 FreeQueryDesc(cstate->queryDesc);
1680 PopActiveSnapshot();
1683 /* Clean up storage */
1688 * Copy from relation or query TO file.
1691 CopyTo(CopyState cstate)
1695 Form_pg_attribute *attr;
1700 tupDesc = RelationGetDescr(cstate->rel);
1702 tupDesc = cstate->queryDesc->tupDesc;
1703 attr = tupDesc->attrs;
1704 num_phys_attrs = tupDesc->natts;
1705 cstate->null_print_client = cstate->null_print; /* default */
1707 /* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
1708 cstate->fe_msgbuf = makeStringInfo();
1710 /* Get info about the columns we need to process. */
1711 cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1712 foreach(cur, cstate->attnumlist)
1714 int attnum = lfirst_int(cur);
1719 getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
1723 getTypeOutputInfo(attr[attnum - 1]->atttypid,
1726 fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
1730 * Create a temporary memory context that we can reset once per row to
1731 * recover palloc'd memory. This avoids any problems with leaks inside
1732 * datatype output routines, and should be faster than retail pfree's
1733 * anyway. (We don't need a whole econtext as CopyFrom does.)
1735 cstate->rowcontext = AllocSetContextCreate(CurrentMemoryContext,
1737 ALLOCSET_DEFAULT_MINSIZE,
1738 ALLOCSET_DEFAULT_INITSIZE,
1739 ALLOCSET_DEFAULT_MAXSIZE);
1743 /* Generate header for a binary copy */
1747 CopySendData(cstate, BinarySignature, 11);
1752 CopySendInt32(cstate, tmp);
1753 /* No header extension */
1755 CopySendInt32(cstate, tmp);
1760 * For non-binary copy, we need to convert null_print to file
1761 * encoding, because it will be sent directly with CopySendString.
1763 if (cstate->need_transcoding)
1764 cstate->null_print_client = pg_server_to_any(cstate->null_print,
1765 cstate->null_print_len,
1766 cstate->file_encoding);
1768 /* if a header has been requested send the line */
1769 if (cstate->header_line)
1771 bool hdr_delim = false;
1773 foreach(cur, cstate->attnumlist)
1775 int attnum = lfirst_int(cur);
1779 CopySendChar(cstate, cstate->delim[0]);
1782 colname = NameStr(attr[attnum - 1]->attname);
1784 CopyAttributeOutCSV(cstate, colname, false,
1785 list_length(cstate->attnumlist) == 1);
1788 CopySendEndOfRow(cstate);
1796 HeapScanDesc scandesc;
1799 values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
1800 nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
1802 scandesc = heap_beginscan(cstate->rel, GetActiveSnapshot(), 0, NULL);
1805 while ((tuple = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
1807 CHECK_FOR_INTERRUPTS();
1809 /* Deconstruct the tuple ... faster than repeated heap_getattr */
1810 heap_deform_tuple(tuple, tupDesc, values, nulls);
1812 /* Format and send the data */
1813 CopyOneRowTo(cstate, HeapTupleGetOid(tuple), values, nulls);
1817 heap_endscan(scandesc);
1824 /* run the plan --- the dest receiver will send tuples */
1825 ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L);
1826 processed = ((DR_copy *) cstate->queryDesc->dest)->processed;
1831 /* Generate trailer for a binary copy */
1832 CopySendInt16(cstate, -1);
1833 /* Need to flush out the trailer */
1834 CopySendEndOfRow(cstate);
1837 MemoryContextDelete(cstate->rowcontext);
1843 * Emit one row during CopyTo().
1846 CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
1848 bool need_delim = false;
1849 FmgrInfo *out_functions = cstate->out_functions;
1850 MemoryContext oldcontext;
1854 MemoryContextReset(cstate->rowcontext);
1855 oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
1859 /* Binary per-tuple header */
1860 CopySendInt16(cstate, list_length(cstate->attnumlist));
1861 /* Send OID if wanted --- note attnumlist doesn't include it */
1864 /* Hack --- assume Oid is same size as int32 */
1865 CopySendInt32(cstate, sizeof(int32));
1866 CopySendInt32(cstate, tupleOid);
1871 /* Text format has no per-tuple header, but send OID if wanted */
1872 /* Assume digits don't need any quoting or encoding conversion */
1875 string = DatumGetCString(DirectFunctionCall1(oidout,
1876 ObjectIdGetDatum(tupleOid)));
1877 CopySendString(cstate, string);
1882 foreach(cur, cstate->attnumlist)
1884 int attnum = lfirst_int(cur);
1885 Datum value = values[attnum - 1];
1886 bool isnull = nulls[attnum - 1];
1888 if (!cstate->binary)
1891 CopySendChar(cstate, cstate->delim[0]);
1897 if (!cstate->binary)
1898 CopySendString(cstate, cstate->null_print_client);
1900 CopySendInt32(cstate, -1);
1904 if (!cstate->binary)
1906 string = OutputFunctionCall(&out_functions[attnum - 1],
1908 if (cstate->csv_mode)
1909 CopyAttributeOutCSV(cstate, string,
1910 cstate->force_quote_flags[attnum - 1],
1911 list_length(cstate->attnumlist) == 1);
1913 CopyAttributeOutText(cstate, string);
1919 outputbytes = SendFunctionCall(&out_functions[attnum - 1],
1921 CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
1922 CopySendData(cstate, VARDATA(outputbytes),
1923 VARSIZE(outputbytes) - VARHDRSZ);
1928 CopySendEndOfRow(cstate);
1930 MemoryContextSwitchTo(oldcontext);
1935 * error context callback for COPY FROM
1937 * The argument for the error context must be CopyState.
1940 CopyFromErrorCallback(void *arg)
1942 CopyState cstate = (CopyState) arg;
1946 /* can't usefully display the data */
1947 if (cstate->cur_attname)
1948 errcontext("COPY %s, line %d, column %s",
1949 cstate->cur_relname, cstate->cur_lineno,
1950 cstate->cur_attname);
1952 errcontext("COPY %s, line %d",
1953 cstate->cur_relname, cstate->cur_lineno);
1957 if (cstate->cur_attname && cstate->cur_attval)
1959 /* error is relevant to a particular column */
1962 attval = limit_printout_length(cstate->cur_attval);
1963 errcontext("COPY %s, line %d, column %s: \"%s\"",
1964 cstate->cur_relname, cstate->cur_lineno,
1965 cstate->cur_attname, attval);
1968 else if (cstate->cur_attname)
1970 /* error is relevant to a particular column, value is NULL */
1971 errcontext("COPY %s, line %d, column %s: null input",
1972 cstate->cur_relname, cstate->cur_lineno,
1973 cstate->cur_attname);
1978 * Error is relevant to a particular line.
1980 * If line_buf still contains the correct line, and it's already
1981 * transcoded, print it. If it's still in a foreign encoding, it's
1982 * quite likely that the error is precisely a failure to do
1983 * encoding conversion (ie, bad data). We dare not try to convert
1984 * it, and at present there's no way to regurgitate it without
1985 * conversion. So we have to punt and just report the line number.
1987 if (cstate->line_buf_valid &&
1988 (cstate->line_buf_converted || !cstate->need_transcoding))
1992 lineval = limit_printout_length(cstate->line_buf.data);
1993 errcontext("COPY %s, line %d: \"%s\"",
1994 cstate->cur_relname, cstate->cur_lineno, lineval);
1999 errcontext("COPY %s, line %d",
2000 cstate->cur_relname, cstate->cur_lineno);
2007 * Make sure we don't print an unreasonable amount of COPY data in a message.
2009 * It would seem a lot easier to just use the sprintf "precision" limit to
2010 * truncate the string. However, some versions of glibc have a bug/misfeature
2011 * that vsnprintf will always fail (return -1) if it is asked to truncate
2012 * a string that contains invalid byte sequences for the current encoding.
2013 * So, do our own truncation. We return a pstrdup'd copy of the input.
2016 limit_printout_length(const char *str)
2018 #define MAX_COPY_DATA_DISPLAY 100
2020 int slen = strlen(str);
2024 /* Fast path if definitely okay */
2025 if (slen <= MAX_COPY_DATA_DISPLAY)
2026 return pstrdup(str);
2028 /* Apply encoding-dependent truncation */
2029 len = pg_mbcliplen(str, slen, MAX_COPY_DATA_DISPLAY);
2032 * Truncate, and add "..." to show we truncated the input.
2034 res = (char *) palloc(len + 4);
2035 memcpy(res, str, len);
2036 strcpy(res + len, "...");
2042 * Copy FROM file to relation.
2045 CopyFrom(CopyState cstate)
2051 ResultRelInfo *resultRelInfo;
2052 EState *estate = CreateExecutorState(); /* for ExecConstraints() */
2053 ExprContext *econtext;
2054 TupleTableSlot *myslot;
2055 MemoryContext oldcontext = CurrentMemoryContext;
2057 ErrorContextCallback errcallback;
2058 CommandId mycid = GetCurrentCommandId(true);
2059 int hi_options = 0; /* start with default heap_insert options */
2060 BulkInsertState bistate;
2061 uint64 processed = 0;
2062 bool useHeapMultiInsert;
2063 int nBufferedTuples = 0;
2065 #define MAX_BUFFERED_TUPLES 1000
2066 HeapTuple *bufferedTuples = NULL; /* initialize to silence warning */
2067 Size bufferedTuplesSize = 0;
2068 int firstBufferedLineNo = 0;
2070 Assert(cstate->rel);
2072 if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
2074 if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
2076 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2077 errmsg("cannot copy to view \"%s\"",
2078 RelationGetRelationName(cstate->rel))));
2079 else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
2081 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2082 errmsg("cannot copy to materialized view \"%s\"",
2083 RelationGetRelationName(cstate->rel))));
2084 else if (cstate->rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2086 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2087 errmsg("cannot copy to foreign table \"%s\"",
2088 RelationGetRelationName(cstate->rel))));
2089 else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
2091 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2092 errmsg("cannot copy to sequence \"%s\"",
2093 RelationGetRelationName(cstate->rel))));
2096 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2097 errmsg("cannot copy to non-table relation \"%s\"",
2098 RelationGetRelationName(cstate->rel))));
2101 tupDesc = RelationGetDescr(cstate->rel);
2104 * Check to see if we can avoid writing WAL
2106 * If archive logging/streaming is not enabled *and* either
2107 * - table was created in same transaction as this COPY
2108 * - data is being written to relfilenode created in this transaction
2109 * then we can skip writing WAL. It's safe because if the transaction
2110 * doesn't commit, we'll discard the table (or the new relfilenode file).
2111 * If it does commit, we'll have done the heap_sync at the bottom of this
2114 * As mentioned in comments in utils/rel.h, the in-same-transaction test
2115 * is not always set correctly, since in rare cases rd_newRelfilenodeSubid
2116 * can be cleared before the end of the transaction. The exact case is
2117 * when a relation sets a new relfilenode twice in same transaction, yet
2118 * the second one fails in an aborted subtransaction, e.g.
2127 * Also, if the target file is new-in-transaction, we assume that checking
2128 * FSM for free space is a waste of time, even if we must use WAL because
2129 * of archiving. This could possibly be wrong, but it's unlikely.
2131 * The comments for heap_insert and RelationGetBufferForTuple specify that
2132 * skipping WAL logging is only safe if we ensure that our tuples do not
2133 * go into pages containing tuples from any other transactions --- but this
2134 * must be the case if we have a new table or new relfilenode, so we need
2135 * no additional work to enforce that.
2138 /* createSubid is creation check, newRelfilenodeSubid is truncation check */
2139 if (cstate->rel->rd_createSubid != InvalidSubTransactionId ||
2140 cstate->rel->rd_newRelfilenodeSubid != InvalidSubTransactionId)
2142 hi_options |= HEAP_INSERT_SKIP_FSM;
2143 if (!XLogIsNeeded())
2144 hi_options |= HEAP_INSERT_SKIP_WAL;
2148 * Optimize if new relfilenode was created in this subxact or one of its
2149 * committed children and we won't see those rows later as part of an
2150 * earlier scan or command. This ensures that if this subtransaction
2151 * aborts then the frozen rows won't be visible after xact cleanup. Note
2152 * that the stronger test of exactly which subtransaction created it is
2153 * crucial for correctness of this optimisation.
2157 if (!ThereAreNoPriorRegisteredSnapshots() || !ThereAreNoReadyPortals())
2159 (ERRCODE_INVALID_TRANSACTION_STATE,
2160 errmsg("cannot perform FREEZE because of prior transaction activity")));
2162 if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
2163 cstate->rel->rd_newRelfilenodeSubid != GetCurrentSubTransactionId())
2165 (ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE,
2166 errmsg("cannot perform FREEZE because the table was not created or truncated in the current subtransaction")));
2168 hi_options |= HEAP_INSERT_FROZEN;
2172 * We need a ResultRelInfo so we can use the regular executor's
2173 * index-entry-making machinery. (There used to be a huge amount of code
2174 * here that basically duplicated execUtils.c ...)
2176 resultRelInfo = makeNode(ResultRelInfo);
2177 InitResultRelInfo(resultRelInfo,
2179 1, /* dummy rangetable index */
2182 ExecOpenIndices(resultRelInfo);
2184 estate->es_result_relations = resultRelInfo;
2185 estate->es_num_result_relations = 1;
2186 estate->es_result_relation_info = resultRelInfo;
2188 /* Set up a tuple slot too */
2189 myslot = ExecInitExtraTupleSlot(estate);
2190 ExecSetSlotDescriptor(myslot, tupDesc);
2191 /* Triggers might need a slot as well */
2192 estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
2195 * It's more efficient to prepare a bunch of tuples for insertion, and
2196 * insert them in one heap_multi_insert() call, than call heap_insert()
2197 * separately for every tuple. However, we can't do that if there are
2198 * BEFORE/INSTEAD OF triggers, or we need to evaluate volatile default
2199 * expressions. Such triggers or expressions might query the table we're
2200 * inserting to, and act differently if the tuples that have already been
2201 * processed and prepared for insertion are not there.
2203 if ((resultRelInfo->ri_TrigDesc != NULL &&
2204 (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2205 resultRelInfo->ri_TrigDesc->trig_insert_instead_row)) ||
2206 cstate->volatile_defexprs)
2208 useHeapMultiInsert = false;
2212 useHeapMultiInsert = true;
2213 bufferedTuples = palloc(MAX_BUFFERED_TUPLES * sizeof(HeapTuple));
2216 /* Prepare to catch AFTER triggers. */
2217 AfterTriggerBeginQuery();
2220 * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
2221 * should do this for COPY, since it's not really an "INSERT" statement as
2222 * such. However, executing these triggers maintains consistency with the
2223 * EACH ROW triggers that we already fire on COPY.
2225 ExecBSInsertTriggers(estate, resultRelInfo);
2227 values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
2228 nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
2230 bistate = GetBulkInsertState();
2231 econtext = GetPerTupleExprContext(estate);
2233 /* Set up callback to identify error line number */
2234 errcallback.callback = CopyFromErrorCallback;
2235 errcallback.arg = (void *) cstate;
2236 errcallback.previous = error_context_stack;
2237 error_context_stack = &errcallback;
2241 TupleTableSlot *slot;
2243 Oid loaded_oid = InvalidOid;
2245 CHECK_FOR_INTERRUPTS();
2247 if (nBufferedTuples == 0)
2250 * Reset the per-tuple exprcontext. We can only do this if the
2251 * tuple buffer is empty. (Calling the context the per-tuple
2252 * memory context is a bit of a misnomer now.)
2254 ResetPerTupleExprContext(estate);
2257 /* Switch into its memory context */
2258 MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2260 if (!NextCopyFrom(cstate, econtext, values, nulls, &loaded_oid))
2263 /* And now we can form the input tuple. */
2264 tuple = heap_form_tuple(tupDesc, values, nulls);
2266 if (loaded_oid != InvalidOid)
2267 HeapTupleSetOid(tuple, loaded_oid);
2270 * Constraints might reference the tableoid column, so initialize
2271 * t_tableOid before evaluating them.
2273 tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
2275 /* Triggers and stuff need to be invoked in query context. */
2276 MemoryContextSwitchTo(oldcontext);
2278 /* Place tuple in tuple slot --- but slot shouldn't free it */
2280 ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2284 /* BEFORE ROW INSERT Triggers */
2285 if (resultRelInfo->ri_TrigDesc &&
2286 resultRelInfo->ri_TrigDesc->trig_insert_before_row)
2288 slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
2290 if (slot == NULL) /* "do nothing" */
2292 else /* trigger might have changed tuple */
2293 tuple = ExecMaterializeSlot(slot);
2298 /* Check the constraints of the tuple */
2299 if (cstate->rel->rd_att->constr)
2300 ExecConstraints(resultRelInfo, slot, estate);
2302 if (useHeapMultiInsert)
2304 /* Add this tuple to the tuple buffer */
2305 if (nBufferedTuples == 0)
2306 firstBufferedLineNo = cstate->cur_lineno;
2307 bufferedTuples[nBufferedTuples++] = tuple;
2308 bufferedTuplesSize += tuple->t_len;
2311 * If the buffer filled up, flush it. Also flush if the total
2312 * size of all the tuples in the buffer becomes large, to
2313 * avoid using large amounts of memory for the buffers when
2314 * the tuples are exceptionally wide.
2316 if (nBufferedTuples == MAX_BUFFERED_TUPLES ||
2317 bufferedTuplesSize > 65535)
2319 CopyFromInsertBatch(cstate, estate, mycid, hi_options,
2320 resultRelInfo, myslot, bistate,
2321 nBufferedTuples, bufferedTuples,
2322 firstBufferedLineNo);
2323 nBufferedTuples = 0;
2324 bufferedTuplesSize = 0;
2329 List *recheckIndexes = NIL;
2331 /* OK, store the tuple and create index entries for it */
2332 heap_insert(cstate->rel, tuple, mycid, hi_options, bistate);
2334 if (resultRelInfo->ri_NumIndices > 0)
2335 recheckIndexes = ExecInsertIndexTuples(slot, &(tuple->t_self),
2338 /* AFTER ROW INSERT Triggers */
2339 ExecARInsertTriggers(estate, resultRelInfo, tuple,
2342 list_free(recheckIndexes);
2346 * We count only tuples not suppressed by a BEFORE INSERT trigger;
2347 * this is the same definition used by execMain.c for counting
2348 * tuples inserted by an INSERT command.
2354 /* Flush any remaining buffered tuples */
2355 if (nBufferedTuples > 0)
2356 CopyFromInsertBatch(cstate, estate, mycid, hi_options,
2357 resultRelInfo, myslot, bistate,
2358 nBufferedTuples, bufferedTuples,
2359 firstBufferedLineNo);
2361 /* Done, clean up */
2362 error_context_stack = errcallback.previous;
2364 FreeBulkInsertState(bistate);
2366 MemoryContextSwitchTo(oldcontext);
2368 /* Execute AFTER STATEMENT insertion triggers */
2369 ExecASInsertTriggers(estate, resultRelInfo);
2371 /* Handle queued AFTER triggers */
2372 AfterTriggerEndQuery(estate);
2377 ExecResetTupleTable(estate->es_tupleTable, false);
2379 ExecCloseIndices(resultRelInfo);
2381 FreeExecutorState(estate);
2384 * If we skipped writing WAL, then we need to sync the heap (but not
2385 * indexes since those use WAL anyway)
2387 if (hi_options & HEAP_INSERT_SKIP_WAL)
2388 heap_sync(cstate->rel);
2394 * A subroutine of CopyFrom, to write the current batch of buffered heap
2395 * tuples to the heap. Also updates indexes and runs AFTER ROW INSERT
2399 CopyFromInsertBatch(CopyState cstate, EState *estate, CommandId mycid,
2400 int hi_options, ResultRelInfo *resultRelInfo,
2401 TupleTableSlot *myslot, BulkInsertState bistate,
2402 int nBufferedTuples, HeapTuple *bufferedTuples,
2403 int firstBufferedLineNo)
2405 MemoryContext oldcontext;
2407 int save_cur_lineno;
2410 * Print error context information correctly, if one of the operations
2413 cstate->line_buf_valid = false;
2414 save_cur_lineno = cstate->cur_lineno;
2417 * heap_multi_insert leaks memory, so switch to short-lived memory context
2418 * before calling it.
2420 oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2421 heap_multi_insert(cstate->rel,
2427 MemoryContextSwitchTo(oldcontext);
2430 * If there are any indexes, update them for all the inserted tuples, and
2431 * run AFTER ROW INSERT triggers.
2433 if (resultRelInfo->ri_NumIndices > 0)
2435 for (i = 0; i < nBufferedTuples; i++)
2437 List *recheckIndexes;
2439 cstate->cur_lineno = firstBufferedLineNo + i;
2440 ExecStoreTuple(bufferedTuples[i], myslot, InvalidBuffer, false);
2442 ExecInsertIndexTuples(myslot, &(bufferedTuples[i]->t_self),
2444 ExecARInsertTriggers(estate, resultRelInfo,
2447 list_free(recheckIndexes);
2452 * There's no indexes, but see if we need to run AFTER ROW INSERT triggers
2455 else if (resultRelInfo->ri_TrigDesc != NULL &&
2456 resultRelInfo->ri_TrigDesc->trig_insert_after_row)
2458 for (i = 0; i < nBufferedTuples; i++)
2460 cstate->cur_lineno = firstBufferedLineNo + i;
2461 ExecARInsertTriggers(estate, resultRelInfo,
2467 /* reset cur_lineno to where we were */
2468 cstate->cur_lineno = save_cur_lineno;
2472 * Setup to read tuples from a file for COPY FROM.
2474 * 'rel': Used as a template for the tuples
2475 * 'filename': Name of server-local file to read
2476 * 'attnamelist': List of char *, columns to include. NIL selects all cols.
2477 * 'options': List of DefElem. See copy_opt_item in gram.y for selections.
2479 * Returns a CopyState, to be passed to NextCopyFrom and related functions.
2482 BeginCopyFrom(Relation rel,
2483 const char *filename,
2489 bool pipe = (filename == NULL);
2491 Form_pg_attribute *attr;
2492 AttrNumber num_phys_attrs,
2494 FmgrInfo *in_functions;
2499 ExprState **defexprs;
2500 MemoryContext oldcontext;
2501 bool volatile_defexprs;
2503 cstate = BeginCopy(true, rel, NULL, NULL, attnamelist, options);
2504 oldcontext = MemoryContextSwitchTo(cstate->copycontext);
2506 /* Initialize state variables */
2507 cstate->fe_eof = false;
2508 cstate->eol_type = EOL_UNKNOWN;
2509 cstate->cur_relname = RelationGetRelationName(cstate->rel);
2510 cstate->cur_lineno = 0;
2511 cstate->cur_attname = NULL;
2512 cstate->cur_attval = NULL;
2514 /* Set up variables to avoid per-attribute overhead. */
2515 initStringInfo(&cstate->attribute_buf);
2516 initStringInfo(&cstate->line_buf);
2517 cstate->line_buf_converted = false;
2518 cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
2519 cstate->raw_buf_index = cstate->raw_buf_len = 0;
2521 tupDesc = RelationGetDescr(cstate->rel);
2522 attr = tupDesc->attrs;
2523 num_phys_attrs = tupDesc->natts;
2525 volatile_defexprs = false;
2528 * Pick up the required catalog information for each attribute in the
2529 * relation, including the input function, the element type (to pass to
2530 * the input function), and info about defaults and constraints. (Which
2531 * input function we use depends on text/binary format choice.)
2533 in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2534 typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
2535 defmap = (int *) palloc(num_phys_attrs * sizeof(int));
2536 defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
2538 for (attnum = 1; attnum <= num_phys_attrs; attnum++)
2540 /* We don't need info for dropped attributes */
2541 if (attr[attnum - 1]->attisdropped)
2544 /* Fetch the input function and typioparam info */
2546 getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
2547 &in_func_oid, &typioparams[attnum - 1]);
2549 getTypeInputInfo(attr[attnum - 1]->atttypid,
2550 &in_func_oid, &typioparams[attnum - 1]);
2551 fmgr_info(in_func_oid, &in_functions[attnum - 1]);
2553 /* Get default info if needed */
2554 if (!list_member_int(cstate->attnumlist, attnum))
2556 /* attribute is NOT to be copied from input */
2557 /* use default value if one exists */
2558 Expr *defexpr = (Expr *) build_column_default(cstate->rel,
2561 if (defexpr != NULL)
2563 /* Run the expression through planner */
2564 defexpr = expression_planner(defexpr);
2566 /* Initialize executable expression in copycontext */
2567 defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
2568 defmap[num_defaults] = attnum - 1;
2572 * If a default expression looks at the table being loaded,
2573 * then it could give the wrong answer when using
2574 * multi-insert. Since database access can be dynamic this is
2575 * hard to test for exactly, so we use the much wider test of
2576 * whether the default expression is volatile. We allow for
2577 * the special case of when the default expression is the
2578 * nextval() of a sequence which in this specific case is
2579 * known to be safe for use with the multi-insert
2580 * optimisation. Hence we use this special case function
2581 * checker rather than the standard check for
2582 * contain_volatile_functions().
2584 if (!volatile_defexprs)
2585 volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
2590 /* We keep those variables in cstate. */
2591 cstate->in_functions = in_functions;
2592 cstate->typioparams = typioparams;
2593 cstate->defmap = defmap;
2594 cstate->defexprs = defexprs;
2595 cstate->volatile_defexprs = volatile_defexprs;
2596 cstate->num_defaults = num_defaults;
2597 cstate->is_program = is_program;
2601 Assert(!is_program); /* the grammar does not allow this */
2602 if (whereToSendOutput == DestRemote)
2603 ReceiveCopyBegin(cstate);
2605 cstate->copy_file = stdin;
2609 cstate->filename = pstrdup(filename);
2611 if (cstate->is_program)
2613 cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
2614 if (cstate->copy_file == NULL)
2616 (errmsg("could not execute command \"%s\": %m",
2617 cstate->filename)));
2623 cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
2624 if (cstate->copy_file == NULL)
2626 (errcode_for_file_access(),
2627 errmsg("could not open file \"%s\" for reading: %m",
2628 cstate->filename)));
2630 fstat(fileno(cstate->copy_file), &st);
2631 if (S_ISDIR(st.st_mode))
2633 (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2634 errmsg("\"%s\" is a directory", cstate->filename)));
2638 if (!cstate->binary)
2640 /* must rely on user to tell us... */
2641 cstate->file_has_oids = cstate->oids;
2645 /* Read and verify binary header */
2650 if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
2651 memcmp(readSig, BinarySignature, 11) != 0)
2653 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2654 errmsg("COPY file signature not recognized")));
2656 if (!CopyGetInt32(cstate, &tmp))
2658 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2659 errmsg("invalid COPY file header (missing flags)")));
2660 cstate->file_has_oids = (tmp & (1 << 16)) != 0;
2662 if ((tmp >> 16) != 0)
2664 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2665 errmsg("unrecognized critical flags in COPY file header")));
2666 /* Header extension length */
2667 if (!CopyGetInt32(cstate, &tmp) ||
2670 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2671 errmsg("invalid COPY file header (missing length)")));
2672 /* Skip extension header, if present */
2675 if (CopyGetData(cstate, readSig, 1, 1) != 1)
2677 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2678 errmsg("invalid COPY file header (wrong length)")));
2682 if (cstate->file_has_oids && cstate->binary)
2684 getTypeBinaryInputInfo(OIDOID,
2685 &in_func_oid, &cstate->oid_typioparam);
2686 fmgr_info(in_func_oid, &cstate->oid_in_function);
2689 /* create workspace for CopyReadAttributes results */
2690 if (!cstate->binary)
2692 AttrNumber attr_count = list_length(cstate->attnumlist);
2693 int nfields = cstate->file_has_oids ? (attr_count + 1) : attr_count;
2695 cstate->max_fields = nfields;
2696 cstate->raw_fields = (char **) palloc(nfields * sizeof(char *));
2699 MemoryContextSwitchTo(oldcontext);
2705 * Read raw fields in the next line for COPY FROM in text or csv mode.
2706 * Return false if no more lines.
2708 * An internal temporary buffer is returned via 'fields'. It is valid until
2709 * the next call of the function. Since the function returns all raw fields
2710 * in the input file, 'nfields' could be different from the number of columns
2713 * NOTE: force_not_null option are not applied to the returned fields.
2716 NextCopyFromRawFields(CopyState cstate, char ***fields, int *nfields)
2721 /* only available for text or csv input */
2722 Assert(!cstate->binary);
2724 /* on input just throw the header line away */
2725 if (cstate->cur_lineno == 0 && cstate->header_line)
2727 cstate->cur_lineno++;
2728 if (CopyReadLine(cstate))
2729 return false; /* done */
2732 cstate->cur_lineno++;
2734 /* Actually read the line into memory here */
2735 done = CopyReadLine(cstate);
2738 * EOF at start of line means we're done. If we see EOF after some
2739 * characters, we act as though it was newline followed by EOF, ie,
2740 * process the line and then exit loop on next iteration.
2742 if (done && cstate->line_buf.len == 0)
2745 /* Parse the line into de-escaped field values */
2746 if (cstate->csv_mode)
2747 fldct = CopyReadAttributesCSV(cstate);
2749 fldct = CopyReadAttributesText(cstate);
2751 *fields = cstate->raw_fields;
2757 * Read next tuple from file for COPY FROM. Return false if no more tuples.
2759 * 'econtext' is used to evaluate default expression for each columns not
2760 * read from the file. It can be NULL when no default values are used, i.e.
2761 * when all columns are read from the file.
2763 * 'values' and 'nulls' arrays must be the same length as columns of the
2764 * relation passed to BeginCopyFrom. This function fills the arrays.
2765 * Oid of the tuple is returned with 'tupleOid' separately.
2768 NextCopyFrom(CopyState cstate, ExprContext *econtext,
2769 Datum *values, bool *nulls, Oid *tupleOid)
2772 Form_pg_attribute *attr;
2773 AttrNumber num_phys_attrs,
2775 num_defaults = cstate->num_defaults;
2776 FmgrInfo *in_functions = cstate->in_functions;
2777 Oid *typioparams = cstate->typioparams;
2781 bool file_has_oids = cstate->file_has_oids;
2782 int *defmap = cstate->defmap;
2783 ExprState **defexprs = cstate->defexprs;
2785 tupDesc = RelationGetDescr(cstate->rel);
2786 attr = tupDesc->attrs;
2787 num_phys_attrs = tupDesc->natts;
2788 attr_count = list_length(cstate->attnumlist);
2789 nfields = file_has_oids ? (attr_count + 1) : attr_count;
2791 /* Initialize all values for row to NULL */
2792 MemSet(values, 0, num_phys_attrs * sizeof(Datum));
2793 MemSet(nulls, true, num_phys_attrs * sizeof(bool));
2795 if (!cstate->binary)
2797 char **field_strings;
2803 /* read raw fields in the next line */
2804 if (!NextCopyFromRawFields(cstate, &field_strings, &fldct))
2807 /* check for overflowing fields */
2808 if (nfields > 0 && fldct > nfields)
2810 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2811 errmsg("extra data after last expected column")));
2815 /* Read the OID field if present */
2818 if (fieldno >= fldct)
2820 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2821 errmsg("missing data for OID column")));
2822 string = field_strings[fieldno++];
2826 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2827 errmsg("null OID in COPY data")));
2828 else if (cstate->oids && tupleOid != NULL)
2830 cstate->cur_attname = "oid";
2831 cstate->cur_attval = string;
2832 *tupleOid = DatumGetObjectId(DirectFunctionCall1(oidin,
2833 CStringGetDatum(string)));
2834 if (*tupleOid == InvalidOid)
2836 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2837 errmsg("invalid OID in COPY data")));
2838 cstate->cur_attname = NULL;
2839 cstate->cur_attval = NULL;
2843 /* Loop to read the user attributes on the line. */
2844 foreach(cur, cstate->attnumlist)
2846 int attnum = lfirst_int(cur);
2849 if (fieldno >= fldct)
2851 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2852 errmsg("missing data for column \"%s\"",
2853 NameStr(attr[m]->attname))));
2854 string = field_strings[fieldno++];
2856 if (cstate->convert_select_flags &&
2857 !cstate->convert_select_flags[m])
2859 /* ignore input field, leaving column as NULL */
2863 if (cstate->csv_mode)
2865 if (string == NULL &&
2866 cstate->force_notnull_flags[m])
2869 * FORCE_NOT_NULL option is set and column is NULL -
2870 * convert it to the NULL string.
2872 string = cstate->null_print;
2874 else if (string != NULL && cstate->force_null_flags[m]
2875 && strcmp(string, cstate->null_print) == 0)
2878 * FORCE_NULL option is set and column matches the NULL
2879 * string. It must have been quoted, or otherwise the
2880 * string would already have been set to NULL. Convert it
2881 * to NULL as specified.
2887 cstate->cur_attname = NameStr(attr[m]->attname);
2888 cstate->cur_attval = string;
2889 values[m] = InputFunctionCall(&in_functions[m],
2892 attr[m]->atttypmod);
2895 cstate->cur_attname = NULL;
2896 cstate->cur_attval = NULL;
2899 Assert(fieldno == nfields);
2907 cstate->cur_lineno++;
2909 if (!CopyGetInt16(cstate, &fld_count))
2911 /* EOF detected (end of file, or protocol-level EOF) */
2915 if (fld_count == -1)
2918 * Received EOF marker. In a V3-protocol copy, wait for the
2919 * protocol-level EOF, and complain if it doesn't come
2920 * immediately. This ensures that we correctly handle CopyFail,
2921 * if client chooses to send that now.
2923 * Note that we MUST NOT try to read more data in an old-protocol
2924 * copy, since there is no protocol-level EOF marker then. We
2925 * could go either way for copy from file, but choose to throw
2926 * error if there's data after the EOF marker, for consistency
2927 * with the new-protocol case.
2931 if (cstate->copy_dest != COPY_OLD_FE &&
2932 CopyGetData(cstate, &dummy, 1, 1) > 0)
2934 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2935 errmsg("received copy data after EOF marker")));
2939 if (fld_count != attr_count)
2941 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2942 errmsg("row field count is %d, expected %d",
2943 (int) fld_count, attr_count)));
2949 cstate->cur_attname = "oid";
2951 DatumGetObjectId(CopyReadBinaryAttribute(cstate,
2953 &cstate->oid_in_function,
2954 cstate->oid_typioparam,
2957 if (isnull || loaded_oid == InvalidOid)
2959 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2960 errmsg("invalid OID in COPY data")));
2961 cstate->cur_attname = NULL;
2962 if (cstate->oids && tupleOid != NULL)
2963 *tupleOid = loaded_oid;
2967 foreach(cur, cstate->attnumlist)
2969 int attnum = lfirst_int(cur);
2972 cstate->cur_attname = NameStr(attr[m]->attname);
2974 values[m] = CopyReadBinaryAttribute(cstate,
2980 cstate->cur_attname = NULL;
2985 * Now compute and insert any defaults available for the columns not
2986 * provided by the input data. Anything not processed here or above will
2989 for (i = 0; i < num_defaults; i++)
2992 * The caller must supply econtext and have switched into the
2993 * per-tuple memory context in it.
2995 Assert(econtext != NULL);
2996 Assert(CurrentMemoryContext == econtext->ecxt_per_tuple_memory);
2998 values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
2999 &nulls[defmap[i]], NULL);
3006 * Clean up storage and release resources for COPY FROM.
3009 EndCopyFrom(CopyState cstate)
3011 /* No COPY FROM related resources except memory. */
3017 * Read the next input line and stash it in line_buf, with conversion to
3020 * Result is true if read was terminated by EOF, false if terminated
3021 * by newline. The terminating newline or EOF marker is not included
3022 * in the final value of line_buf.
3025 CopyReadLine(CopyState cstate)
3029 resetStringInfo(&cstate->line_buf);
3030 cstate->line_buf_valid = true;
3032 /* Mark that encoding conversion hasn't occurred yet */
3033 cstate->line_buf_converted = false;
3035 /* Parse data and transfer into line_buf */
3036 result = CopyReadLineText(cstate);
3041 * Reached EOF. In protocol version 3, we should ignore anything
3042 * after \. up to the protocol end of copy data. (XXX maybe better
3043 * not to treat \. as special?)
3045 if (cstate->copy_dest == COPY_NEW_FE)
3049 cstate->raw_buf_index = cstate->raw_buf_len;
3050 } while (CopyLoadRawBuf(cstate));
3056 * If we didn't hit EOF, then we must have transferred the EOL marker
3057 * to line_buf along with the data. Get rid of it.
3059 switch (cstate->eol_type)
3062 Assert(cstate->line_buf.len >= 1);
3063 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3064 cstate->line_buf.len--;
3065 cstate->line_buf.data[cstate->line_buf.len] = '\0';
3068 Assert(cstate->line_buf.len >= 1);
3069 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\r');
3070 cstate->line_buf.len--;
3071 cstate->line_buf.data[cstate->line_buf.len] = '\0';
3074 Assert(cstate->line_buf.len >= 2);
3075 Assert(cstate->line_buf.data[cstate->line_buf.len - 2] == '\r');
3076 Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3077 cstate->line_buf.len -= 2;
3078 cstate->line_buf.data[cstate->line_buf.len] = '\0';
3081 /* shouldn't get here */
3087 /* Done reading the line. Convert it to server encoding. */
3088 if (cstate->need_transcoding)
3092 cvt = pg_any_to_server(cstate->line_buf.data,
3093 cstate->line_buf.len,
3094 cstate->file_encoding);
3095 if (cvt != cstate->line_buf.data)
3097 /* transfer converted data back to line_buf */
3098 resetStringInfo(&cstate->line_buf);
3099 appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
3104 /* Now it's safe to use the buffer in error messages */
3105 cstate->line_buf_converted = true;
3111 * CopyReadLineText - inner loop of CopyReadLine for text mode
3114 CopyReadLineText(CopyState cstate)
3119 bool need_data = false;
3120 bool hit_eof = false;
3121 bool result = false;
3125 bool first_char_in_line = true;
3126 bool in_quote = false,
3127 last_was_esc = false;
3129 char escapec = '\0';
3131 if (cstate->csv_mode)
3133 quotec = cstate->quote[0];
3134 escapec = cstate->escape[0];
3135 /* ignore special escape processing if it's the same as quotec */
3136 if (quotec == escapec)
3140 mblen_str[1] = '\0';
3143 * The objective of this loop is to transfer the entire next input line
3144 * into line_buf. Hence, we only care for detecting newlines (\r and/or
3145 * \n) and the end-of-copy marker (\.).
3147 * In CSV mode, \r and \n inside a quoted field are just part of the data
3148 * value and are put in line_buf. We keep just enough state to know if we
3149 * are currently in a quoted field or not.
3151 * These four characters, and the CSV escape and quote characters, are
3152 * assumed the same in frontend and backend encodings.
3154 * For speed, we try to move data from raw_buf to line_buf in chunks
3155 * rather than one character at a time. raw_buf_ptr points to the next
3156 * character to examine; any characters from raw_buf_index to raw_buf_ptr
3157 * have been determined to be part of the line, but not yet transferred to
3160 * For a little extra speed within the loop, we copy raw_buf and
3161 * raw_buf_len into local variables.
3163 copy_raw_buf = cstate->raw_buf;
3164 raw_buf_ptr = cstate->raw_buf_index;
3165 copy_buf_len = cstate->raw_buf_len;
3173 * Load more data if needed. Ideally we would just force four bytes
3174 * of read-ahead and avoid the many calls to
3175 * IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(), but the COPY_OLD_FE protocol
3176 * does not allow us to read too far ahead or we might read into the
3177 * next data, so we read-ahead only as far we know we can. One
3178 * optimization would be to read-ahead four byte here if
3179 * cstate->copy_dest != COPY_OLD_FE, but it hardly seems worth it,
3180 * considering the size of the buffer.
3182 if (raw_buf_ptr >= copy_buf_len || need_data)
3187 * Try to read some more data. This will certainly reset
3188 * raw_buf_index to zero, and raw_buf_ptr must go with it.
3190 if (!CopyLoadRawBuf(cstate))
3193 copy_buf_len = cstate->raw_buf_len;
3196 * If we are completely out of data, break out of the loop,
3199 if (copy_buf_len <= 0)
3207 /* OK to fetch a character */
3208 prev_raw_ptr = raw_buf_ptr;
3209 c = copy_raw_buf[raw_buf_ptr++];
3211 if (cstate->csv_mode)
3214 * If character is '\\' or '\r', we may need to look ahead below.
3215 * Force fetch of the next character if we don't already have it.
3216 * We need to do this before changing CSV state, in case one of
3217 * these characters is also the quote or escape character.
3219 * Note: old-protocol does not like forced prefetch, but it's OK
3220 * here since we cannot validly be at EOF.
3222 if (c == '\\' || c == '\r')
3224 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
3228 * Dealing with quotes and escapes here is mildly tricky. If the
3229 * quote char is also the escape char, there's no problem - we
3230 * just use the char as a toggle. If they are different, we need
3231 * to ensure that we only take account of an escape inside a
3232 * quoted field and immediately preceding a quote char, and not
3233 * the second in a escape-escape sequence.
3235 if (in_quote && c == escapec)
3236 last_was_esc = !last_was_esc;
3237 if (c == quotec && !last_was_esc)
3238 in_quote = !in_quote;
3240 last_was_esc = false;
3243 * Updating the line count for embedded CR and/or LF chars is
3244 * necessarily a little fragile - this test is probably about the
3245 * best we can do. (XXX it's arguable whether we should do this
3246 * at all --- is cur_lineno a physical or logical count?)
3248 if (in_quote && c == (cstate->eol_type == EOL_NL ? '\n' : '\r'))
3249 cstate->cur_lineno++;
3253 if (c == '\r' && (!cstate->csv_mode || !in_quote))
3255 /* Check for \r\n on first line, _and_ handle \r\n. */
3256 if (cstate->eol_type == EOL_UNKNOWN ||
3257 cstate->eol_type == EOL_CRNL)
3260 * If need more data, go back to loop top to load it.
3262 * Note that if we are at EOF, c will wind up as '\0' because
3263 * of the guaranteed pad of raw_buf.
3265 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
3268 c = copy_raw_buf[raw_buf_ptr];
3272 raw_buf_ptr++; /* eat newline */
3273 cstate->eol_type = EOL_CRNL; /* in case not set yet */
3277 /* found \r, but no \n */
3278 if (cstate->eol_type == EOL_CRNL)
3280 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3282 errmsg("literal carriage return found in data") :
3283 errmsg("unquoted carriage return found in data"),
3285 errhint("Use \"\\r\" to represent carriage return.") :
3286 errhint("Use quoted CSV field to represent carriage return.")));
3289 * if we got here, it is the first line and we didn't find
3290 * \n, so don't consume the peeked character
3292 cstate->eol_type = EOL_CR;
3295 else if (cstate->eol_type == EOL_NL)
3297 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3299 errmsg("literal carriage return found in data") :
3300 errmsg("unquoted carriage return found in data"),
3302 errhint("Use \"\\r\" to represent carriage return.") :
3303 errhint("Use quoted CSV field to represent carriage return.")));
3304 /* If reach here, we have found the line terminator */
3309 if (c == '\n' && (!cstate->csv_mode || !in_quote))
3311 if (cstate->eol_type == EOL_CR || cstate->eol_type == EOL_CRNL)
3313 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3315 errmsg("literal newline found in data") :
3316 errmsg("unquoted newline found in data"),
3318 errhint("Use \"\\n\" to represent newline.") :
3319 errhint("Use quoted CSV field to represent newline.")));
3320 cstate->eol_type = EOL_NL; /* in case not set yet */
3321 /* If reach here, we have found the line terminator */
3326 * In CSV mode, we only recognize \. alone on a line. This is because
3327 * \. is a valid CSV data value.
3329 if (c == '\\' && (!cstate->csv_mode || first_char_in_line))
3333 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
3334 IF_NEED_REFILL_AND_EOF_BREAK(0);
3337 * get next character
3338 * Note: we do not change c so if it isn't \., we can fall
3339 * through and continue processing for file encoding.
3342 c2 = copy_raw_buf[raw_buf_ptr];
3346 raw_buf_ptr++; /* consume the '.' */
3349 * Note: if we loop back for more data here, it does not
3350 * matter that the CSV state change checks are re-executed; we
3351 * will come back here with no important state changed.
3353 if (cstate->eol_type == EOL_CRNL)
3355 /* Get the next character */
3356 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
3357 /* if hit_eof, c2 will become '\0' */
3358 c2 = copy_raw_buf[raw_buf_ptr++];
3362 if (!cstate->csv_mode)
3364 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3365 errmsg("end-of-copy marker does not match previous newline style")));
3367 NO_END_OF_COPY_GOTO;
3369 else if (c2 != '\r')
3371 if (!cstate->csv_mode)
3373 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3374 errmsg("end-of-copy marker corrupt")));
3376 NO_END_OF_COPY_GOTO;
3380 /* Get the next character */
3381 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
3382 /* if hit_eof, c2 will become '\0' */
3383 c2 = copy_raw_buf[raw_buf_ptr++];
3385 if (c2 != '\r' && c2 != '\n')
3387 if (!cstate->csv_mode)
3389 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3390 errmsg("end-of-copy marker corrupt")));
3392 NO_END_OF_COPY_GOTO;
3395 if ((cstate->eol_type == EOL_NL && c2 != '\n') ||
3396 (cstate->eol_type == EOL_CRNL && c2 != '\n') ||
3397 (cstate->eol_type == EOL_CR && c2 != '\r'))
3400 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3401 errmsg("end-of-copy marker does not match previous newline style")));
3405 * Transfer only the data before the \. into line_buf, then
3406 * discard the data and the \. sequence.
3408 if (prev_raw_ptr > cstate->raw_buf_index)
3409 appendBinaryStringInfo(&cstate->line_buf,
3410 cstate->raw_buf + cstate->raw_buf_index,
3411 prev_raw_ptr - cstate->raw_buf_index);
3412 cstate->raw_buf_index = raw_buf_ptr;
3413 result = true; /* report EOF */
3416 else if (!cstate->csv_mode)
3419 * If we are here, it means we found a backslash followed by
3420 * something other than a period. In non-CSV mode, anything
3421 * after a backslash is special, so we skip over that second
3422 * character too. If we didn't do that \\. would be
3423 * considered an eof-of copy, while in non-CSV mode it is a
3424 * literal backslash followed by a period. In CSV mode,
3425 * backslashes are not special, so we want to process the
3426 * character after the backslash just like a normal character,
3427 * so we don't increment in those cases.
3433 * This label is for CSV cases where \. appears at the start of a
3434 * line, but there is more text after it, meaning it was a data value.
3435 * We are more strict for \. in CSV mode because \. could be a data
3436 * value, while in non-CSV mode, \. cannot be a data value.
3441 * Process all bytes of a multi-byte character as a group.
3443 * We only support multi-byte sequences where the first byte has the
3444 * high-bit set, so as an optimization we can avoid this block
3445 * entirely if it is not set.
3447 if (cstate->encoding_embeds_ascii && IS_HIGHBIT_SET(c))
3452 /* All our encodings only read the first byte to get the length */
3453 mblen = pg_encoding_mblen(cstate->file_encoding, mblen_str);
3454 IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(mblen - 1);
3455 IF_NEED_REFILL_AND_EOF_BREAK(mblen - 1);
3456 raw_buf_ptr += mblen - 1;
3458 first_char_in_line = false;
3459 } /* end of outer loop */
3462 * Transfer any still-uncopied data to line_buf.
3470 * Return decimal value for a hexadecimal digit
3473 GetDecimalFromHex(char hex)
3475 if (isdigit((unsigned char) hex))
3478 return tolower((unsigned char) hex) - 'a' + 10;
3482 * Parse the current line into separate attributes (fields),
3483 * performing de-escaping as needed.
3485 * The input is in line_buf. We use attribute_buf to hold the result
3486 * strings. cstate->raw_fields[k] is set to point to the k'th attribute
3487 * string, or NULL when the input matches the null marker string.
3488 * This array is expanded as necessary.
3490 * (Note that the caller cannot check for nulls since the returned
3491 * string would be the post-de-escaping equivalent, which may look
3492 * the same as some valid data string.)
3494 * delim is the column delimiter string (must be just one byte for now).
3495 * null_print is the null marker string. Note that this is compared to
3496 * the pre-de-escaped input string.
3498 * The return value is the number of fields actually read.
3501 CopyReadAttributesText(CopyState cstate)
3503 char delimc = cstate->delim[0];
3510 * We need a special case for zero-column tables: check that the input
3511 * line is empty, and return.
3513 if (cstate->max_fields <= 0)
3515 if (cstate->line_buf.len != 0)
3517 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3518 errmsg("extra data after last expected column")));
3522 resetStringInfo(&cstate->attribute_buf);
3525 * The de-escaped attributes will certainly not be longer than the input
3526 * data line, so we can just force attribute_buf to be large enough and
3527 * then transfer data without any checks for enough space. We need to do
3528 * it this way because enlarging attribute_buf mid-stream would invalidate
3529 * pointers already stored into cstate->raw_fields[].
3531 if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
3532 enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
3533 output_ptr = cstate->attribute_buf.data;
3535 /* set pointer variables for loop */
3536 cur_ptr = cstate->line_buf.data;
3537 line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
3539 /* Outer loop iterates over fields */
3543 bool found_delim = false;
3547 bool saw_non_ascii = false;
3549 /* Make sure there is enough space for the next value */
3550 if (fieldno >= cstate->max_fields)
3552 cstate->max_fields *= 2;
3553 cstate->raw_fields =
3554 repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
3557 /* Remember start of field on both input and output sides */
3558 start_ptr = cur_ptr;
3559 cstate->raw_fields[fieldno] = output_ptr;
3562 * Scan data for field.
3564 * Note that in this loop, we are scanning to locate the end of field
3565 * and also speculatively performing de-escaping. Once we find the
3566 * end-of-field, we can match the raw field contents against the null
3567 * marker string. Only after that comparison fails do we know that
3568 * de-escaping is actually the right thing to do; therefore we *must
3569 * not* throw any syntax errors before we've done the null-marker
3577 if (cur_ptr >= line_end_ptr)
3587 if (cur_ptr >= line_end_ptr)
3605 if (cur_ptr < line_end_ptr)
3611 val = (val << 3) + OCTVALUE(c);
3612 if (cur_ptr < line_end_ptr)
3618 val = (val << 3) + OCTVALUE(c);
3624 if (c == '\0' || IS_HIGHBIT_SET(c))
3625 saw_non_ascii = true;
3630 if (cur_ptr < line_end_ptr)
3632 char hexchar = *cur_ptr;
3634 if (isxdigit((unsigned char) hexchar))
3636 int val = GetDecimalFromHex(hexchar);
3639 if (cur_ptr < line_end_ptr)
3642 if (isxdigit((unsigned char) hexchar))
3645 val = (val << 4) + GetDecimalFromHex(hexchar);
3649 if (c == '\0' || IS_HIGHBIT_SET(c))
3650 saw_non_ascii = true;
3674 * in all other cases, take the char after '\'
3680 /* Add c to output string */
3684 /* Check whether raw input matched null marker */
3685 input_len = end_ptr - start_ptr;
3686 if (input_len == cstate->null_print_len &&
3687 strncmp(start_ptr, cstate->null_print, input_len) == 0)
3688 cstate->raw_fields[fieldno] = NULL;
3692 * At this point we know the field is supposed to contain data.
3694 * If we de-escaped any non-7-bit-ASCII chars, make sure the
3695 * resulting string is valid data for the db encoding.
3699 char *fld = cstate->raw_fields[fieldno];
3701 pg_verifymbstr(fld, output_ptr - fld, false);
3705 /* Terminate attribute value in output area */
3706 *output_ptr++ = '\0';
3709 /* Done if we hit EOL instead of a delim */
3714 /* Clean up state of attribute_buf */
3716 Assert(*output_ptr == '\0');
3717 cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
3723 * Parse the current line into separate attributes (fields),
3724 * performing de-escaping as needed. This has exactly the same API as
3725 * CopyReadAttributesText, except we parse the fields according to
3726 * "standard" (i.e. common) CSV usage.
3729 CopyReadAttributesCSV(CopyState cstate)
3731 char delimc = cstate->delim[0];
3732 char quotec = cstate->quote[0];
3733 char escapec = cstate->escape[0];
3740 * We need a special case for zero-column tables: check that the input
3741 * line is empty, and return.
3743 if (cstate->max_fields <= 0)
3745 if (cstate->line_buf.len != 0)
3747 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3748 errmsg("extra data after last expected column")));
3752 resetStringInfo(&cstate->attribute_buf);
3755 * The de-escaped attributes will certainly not be longer than the input
3756 * data line, so we can just force attribute_buf to be large enough and
3757 * then transfer data without any checks for enough space. We need to do
3758 * it this way because enlarging attribute_buf mid-stream would invalidate
3759 * pointers already stored into cstate->raw_fields[].
3761 if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
3762 enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
3763 output_ptr = cstate->attribute_buf.data;
3765 /* set pointer variables for loop */
3766 cur_ptr = cstate->line_buf.data;
3767 line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
3769 /* Outer loop iterates over fields */
3773 bool found_delim = false;
3774 bool saw_quote = false;
3779 /* Make sure there is enough space for the next value */
3780 if (fieldno >= cstate->max_fields)
3782 cstate->max_fields *= 2;
3783 cstate->raw_fields =
3784 repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
3787 /* Remember start of field on both input and output sides */
3788 start_ptr = cur_ptr;
3789 cstate->raw_fields[fieldno] = output_ptr;
3792 * Scan data for field,
3794 * The loop starts in "not quote" mode and then toggles between that
3795 * and "in quote" mode. The loop exits normally if it is in "not
3796 * quote" mode and a delimiter or line end is seen.
3806 if (cur_ptr >= line_end_ptr)
3809 /* unquoted field delimiter */
3815 /* start of quoted field (or part of field) */
3821 /* Add c to output string */
3829 if (cur_ptr >= line_end_ptr)
3831 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3832 errmsg("unterminated CSV quoted field")));
3836 /* escape within a quoted field */
3840 * peek at the next char if available, and escape it if it
3841 * is an escape char or a quote char
3843 if (cur_ptr < line_end_ptr)
3845 char nextc = *cur_ptr;
3847 if (nextc == escapec || nextc == quotec)
3849 *output_ptr++ = nextc;
3857 * end of quoted field. Must do this test after testing for
3858 * escape in case quote char and escape char are the same
3859 * (which is the common case).
3864 /* Add c to output string */
3870 /* Terminate attribute value in output area */
3871 *output_ptr++ = '\0';
3873 /* Check whether raw input matched null marker */
3874 input_len = end_ptr - start_ptr;
3875 if (!saw_quote && input_len == cstate->null_print_len &&
3876 strncmp(start_ptr, cstate->null_print, input_len) == 0)
3877 cstate->raw_fields[fieldno] = NULL;
3880 /* Done if we hit EOL instead of a delim */
3885 /* Clean up state of attribute_buf */
3887 Assert(*output_ptr == '\0');
3888 cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
3895 * Read a binary attribute
3898 CopyReadBinaryAttribute(CopyState cstate,
3899 int column_no, FmgrInfo *flinfo,
3900 Oid typioparam, int32 typmod,
3906 if (!CopyGetInt32(cstate, &fld_size))
3908 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3909 errmsg("unexpected EOF in COPY data")));
3913 return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
3917 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3918 errmsg("invalid field size")));
3920 /* reset attribute_buf to empty, and load raw data in it */
3921 resetStringInfo(&cstate->attribute_buf);
3923 enlargeStringInfo(&cstate->attribute_buf, fld_size);
3924 if (CopyGetData(cstate, cstate->attribute_buf.data,
3925 fld_size, fld_size) != fld_size)
3927 (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3928 errmsg("unexpected EOF in COPY data")));
3930 cstate->attribute_buf.len = fld_size;
3931 cstate->attribute_buf.data[fld_size] = '\0';
3933 /* Call the column type's binary input converter */
3934 result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
3935 typioparam, typmod);
3937 /* Trouble if it didn't eat the whole buffer */
3938 if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
3940 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
3941 errmsg("incorrect binary data format")));
3948 * Send text representation of one attribute, with conversion and escaping
3950 #define DUMPSOFAR() \
3953 CopySendData(cstate, start, ptr - start); \
3957 CopyAttributeOutText(CopyState cstate, char *string)
3962 char delimc = cstate->delim[0];
3964 if (cstate->need_transcoding)
3965 ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
3970 * We have to grovel through the string searching for control characters
3971 * and instances of the delimiter character. In most cases, though, these
3972 * are infrequent. To avoid overhead from calling CopySendData once per
3973 * character, we dump out all characters between escaped characters in a
3974 * single call. The loop invariant is that the data from "start" to "ptr"
3975 * can be sent literally, but hasn't yet been.
3977 * We can skip pg_encoding_mblen() overhead when encoding is safe, because
3978 * in valid backend encodings, extra bytes of a multibyte character never
3979 * look like ASCII. This loop is sufficiently performance-critical that
3980 * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
3981 * of the normal safe-encoding path.
3983 if (cstate->encoding_embeds_ascii)
3986 while ((c = *ptr) != '\0')
3988 if ((unsigned char) c < (unsigned char) 0x20)
3991 * \r and \n must be escaped, the others are traditional. We
3992 * prefer to dump these using the C-like notation, rather than
3993 * a backslash and the literal character, because it makes the
3994 * dump file a bit more proof against Microsoftish data
4018 /* If it's the delimiter, must backslash it */
4021 /* All ASCII control chars are length 1 */
4023 continue; /* fall to end of loop */
4025 /* if we get here, we need to convert the control char */
4027 CopySendChar(cstate, '\\');
4028 CopySendChar(cstate, c);
4029 start = ++ptr; /* do not include char in next run */
4031 else if (c == '\\' || c == delimc)
4034 CopySendChar(cstate, '\\');
4035 start = ptr++; /* we include char in next run */
4037 else if (IS_HIGHBIT_SET(c))
4038 ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
4046 while ((c = *ptr) != '\0')
4048 if ((unsigned char) c < (unsigned char) 0x20)
4051 * \r and \n must be escaped, the others are traditional. We
4052 * prefer to dump these using the C-like notation, rather than
4053 * a backslash and the literal character, because it makes the
4054 * dump file a bit more proof against Microsoftish data
4078 /* If it's the delimiter, must backslash it */
4081 /* All ASCII control chars are length 1 */
4083 continue; /* fall to end of loop */
4085 /* if we get here, we need to convert the control char */
4087 CopySendChar(cstate, '\\');
4088 CopySendChar(cstate, c);
4089 start = ++ptr; /* do not include char in next run */
4091 else if (c == '\\' || c == delimc)
4094 CopySendChar(cstate, '\\');
4095 start = ptr++; /* we include char in next run */
4106 * Send text representation of one attribute, with conversion and
4107 * CSV-style escaping
4110 CopyAttributeOutCSV(CopyState cstate, char *string,
4111 bool use_quote, bool single_attr)
4116 char delimc = cstate->delim[0];
4117 char quotec = cstate->quote[0];
4118 char escapec = cstate->escape[0];
4120 /* force quoting if it matches null_print (before conversion!) */
4121 if (!use_quote && strcmp(string, cstate->null_print) == 0)
4124 if (cstate->need_transcoding)
4125 ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
4130 * Make a preliminary pass to discover if it needs quoting
4135 * Because '\.' can be a data value, quote it if it appears alone on a
4136 * line so it is not interpreted as the end-of-data marker.
4138 if (single_attr && strcmp(ptr, "\\.") == 0)
4144 while ((c = *tptr) != '\0')
4146 if (c == delimc || c == quotec || c == '\n' || c == '\r')
4151 if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
4152 tptr += pg_encoding_mblen(cstate->file_encoding, tptr);
4161 CopySendChar(cstate, quotec);
4164 * We adopt the same optimization strategy as in CopyAttributeOutText
4167 while ((c = *ptr) != '\0')
4169 if (c == quotec || c == escapec)
4172 CopySendChar(cstate, escapec);
4173 start = ptr; /* we include char in next run */
4175 if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
4176 ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
4182 CopySendChar(cstate, quotec);
4186 /* If it doesn't need quoting, we can just dump it as-is */
4187 CopySendString(cstate, ptr);
4192 * CopyGetAttnums - build an integer list of attnums to be copied
4194 * The input attnamelist is either the user-specified column list,
4195 * or NIL if there was none (in which case we want all the non-dropped
4198 * rel can be NULL ... it's only used for error reports.
4201 CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
4203 List *attnums = NIL;
4205 if (attnamelist == NIL)
4207 /* Generate default column list */
4208 Form_pg_attribute *attr = tupDesc->attrs;
4209 int attr_count = tupDesc->natts;
4212 for (i = 0; i < attr_count; i++)
4214 if (attr[i]->attisdropped)
4216 attnums = lappend_int(attnums, i + 1);
4221 /* Validate the user-supplied list and extract attnums */
4224 foreach(l, attnamelist)
4226 char *name = strVal(lfirst(l));
4230 /* Lookup column name */
4231 attnum = InvalidAttrNumber;
4232 for (i = 0; i < tupDesc->natts; i++)
4234 if (tupDesc->attrs[i]->attisdropped)
4236 if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
4238 attnum = tupDesc->attrs[i]->attnum;
4242 if (attnum == InvalidAttrNumber)
4246 (errcode(ERRCODE_UNDEFINED_COLUMN),
4247 errmsg("column \"%s\" of relation \"%s\" does not exist",
4248 name, RelationGetRelationName(rel))));
4251 (errcode(ERRCODE_UNDEFINED_COLUMN),
4252 errmsg("column \"%s\" does not exist",
4255 /* Check for duplicates */
4256 if (list_member_int(attnums, attnum))
4258 (errcode(ERRCODE_DUPLICATE_COLUMN),
4259 errmsg("column \"%s\" specified more than once",
4261 attnums = lappend_int(attnums, attnum);
4270 * copy_dest_startup --- executor startup
4273 copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
4279 * copy_dest_receive --- receive one tuple
4282 copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
4284 DR_copy *myState = (DR_copy *) self;
4285 CopyState cstate = myState->cstate;
4287 /* Make sure the tuple is fully deconstructed */
4288 slot_getallattrs(slot);
4290 /* And send the data */
4291 CopyOneRowTo(cstate, InvalidOid, slot->tts_values, slot->tts_isnull);
4292 myState->processed++;
4296 * copy_dest_shutdown --- executor end
4299 copy_dest_shutdown(DestReceiver *self)
4305 * copy_dest_destroy --- release DestReceiver object
4308 copy_dest_destroy(DestReceiver *self)
4314 * CreateCopyDestReceiver -- create a suitable DestReceiver object
4317 CreateCopyDestReceiver(void)
4319 DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
4321 self->pub.receiveSlot = copy_dest_receive;
4322 self->pub.rStartup = copy_dest_startup;
4323 self->pub.rShutdown = copy_dest_shutdown;
4324 self->pub.rDestroy = copy_dest_destroy;
4325 self->pub.mydest = DestCopyOut;
4327 self->cstate = NULL; /* will be set later */
4328 self->processed = 0;
4330 return (DestReceiver *) self;