copy.c 84.5 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * copy.c
4
 *		Implements the COPY utility command.
5
 *
6
 * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
7
 * Portions Copyright (c) 1994, Regents of the University of California
8 9 10
 *
 *
 * IDENTIFICATION
11
 *	  $PostgreSQL: pgsql/src/backend/commands/copy.c,v 1.266 2006/05/26 22:50:02 tgl Exp $
12 13 14
 *
 *-------------------------------------------------------------------------
 */
15
#include "postgres.h"
16

17
#include <ctype.h>
M
Marc G. Fournier 已提交
18
#include <unistd.h>
B
Bruce Momjian 已提交
19
#include <sys/stat.h>
20 21
#include <netinet/in.h>
#include <arpa/inet.h>
M
Marc G. Fournier 已提交
22

23
#include "access/genam.h"
B
Bruce Momjian 已提交
24
#include "access/heapam.h"
25
#include "access/printtup.h"
B
Bruce Momjian 已提交
26
#include "catalog/index.h"
27
#include "catalog/namespace.h"
B
Bruce Momjian 已提交
28
#include "catalog/pg_index.h"
B
Bruce Momjian 已提交
29
#include "catalog/pg_type.h"
30
#include "commands/copy.h"
31
#include "commands/trigger.h"
B
Bruce Momjian 已提交
32
#include "executor/executor.h"
33
#include "libpq/libpq.h"
34
#include "libpq/pqformat.h"
35
#include "mb/pg_wchar.h"
B
Bruce Momjian 已提交
36
#include "miscadmin.h"
37 38
#include "nodes/makefuncs.h"
#include "parser/parse_coerce.h"
39
#include "parser/parse_relation.h"
40
#include "rewrite/rewriteHandler.h"
41
#include "storage/fd.h"
42
#include "tcop/pquery.h"
43
#include "tcop/tcopprot.h"
B
Bruce Momjian 已提交
44 45
#include "utils/acl.h"
#include "utils/builtins.h"
46
#include "utils/lsyscache.h"
47 48
#include "utils/memutils.h"
#include "utils/relcache.h"
B
Bruce Momjian 已提交
49
#include "utils/syscache.h"
50

51

52
#define ISOCTAL(c) (((c) >= '0') && ((c) <= '7'))
53
#define OCTVALUE(c) ((c) - '0')
54

55 56 57 58 59 60 61
/*
 * Represents the different source/dest cases we need to worry about at
 * the bottom level
 */
typedef enum CopyDest
{
	COPY_FILE,					/* to/from file */
62 63
	COPY_OLD_FE,				/* to/from frontend (2.0 protocol) */
	COPY_NEW_FE					/* to/from frontend (3.0 protocol) */
64
} CopyDest;
65

66
/*
67
 *	Represents the end-of-line terminator type of the input
68 69 70 71 72 73 74
 */
typedef enum EolType
{
	EOL_UNKNOWN,
	EOL_NL,
	EOL_CR,
	EOL_CRNL
75
} EolType;
76

77
/*
78
 * This struct contains all the state variables used throughout a COPY
B
Bruce Momjian 已提交
79 80
 * operation. For simplicity, we use the same struct for all variants of COPY,
 * even though some fields are used in only some cases.
81
 *
B
Bruce Momjian 已提交
82 83 84 85 86 87 88 89 90 91
 * Multi-byte encodings: all supported client-side encodings encode multi-byte
 * characters by having the first byte's high bit set. Subsequent bytes of the
 * character can have the high bit not set. When scanning data in such an
 * encoding to look for a match to a single-byte (ie ASCII) character, we must
 * use the full pg_encoding_mblen() machinery to skip over multibyte
 * characters, else we might find a false match to a trailing byte. In
 * supported server encodings, there is no possibility of a false match, and
 * it's faster to make useless comparisons to trailing bytes than it is to
 * invoke pg_encoding_mblen() to skip over them. encoding_embeds_ascii is TRUE
 * when we have to do it the hard way.
92
 */
93 94 95 96 97
typedef struct CopyStateData
{
	/* low-level state data */
	CopyDest	copy_dest;		/* type of copy source/destination */
	FILE	   *copy_file;		/* used if copy_dest == COPY_FILE */
98 99
	StringInfo	fe_msgbuf;		/* used for all dests during COPY TO, only
								 * for dest == COPY_NEW_FE in COPY FROM */
100 101 102 103
	bool		fe_copy;		/* true for all FE copy dests */
	bool		fe_eof;			/* true if detected end of copy data */
	EolType		eol_type;		/* EOL type of input */
	int			client_encoding;	/* remote side's character encoding */
B
Bruce Momjian 已提交
104
	bool		need_transcoding;		/* client encoding diff from server? */
B
Bruce Momjian 已提交
105
	bool		encoding_embeds_ascii;	/* ASCII can be non-first byte? */
106
	uint64		processed;		/* # of tuples processed */
107 108 109 110 111 112 113 114 115

	/* parameters from the COPY command */
	Relation	rel;			/* relation to copy to or from */
	List	   *attnumlist;		/* integer list of attnums to copy */
	bool		binary;			/* binary format? */
	bool		oids;			/* include OIDs? */
	bool		csv_mode;		/* Comma Separated Value format? */
	bool		header_line;	/* CSV header line? */
	char	   *null_print;		/* NULL marker string (server encoding!) */
B
Bruce Momjian 已提交
116
	int			null_print_len; /* length of same */
117 118 119
	char	   *delim;			/* column delimiter (must be 1 byte) */
	char	   *quote;			/* CSV quote char (must be 1 byte) */
	char	   *escape;			/* CSV escape char (must be 1 byte) */
B
Bruce Momjian 已提交
120 121
	List	   *force_quote_atts;		/* integer list of attnums to FQ */
	List	   *force_notnull_atts;		/* integer list of attnums to FNN */
122 123 124 125 126 127

	/* these are just for error messages, see copy_in_error_callback */
	const char *cur_relname;	/* table name for error messages */
	int			cur_lineno;		/* line number for error messages */
	const char *cur_attname;	/* current att for error messages */
	const char *cur_attval;		/* current att value for error messages */
128

129 130 131
	/*
	 * These variables are used to reduce overhead in textual COPY FROM.
	 *
132 133
	 * attribute_buf holds the separated, de-escaped text for each field of
	 * the current line.  The CopyReadAttributes functions return arrays of
134 135 136 137
	 * pointers into this buffer.  We avoid palloc/pfree overhead by re-using
	 * the buffer on each cycle.
	 */
	StringInfoData attribute_buf;
138

139
	/*
B
Bruce Momjian 已提交
140 141 142 143 144
	 * Similarly, line_buf holds the whole input line being processed. The
	 * input cycle is first to read the whole line into line_buf, convert it
	 * to server encoding there, and then extract the individual attribute
	 * fields into attribute_buf.  line_buf is preserved unmodified so that we
	 * can display it in error messages if appropriate.
145 146
	 */
	StringInfoData line_buf;
B
Bruce Momjian 已提交
147
	bool		line_buf_converted;		/* converted to server encoding? */
148

149 150
	/*
	 * Finally, raw_buf holds raw data read from the data source (file or
B
Bruce Momjian 已提交
151
	 * client connection).	CopyReadLine parses this data sufficiently to
152 153 154 155 156 157 158 159 160 161 162 163 164
	 * locate line boundaries, then transfers the data to line_buf and
	 * converts it.  Note: we guarantee that there is a \0 at
	 * raw_buf[raw_buf_len].
	 */
#define RAW_BUF_SIZE 65536		/* we palloc RAW_BUF_SIZE+1 bytes */
	char	   *raw_buf;
	int			raw_buf_index;	/* next byte to process */
	int			raw_buf_len;	/* total # of bytes stored */
} CopyStateData;

typedef CopyStateData *CopyState;


B
Bruce Momjian 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
/*
 * These macros centralize code used to process line_buf and raw_buf buffers.
 * They are macros because they often do continue/break control and to avoid
 * function call overhead in tight COPY loops.
 *
 * We must use "if (1)" because "do {} while(0)" overrides the continue/break
 * processing.  See http://www.cit.gu.edu.au/~anthony/info/C/C.macros.
 */

/*
 * This keeps the character read at the top of the loop in the buffer
 * even if there is more than one read-ahead.
 */
#define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen) \
if (1) \
{ \
	if (raw_buf_ptr + (extralen) >= copy_buf_len && !hit_eof) \
	{ \
		raw_buf_ptr = prev_raw_ptr; /* undo fetch */ \
		need_data = true; \
		continue; \
	} \
} else


/* This consumes the remainder of the buffer and breaks */
#define IF_NEED_REFILL_AND_EOF_BREAK(extralen) \
if (1) \
{ \
	if (raw_buf_ptr + (extralen) >= copy_buf_len && hit_eof) \
	{ \
		if (extralen) \
			raw_buf_ptr = copy_buf_len; /* consume the partial character */ \
		/* backslash just before EOF, treat as data char */ \
		result = true; \
		break; \
	} \
} else


/*
 * Transfer any approved data to line_buf; must do this to be sure
 * there is some room in raw_buf.
 */
#define REFILL_LINEBUF \
if (1) \
{ \
	if (raw_buf_ptr > cstate->raw_buf_index) \
	{ \
		appendBinaryStringInfo(&cstate->line_buf, \
							 cstate->raw_buf + cstate->raw_buf_index, \
							   raw_buf_ptr - cstate->raw_buf_index); \
		cstate->raw_buf_index = raw_buf_ptr; \
	} \
} else

/* Undo any read-ahead and jump out of the block. */
#define NO_END_OF_COPY_GOTO \
if (1) \
{ \
	raw_buf_ptr = prev_raw_ptr + 1; \
	goto not_end_of_copy; \
} else


230
static const char BinarySignature[11] = "PGCOPY\n\377\r\n\0";
231

232 233

/* non-export function prototypes */
234 235 236 237 238
static void DoCopyTo(CopyState cstate);
static void CopyTo(CopyState cstate);
static void CopyFrom(CopyState cstate);
static bool CopyReadLine(CopyState cstate);
static bool CopyReadLineText(CopyState cstate);
B
Bruce Momjian 已提交
239 240 241 242
static int CopyReadAttributesText(CopyState cstate, int maxfields,
					   char **fieldvals);
static int CopyReadAttributesCSV(CopyState cstate, int maxfields,
					  char **fieldvals);
243
static Datum CopyReadBinaryAttribute(CopyState cstate,
B
Bruce Momjian 已提交
244 245 246
						int column_no, FmgrInfo *flinfo,
						Oid typioparam, int32 typmod,
						bool *isnull);
247 248
static void CopyAttributeOutText(CopyState cstate, char *string);
static void CopyAttributeOutCSV(CopyState cstate, char *string,
249
					bool use_quote, bool single_attr);
250
static List *CopyGetAttnums(Relation rel, List *attnamelist);
251 252 253 254 255 256 257 258 259 260
static char *limit_printout_length(const char *str);

/* Low-level communications functions */
static void SendCopyBegin(CopyState cstate);
static void ReceiveCopyBegin(CopyState cstate);
static void SendCopyEnd(CopyState cstate);
static void CopySendData(CopyState cstate, void *databuf, int datasize);
static void CopySendString(CopyState cstate, const char *str);
static void CopySendChar(CopyState cstate, char c);
static void CopySendEndOfRow(CopyState cstate);
B
Bruce Momjian 已提交
261 262
static int CopyGetData(CopyState cstate, void *databuf,
			int minread, int maxread);
263 264 265 266
static void CopySendInt32(CopyState cstate, int32 val);
static bool CopyGetInt32(CopyState cstate, int32 *val);
static void CopySendInt16(CopyState cstate, int16 val);
static bool CopyGetInt16(CopyState cstate, int16 *val);
M
 
Marc G. Fournier 已提交
267

268

M
 
Marc G. Fournier 已提交
269
/*
270 271
 * Send copy start/stop messages for frontend copies.  These have changed
 * in past protocol redesigns.
M
 
Marc G. Fournier 已提交
272
 */
273
static void
274
SendCopyBegin(CopyState cstate)
B
Bruce Momjian 已提交
275
{
276 277
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
278 279
		/* new way */
		StringInfoData buf;
280 281
		int			natts = list_length(cstate->attnumlist);
		int16		format = (cstate->binary ? 1 : 0);
B
Bruce Momjian 已提交
282
		int			i;
283 284

		pq_beginmessage(&buf, 'H');
B
Bruce Momjian 已提交
285
		pq_sendbyte(&buf, format);		/* overall format */
286 287
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
288
			pq_sendint(&buf, format, 2);		/* per-column formats */
289
		pq_endmessage(&buf);
290
		cstate->copy_dest = COPY_NEW_FE;
291 292
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
293
	{
294
		/* old way */
295
		if (cstate->binary)
296 297
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
298
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
299 300
		pq_putemptymessage('H');
		/* grottiness needed for old COPY OUT protocol */
301
		pq_startcopyout();
302
		cstate->copy_dest = COPY_OLD_FE;
303
	}
B
Bruce Momjian 已提交
304
	else
305
	{
306
		/* very old way */
307
		if (cstate->binary)
308 309
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
310
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
311 312
		pq_putemptymessage('B');
		/* grottiness needed for old COPY OUT protocol */
313
		pq_startcopyout();
314
		cstate->copy_dest = COPY_OLD_FE;
315
	}
M
 
Marc G. Fournier 已提交
316
}
B
Bruce Momjian 已提交
317

318
static void
319
ReceiveCopyBegin(CopyState cstate)
B
Bruce Momjian 已提交
320
{
321 322
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
323 324
		/* new way */
		StringInfoData buf;
325 326
		int			natts = list_length(cstate->attnumlist);
		int16		format = (cstate->binary ? 1 : 0);
B
Bruce Momjian 已提交
327
		int			i;
328 329

		pq_beginmessage(&buf, 'G');
B
Bruce Momjian 已提交
330
		pq_sendbyte(&buf, format);		/* overall format */
331 332
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
333
			pq_sendint(&buf, format, 2);		/* per-column formats */
334
		pq_endmessage(&buf);
335 336
		cstate->copy_dest = COPY_NEW_FE;
		cstate->fe_msgbuf = makeStringInfo();
337 338 339
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
340
		/* old way */
341
		if (cstate->binary)
342 343
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
344
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
345
		pq_putemptymessage('G');
346
		cstate->copy_dest = COPY_OLD_FE;
347 348 349
	}
	else
	{
350
		/* very old way */
351
		if (cstate->binary)
352 353
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
354
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
355
		pq_putemptymessage('D');
356
		cstate->copy_dest = COPY_OLD_FE;
357 358 359
	}
	/* We *must* flush here to ensure FE knows it can send. */
	pq_flush();
M
 
Marc G. Fournier 已提交
360 361
}

362
static void
363
SendCopyEnd(CopyState cstate)
B
Bruce Momjian 已提交
364
{
365
	if (cstate->copy_dest == COPY_NEW_FE)
366
	{
367 368
		/* Shouldn't have any unsent data */
		Assert(cstate->fe_msgbuf->len == 0);
369 370 371 372 373
		/* Send Copy Done message */
		pq_putemptymessage('c');
	}
	else
	{
374 375 376
		CopySendData(cstate, "\\.", 2);
		/* Need to flush out the trailer (this also appends a newline) */
		CopySendEndOfRow(cstate);
377
		pq_endcopyout(false);
378
	}
M
 
Marc G. Fournier 已提交
379 380
}

381
/*----------
382 383 384
 * CopySendData sends output data to the destination (file or frontend)
 * CopySendString does the same for null-terminated strings
 * CopySendChar does the same for single characters
385
 * CopySendEndOfRow does the appropriate thing at end of each data row
386
 *	(data is not actually flushed except by CopySendEndOfRow)
387 388
 *
 * NB: no data conversion is applied by these functions
389
 *----------
M
 
Marc G. Fournier 已提交
390
 */
391
static void
392
CopySendData(CopyState cstate, void *databuf, int datasize)
B
Bruce Momjian 已提交
393
{
394
	appendBinaryStringInfo(cstate->fe_msgbuf, (char *) databuf, datasize);
M
 
Marc G. Fournier 已提交
395 396
}

397
static void
398
CopySendString(CopyState cstate, const char *str)
399
{
400
	appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
401 402 403
}

static void
404
CopySendChar(CopyState cstate, char c)
405
{
406
	appendStringInfoCharMacro(cstate->fe_msgbuf, c);
407 408
}

409
static void
410
CopySendEndOfRow(CopyState cstate)
411
{
412 413
	StringInfo	fe_msgbuf = cstate->fe_msgbuf;

414
	switch (cstate->copy_dest)
415 416
	{
		case COPY_FILE:
417
			if (!cstate->binary)
418 419 420
			{
				/* Default line termination depends on platform */
#ifndef WIN32
421
				CopySendChar(cstate, '\n');
422
#else
423
				CopySendString(cstate, "\r\n");
424 425
#endif
			}
426 427 428 429 430 431 432

			(void) fwrite(fe_msgbuf->data, fe_msgbuf->len,
						  1, cstate->copy_file);
			if (ferror(cstate->copy_file))
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not write to COPY file: %m")));
433 434 435
			break;
		case COPY_OLD_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
436 437
			if (!cstate->binary)
				CopySendChar(cstate, '\n');
438 439 440 441 442 443 444 445

			if (pq_putbytes(fe_msgbuf->data, fe_msgbuf->len))
			{
				/* no hope of recovering connection sync, so FATAL */
				ereport(FATAL,
						(errcode(ERRCODE_CONNECTION_FAILURE),
						 errmsg("connection lost during COPY to stdout")));
			}
446 447 448
			break;
		case COPY_NEW_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
449 450
			if (!cstate->binary)
				CopySendChar(cstate, '\n');
451

452
			/* Dump the accumulated row as one CopyData message */
453
			(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
454 455
			break;
	}
456 457 458 459

	/* Reset fe_msgbuf to empty */
	fe_msgbuf->len = 0;
	fe_msgbuf->data[0] = '\0';
460 461
}

462 463 464
/*
 * CopyGetData reads data from the source (file or frontend)
 *
465
 * We attempt to read at least minread, and at most maxread, bytes from
B
Bruce Momjian 已提交
466
 * the source.	The actual number of bytes read is returned; if this is
467
 * less than minread, EOF was detected.
468 469 470 471 472
 *
 * Note: when copying from the frontend, we expect a proper EOF mark per
 * protocol; if the frontend simply drops the connection, we raise error.
 * It seems unwise to allow the COPY IN to complete normally in that case.
 *
473
 * NB: no data conversion is applied here.
474
 */
475 476
static int
CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
B
Bruce Momjian 已提交
477
{
B
Bruce Momjian 已提交
478
	int			bytesread = 0;
479 480

	switch (cstate->copy_dest)
B
Bruce Momjian 已提交
481
	{
482
		case COPY_FILE:
483 484 485 486 487
			bytesread = fread(databuf, 1, maxread, cstate->copy_file);
			if (ferror(cstate->copy_file))
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not read from COPY file: %m")));
488 489
			break;
		case COPY_OLD_FE:
B
Bruce Momjian 已提交
490

491 492 493
			/*
			 * We cannot read more than minread bytes (which in practice is 1)
			 * because old protocol doesn't have any clear way of separating
B
Bruce Momjian 已提交
494 495 496
			 * the COPY stream from following data.  This is slow, but not any
			 * slower than the code path was originally, and we don't care
			 * much anymore about the performance of old protocol.
497 498
			 */
			if (pq_getbytes((char *) databuf, minread))
499 500
			{
				/* Only a \. terminator is legal EOF in old protocol */
501 502 503
				ereport(ERROR,
						(errcode(ERRCODE_CONNECTION_FAILURE),
						 errmsg("unexpected EOF on client connection")));
504
			}
505
			bytesread = minread;
506 507
			break;
		case COPY_NEW_FE:
508
			while (maxread > 0 && bytesread < minread && !cstate->fe_eof)
509
			{
B
Bruce Momjian 已提交
510
				int			avail;
B
Bruce Momjian 已提交
511

512
				while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
513 514 515 516
				{
					/* Try to receive another message */
					int			mtype;

B
Bruce Momjian 已提交
517
			readmessage:
518 519
					mtype = pq_getbyte();
					if (mtype == EOF)
520 521
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
522
							 errmsg("unexpected EOF on client connection")));
523
					if (pq_getmessage(cstate->fe_msgbuf, 0))
524 525
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
526
							 errmsg("unexpected EOF on client connection")));
527 528
					switch (mtype)
					{
B
Bruce Momjian 已提交
529
						case 'd':		/* CopyData */
530
							break;
B
Bruce Momjian 已提交
531
						case 'c':		/* CopyDone */
532
							/* COPY IN correctly terminated by frontend */
533 534
							cstate->fe_eof = true;
							return bytesread;
B
Bruce Momjian 已提交
535
						case 'f':		/* CopyFail */
536 537 538
							ereport(ERROR,
									(errcode(ERRCODE_QUERY_CANCELED),
									 errmsg("COPY from stdin failed: %s",
B
Bruce Momjian 已提交
539
									   pq_getmsgstring(cstate->fe_msgbuf))));
540
							break;
541 542
						case 'H':		/* Flush */
						case 'S':		/* Sync */
B
Bruce Momjian 已提交
543

544
							/*
B
Bruce Momjian 已提交
545 546 547 548
							 * Ignore Flush/Sync for the convenience of client
							 * libraries (such as libpq) that may send those
							 * without noticing that the command they just
							 * sent was COPY.
549 550
							 */
							goto readmessage;
551
						default:
552 553 554 555
							ereport(ERROR,
									(errcode(ERRCODE_PROTOCOL_VIOLATION),
									 errmsg("unexpected message type 0x%02X during COPY from stdin",
											mtype)));
556 557 558
							break;
					}
				}
559 560 561 562
				avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
				if (avail > maxread)
					avail = maxread;
				pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
563
				databuf = (void *) ((char *) databuf + avail);
564 565
				maxread -= avail;
				bytesread += avail;
B
Bruce Momjian 已提交
566
			}
567
			break;
568
	}
B
Bruce Momjian 已提交
569

570
	return bytesread;
M
 
Marc G. Fournier 已提交
571
}
B
Bruce Momjian 已提交
572

M
 
Marc G. Fournier 已提交
573

574 575 576 577 578 579 580 581
/*
 * These functions do apply some data conversion
 */

/*
 * CopySendInt32 sends an int32 in network byte order
 */
static void
582
CopySendInt32(CopyState cstate, int32 val)
583 584 585 586
{
	uint32		buf;

	buf = htonl((uint32) val);
587
	CopySendData(cstate, &buf, sizeof(buf));
588 589 590 591
}

/*
 * CopyGetInt32 reads an int32 that appears in network byte order
592 593
 *
 * Returns true if OK, false if EOF
594
 */
595 596
static bool
CopyGetInt32(CopyState cstate, int32 *val)
597 598 599
{
	uint32		buf;

600
	if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
601 602
	{
		*val = 0;				/* suppress compiler warning */
603
		return false;
604
	}
605 606
	*val = (int32) ntohl(buf);
	return true;
607 608 609 610 611 612
}

/*
 * CopySendInt16 sends an int16 in network byte order
 */
static void
613
CopySendInt16(CopyState cstate, int16 val)
614 615 616 617
{
	uint16		buf;

	buf = htons((uint16) val);
618
	CopySendData(cstate, &buf, sizeof(buf));
619 620 621 622 623
}

/*
 * CopyGetInt16 reads an int16 that appears in network byte order
 */
624 625
static bool
CopyGetInt16(CopyState cstate, int16 *val)
626 627 628
{
	uint16		buf;

629
	if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
630 631
	{
		*val = 0;				/* suppress compiler warning */
632
		return false;
633
	}
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
	*val = (int16) ntohs(buf);
	return true;
}


/*
 * CopyLoadRawBuf loads some more data into raw_buf
 *
 * Returns TRUE if able to obtain at least one more byte, else FALSE.
 *
 * If raw_buf_index < raw_buf_len, the unprocessed bytes are transferred
 * down to the start of the buffer and then we load more data after that.
 * This case is used only when a frontend multibyte character crosses a
 * bufferload boundary.
 */
static bool
CopyLoadRawBuf(CopyState cstate)
{
B
Bruce Momjian 已提交
652 653
	int			nbytes;
	int			inbytes;
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671

	if (cstate->raw_buf_index < cstate->raw_buf_len)
	{
		/* Copy down the unprocessed data */
		nbytes = cstate->raw_buf_len - cstate->raw_buf_index;
		memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
				nbytes);
	}
	else
		nbytes = 0;				/* no data need be saved */

	inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
						  1, RAW_BUF_SIZE - nbytes);
	nbytes += inbytes;
	cstate->raw_buf[nbytes] = '\0';
	cstate->raw_buf_index = 0;
	cstate->raw_buf_len = nbytes;
	return (inbytes > 0);
672 673
}

M
 
Marc G. Fournier 已提交
674

675
/*
676
 *	 DoCopy executes the SQL COPY statement.
677
 *
678
 * Either unload or reload contents of table <relation>, depending on <from>.
679 680 681
 * (<from> = TRUE means we are inserting into the table.)
 *
 * If <pipe> is false, transfer is between the table and the file named
682 683
 * <filename>.	Otherwise, transfer is between the table and our regular
 * input/output stream. The latter could be either stdin/stdout or a
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
 * socket, depending on whether we're running under Postmaster control.
 *
 * Iff <binary>, unload or reload in the binary format, as opposed to the
 * more wasteful but more robust and portable text format.
 *
 * Iff <oids>, unload or reload the format that includes OID information.
 * On input, we accept OIDs whether or not the table has an OID column,
 * but silently drop them if it does not.  On output, we report an error
 * if the user asks for OIDs in a table that has none (not providing an
 * OID column might seem friendlier, but could seriously confuse programs).
 *
 * If in the text format, delimit columns with delimiter <delim> and print
 * NULL values as <null_print>.
 *
 * Do not allow a Postgres user without superuser privilege to read from
 * or write to a file.
 *
 * Do not allow the copy if user doesn't have proper permission to access
 * the table.
703
 */
704
uint64
705
DoCopy(const CopyStmt *stmt)
706
{
707
	CopyState	cstate;
B
Bruce Momjian 已提交
708 709 710 711 712
	RangeVar   *relation = stmt->relation;
	char	   *filename = stmt->filename;
	bool		is_from = stmt->is_from;
	bool		pipe = (stmt->filename == NULL);
	List	   *attnamelist = stmt->attlist;
B
Bruce Momjian 已提交
713 714
	List	   *force_quote = NIL;
	List	   *force_notnull = NIL;
715
	AclMode		required_access = (is_from ? ACL_INSERT : ACL_SELECT);
716
	AclResult	aclresult;
717
	ListCell   *option;
718
	uint64		processed;
719 720 721

	/* Allocate workspace and zero all fields */
	cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
722

723 724 725 726 727 728 729
	/* Extract options from the statement node tree */
	foreach(option, stmt->options)
	{
		DefElem    *defel = (DefElem *) lfirst(option);

		if (strcmp(defel->defname, "binary") == 0)
		{
730
			if (cstate->binary)
731 732 733
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
734
			cstate->binary = intVal(defel->arg);
735 736 737
		}
		else if (strcmp(defel->defname, "oids") == 0)
		{
738
			if (cstate->oids)
739 740 741
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
742
			cstate->oids = intVal(defel->arg);
743 744 745
		}
		else if (strcmp(defel->defname, "delimiter") == 0)
		{
746
			if (cstate->delim)
747 748 749
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
750
			cstate->delim = strVal(defel->arg);
751 752 753
		}
		else if (strcmp(defel->defname, "null") == 0)
		{
754
			if (cstate->null_print)
755 756 757
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
758
			cstate->null_print = strVal(defel->arg);
759
		}
B
Bruce Momjian 已提交
760 761
		else if (strcmp(defel->defname, "csv") == 0)
		{
762
			if (cstate->csv_mode)
B
Bruce Momjian 已提交
763 764 765
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
766
			cstate->csv_mode = intVal(defel->arg);
B
Bruce Momjian 已提交
767
		}
768 769
		else if (strcmp(defel->defname, "header") == 0)
		{
770
			if (cstate->header_line)
771 772 773
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
774
			cstate->header_line = intVal(defel->arg);
775
		}
B
Bruce Momjian 已提交
776 777
		else if (strcmp(defel->defname, "quote") == 0)
		{
778
			if (cstate->quote)
B
Bruce Momjian 已提交
779 780 781
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
782
			cstate->quote = strVal(defel->arg);
B
Bruce Momjian 已提交
783 784 785
		}
		else if (strcmp(defel->defname, "escape") == 0)
		{
786
			if (cstate->escape)
B
Bruce Momjian 已提交
787 788 789
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
790
			cstate->escape = strVal(defel->arg);
B
Bruce Momjian 已提交
791
		}
B
Bruce Momjian 已提交
792
		else if (strcmp(defel->defname, "force_quote") == 0)
B
Bruce Momjian 已提交
793
		{
B
Bruce Momjian 已提交
794
			if (force_quote)
B
Bruce Momjian 已提交
795 796 797
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
798
			force_quote = (List *) defel->arg;
B
Bruce Momjian 已提交
799
		}
B
Bruce Momjian 已提交
800
		else if (strcmp(defel->defname, "force_notnull") == 0)
B
Bruce Momjian 已提交
801
		{
B
Bruce Momjian 已提交
802
			if (force_notnull)
B
Bruce Momjian 已提交
803 804 805
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
806
			force_notnull = (List *) defel->arg;
B
Bruce Momjian 已提交
807
		}
808
		else
809
			elog(ERROR, "option \"%s\" not recognized",
810 811 812
				 defel->defname);
	}

813 814
	/* Check for incompatible options */
	if (cstate->binary && cstate->delim)
815 816 817
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify DELIMITER in BINARY mode")));
818

819
	if (cstate->binary && cstate->csv_mode)
B
Bruce Momjian 已提交
820 821 822 823
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify CSV in BINARY mode")));

824
	if (cstate->binary && cstate->null_print)
825 826 827
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify NULL in BINARY mode")));
B
Bruce Momjian 已提交
828

829 830 831
	/* Set defaults for omitted options */
	if (!cstate->delim)
		cstate->delim = cstate->csv_mode ? "," : "\t";
B
Bruce Momjian 已提交
832

833 834 835
	if (!cstate->null_print)
		cstate->null_print = cstate->csv_mode ? "" : "\\N";
	cstate->null_print_len = strlen(cstate->null_print);
B
Bruce Momjian 已提交
836

837
	if (cstate->csv_mode)
B
Bruce Momjian 已提交
838
	{
839 840 841 842
		if (!cstate->quote)
			cstate->quote = "\"";
		if (!cstate->escape)
			cstate->escape = cstate->quote;
B
Bruce Momjian 已提交
843
	}
B
Bruce Momjian 已提交
844

845
	/* Only single-character delimiter strings are supported. */
846
	if (strlen(cstate->delim) != 1)
B
Bruce Momjian 已提交
847 848 849 850
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY delimiter must be a single character")));

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
	/* Disallow end-of-line characters */
	if (strchr(cstate->delim, '\r') != NULL ||
	    strchr(cstate->delim, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("COPY delimiter cannot be newline or carriage return")));

	if (strchr(cstate->null_print, '\r') != NULL ||
		strchr(cstate->null_print, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("COPY null cannot use newline or carriage return")));

	/* Disallow backslash in non-CSV mode */
	if (!cstate->csv_mode && strchr(cstate->delim, '\\') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				 errmsg("COPY delimiter cannot be backslash")));

B
Bruce Momjian 已提交
870
	/* Check header */
871
	if (!cstate->csv_mode && cstate->header_line)
872 873 874 875
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY HEADER available only in CSV mode")));

876
	/* Check quote */
877
	if (!cstate->csv_mode && cstate->quote != NULL)
B
Bruce Momjian 已提交
878 879 880 881
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY quote available only in CSV mode")));

882
	if (cstate->csv_mode && strlen(cstate->quote) != 1)
B
Bruce Momjian 已提交
883 884 885 886
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY quote must be a single character")));

887
	/* Check escape */
888
	if (!cstate->csv_mode && cstate->escape != NULL)
B
Bruce Momjian 已提交
889 890 891 892
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY escape available only in CSV mode")));

893
	if (cstate->csv_mode && strlen(cstate->escape) != 1)
B
Bruce Momjian 已提交
894 895 896 897
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("COPY escape must be a single character")));

898
	/* Check force_quote */
899
	if (!cstate->csv_mode && force_quote != NIL)
B
Bruce Momjian 已提交
900 901
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
902 903
				 errmsg("COPY force quote available only in CSV mode")));
	if (force_quote != NIL && is_from)
B
Bruce Momjian 已提交
904 905
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
906
				 errmsg("COPY force quote only available using COPY TO")));
B
Bruce Momjian 已提交
907

908
	/* Check force_notnull */
909
	if (!cstate->csv_mode && force_notnull != NIL)
B
Bruce Momjian 已提交
910 911
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
912
				 errmsg("COPY force not null available only in CSV mode")));
B
Bruce Momjian 已提交
913
	if (force_notnull != NIL && !is_from)
B
Bruce Momjian 已提交
914 915
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
916
			  errmsg("COPY force not null only available using COPY FROM")));
B
Bruce Momjian 已提交
917

918
	/* Don't allow the delimiter to appear in the null string. */
919
	if (strchr(cstate->null_print, cstate->delim[0]) != NULL)
B
Bruce Momjian 已提交
920 921
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
B
Bruce Momjian 已提交
922
		errmsg("COPY delimiter must not appear in the NULL specification")));
B
Bruce Momjian 已提交
923

924 925 926
	/* Don't allow the CSV quote char to appear in the null string. */
	if (cstate->csv_mode &&
		strchr(cstate->null_print, cstate->quote[0]) != NULL)
B
Bruce Momjian 已提交
927 928 929
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				 errmsg("CSV quote character must not appear in the NULL specification")));
B
Bruce Momjian 已提交
930

931
	/* Open and lock the relation, using the appropriate lock type. */
932 933
	cstate->rel = heap_openrv(relation,
							  (is_from ? RowExclusiveLock : AccessShareLock));
934

935
	/* check read-only transaction */
936
	if (XactReadOnly && is_from &&
937
		!isTempNamespace(RelationGetNamespace(cstate->rel)))
938 939 940
		ereport(ERROR,
				(errcode(ERRCODE_READ_ONLY_SQL_TRANSACTION),
				 errmsg("transaction is read-only")));
941

942
	/* Check permissions. */
943
	aclresult = pg_class_aclcheck(RelationGetRelid(cstate->rel), GetUserId(),
944 945
								  required_access);
	if (aclresult != ACLCHECK_OK)
946
		aclcheck_error(aclresult, ACL_KIND_CLASS,
947
					   RelationGetRelationName(cstate->rel));
948
	if (!pipe && !superuser())
949 950 951 952
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
				 errmsg("must be superuser to COPY to or from a file"),
				 errhint("Anyone can COPY to stdout or from stdin. "
B
Bruce Momjian 已提交
953
						 "psql's \\copy command also works for anyone.")));
B
Bruce Momjian 已提交
954

955
	/* Don't allow COPY w/ OIDs to or from a table without them */
956
	if (cstate->oids && !cstate->rel->rd_rel->relhasoids)
957 958 959
		ereport(ERROR,
				(errcode(ERRCODE_UNDEFINED_COLUMN),
				 errmsg("table \"%s\" does not have OIDs",
960
						RelationGetRelationName(cstate->rel))));
B
Bruce Momjian 已提交
961

962
	/* Generate or convert list of attributes to process */
963
	cstate->attnumlist = CopyGetAttnums(cstate->rel, attnamelist);
964

965
	/* Convert FORCE QUOTE name list to column numbers, check validity */
B
Bruce Momjian 已提交
966
	if (force_quote)
B
Bruce Momjian 已提交
967
	{
968
		TupleDesc	tupDesc = RelationGetDescr(cstate->rel);
B
Bruce Momjian 已提交
969
		Form_pg_attribute *attr = tupDesc->attrs;
970
		ListCell   *cur;
B
Bruce Momjian 已提交
971

972
		cstate->force_quote_atts = CopyGetAttnums(cstate->rel, force_quote);
B
Bruce Momjian 已提交
973

974
		foreach(cur, cstate->force_quote_atts)
B
Bruce Momjian 已提交
975
		{
976
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
977

978
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
979 980
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
B
Bruce Momjian 已提交
981 982
				   errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
						  NameStr(attr[attnum - 1]->attname))));
B
Bruce Momjian 已提交
983 984
		}
	}
B
Bruce Momjian 已提交
985

986
	/* Convert FORCE NOT NULL name list to column numbers, check validity */
B
Bruce Momjian 已提交
987
	if (force_notnull)
B
Bruce Momjian 已提交
988
	{
989
		TupleDesc	tupDesc = RelationGetDescr(cstate->rel);
B
Bruce Momjian 已提交
990
		Form_pg_attribute *attr = tupDesc->attrs;
991
		ListCell   *cur;
B
Bruce Momjian 已提交
992

993 994
		cstate->force_notnull_atts = CopyGetAttnums(cstate->rel,
													force_notnull);
B
Bruce Momjian 已提交
995

996
		foreach(cur, cstate->force_notnull_atts)
B
Bruce Momjian 已提交
997
		{
998
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
999

1000
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1001 1002
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
B
Bruce Momjian 已提交
1003 1004
				errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
					   NameStr(attr[attnum - 1]->attname))));
B
Bruce Momjian 已提交
1005 1006
		}
	}
B
Bruce Momjian 已提交
1007

1008
	/* Set up variables to avoid per-attribute overhead. */
1009 1010 1011 1012 1013
	initStringInfo(&cstate->attribute_buf);
	initStringInfo(&cstate->line_buf);
	cstate->line_buf_converted = false;
	cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
	cstate->raw_buf_index = cstate->raw_buf_len = 0;
1014
	cstate->processed = 0;
1015

1016 1017 1018 1019 1020
	/*
	 * Set up encoding conversion info.  Even if the client and server
	 * encodings are the same, we must apply pg_client_to_server() to
	 * validate data in multibyte encodings.
	 */
1021
	cstate->client_encoding = pg_get_client_encoding();
1022 1023 1024
	cstate->need_transcoding =
		(cstate->client_encoding != GetDatabaseEncoding() ||
		 pg_database_encoding_max_length() > 1);
B
Bruce Momjian 已提交
1025 1026
	/* See Multibyte encoding comment above */
	cstate->encoding_embeds_ascii = PG_ENCODING_IS_CLIENT_ONLY(cstate->client_encoding);
1027

1028
	cstate->copy_dest = COPY_FILE;		/* default */
1029

1030
	if (is_from)
1031
	{							/* copy from file to database */
1032
		if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
1033
		{
1034
			if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
1035 1036 1037
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy to view \"%s\"",
1038 1039
								RelationGetRelationName(cstate->rel))));
			else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
1040 1041 1042
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy to sequence \"%s\"",
1043
								RelationGetRelationName(cstate->rel))));
1044
			else
1045 1046
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
B
Bruce Momjian 已提交
1047 1048
						 errmsg("cannot copy to non-table relation \"%s\"",
								RelationGetRelationName(cstate->rel))));
1049
		}
1050 1051
		if (pipe)
		{
1052
			if (whereToSendOutput == DestRemote)
1053
				ReceiveCopyBegin(cstate);
1054
			else
1055
				cstate->copy_file = stdin;
1056 1057 1058
		}
		else
		{
1059 1060
			struct stat st;

1061
			cstate->copy_file = AllocateFile(filename, PG_BINARY_R);
1062

1063
			if (cstate->copy_file == NULL)
1064 1065
				ereport(ERROR,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
1066 1067
						 errmsg("could not open file \"%s\" for reading: %m",
								filename)));
1068

1069
			fstat(fileno(cstate->copy_file), &st);
1070 1071
			if (S_ISDIR(st.st_mode))
			{
1072
				FreeFile(cstate->copy_file);
1073 1074 1075
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("\"%s\" is a directory", filename)));
1076
			}
1077
		}
1078 1079

		CopyFrom(cstate);
1080 1081 1082
	}
	else
	{							/* copy from database to file */
1083
		if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
1084
		{
1085
			if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
1086 1087 1088
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from view \"%s\"",
1089 1090
								RelationGetRelationName(cstate->rel))));
			else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
1091 1092 1093
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from sequence \"%s\"",
1094
								RelationGetRelationName(cstate->rel))));
1095
			else
1096 1097
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
B
Bruce Momjian 已提交
1098 1099
						 errmsg("cannot copy from non-table relation \"%s\"",
								RelationGetRelationName(cstate->rel))));
1100
		}
1101 1102
		if (pipe)
		{
1103
			if (whereToSendOutput == DestRemote)
1104
				cstate->fe_copy = true;
1105
			else
1106
				cstate->copy_file = stdout;
1107 1108 1109
		}
		else
		{
1110
			mode_t		oumask; /* Pre-existing umask value */
1111
			struct stat st;
1112

1113
			/*
B
Bruce Momjian 已提交
1114 1115
			 * Prevent write to relative path ... too easy to shoot oneself in
			 * the foot by overwriting a database file ...
1116
			 */
1117
			if (!is_absolute_path(filename))
1118 1119
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_NAME),
B
Bruce Momjian 已提交
1120
					  errmsg("relative path not allowed for COPY to file")));
1121

1122
			oumask = umask((mode_t) 022);
1123
			cstate->copy_file = AllocateFile(filename, PG_BINARY_W);
1124
			umask(oumask);
1125

1126
			if (cstate->copy_file == NULL)
1127 1128
				ereport(ERROR,
						(errcode_for_file_access(),
B
Bruce Momjian 已提交
1129 1130
						 errmsg("could not open file \"%s\" for writing: %m",
								filename)));
1131

1132
			fstat(fileno(cstate->copy_file), &st);
1133 1134
			if (S_ISDIR(st.st_mode))
			{
1135
				FreeFile(cstate->copy_file);
1136 1137 1138
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("\"%s\" is a directory", filename)));
1139
			}
1140
		}
1141

1142
		DoCopyTo(cstate);
1143 1144 1145
	}

	if (!pipe)
1146 1147
	{
		/* we assume only the write case could fail here */
1148
		if (FreeFile(cstate->copy_file))
1149 1150 1151 1152 1153
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write to file \"%s\": %m",
							filename)));
	}
1154

1155
	/*
B
Bruce Momjian 已提交
1156 1157 1158
	 * Close the relation.	If reading, we can release the AccessShareLock we
	 * got; if writing, we should hold the lock until end of transaction to
	 * ensure that updates will be committed before lock is released.
1159
	 */
1160 1161 1162
	heap_close(cstate->rel, (is_from ? NoLock : AccessShareLock));

	/* Clean up storage (probably not really necessary) */
1163 1164
	processed = cstate->processed;

1165 1166 1167 1168
	pfree(cstate->attribute_buf.data);
	pfree(cstate->line_buf.data);
	pfree(cstate->raw_buf);
	pfree(cstate);
1169 1170

	return processed;
1171 1172
}

1173

1174 1175 1176 1177 1178
/*
 * This intermediate routine just exists to localize the effects of setjmp
 * so we don't need to plaster a lot of variables with "volatile".
 */
static void
1179
DoCopyTo(CopyState cstate)
1180 1181 1182
{
	PG_TRY();
	{
1183 1184
		if (cstate->fe_copy)
			SendCopyBegin(cstate);
1185

1186
		CopyTo(cstate);
1187

1188 1189
		if (cstate->fe_copy)
			SendCopyEnd(cstate);
1190 1191 1192 1193
	}
	PG_CATCH();
	{
		/*
B
Bruce Momjian 已提交
1194
		 * Make sure we turn off old-style COPY OUT mode upon error. It is
B
Bruce Momjian 已提交
1195 1196
		 * okay to do this in all cases, since it does nothing if the mode is
		 * not on.
1197 1198 1199 1200 1201 1202 1203
		 */
		pq_endcopyout(true);
		PG_RE_THROW();
	}
	PG_END_TRY();
}

1204 1205 1206
/*
 * Copy from relation TO file.
 */
1207
static void
1208
CopyTo(CopyState cstate)
1209
{
1210
	HeapTuple	tuple;
1211
	TupleDesc	tupDesc;
1212
	HeapScanDesc scandesc;
1213 1214
	int			num_phys_attrs;
	int			attr_count;
1215
	Form_pg_attribute *attr;
1216
	FmgrInfo   *out_functions;
B
Bruce Momjian 已提交
1217
	bool	   *force_quote;
1218
	char	   *string;
1219
	char	   *null_print_client;
1220
	ListCell   *cur;
1221 1222
	MemoryContext oldcontext;
	MemoryContext mycontext;
1223

1224
	tupDesc = cstate->rel->rd_att;
1225 1226
	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
1227
	attr_count = list_length(cstate->attnumlist);
B
Bruce Momjian 已提交
1228
	null_print_client = cstate->null_print;		/* default */
1229

1230 1231 1232
	/* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
	cstate->fe_msgbuf = makeStringInfo();

1233
	/* Get info about the columns we need to process. */
1234 1235
	out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
	force_quote = (bool *) palloc(num_phys_attrs * sizeof(bool));
1236
	foreach(cur, cstate->attnumlist)
1237
	{
1238
		int			attnum = lfirst_int(cur);
1239
		Oid			out_func_oid;
1240
		bool		isvarlena;
B
Bruce Momjian 已提交
1241

1242
		if (cstate->binary)
1243
			getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
1244 1245
									&out_func_oid,
									&isvarlena);
1246 1247
		else
			getTypeOutputInfo(attr[attnum - 1]->atttypid,
1248 1249
							  &out_func_oid,
							  &isvarlena);
B
Bruce Momjian 已提交
1250
		fmgr_info(out_func_oid, &out_functions[attnum - 1]);
B
Bruce Momjian 已提交
1251

1252
		if (list_member_int(cstate->force_quote_atts, attnum))
B
Bruce Momjian 已提交
1253 1254 1255
			force_quote[attnum - 1] = true;
		else
			force_quote[attnum - 1] = false;
1256
	}
1257

1258
	/*
B
Bruce Momjian 已提交
1259
	 * Create a temporary memory context that we can reset once per row to
B
Bruce Momjian 已提交
1260 1261 1262
	 * recover palloc'd memory.  This avoids any problems with leaks inside
	 * datatype output routines, and should be faster than retail pfree's
	 * anyway.	(We don't need a whole econtext as CopyFrom does.)
1263 1264 1265 1266 1267 1268 1269
	 */
	mycontext = AllocSetContextCreate(CurrentMemoryContext,
									  "COPY TO",
									  ALLOCSET_DEFAULT_MINSIZE,
									  ALLOCSET_DEFAULT_INITSIZE,
									  ALLOCSET_DEFAULT_MAXSIZE);

1270
	if (cstate->binary)
1271
	{
1272 1273 1274 1275
		/* Generate header for a binary copy */
		int32		tmp;

		/* Signature */
1276
		CopySendData(cstate, (char *) BinarySignature, 11);
1277 1278
		/* Flags field */
		tmp = 0;
1279
		if (cstate->oids)
1280
			tmp |= (1 << 16);
1281
		CopySendInt32(cstate, tmp);
1282 1283
		/* No header extension */
		tmp = 0;
1284
		CopySendInt32(cstate, tmp);
1285
	}
1286 1287 1288 1289 1290 1291
	else
	{
		/*
		 * For non-binary copy, we need to convert null_print to client
		 * encoding, because it will be sent directly with CopySendString.
		 */
1292
		if (cstate->need_transcoding)
1293 1294
			null_print_client = pg_server_to_client(cstate->null_print,
													cstate->null_print_len);
1295 1296

		/* if a header has been requested send the line */
1297
		if (cstate->header_line)
1298
		{
B
Bruce Momjian 已提交
1299 1300
			bool		hdr_delim = false;

1301
			foreach(cur, cstate->attnumlist)
1302 1303
			{
				int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1304
				char	   *colname;
1305 1306

				if (hdr_delim)
1307
					CopySendChar(cstate, cstate->delim[0]);
1308 1309 1310 1311
				hdr_delim = true;

				colname = NameStr(attr[attnum - 1]->attname);

1312 1313
				CopyAttributeOutCSV(cstate, colname, false,
									list_length(cstate->attnumlist) == 1);
1314 1315
			}

1316
			CopySendEndOfRow(cstate);
1317
		}
1318
	}
1319

1320
	scandesc = heap_beginscan(cstate->rel, ActiveSnapshot, 0, NULL);
1321

1322
	while ((tuple = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
1323
	{
1324
		bool		need_delim = false;
B
Bruce Momjian 已提交
1325

1326
		CHECK_FOR_INTERRUPTS();
1327

1328 1329 1330
		MemoryContextReset(mycontext);
		oldcontext = MemoryContextSwitchTo(mycontext);

1331
		if (cstate->binary)
1332 1333
		{
			/* Binary per-tuple header */
1334
			CopySendInt16(cstate, attr_count);
1335
			/* Send OID if wanted --- note attr_count doesn't include it */
1336
			if (cstate->oids)
1337
			{
B
Bruce Momjian 已提交
1338
				Oid			oid = HeapTupleGetOid(tuple);
1339

1340
				/* Hack --- assume Oid is same size as int32 */
1341 1342
				CopySendInt32(cstate, sizeof(int32));
				CopySendInt32(cstate, oid);
1343 1344 1345
			}
		}
		else
1346
		{
1347
			/* Text format has no per-tuple header, but send OID if wanted */
1348 1349
			/* Assume digits don't need any quoting or encoding conversion */
			if (cstate->oids)
1350 1351
			{
				string = DatumGetCString(DirectFunctionCall1(oidout,
B
Bruce Momjian 已提交
1352
								  ObjectIdGetDatum(HeapTupleGetOid(tuple))));
1353
				CopySendString(cstate, string);
1354 1355
				need_delim = true;
			}
1356 1357
		}

1358
		foreach(cur, cstate->attnumlist)
1359
		{
1360
			int			attnum = lfirst_int(cur);
1361
			Datum		value;
1362 1363
			bool		isnull;

1364
			value = heap_getattr(tuple, attnum, tupDesc, &isnull);
1365

1366
			if (!cstate->binary)
1367 1368
			{
				if (need_delim)
1369
					CopySendChar(cstate, cstate->delim[0]);
1370 1371 1372
				need_delim = true;
			}

1373
			if (isnull)
1374
			{
1375 1376
				if (!cstate->binary)
					CopySendString(cstate, null_print_client);
1377
				else
1378
					CopySendInt32(cstate, -1);
1379 1380 1381
			}
			else
			{
1382
				if (!cstate->binary)
1383
				{
1384 1385
					string = OutputFunctionCall(&out_functions[attnum - 1],
												value);
1386 1387
					if (cstate->csv_mode)
						CopyAttributeOutCSV(cstate, string,
1388 1389
											force_quote[attnum - 1],
											list_length(cstate->attnumlist) == 1);
B
Bruce Momjian 已提交
1390
					else
1391
						CopyAttributeOutText(cstate, string);
1392
				}
1393 1394
				else
				{
1395 1396
					bytea	   *outputbytes;

1397 1398
					outputbytes = SendFunctionCall(&out_functions[attnum - 1],
												   value);
1399 1400
					CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
					CopySendData(cstate, VARDATA(outputbytes),
1401
								 VARSIZE(outputbytes) - VARHDRSZ);
1402
				}
1403
			}
1404 1405
		}

1406
		CopySendEndOfRow(cstate);
1407 1408

		MemoryContextSwitchTo(oldcontext);
1409 1410
		
		cstate->processed++;
1411
	}
1412

1413
	heap_endscan(scandesc);
1414

1415
	if (cstate->binary)
1416 1417
	{
		/* Generate trailer for a binary copy */
1418
		CopySendInt16(cstate, -1);
1419 1420
		/* Need to flush out the trailer */
		CopySendEndOfRow(cstate);
1421 1422
	}

1423 1424
	MemoryContextDelete(mycontext);

1425
	pfree(out_functions);
B
Bruce Momjian 已提交
1426
	pfree(force_quote);
1427 1428
}

1429

1430 1431 1432 1433 1434 1435
/*
 * error context callback for COPY FROM
 */
static void
copy_in_error_callback(void *arg)
{
1436 1437 1438
	CopyState	cstate = (CopyState) arg;

	if (cstate->binary)
1439 1440
	{
		/* can't usefully display the data */
1441
		if (cstate->cur_attname)
1442
			errcontext("COPY %s, line %d, column %s",
1443 1444
					   cstate->cur_relname, cstate->cur_lineno,
					   cstate->cur_attname);
1445
		else
1446 1447
			errcontext("COPY %s, line %d",
					   cstate->cur_relname, cstate->cur_lineno);
1448 1449 1450
	}
	else
	{
1451
		if (cstate->cur_attname && cstate->cur_attval)
1452 1453
		{
			/* error is relevant to a particular column */
B
Bruce Momjian 已提交
1454
			char	   *attval;
1455 1456

			attval = limit_printout_length(cstate->cur_attval);
1457
			errcontext("COPY %s, line %d, column %s: \"%s\"",
1458 1459 1460
					   cstate->cur_relname, cstate->cur_lineno,
					   cstate->cur_attname, attval);
			pfree(attval);
1461
		}
1462 1463 1464 1465 1466 1467 1468
		else if (cstate->cur_attname)
		{
			/* error is relevant to a particular column, value is NULL */
			errcontext("COPY %s, line %d, column %s: NULL input",
					   cstate->cur_relname, cstate->cur_lineno,
					   cstate->cur_attname);
		}
1469 1470 1471
		else
		{
			/* error is relevant to a particular line */
1472
			if (cstate->line_buf_converted || !cstate->need_transcoding)
1473
			{
B
Bruce Momjian 已提交
1474
				char	   *lineval;
1475 1476

				lineval = limit_printout_length(cstate->line_buf.data);
1477
				errcontext("COPY %s, line %d: \"%s\"",
1478 1479
						   cstate->cur_relname, cstate->cur_lineno, lineval);
				pfree(lineval);
1480 1481 1482 1483
			}
			else
			{
				/*
B
Bruce Momjian 已提交
1484 1485 1486 1487 1488 1489
				 * Here, the line buffer is still in a foreign encoding, and
				 * indeed it's quite likely that the error is precisely a
				 * failure to do encoding conversion (ie, bad data).  We dare
				 * not try to convert it, and at present there's no way to
				 * regurgitate it without conversion.  So we have to punt and
				 * just report the line number.
1490
				 */
1491 1492
				errcontext("COPY %s, line %d",
						   cstate->cur_relname, cstate->cur_lineno);
1493 1494 1495
			}
		}
	}
1496 1497
}

1498 1499 1500 1501 1502 1503 1504
/*
 * Make sure we don't print an unreasonable amount of COPY data in a message.
 *
 * It would seem a lot easier to just use the sprintf "precision" limit to
 * truncate the string.  However, some versions of glibc have a bug/misfeature
 * that vsnprintf will always fail (return -1) if it is asked to truncate
 * a string that contains invalid byte sequences for the current encoding.
1505
 * So, do our own truncation.  We return a pstrdup'd copy of the input.
1506
 */
1507 1508
static char *
limit_printout_length(const char *str)
1509 1510 1511
{
#define MAX_COPY_DATA_DISPLAY 100

1512
	int			slen = strlen(str);
B
Bruce Momjian 已提交
1513
	int			len;
1514
	char	   *res;
1515 1516

	/* Fast path if definitely okay */
1517 1518
	if (slen <= MAX_COPY_DATA_DISPLAY)
		return pstrdup(str);
1519 1520

	/* Apply encoding-dependent truncation */
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530
	len = pg_mbcliplen(str, slen, MAX_COPY_DATA_DISPLAY);

	/*
	 * Truncate, and add "..." to show we truncated the input.
	 */
	res = (char *) palloc(len + 4);
	memcpy(res, str, len);
	strcpy(res + len, "...");

	return res;
1531
}
1532

1533 1534 1535
/*
 * Copy FROM file to relation.
 */
1536
static void
1537
CopyFrom(CopyState cstate)
1538
{
1539
	HeapTuple	tuple;
1540
	TupleDesc	tupDesc;
1541
	Form_pg_attribute *attr;
B
Bruce Momjian 已提交
1542 1543 1544
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
1545
	FmgrInfo   *in_functions;
1546
	FmgrInfo	oid_in_function;
1547 1548
	Oid		   *typioparams;
	Oid			oid_typioparam;
B
Bruce Momjian 已提交
1549
	bool	   *force_notnull;
1550
	int			attnum;
B
Bruce Momjian 已提交
1551
	int			i;
1552 1553
	Oid			in_func_oid;
	Datum	   *values;
1554
	char	   *nulls;
1555 1556
	int			nfields;
	char	  **field_strings;
1557
	bool		done = false;
1558
	bool		isnull;
1559
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
1560
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
1561
	TupleTableSlot *slot;
1562
	bool		file_has_oids;
1563
	int		   *defmap;
1564
	ExprState **defexprs;		/* array of default att expressions */
B
Bruce Momjian 已提交
1565
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
1566
	MemoryContext oldcontext = CurrentMemoryContext;
1567
	ErrorContextCallback errcontext;
1568

1569
	tupDesc = RelationGetDescr(cstate->rel);
1570
	attr = tupDesc->attrs;
1571
	num_phys_attrs = tupDesc->natts;
1572
	attr_count = list_length(cstate->attnumlist);
1573
	num_defaults = 0;
1574 1575

	/*
1576
	 * We need a ResultRelInfo so we can use the regular executor's
B
Bruce Momjian 已提交
1577 1578
	 * index-entry-making machinery.  (There used to be a huge amount of code
	 * here that basically duplicated execUtils.c ...)
1579
	 */
1580
	resultRelInfo = makeNode(ResultRelInfo);
B
Bruce Momjian 已提交
1581
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
1582 1583
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
1584 1585 1586 1587
	if (resultRelInfo->ri_TrigDesc)
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
			palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
	resultRelInfo->ri_TrigInstrument = NULL;
1588

1589
	ExecOpenIndices(resultRelInfo);
1590

1591 1592 1593
	estate->es_result_relations = resultRelInfo;
	estate->es_num_result_relations = 1;
	estate->es_result_relation_info = resultRelInfo;
1594

1595 1596
	/* Set up a tuple slot too */
	slot = MakeSingleTupleTableSlot(tupDesc);
1597

1598 1599
	econtext = GetPerTupleExprContext(estate);

1600
	/*
1601
	 * Pick up the required catalog information for each attribute in the
B
Bruce Momjian 已提交
1602 1603 1604
	 * relation, including the input function, the element type (to pass to
	 * the input function), and info about defaults and constraints. (Which
	 * input function we use depends on text/binary format choice.)
1605
	 */
1606
	in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1607
	typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
1608 1609 1610
	defmap = (int *) palloc(num_phys_attrs * sizeof(int));
	defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
	force_notnull = (bool *) palloc(num_phys_attrs * sizeof(bool));
1611

1612
	for (attnum = 1; attnum <= num_phys_attrs; attnum++)
1613
	{
1614
		/* We don't need info for dropped attributes */
1615
		if (attr[attnum - 1]->attisdropped)
1616
			continue;
B
Bruce Momjian 已提交
1617

1618
		/* Fetch the input function and typioparam info */
1619
		if (cstate->binary)
1620
			getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
B
Bruce Momjian 已提交
1621
								   &in_func_oid, &typioparams[attnum - 1]);
1622
		else
1623
			getTypeInputInfo(attr[attnum - 1]->atttypid,
1624
							 &in_func_oid, &typioparams[attnum - 1]);
1625
		fmgr_info(in_func_oid, &in_functions[attnum - 1]);
B
Bruce Momjian 已提交
1626

1627
		if (list_member_int(cstate->force_notnull_atts, attnum))
B
Bruce Momjian 已提交
1628
			force_notnull[attnum - 1] = true;
B
Bruce Momjian 已提交
1629
		else
B
Bruce Momjian 已提交
1630
			force_notnull[attnum - 1] = false;
B
Bruce Momjian 已提交
1631

1632
		/* Get default info if needed */
1633
		if (!list_member_int(cstate->attnumlist, attnum))
1634
		{
1635
			/* attribute is NOT to be copied from input */
1636
			/* use default value if one exists */
1637
			Node	   *defexpr = build_column_default(cstate->rel, attnum);
1638 1639

			if (defexpr != NULL)
B
Bruce Momjian 已提交
1640
			{
1641 1642
				defexprs[num_defaults] = ExecPrepareExpr((Expr *) defexpr,
														 estate);
1643
				defmap[num_defaults] = attnum - 1;
1644
				num_defaults++;
1645
			}
1646
		}
1647 1648
	}

1649
	/* Prepare to catch AFTER triggers. */
1650 1651
	AfterTriggerBeginQuery();

1652
	/*
B
Bruce Momjian 已提交
1653 1654 1655 1656
	 * Check BEFORE STATEMENT insertion triggers. It's debateable whether we
	 * should do this for COPY, since it's not really an "INSERT" statement as
	 * such. However, executing these triggers maintains consistency with the
	 * EACH ROW triggers that we already fire on COPY.
1657 1658 1659
	 */
	ExecBSInsertTriggers(estate, resultRelInfo);

1660 1661
	if (!cstate->binary)
		file_has_oids = cstate->oids;	/* must rely on user to tell us... */
1662 1663
	else
	{
1664
		/* Read and verify binary header */
1665
		char		readSig[11];
1666 1667 1668
		int32		tmp;

		/* Signature */
1669 1670
		if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
			memcmp(readSig, BinarySignature, 11) != 0)
1671 1672 1673
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("COPY file signature not recognized")));
1674
		/* Flags field */
1675
		if (!CopyGetInt32(cstate, &tmp))
1676 1677 1678
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("invalid COPY file header (missing flags)")));
1679
		file_has_oids = (tmp & (1 << 16)) != 0;
B
Bruce Momjian 已提交
1680
		tmp &= ~(1 << 16);
1681
		if ((tmp >> 16) != 0)
1682 1683
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
1684
				 errmsg("unrecognized critical flags in COPY file header")));
1685
		/* Header extension length */
1686 1687
		if (!CopyGetInt32(cstate, &tmp) ||
			tmp < 0)
1688 1689
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
1690
					 errmsg("invalid COPY file header (missing length)")));
1691 1692 1693
		/* Skip extension header, if present */
		while (tmp-- > 0)
		{
1694
			if (CopyGetData(cstate, readSig, 1, 1) != 1)
1695 1696
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
1697
						 errmsg("invalid COPY file header (wrong length)")));
1698
		}
1699 1700
	}

1701
	if (file_has_oids && cstate->binary)
1702 1703
	{
		getTypeBinaryInputInfo(OIDOID,
1704
							   &in_func_oid, &oid_typioparam);
1705 1706 1707
		fmgr_info(in_func_oid, &oid_in_function);
	}

1708 1709
	values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
	nulls = (char *) palloc(num_phys_attrs * sizeof(char));
1710

1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721
	/* create workspace for CopyReadAttributes results */
	nfields = file_has_oids ? (attr_count + 1) : attr_count;
	field_strings = (char **) palloc(nfields * sizeof(char *));

	/* Initialize state variables */
	cstate->fe_eof = false;
	cstate->eol_type = EOL_UNKNOWN;
	cstate->cur_relname = RelationGetRelationName(cstate->rel);
	cstate->cur_lineno = 0;
	cstate->cur_attname = NULL;
	cstate->cur_attval = NULL;
1722 1723 1724

	/* Set up callback to identify error line number */
	errcontext.callback = copy_in_error_callback;
1725
	errcontext.arg = (void *) cstate;
1726 1727 1728
	errcontext.previous = error_context_stack;
	error_context_stack = &errcontext;

1729
	/* on input just throw the header line away */
1730
	if (cstate->header_line)
1731
	{
1732 1733
		cstate->cur_lineno++;
		done = CopyReadLine(cstate);
1734 1735
	}

1736 1737
	while (!done)
	{
B
Bruce Momjian 已提交
1738 1739
		bool		skip_tuple;
		Oid			loaded_oid = InvalidOid;
B
Bruce Momjian 已提交
1740

1741
		CHECK_FOR_INTERRUPTS();
1742

1743
		cstate->cur_lineno++;
B
Bruce Momjian 已提交
1744

1745
		/* Reset the per-tuple exprcontext */
1746 1747
		ResetPerTupleExprContext(estate);

1748
		/* Switch into its memory context */
1749 1750
		MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));

1751
		/* Initialize all values for row to NULL */
1752 1753
		MemSet(values, 0, num_phys_attrs * sizeof(Datum));
		MemSet(nulls, 'n', num_phys_attrs * sizeof(char));
1754

1755
		if (!cstate->binary)
1756
		{
1757
			ListCell   *cur;
1758 1759 1760
			int			fldct;
			int			fieldno;
			char	   *string;
1761

1762
			/* Actually read the line into memory here */
1763
			done = CopyReadLine(cstate);
1764 1765

			/*
B
Bruce Momjian 已提交
1766
			 * EOF at start of line means we're done.  If we see EOF after
B
Bruce Momjian 已提交
1767 1768
			 * some characters, we act as though it was newline followed by
			 * EOF, ie, process the line and then exit loop on next iteration.
1769
			 */
1770
			if (done && cstate->line_buf.len == 0)
1771 1772
				break;

1773 1774 1775 1776 1777 1778 1779 1780
			/* Parse the line into de-escaped field values */
			if (cstate->csv_mode)
				fldct = CopyReadAttributesCSV(cstate, nfields, field_strings);
			else
				fldct = CopyReadAttributesText(cstate, nfields, field_strings);
			fieldno = 0;

			/* Read the OID field if present */
1781
			if (file_has_oids)
1782
			{
1783 1784 1785 1786 1787
				if (fieldno >= fldct)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for OID column")));
				string = field_strings[fieldno++];
B
Bruce Momjian 已提交
1788

1789
				if (string == NULL)
1790 1791 1792
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("null OID in COPY data")));
1793 1794
				else
				{
1795 1796
					cstate->cur_attname = "oid";
					cstate->cur_attval = string;
1797
					loaded_oid = DatumGetObjectId(DirectFunctionCall1(oidin,
B
Bruce Momjian 已提交
1798
												   CStringGetDatum(string)));
1799
					if (loaded_oid == InvalidOid)
1800 1801 1802
						ereport(ERROR,
								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
								 errmsg("invalid OID in COPY data")));
1803 1804
					cstate->cur_attname = NULL;
					cstate->cur_attval = NULL;
1805 1806
				}
			}
B
Bruce Momjian 已提交
1807

1808
			/* Loop to read the user attributes on the line. */
1809
			foreach(cur, cstate->attnumlist)
1810
			{
1811
				int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1812
				int			m = attnum - 1;
1813

1814
				if (fieldno >= fldct)
1815 1816 1817 1818
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for column \"%s\"",
									NameStr(attr[m]->attname))));
1819
				string = field_strings[fieldno++];
1820

1821
				if (cstate->csv_mode && string == NULL && force_notnull[m])
B
Bruce Momjian 已提交
1822
				{
1823 1824
					/* Go ahead and read the NULL string */
					string = cstate->null_print;
B
Bruce Momjian 已提交
1825 1826
				}

1827 1828 1829 1830 1831 1832
				cstate->cur_attname = NameStr(attr[m]->attname);
				cstate->cur_attval = string;
				values[m] = InputFunctionCall(&in_functions[m],
											  string,
											  typioparams[m],
											  attr[m]->atttypmod);
1833
				if (string != NULL)
1834
					nulls[m] = ' ';
1835 1836
				cstate->cur_attname = NULL;
				cstate->cur_attval = NULL;
1837
			}
B
Bruce Momjian 已提交
1838

1839
			Assert(fieldno == nfields);
1840 1841
		}
		else
1842 1843
		{
			/* binary */
1844
			int16		fld_count;
1845
			ListCell   *cur;
1846

1847 1848
			if (!CopyGetInt16(cstate, &fld_count) ||
				fld_count == -1)
1849
			{
1850 1851 1852 1853 1854
				done = true;
				break;
			}

			if (fld_count != attr_count)
1855 1856 1857 1858
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("row field count is %d, expected %d",
								(int) fld_count, attr_count)));
1859 1860 1861

			if (file_has_oids)
			{
1862
				cstate->cur_attname = "oid";
1863
				loaded_oid =
1864 1865
					DatumGetObjectId(CopyReadBinaryAttribute(cstate,
															 0,
1866 1867 1868
															 &oid_in_function,
															 oid_typioparam,
															 -1,
1869 1870
															 &isnull));
				if (isnull || loaded_oid == InvalidOid)
1871 1872 1873
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("invalid OID in COPY data")));
1874
				cstate->cur_attname = NULL;
1875
			}
1876

1877
			i = 0;
1878
			foreach(cur, cstate->attnumlist)
1879
			{
1880
				int			attnum = lfirst_int(cur);
1881
				int			m = attnum - 1;
1882

1883
				cstate->cur_attname = NameStr(attr[m]->attname);
1884
				i++;
1885 1886
				values[m] = CopyReadBinaryAttribute(cstate,
													i,
1887
													&in_functions[m],
1888
													typioparams[m],
1889
													attr[m]->atttypmod,
1890 1891
													&isnull);
				nulls[m] = isnull ? 'n' : ' ';
1892
				cstate->cur_attname = NULL;
1893 1894 1895
			}
		}

1896
		/*
B
Bruce Momjian 已提交
1897 1898 1899
		 * Now compute and insert any defaults available for the columns not
		 * provided by the input data.	Anything not processed here or above
		 * will remain NULL.
1900 1901 1902 1903 1904 1905 1906 1907 1908
		 */
		for (i = 0; i < num_defaults; i++)
		{
			values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
											 &isnull, NULL);
			if (!isnull)
				nulls[defmap[i]] = ' ';
		}

1909
		/* And now we can form the input tuple. */
1910
		tuple = heap_formtuple(tupDesc, values, nulls);
B
Bruce Momjian 已提交
1911

1912
		if (cstate->oids && file_has_oids)
1913
			HeapTupleSetOid(tuple, loaded_oid);
1914

1915
		/* Triggers and stuff need to be invoked in query context. */
1916 1917
		MemoryContextSwitchTo(oldcontext);

1918
		skip_tuple = false;
1919

1920
		/* BEFORE ROW INSERT Triggers */
1921
		if (resultRelInfo->ri_TrigDesc &&
B
Bruce Momjian 已提交
1922
		  resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
1923
		{
1924
			HeapTuple	newtuple;
1925

1926
			newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);
1927 1928 1929 1930 1931

			if (newtuple == NULL)		/* "do nothing" */
				skip_tuple = true;
			else if (newtuple != tuple) /* modified by Trigger(s) */
			{
1932
				heap_freetuple(tuple);
1933 1934 1935 1936 1937 1938
				tuple = newtuple;
			}
		}

		if (!skip_tuple)
		{
1939
			/* Place tuple in tuple slot */
1940 1941
			ExecStoreTuple(tuple, slot, InvalidBuffer, false);

1942
			/* Check the constraints of the tuple */
1943
			if (cstate->rel->rd_att->constr)
1944
				ExecConstraints(resultRelInfo, slot, estate);
1945

1946
			/* OK, store the tuple and create index entries for it */
1947
			simple_heap_insert(cstate->rel, tuple);
1948

1949
			if (resultRelInfo->ri_NumIndices > 0)
1950 1951
				ExecInsertIndexTuples(slot, &(tuple->t_self), estate, false);

1952
			/* AFTER ROW INSERT Triggers */
1953
			ExecARInsertTriggers(estate, resultRelInfo, tuple);
1954 1955 1956 1957 1958 1959 1960

			/*
			 * We count only tuples not suppressed by a BEFORE INSERT trigger;
			 * this is the same definition used by execMain.c for counting
			 * tuples inserted by an INSERT command.
			 */
			cstate->processed++;
1961 1962
		}
	}
1963

1964
	/* Done, clean up */
1965
	error_context_stack = errcontext.previous;
1966

1967 1968
	MemoryContextSwitchTo(oldcontext);

1969
	/* Execute AFTER STATEMENT insertion triggers */
1970 1971
	ExecASInsertTriggers(estate, resultRelInfo);

1972
	/* Handle queued AFTER triggers */
1973
	AfterTriggerEndQuery(estate);
1974

1975
	pfree(values);
B
Bruce Momjian 已提交
1976
	pfree(nulls);
1977
	pfree(field_strings);
B
Bruce Momjian 已提交
1978

B
Bruce Momjian 已提交
1979
	pfree(in_functions);
1980
	pfree(typioparams);
B
Bruce Momjian 已提交
1981 1982
	pfree(defmap);
	pfree(defexprs);
B
Bruce Momjian 已提交
1983
	pfree(force_notnull);
V
Vadim B. Mikheev 已提交
1984

1985
	ExecDropSingleTupleTableSlot(slot);
1986

1987
	ExecCloseIndices(resultRelInfo);
1988 1989

	FreeExecutorState(estate);
1990
}
1991 1992


1993
/*
1994 1995
 * Read the next input line and stash it in line_buf, with conversion to
 * server encoding.
B
Bruce Momjian 已提交
1996
 *
1997
 * Result is true if read was terminated by EOF, false if terminated
B
Bruce Momjian 已提交
1998
 * by newline.	The terminating newline or EOF marker is not included
1999
 * in the final value of line_buf.
2000
 */
2001
static bool
2002
CopyReadLine(CopyState cstate)
2003
{
2004
	bool		result;
2005

2006 2007 2008 2009 2010 2011 2012 2013
	/* Reset line_buf to empty */
	cstate->line_buf.len = 0;
	cstate->line_buf.data[0] = '\0';

	/* Mark that encoding conversion hasn't occurred yet */
	cstate->line_buf_converted = false;

	/* Parse data and transfer into line_buf */
B
Bruce Momjian 已提交
2014
	result = CopyReadLineText(cstate);
2015 2016 2017 2018 2019

	if (result)
	{
		/*
		 * Reached EOF.  In protocol version 3, we should ignore anything
B
Bruce Momjian 已提交
2020 2021
		 * after \. up to the protocol end of copy data.  (XXX maybe better
		 * not to treat \. as special?)
2022 2023 2024
		 */
		if (cstate->copy_dest == COPY_NEW_FE)
		{
B
Bruce Momjian 已提交
2025 2026
			do
			{
2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066
				cstate->raw_buf_index = cstate->raw_buf_len;
			} while (CopyLoadRawBuf(cstate));
		}
	}
	else
	{
		/*
		 * If we didn't hit EOF, then we must have transferred the EOL marker
		 * to line_buf along with the data.  Get rid of it.
		 */
		switch (cstate->eol_type)
		{
			case EOL_NL:
				Assert(cstate->line_buf.len >= 1);
				Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
				cstate->line_buf.len--;
				cstate->line_buf.data[cstate->line_buf.len] = '\0';
				break;
			case EOL_CR:
				Assert(cstate->line_buf.len >= 1);
				Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\r');
				cstate->line_buf.len--;
				cstate->line_buf.data[cstate->line_buf.len] = '\0';
				break;
			case EOL_CRNL:
				Assert(cstate->line_buf.len >= 2);
				Assert(cstate->line_buf.data[cstate->line_buf.len - 2] == '\r');
				Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
				cstate->line_buf.len -= 2;
				cstate->line_buf.data[cstate->line_buf.len] = '\0';
				break;
			case EOL_UNKNOWN:
				/* shouldn't get here */
				Assert(false);
				break;
		}
	}

	/* Done reading the line.  Convert it to server encoding. */
	if (cstate->need_transcoding)
2067
	{
2068 2069
		char	   *cvt;

2070 2071
		cvt = pg_client_to_server(cstate->line_buf.data,
								  cstate->line_buf.len);
2072 2073 2074 2075 2076 2077 2078 2079
		if (cvt != cstate->line_buf.data)
		{
			/* transfer converted data back to line_buf */
			cstate->line_buf.len = 0;
			cstate->line_buf.data[0] = '\0';
			appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
			pfree(cvt);
		}
2080 2081
	}

2082 2083
	/* Now it's safe to use the buffer in error messages */
	cstate->line_buf_converted = true;
2084

2085 2086
	return result;
}
2087

2088
/*
B
Bruce Momjian 已提交
2089
 * CopyReadLineText - inner loop of CopyReadLine for text mode
2090 2091 2092 2093 2094 2095 2096
 */
static bool
CopyReadLineText(CopyState cstate)
{
	char	   *copy_raw_buf;
	int			raw_buf_ptr;
	int			copy_buf_len;
B
Bruce Momjian 已提交
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106
	bool		need_data = false;
	bool		hit_eof = false;
	bool		result = false;
	char		mblen_str[2];
	/* CSV variables */
	bool		first_char_in_line = true;
	bool		in_quote = false,
				last_was_esc = false;
	char		quotec = '\0';
	char		escapec = '\0';
2107

B
Bruce Momjian 已提交
2108 2109 2110 2111 2112 2113 2114 2115
	if (cstate->csv_mode)
	{
		quotec = cstate->quote[0];
		escapec = cstate->escape[0];
		/* ignore special escape processing if it's the same as quotec */
		if (quotec == escapec)
			escapec = '\0';
	}
2116

B
Bruce Momjian 已提交
2117
	mblen_str[1] = '\0';
2118

2119
	/*
B
Bruce Momjian 已提交
2120 2121 2122
	 * The objective of this loop is to transfer the entire next input line
	 * into line_buf.  Hence, we only care for detecting newlines (\r and/or
	 * \n) and the end-of-copy marker (\.).
2123
	 *
B
Bruce Momjian 已提交
2124 2125 2126
	 * In CSV mode, \r and \n inside a quoted field are just part of the data
	 * value and are put in line_buf.  We keep just enough state to know if we
	 * are currently in a quoted field or not.
2127
	 *
B
Bruce Momjian 已提交
2128 2129
	 * These four characters, and the CSV escape and quote characters, are
	 * assumed the same in frontend and backend encodings.
2130
	 *
B
Bruce Momjian 已提交
2131 2132 2133 2134 2135
	 * For speed, we try to move data from raw_buf to line_buf in chunks
     * rather than one character at a time.  raw_buf_ptr points to the next
	 * character to examine; any characters from raw_buf_index to raw_buf_ptr
	 * have been determined to be part of the line, but not yet transferred
	 * to line_buf.
2136
	 *
2137 2138
	 * For a little extra speed within the loop, we copy raw_buf and
	 * raw_buf_len into local variables.
2139
	 */
2140 2141 2142 2143
	copy_raw_buf = cstate->raw_buf;
	raw_buf_ptr = cstate->raw_buf_index;
	copy_buf_len = cstate->raw_buf_len;

2144
	for (;;)
2145
	{
B
Bruce Momjian 已提交
2146 2147
		int			prev_raw_ptr;
		char		c;
2148

B
Bruce Momjian 已提交
2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
		/*
		 *	Load more data if needed.  Ideally we would just force four bytes
		 *	of read-ahead and avoid the many calls to
		 *	IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(), but the COPY_OLD_FE
		 *	protocol does not allow us to read too far ahead or we might
		 *	read into the next data, so we read-ahead only as far we know
		 *	we can.  One optimization would be to read-ahead four byte here
		 *	if cstate->copy_dest != COPY_OLD_FE, but it hardly seems worth it,
		 *	considering the size of the buffer.
		 */
2159
		if (raw_buf_ptr >= copy_buf_len || need_data)
2160
		{
B
Bruce Momjian 已提交
2161
			REFILL_LINEBUF;
B
Bruce Momjian 已提交
2162

2163
			/*
B
Bruce Momjian 已提交
2164
			 * Try to read some more data.	This will certainly reset
2165 2166 2167 2168 2169 2170
			 * raw_buf_index to zero, and raw_buf_ptr must go with it.
			 */
			if (!CopyLoadRawBuf(cstate))
				hit_eof = true;
			raw_buf_ptr = 0;
			copy_buf_len = cstate->raw_buf_len;
B
Bruce Momjian 已提交
2171

2172 2173 2174 2175 2176 2177 2178 2179 2180 2181
			/*
			 * If we are completely out of data, break out of the loop,
			 * reporting EOF.
			 */
			if (copy_buf_len <= 0)
			{
				result = true;
				break;
			}
			need_data = false;
2182 2183
		}

2184 2185 2186 2187
		/* OK to fetch a character */
		prev_raw_ptr = raw_buf_ptr;
		c = copy_raw_buf[raw_buf_ptr++];

B
Bruce Momjian 已提交
2188
		if (cstate->csv_mode)
2189
		{
2190
			/*
B
Bruce Momjian 已提交
2191 2192 2193 2194 2195 2196 2197
			 * If character is '\\' or '\r', we may need to look ahead below.
			 * Force fetch of the next character if we don't already have it. We
			 * need to do this before changing CSV state, in case one of these
			 * characters is also the quote or escape character.
			 *
			 * Note: old-protocol does not like forced prefetch, but it's OK here
			 * since we cannot validly be at EOF.
2198
			 */
B
Bruce Momjian 已提交
2199
			if (c == '\\' || c == '\r')
B
Bruce Momjian 已提交
2200
			{
B
Bruce Momjian 已提交
2201
				IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2202
			}
2203

2204
			/*
B
Bruce Momjian 已提交
2205 2206 2207 2208 2209 2210
			 * Dealing with quotes and escapes here is mildly tricky. If the quote
			 * char is also the escape char, there's no problem - we  just use the
			 * char as a toggle. If they are different, we need to ensure that we
			 * only take account of an escape inside a quoted field and
			 * immediately preceding a quote char, and not the second in a
			 * escape-escape sequence.
2211
			 */
B
Bruce Momjian 已提交
2212 2213 2214 2215 2216
			if (in_quote && c == escapec)
				last_was_esc = !last_was_esc;
			if (c == quotec && !last_was_esc)
				in_quote = !in_quote;
			if (c != escapec)
B
Bruce Momjian 已提交
2217 2218
				last_was_esc = false;

2219
			/*
B
Bruce Momjian 已提交
2220 2221 2222 2223
			 * Updating the line count for embedded CR and/or LF chars is
			 * necessarily a little fragile - this test is probably about the best
			 * we can do.  (XXX it's arguable whether we should do this at all ---
			 * is cur_lineno a physical or logical count?)
2224
			 */
B
Bruce Momjian 已提交
2225 2226
			if (in_quote && c == (cstate->eol_type == EOL_NL ? '\n' : '\r'))
				cstate->cur_lineno++;
2227 2228
		}

B
Bruce Momjian 已提交
2229 2230
		/* Process \r */
		if (c == '\r' && (!cstate->csv_mode || !in_quote))
2231 2232 2233 2234 2235 2236 2237 2238
		{
			/* Check for \r\n on first line, _and_ handle \r\n. */
			if (cstate->eol_type == EOL_UNKNOWN ||
				cstate->eol_type == EOL_CRNL)
			{
				/*
				 * If need more data, go back to loop top to load it.
				 *
2239 2240
				 * Note that if we are at EOF, c will wind up as '\0' because
				 * of the guaranteed pad of raw_buf.
2241
				 */
B
Bruce Momjian 已提交
2242 2243 2244
				IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);

				/* get next char */
2245 2246 2247 2248
				c = copy_raw_buf[raw_buf_ptr];

				if (c == '\n')
				{
B
Bruce Momjian 已提交
2249 2250
					raw_buf_ptr++;		/* eat newline */
					cstate->eol_type = EOL_CRNL;		/* in case not set yet */
2251 2252 2253 2254 2255 2256 2257
				}
				else
				{
					/* found \r, but no \n */
					if (cstate->eol_type == EOL_CRNL)
						ereport(ERROR,
								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
2258 2259 2260 2261 2262 2263
							 errmsg(!cstate->csv_mode ?
									"literal carriage return found in data" :
									"unquoted carriage return found in data"),
								 errhint(!cstate->csv_mode ?
										"Use \"\\r\" to represent carriage return." :
										"Use quoted CSV field to represent carriage return.")));
2264
					/*
B
Bruce Momjian 已提交
2265 2266
					 * if we got here, it is the first line and we didn't find
					 * \n, so don't consume the peeked character
2267 2268 2269 2270 2271 2272 2273
					 */
					cstate->eol_type = EOL_CR;
				}
			}
			else if (cstate->eol_type == EOL_NL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
2274 2275 2276 2277 2278 2279
					 errmsg(!cstate->csv_mode ?
								"literal carriage return found in data" :
								"unquoted carriage return found in data"),
						 errhint(!cstate->csv_mode ?
								"Use \"\\r\" to represent carriage return." :
								"Use quoted CSV field to represent carriage return.")));
2280 2281 2282 2283
			/* If reach here, we have found the line terminator */
			break;
		}

B
Bruce Momjian 已提交
2284 2285
		/* Process \n */
		if (c == '\n' && (!cstate->csv_mode || !in_quote))
2286 2287 2288 2289
		{
			if (cstate->eol_type == EOL_CR || cstate->eol_type == EOL_CRNL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
B
Bruce Momjian 已提交
2290 2291 2292 2293 2294 2295
						 errmsg(!cstate->csv_mode ?
								"literal newline found in data" :
								"unquoted newline found in data"),
						 errhint(!cstate->csv_mode ?
								 "Use \"\\n\" to represent newline." :
								 "Use quoted CSV field to represent newline.")));
B
Bruce Momjian 已提交
2296
			cstate->eol_type = EOL_NL;	/* in case not set yet */
2297 2298 2299 2300 2301
			/* If reach here, we have found the line terminator */
			break;
		}

		/*
B
Bruce Momjian 已提交
2302 2303
		 *	In CSV mode, we only recognize \. alone on a line.  This is
		 *	because \. is a valid CSV data value.
2304
		 */
B
Bruce Momjian 已提交
2305
		if (c == '\\' && (!cstate->csv_mode || first_char_in_line))
2306
		{
B
Bruce Momjian 已提交
2307
			char		c2;
2308

B
Bruce Momjian 已提交
2309 2310
			IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
			IF_NEED_REFILL_AND_EOF_BREAK(0);
2311

B
Bruce Momjian 已提交
2312 2313 2314 2315 2316
			/* -----
			 * get next character
			 * Note: we do not change c so if it isn't \., we can fall
			 * through and continue processing for client encoding.
			 * -----
2317 2318 2319 2320 2321
			 */
			c2 = copy_raw_buf[raw_buf_ptr];

			if (c2 == '.')
			{
B
Bruce Momjian 已提交
2322
				raw_buf_ptr++;	/* consume the '.' */
2323 2324 2325

				/*
				 * Note: if we loop back for more data here, it does not
B
Bruce Momjian 已提交
2326 2327
				 * matter that the CSV state change checks are re-executed; we
				 * will come back here with no important state changed.
2328 2329 2330
				 */
				if (cstate->eol_type == EOL_CRNL)
				{
B
Bruce Momjian 已提交
2331 2332
					/* Get the next character */
					IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2333 2334
					/* if hit_eof, c2 will become '\0' */
					c2 = copy_raw_buf[raw_buf_ptr++];
B
Bruce Momjian 已提交
2335

2336
					if (c2 == '\n')
B
Bruce Momjian 已提交
2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
					{
						if (!cstate->csv_mode)
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("end-of-copy marker does not match previous newline style")));
						else
							NO_END_OF_COPY_GOTO;
					}
					else if (c2 != '\r')
					{
						if (!cstate->csv_mode)
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("end-of-copy marker corrupt")));
						else
							NO_END_OF_COPY_GOTO;
					}
2354
				}
B
Bruce Momjian 已提交
2355 2356 2357

				/* Get the next character */
				IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(0);
2358 2359
				/* if hit_eof, c2 will become '\0' */
				c2 = copy_raw_buf[raw_buf_ptr++];
B
Bruce Momjian 已提交
2360

2361
				if (c2 != '\r' && c2 != '\n')
B
Bruce Momjian 已提交
2362 2363 2364 2365 2366 2367 2368 2369 2370
				{
					if (!cstate->csv_mode)
						ereport(ERROR,
								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
								 errmsg("end-of-copy marker corrupt")));
					else
						NO_END_OF_COPY_GOTO;
				}

2371 2372 2373
				if ((cstate->eol_type == EOL_NL && c2 != '\n') ||
					(cstate->eol_type == EOL_CRNL && c2 != '\n') ||
					(cstate->eol_type == EOL_CR && c2 != '\r'))
B
Bruce Momjian 已提交
2374
				{
2375 2376 2377
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("end-of-copy marker does not match previous newline style")));
B
Bruce Momjian 已提交
2378
				}
2379 2380

				/*
B
Bruce Momjian 已提交
2381 2382
				 * Transfer only the data before the \. into line_buf, then
				 * discard the data and the \. sequence.
2383 2384
				 */
				if (prev_raw_ptr > cstate->raw_buf_index)
B
Bruce Momjian 已提交
2385 2386
					appendBinaryStringInfo(&cstate->line_buf,
									 cstate->raw_buf + cstate->raw_buf_index,
B
Bruce Momjian 已提交
2387
									   prev_raw_ptr - cstate->raw_buf_index);
2388 2389 2390 2391
				cstate->raw_buf_index = raw_buf_ptr;
				result = true;	/* report EOF */
				break;
			}
B
Bruce Momjian 已提交
2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404
			else if (!cstate->csv_mode)
				/*
				 *	If we are here, it means we found a backslash followed by
				 *	something other than a period.  In non-CSV mode, anything
				 *	after a backslash is special, so we skip over that second
				 *	character too.  If we didn't do that \\. would be
				 *	considered an eof-of copy, while in non-CVS mode it is a
				 *	literal backslash followed by a period.  In CSV mode,
				 *	backslashes are not special, so we want to process the
				 *	character after the backslash just like a normal character,
				 *	so we don't increment in those cases.
				 */
				raw_buf_ptr++;
2405 2406 2407
		}

		/*
B
Bruce Momjian 已提交
2408 2409 2410 2411 2412 2413 2414 2415 2416
		 * This label is for CSV cases where \. appears at the start of a line,
		 * but there is more text after it, meaning it was a data value.
		 * We are more strict for \. in CSV mode because \. could be a data
		 * value, while in non-CSV mode, \. cannot be a data value.
		 */
not_end_of_copy:

		/*
		 * Process all bytes of a multi-byte character as a group.
2417
		 *
B
Bruce Momjian 已提交
2418 2419 2420
		 * We only support multi-byte sequences where the first byte
		 * has the high-bit set, so as an optimization we can avoid
		 * this block entirely if it is not set.
2421
		 */
B
Bruce Momjian 已提交
2422
		if (cstate->encoding_embeds_ascii && IS_HIGHBIT_SET(c))
2423 2424 2425
		{
			int			mblen;

B
Bruce Momjian 已提交
2426 2427 2428 2429 2430
			mblen_str[0] = c;
			/* All our encodings only read the first byte to get the length */
			mblen = pg_encoding_mblen(cstate->client_encoding, mblen_str);
			IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(mblen - 1);
			IF_NEED_REFILL_AND_EOF_BREAK(mblen - 1);
B
Bruce Momjian 已提交
2431
			raw_buf_ptr += mblen - 1;
2432
		}
B
Bruce Momjian 已提交
2433
		first_char_in_line = false;
2434 2435 2436 2437 2438
	}							/* end of outer loop */

	/*
	 * Transfer any still-uncopied data to line_buf.
	 */
B
Bruce Momjian 已提交
2439
	REFILL_LINEBUF;
2440

2441 2442 2443
	return result;
}

2444 2445 2446
/*
 *	Return decimal value for a hexadecimal digit
 */
2447 2448
static int
GetDecimalFromHex(char hex)
2449
{
2450
	if (isdigit((unsigned char) hex))
2451 2452
		return hex - '0';
	else
2453
		return tolower((unsigned char) hex) - 'a' + 10;
2454 2455
}

2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
/*
 * Parse the current line into separate attributes (fields),
 * performing de-escaping as needed.
 *
 * The input is in line_buf.  We use attribute_buf to hold the result
 * strings.  fieldvals[k] is set to point to the k'th attribute string,
 * or NULL when the input matches the null marker string.  (Note that the
 * caller cannot check for nulls since the returned string would be the
 * post-de-escaping equivalent, which may look the same as some valid data
 * string.)
2466
 *
2467 2468 2469 2470
 * delim is the column delimiter string (must be just one byte for now).
 * null_print is the null marker string.  Note that this is compared to
 * the pre-de-escaped input string.
 *
B
Bruce Momjian 已提交
2471
 * The return value is the number of fields actually read.	(We error out
2472
 * if this would exceed maxfields, which is the length of fieldvals[].)
2473
 */
2474 2475
static int
CopyReadAttributesText(CopyState cstate, int maxfields, char **fieldvals)
2476
{
2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
	char		delimc = cstate->delim[0];
	int			fieldno;
	char	   *output_ptr;
	char	   *cur_ptr;
	char	   *line_end_ptr;

	/*
	 * We need a special case for zero-column tables: check that the input
	 * line is empty, and return.
	 */
	if (maxfields <= 0)
	{
		if (cstate->line_buf.len != 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));
		return 0;
	}
2495 2496

	/* reset attribute_buf to empty */
2497 2498
	cstate->attribute_buf.len = 0;
	cstate->attribute_buf.data[0] = '\0';
2499

2500 2501 2502
	/*
	 * The de-escaped attributes will certainly not be longer than the input
	 * data line, so we can just force attribute_buf to be large enough and
B
Bruce Momjian 已提交
2503 2504 2505
	 * then transfer data without any checks for enough space.	We need to do
	 * it this way because enlarging attribute_buf mid-stream would invalidate
	 * pointers already stored into fieldvals[].
2506 2507 2508 2509 2510 2511 2512 2513
	 */
	if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
		enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
	output_ptr = cstate->attribute_buf.data;

	/* set pointer variables for loop */
	cur_ptr = cstate->line_buf.data;
	line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
2514

2515 2516
	/* Outer loop iterates over fields */
	fieldno = 0;
2517 2518
	for (;;)
	{
2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
		bool		found_delim = false;
		char	   *start_ptr;
		char	   *end_ptr;
		int			input_len;

		/* Make sure space remains in fieldvals[] */
		if (fieldno >= maxfields)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));

		/* Remember start of field on both input and output sides */
		start_ptr = cur_ptr;
		fieldvals[fieldno] = output_ptr;

		/* Scan data for field */
		for (;;)
2536
		{
B
Bruce Momjian 已提交
2537
			char		c;
2538 2539 2540

			end_ptr = cur_ptr;
			if (cur_ptr >= line_end_ptr)
2541
				break;
2542 2543 2544 2545 2546 2547 2548
			c = *cur_ptr++;
			if (c == delimc)
			{
				found_delim = true;
				break;
			}
			if (c == '\\')
2549
			{
2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562
				if (cur_ptr >= line_end_ptr)
					break;
				c = *cur_ptr++;
				switch (c)
				{
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
2563
						{
B
Bruce Momjian 已提交
2564 2565 2566 2567 2568
							/* handle \013 */
							int			val;

							val = OCTVALUE(c);
							if (cur_ptr < line_end_ptr)
B
Bruce Momjian 已提交
2569
							{
B
Bruce Momjian 已提交
2570 2571
								c = *cur_ptr;
								if (ISOCTAL(c))
B
Bruce Momjian 已提交
2572
								{
B
Bruce Momjian 已提交
2573 2574 2575
									cur_ptr++;
									val = (val << 3) + OCTVALUE(c);
									if (cur_ptr < line_end_ptr)
2576
									{
B
Bruce Momjian 已提交
2577 2578 2579 2580 2581 2582
										c = *cur_ptr;
										if (ISOCTAL(c))
										{
											cur_ptr++;
											val = (val << 3) + OCTVALUE(c);
										}
2583
									}
B
Bruce Momjian 已提交
2584
								}
2585
							}
B
Bruce Momjian 已提交
2586
							c = val & 0377;
2587
						}
B
Bruce Momjian 已提交
2588
						break;
2589 2590 2591
					case 'x':
						/* Handle \x3F */
						if (cur_ptr < line_end_ptr)
2592
						{
B
Bruce Momjian 已提交
2593
							char		hexchar = *cur_ptr;
2594

2595
							if (isxdigit((unsigned char) hexchar))
2596
							{
B
Bruce Momjian 已提交
2597
								int			val = GetDecimalFromHex(hexchar);
2598 2599 2600

								cur_ptr++;
								if (cur_ptr < line_end_ptr)
2601
								{
2602
									hexchar = *cur_ptr;
2603
									if (isxdigit((unsigned char) hexchar))
2604 2605 2606 2607
									{
										cur_ptr++;
										val = (val << 4) + GetDecimalFromHex(hexchar);
									}
2608
								}
2609
								c = val & 0xff;
2610 2611
							}
						}
2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636
						break;
					case 'b':
						c = '\b';
						break;
					case 'f':
						c = '\f';
						break;
					case 'n':
						c = '\n';
						break;
					case 'r':
						c = '\r';
						break;
					case 't':
						c = '\t';
						break;
					case 'v':
						c = '\v';
						break;

						/*
						 * in all other cases, take the char after '\'
						 * literally
						 */
				}
2637
			}
2638 2639 2640

			/* Add c to output string */
			*output_ptr++ = c;
2641
		}
2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655

		/* Terminate attribute value in output area */
		*output_ptr++ = '\0';

		/* Check whether raw input matched null marker */
		input_len = end_ptr - start_ptr;
		if (input_len == cstate->null_print_len &&
			strncmp(start_ptr, cstate->null_print, input_len) == 0)
			fieldvals[fieldno] = NULL;

		fieldno++;
		/* Done if we hit EOL instead of a delim */
		if (!found_delim)
			break;
2656
	}
2657

2658 2659 2660 2661
	/* Clean up state of attribute_buf */
	output_ptr--;
	Assert(*output_ptr == '\0');
	cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
2662

2663
	return fieldno;
2664 2665
}

B
Bruce Momjian 已提交
2666
/*
2667 2668 2669 2670
 * Parse the current line into separate attributes (fields),
 * performing de-escaping as needed.  This has exactly the same API as
 * CopyReadAttributesText, except we parse the fields according to
 * "standard" (i.e. common) CSV usage.
B
Bruce Momjian 已提交
2671
 */
2672 2673
static int
CopyReadAttributesCSV(CopyState cstate, int maxfields, char **fieldvals)
B
Bruce Momjian 已提交
2674
{
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694
	char		delimc = cstate->delim[0];
	char		quotec = cstate->quote[0];
	char		escapec = cstate->escape[0];
	int			fieldno;
	char	   *output_ptr;
	char	   *cur_ptr;
	char	   *line_end_ptr;

	/*
	 * We need a special case for zero-column tables: check that the input
	 * line is empty, and return.
	 */
	if (maxfields <= 0)
	{
		if (cstate->line_buf.len != 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));
		return 0;
	}
B
Bruce Momjian 已提交
2695 2696

	/* reset attribute_buf to empty */
2697 2698
	cstate->attribute_buf.len = 0;
	cstate->attribute_buf.data[0] = '\0';
B
Bruce Momjian 已提交
2699

2700 2701 2702
	/*
	 * The de-escaped attributes will certainly not be longer than the input
	 * data line, so we can just force attribute_buf to be large enough and
B
Bruce Momjian 已提交
2703 2704 2705
	 * then transfer data without any checks for enough space.	We need to do
	 * it this way because enlarging attribute_buf mid-stream would invalidate
	 * pointers already stored into fieldvals[].
2706 2707 2708 2709 2710 2711 2712 2713
	 */
	if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
		enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
	output_ptr = cstate->attribute_buf.data;

	/* set pointer variables for loop */
	cur_ptr = cstate->line_buf.data;
	line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
B
Bruce Momjian 已提交
2714

2715 2716
	/* Outer loop iterates over fields */
	fieldno = 0;
B
Bruce Momjian 已提交
2717 2718
	for (;;)
	{
2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730
		bool		found_delim = false;
		bool		in_quote = false;
		bool		saw_quote = false;
		char	   *start_ptr;
		char	   *end_ptr;
		int			input_len;

		/* Make sure space remains in fieldvals[] */
		if (fieldno >= maxfields)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));
B
Bruce Momjian 已提交
2731

2732 2733 2734
		/* Remember start of field on both input and output sides */
		start_ptr = cur_ptr;
		fieldvals[fieldno] = output_ptr;
B
Bruce Momjian 已提交
2735

2736 2737
		/* Scan data for field */
		for (;;)
B
Bruce Momjian 已提交
2738
		{
B
Bruce Momjian 已提交
2739
			char		c;
B
Bruce Momjian 已提交
2740

2741 2742 2743 2744 2745 2746
			end_ptr = cur_ptr;
			if (cur_ptr >= line_end_ptr)
				break;
			c = *cur_ptr++;
			/* unquoted field delimiter */
			if (c == delimc && !in_quote)
B
Bruce Momjian 已提交
2747
			{
2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765
				found_delim = true;
				break;
			}
			/* start of quoted field (or part of field) */
			if (c == quotec && !in_quote)
			{
				saw_quote = true;
				in_quote = true;
				continue;
			}
			/* escape within a quoted field */
			if (c == escapec && in_quote)
			{
				/*
				 * peek at the next char if available, and escape it if it is
				 * an escape char or a quote char
				 */
				if (cur_ptr < line_end_ptr)
B
Bruce Momjian 已提交
2766
				{
B
Bruce Momjian 已提交
2767
					char		nextc = *cur_ptr;
2768 2769 2770 2771 2772 2773 2774

					if (nextc == escapec || nextc == quotec)
					{
						*output_ptr++ = nextc;
						cur_ptr++;
						continue;
					}
B
Bruce Momjian 已提交
2775 2776
				}
			}
B
Bruce Momjian 已提交
2777

2778 2779 2780 2781 2782 2783 2784 2785 2786 2787
			/*
			 * end of quoted field. Must do this test after testing for escape
			 * in case quote char and escape char are the same (which is the
			 * common case).
			 */
			if (c == quotec && in_quote)
			{
				in_quote = false;
				continue;
			}
B
Bruce Momjian 已提交
2788

2789 2790
			/* Add c to output string */
			*output_ptr++ = c;
B
Bruce Momjian 已提交
2791 2792
		}

2793 2794
		/* Terminate attribute value in output area */
		*output_ptr++ = '\0';
B
Bruce Momjian 已提交
2795

2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812
		/* Shouldn't still be in quote mode */
		if (in_quote)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("unterminated CSV quoted field")));

		/* Check whether raw input matched null marker */
		input_len = end_ptr - start_ptr;
		if (!saw_quote && input_len == cstate->null_print_len &&
			strncmp(start_ptr, cstate->null_print, input_len) == 0)
			fieldvals[fieldno] = NULL;

		fieldno++;
		/* Done if we hit EOL instead of a delim */
		if (!found_delim)
			break;
	}
B
Bruce Momjian 已提交
2813

2814 2815 2816 2817 2818 2819
	/* Clean up state of attribute_buf */
	output_ptr--;
	Assert(*output_ptr == '\0');
	cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);

	return fieldno;
B
Bruce Momjian 已提交
2820 2821
}

2822

2823 2824 2825 2826
/*
 * Read a binary attribute
 */
static Datum
2827 2828
CopyReadBinaryAttribute(CopyState cstate,
						int column_no, FmgrInfo *flinfo,
2829
						Oid typioparam, int32 typmod,
2830 2831 2832 2833 2834
						bool *isnull)
{
	int32		fld_size;
	Datum		result;

2835
	if (!CopyGetInt32(cstate, &fld_size))
2836 2837 2838
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("unexpected EOF in COPY data")));
2839 2840 2841
	if (fld_size == -1)
	{
		*isnull = true;
2842
		return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
2843 2844
	}
	if (fld_size < 0)
2845 2846
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
2847
				 errmsg("invalid field size")));
2848 2849

	/* reset attribute_buf to empty, and load raw data in it */
2850 2851 2852
	cstate->attribute_buf.len = 0;
	cstate->attribute_buf.data[0] = '\0';
	cstate->attribute_buf.cursor = 0;
2853

2854
	enlargeStringInfo(&cstate->attribute_buf, fld_size);
2855

2856 2857
	if (CopyGetData(cstate, cstate->attribute_buf.data,
					fld_size, fld_size) != fld_size)
2858 2859 2860
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("unexpected EOF in COPY data")));
2861

2862 2863
	cstate->attribute_buf.len = fld_size;
	cstate->attribute_buf.data[fld_size] = '\0';
2864 2865

	/* Call the column type's binary input converter */
2866 2867
	result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
								 typioparam, typmod);
2868 2869

	/* Trouble if it didn't eat the whole buffer */
2870
	if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
2871
		ereport(ERROR,
2872
				(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
2873
				 errmsg("incorrect binary data format")));
2874 2875 2876 2877 2878 2879 2880 2881

	*isnull = false;
	return result;
}

/*
 * Send text representation of one attribute, with conversion and escaping
 */
2882 2883 2884 2885 2886 2887
#define DUMPSOFAR() \
	do { \
		if (ptr > start) \
			CopySendData(cstate, start, ptr - start); \
	} while (0)

2888
static void
2889
CopyAttributeOutText(CopyState cstate, char *string)
2890
{
2891 2892
	char	   *ptr;
	char	   *start;
2893
	char		c;
2894
	char		delimc = cstate->delim[0];
2895

2896
	if (cstate->need_transcoding)
2897
		ptr = pg_server_to_client(string, strlen(string));
2898
	else
2899
		ptr = string;
2900

2901 2902 2903 2904 2905 2906 2907 2908 2909 2910
	/*
	 * We have to grovel through the string searching for control characters
	 * and instances of the delimiter character.  In most cases, though, these
	 * are infrequent.  To avoid overhead from calling CopySendData once per
	 * character, we dump out all characters between replaceable characters
	 * in a single call.  The loop invariant is that the data from "start"
	 * to "ptr" can be sent literally, but hasn't yet been.
	 */
	start = ptr;
	while ((c = *ptr) != '\0')
2911
	{
2912 2913 2914
		switch (c)
		{
			case '\b':
2915
				DUMPSOFAR();
2916
				CopySendString(cstate, "\\b");
2917
				start = ++ptr;
2918 2919
				break;
			case '\f':
2920
				DUMPSOFAR();
2921
				CopySendString(cstate, "\\f");
2922
				start = ++ptr;
2923 2924
				break;
			case '\n':
2925
				DUMPSOFAR();
2926
				CopySendString(cstate, "\\n");
2927
				start = ++ptr;
2928 2929
				break;
			case '\r':
2930
				DUMPSOFAR();
2931
				CopySendString(cstate, "\\r");
2932
				start = ++ptr;
2933 2934
				break;
			case '\t':
2935
				DUMPSOFAR();
2936
				CopySendString(cstate, "\\t");
2937
				start = ++ptr;
2938 2939
				break;
			case '\v':
2940
				DUMPSOFAR();
2941
				CopySendString(cstate, "\\v");
2942
				start = ++ptr;
2943 2944
				break;
			case '\\':
2945
				DUMPSOFAR();
2946
				CopySendString(cstate, "\\\\");
2947
				start = ++ptr;
2948 2949 2950
				break;
			default:
				if (c == delimc)
2951 2952
				{
					DUMPSOFAR();
2953
					CopySendChar(cstate, '\\');
2954 2955
					start = ptr; /* we include char in next run */
				}
2956

2957
				/*
B
Bruce Momjian 已提交
2958 2959 2960
				 * We can skip pg_encoding_mblen() overhead when encoding is
				 * safe, because in valid backend encodings, extra bytes of a
				 * multibyte character never look like ASCII.
2961
				 */
2962 2963 2964 2965
				if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
					ptr += pg_encoding_mblen(cstate->client_encoding, ptr);
				else
					ptr++;
2966 2967
				break;
		}
2968
	}
2969 2970

	DUMPSOFAR();
2971
}
2972

B
Bruce Momjian 已提交
2973
/*
2974 2975
 * Send text representation of one attribute, with conversion and
 * CSV-style escaping
B
Bruce Momjian 已提交
2976 2977
 */
static void
2978
CopyAttributeOutCSV(CopyState cstate, char *string,
2979
					bool use_quote, bool single_attr)
B
Bruce Momjian 已提交
2980
{
2981 2982
	char	   *ptr;
	char	   *start;
B
Bruce Momjian 已提交
2983
	char		c;
2984 2985 2986
	char		delimc = cstate->delim[0];
	char		quotec = cstate->quote[0];
	char		escapec = cstate->escape[0];
B
Bruce Momjian 已提交
2987

2988 2989
	/* force quoting if it matches null_print (before conversion!) */
	if (!use_quote && strcmp(string, cstate->null_print) == 0)
2990 2991 2992
		use_quote = true;

	if (cstate->need_transcoding)
2993
		ptr = pg_server_to_client(string, strlen(string));
B
Bruce Momjian 已提交
2994
	else
2995
		ptr = string;
B
Bruce Momjian 已提交
2996

B
Bruce Momjian 已提交
2997
	/*
2998
	 * Make a preliminary pass to discover if it needs quoting
B
Bruce Momjian 已提交
2999
	 */
3000
	if (!use_quote)
B
Bruce Momjian 已提交
3001
	{
3002 3003 3004 3005 3006
		/*
		 *	Because '\.' can be a data value, quote it if it appears
		 *	alone on a line so it is not interpreted as the end-of-data
		 *	marker.
		 */
3007
		if (single_attr && strcmp(ptr, "\\.") == 0)
3008 3009 3010
 			use_quote = true;
 		else
 		{
3011 3012 3013
			char	   *tptr = ptr;

			while ((c = *tptr) != '\0')
3014
			{
3015 3016 3017 3018 3019
				if (c == delimc || c == quotec || c == '\n' || c == '\r')
				{
					use_quote = true;
					break;
				}
3020 3021
				if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
					tptr += pg_encoding_mblen(cstate->client_encoding, tptr);
3022
				else
3023
					tptr++;
3024 3025
			}
		}
B
Bruce Momjian 已提交
3026 3027
	}

B
Bruce Momjian 已提交
3028
	if (use_quote)
3029
	{
3030
		CopySendChar(cstate, quotec);
B
Bruce Momjian 已提交
3031

3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
		/*
		 * We adopt the same optimization strategy as in CopyAttributeOutText
		 */
		start = ptr;
		while ((c = *ptr) != '\0')
		{
			if (c == quotec || c == escapec)
			{
				DUMPSOFAR();
				CopySendChar(cstate, escapec);
				start = ptr;	/* we include char in next run */
			}
			if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
				ptr += pg_encoding_mblen(cstate->client_encoding, ptr);
			else
				ptr++;
		}
		DUMPSOFAR();
B
Bruce Momjian 已提交
3050

3051
		CopySendChar(cstate, quotec);
3052 3053 3054 3055 3056 3057
	}
	else
	{
		/* If it doesn't need quoting, we can just dump it as-is */
		CopySendString(cstate, ptr);
	}
B
Bruce Momjian 已提交
3058 3059
}

3060
/*
3061 3062 3063 3064 3065
 * CopyGetAttnums - build an integer list of attnums to be copied
 *
 * The input attnamelist is either the user-specified column list,
 * or NIL if there was none (in which case we want all the non-dropped
 * columns).
3066
 */
3067 3068
static List *
CopyGetAttnums(Relation rel, List *attnamelist)
3069
{
B
Bruce Momjian 已提交
3070
	List	   *attnums = NIL;
B
Bruce Momjian 已提交
3071

3072
	if (attnamelist == NIL)
B
Bruce Momjian 已提交
3073
	{
3074
		/* Generate default column list */
B
Bruce Momjian 已提交
3075
		TupleDesc	tupDesc = RelationGetDescr(rel);
3076
		Form_pg_attribute *attr = tupDesc->attrs;
B
Bruce Momjian 已提交
3077
		int			attr_count = tupDesc->natts;
3078
		int			i;
B
Bruce Momjian 已提交
3079 3080 3081

		for (i = 0; i < attr_count; i++)
		{
3082 3083
			if (attr[i]->attisdropped)
				continue;
3084
			attnums = lappend_int(attnums, i + 1);
3085 3086 3087 3088 3089
		}
	}
	else
	{
		/* Validate the user-supplied list and extract attnums */
3090
		ListCell   *l;
3091 3092 3093

		foreach(l, attnamelist)
		{
3094
			char	   *name = strVal(lfirst(l));
3095 3096
			int			attnum;

3097
			/* Lookup column name */
3098 3099
			/* Note we disallow system columns here */
			attnum = attnameAttNum(rel, name, false);
3100 3101 3102 3103 3104
			if (attnum == InvalidAttrNumber)
				ereport(ERROR,
						(errcode(ERRCODE_UNDEFINED_COLUMN),
						 errmsg("column \"%s\" of relation \"%s\" does not exist",
								name, RelationGetRelationName(rel))));
3105
			/* Check for duplicates */
3106
			if (list_member_int(attnums, attnum))
3107 3108
				ereport(ERROR,
						(errcode(ERRCODE_DUPLICATE_COLUMN),
B
Bruce Momjian 已提交
3109 3110
						 errmsg("column \"%s\" specified more than once",
								name)));
3111
			attnums = lappend_int(attnums, attnum);
B
Bruce Momjian 已提交
3112 3113
		}
	}
3114

3115 3116
	return attnums;
}