copy.c 187.0 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * copy.c
B
Bruce Momjian 已提交
4
 *		Implements the COPY utility command
5
 *
6 7
 * Portions Copyright (c) 2005-2008, Greenplum inc
 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
B
Add:  
Bruce Momjian 已提交
8
 * Portions Copyright (c) 1994, Regents of the University of California
9 10 11
 *
 *
 * IDENTIFICATION
12
 *	  $PostgreSQL: pgsql/src/backend/commands/copy.c,v 1.274 2007/01/05 22:19:25 momjian Exp $
13 14 15
 *
 *-------------------------------------------------------------------------
 */
16
#include "postgres.h"
17

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

25
#include "access/fileam.h"
B
Bruce Momjian 已提交
26
#include "access/heapam.h"
27 28
#include "access/aosegfiles.h"
#include "access/appendonlywriter.h"
29
#include "access/xact.h"
30
#include "catalog/gp_policy.h"
31
#include "catalog/namespace.h"
B
Bruce Momjian 已提交
32
#include "catalog/pg_type.h"
33 34 35 36
#include "catalog/catalog.h"
#include "cdb/cdbappendonlyam.h"
#include "cdb/cdbaocsam.h"
#include "cdb/cdbpartition.h"
37
#include "commands/copy.h"
38
#include "commands/tablecmds.h"
39
#include "commands/trigger.h"
B
Bruce Momjian 已提交
40
#include "executor/executor.h"
41
#include "libpq/libpq.h"
42
#include "libpq/pqformat.h"
43
#include "mb/pg_wchar.h"
B
Bruce Momjian 已提交
44
#include "miscadmin.h"
45
#include "optimizer/planner.h"
46
#include "parser/parse_relation.h"
47
#include "rewrite/rewriteHandler.h"
48
#include "storage/fd.h"
49
#include "storage/smgr.h"
50
#include "tcop/tcopprot.h"
B
Bruce Momjian 已提交
51 52
#include "utils/acl.h"
#include "utils/builtins.h"
53
#include "utils/lsyscache.h"
54
#include "utils/memutils.h"
55
#include "utils/builtins.h"
56

57 58 59 60 61 62 63 64 65 66 67 68 69
#include "cdb/cdbvars.h"
#include "cdb/cdbcopy.h"
#include "cdb/cdbhash.h"
#include "cdb/cdbdispatchresult.h"
#include "cdb/cdbsreh.h"
#include "cdb/cdbrelsize.h"
#include "cdb/cdbutil.h"
#include "cdb/cdbvarblock.h"
#include "cdb/cdbbufferedappend.h"
#include "commands/vacuum.h"
#include "utils/lsyscache.h"
#include "nodes/makefuncs.h"
#include "postmaster/autovacuum.h"
70

71 72 73 74 75 76 77
/* DestReceiver for COPY (SELECT) TO */
typedef struct
{
	DestReceiver pub;			/* publicly-known function pointers */
	CopyState	cstate;			/* CopyStateData for the command */
} DR_copy;

78
/* non-export function prototypes */
79
static void DoCopyTo(CopyState cstate);
80
extern void CopyToDispatch(CopyState cstate);
81
static void CopyTo(CopyState cstate);
82
extern void CopyFromDispatch(CopyState cstate);
83
static void CopyFrom(CopyState cstate);
84
static char *CopyReadOidAttr(CopyState cstate, bool *isnull);
85 86
static void CopyAttributeOutText(CopyState cstate, char *string);
static void CopyAttributeOutCSV(CopyState cstate, char *string,
87 88 89 90
								bool use_quote, bool single_attr);
static bool DetectLineEnd(CopyState cstate, size_t bytesread  __attribute__((unused)));
static void CopyReadAttributesTextNoDelim(CopyState cstate, bool *nulls,
										  int num_phys_attrs, int attnum);
91 92 93 94 95

/* Low-level communications functions */
static void SendCopyBegin(CopyState cstate);
static void ReceiveCopyBegin(CopyState cstate);
static void SendCopyEnd(CopyState cstate);
96
static void CopySendData(CopyState cstate, const void *databuf, int datasize);
97 98
static void CopySendString(CopyState cstate, const char *str);
static void CopySendChar(CopyState cstate, char c);
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
static int	CopyGetData(CopyState cstate, void *databuf, int datasize);

/* byte scaning utils */
static char *scanTextLine(CopyState cstate, const char *s, char c, size_t len);
static char *scanCSVLine(CopyState cstate, const char *s, char c1, char c2, char c3, size_t len);

static void CopyExtractRowMetaData(CopyState cstate);
static void preProcessDataLine(CopyState cstate);
static void concatenateEol(CopyState cstate);
static char *escape_quotes(const char *src);
static void attr_get_key(CopyState cstate, CdbCopy *cdbCopy, int original_lineno_for_qe,
						 unsigned int target_seg, AttrNumber p_nattrs, AttrNumber *attrs,
						 Form_pg_attribute *attr_descs, int *attr_offsets, bool *attr_nulls,
						 FmgrInfo *in_functions, Oid *typioparams, Datum *values);
static void copy_in_error_callback(void *arg);
static void CopyInitPartitioningState(EState *estate);
static void CopyInitDataParser(CopyState cstate);
static bool CopyCheckIsLastLine(CopyState cstate);
static char *extract_line_buf(CopyState cstate);
uint64
DoCopyInternal(const CopyStmt *stmt, const char *queryString, CopyState cstate);

/* ==========================================================================
 * The follwing macros aid in major refactoring of data processing code (in
 * CopyFrom(+Dispatch)). We use macros because in some cases the code must be in
 * line in order to work (for example elog_dismiss() in PG_CATCH) while in
 * other cases we'd like to inline the code for performance reasons.
 *
 * NOTE that an almost identical set of macros exists in fileam.c. If you make
 * changes here you may want to consider taking a look there as well.
 * ==========================================================================
 */
M
 
Marc G. Fournier 已提交
131

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
#define RESET_LINEBUF \
cstate->line_buf.len = 0; \
cstate->line_buf.data[0] = '\0'; \
cstate->line_buf.cursor = 0;

#define RESET_ATTRBUF \
cstate->attribute_buf.len = 0; \
cstate->attribute_buf.data[0] = '\0'; \
cstate->attribute_buf.cursor = 0;

#define RESET_LINEBUF_WITH_LINENO \
line_buf_with_lineno.len = 0; \
line_buf_with_lineno.data[0] = '\0'; \
line_buf_with_lineno.cursor = 0;

/*
 * A data error happened. This code block will always be inside a PG_CATCH()
 * block right when a higher stack level produced an error. We handle the error
 * by checking which error mode is set (SREH or all-or-nothing) and do the right
 * thing accordingly. Note that we MUST have this code in a macro (as opposed
 * to a function) as elog_dismiss() has to be inlined with PG_CATCH in order to
 * access local error state variables.
 *
 * changing me? take a look at FILEAM_HANDLE_ERROR in fileam.c as well.
 */
#define COPY_HANDLE_ERROR \
if (cstate->errMode == ALL_OR_NOTHING) \
{ \
	/* re-throw error and abort */ \
	if (Gp_role == GP_ROLE_DISPATCH) \
		cdbCopyEnd(cdbCopy); \
	PG_RE_THROW(); \
} \
else \
{ \
	/* SREH - release error state and handle error */ \
\
	ErrorData	*edata; \
	MemoryContext oldcontext;\
	bool	rawdata_is_a_copy = false; \
	cur_row_rejected = true; \
\
	/* SREH must only handle data errors. all other errors must not be caught */\
	if (ERRCODE_TO_CATEGORY(elog_geterrcode()) != ERRCODE_DATA_EXCEPTION)\
	{\
		/* re-throw error and abort */ \
		if (Gp_role == GP_ROLE_DISPATCH) \
			cdbCopyEnd(cdbCopy); \
		PG_RE_THROW(); \
	}\
\
	/* save a copy of the error info */ \
	oldcontext = MemoryContextSwitchTo(cstate->cdbsreh->badrowcontext);\
	edata = CopyErrorData();\
	MemoryContextSwitchTo(oldcontext);\
\
	if (!elog_dismiss(DEBUG5)) \
		PG_RE_THROW(); /* <-- hope to never get here! */ \
\
	if (Gp_role == GP_ROLE_DISPATCH)\
	{\
		Insist(cstate->err_loc_type == ROWNUM_ORIGINAL);\
		cstate->cdbsreh->rawdata = (char *) palloc(strlen(cstate->line_buf.data) * \
												   sizeof(char) + 1 + 24); \
\
		rawdata_is_a_copy = true; \
		sprintf(cstate->cdbsreh->rawdata, "%d%c%d%c%s", \
			    original_lineno_for_qe, \
				COPY_METADATA_DELIM, \
				cstate->line_buf_converted, \
				COPY_METADATA_DELIM, \
				cstate->line_buf.data);	\
	}\
	else\
	{\
		/* truncate trailing eol chars if we need to store this row in errtbl */ \
		if (cstate->cdbsreh->errtbl) \
			truncateEol(&cstate->line_buf, cstate->eol_type); \
\
		if (Gp_role == GP_ROLE_EXECUTE)\
		{\
			/* if line has embedded rownum, update the cursor to the pos right after */ \
			Insist(cstate->err_loc_type == ROWNUM_EMBEDDED);\
			cstate->line_buf.cursor = 0;\
			if(!cstate->md_error) \
				CopyExtractRowMetaData(cstate); \
		}\
\
		cstate->cdbsreh->rawdata = cstate->line_buf.data + cstate->line_buf.cursor; \
	}\
\
	cstate->cdbsreh->is_server_enc = cstate->line_buf_converted; \
	cstate->cdbsreh->linenumber = cstate->cur_lineno; \
	cstate->cdbsreh->processed = ++cstate->processed; \
	cstate->cdbsreh->consec_csv_err = cstate->num_consec_csv_err; \
\
	/* set the error message. Use original msg and add column name if available */ \
	if (cstate->cur_attname)\
	{\
		cstate->cdbsreh->errmsg = (char *) palloc((strlen(edata->message) + \
												  strlen(cstate->cur_attname) + \
												  10 + 1) * sizeof(char)); \
		sprintf(cstate->cdbsreh->errmsg, "%s, column %s", \
				edata->message, \
				cstate->cur_attname); \
	}\
	else\
	{\
		cstate->cdbsreh->errmsg = pstrdup(edata->message); \
	}\
\
	/* after all the prep work let cdbsreh do the real work */ \
	HandleSingleRowError(cstate->cdbsreh); \
\
	/* cleanup any extra memory copies we made */\
	if (rawdata_is_a_copy) \
		pfree(cstate->cdbsreh->rawdata); \
	if (!IsRejectLimitReached(cstate->cdbsreh)) \
		pfree(cstate->cdbsreh->errmsg); \
\
	MemoryContextReset(cstate->cdbsreh->badrowcontext);\
\
}

/*
 * if in SREH mode and data error occured it was already handled in
 * COPY_HANDLE_ERROR. Therefore, skip to the next row before attempting
 * to do any further processing on this one. There's a QE and QD versions
 * since the QE doesn't have a linebuf_with_lineno stringInfo.
 */
#define QD_GOTO_NEXT_ROW \
RESET_LINEBUF_WITH_LINENO; \
RESET_LINEBUF; \
cur_row_rejected = false; /* reset for next run */ \
continue; /* move on to the next data line */

#define QE_GOTO_NEXT_ROW \
RESET_LINEBUF; \
cur_row_rejected = false; /* reset for next run */ \
cstate->cur_attname = NULL;\
continue; /* move on to the next data line */
273

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

		pq_beginmessage(&buf, 'H');
B
Bruce Momjian 已提交
290
		pq_sendbyte(&buf, format);		/* overall format */
291 292
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
293
			pq_sendint(&buf, format, 2);		/* per-column formats */
294
		pq_endmessage(&buf);
295
		cstate->copy_dest = COPY_NEW_FE;
296 297
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
298
	{
299 300 301
		/* old way */
		pq_putemptymessage('H');
		/* grottiness needed for old COPY OUT protocol */
302
		pq_startcopyout();
303
		cstate->copy_dest = COPY_OLD_FE;
304
	}
B
Bruce Momjian 已提交
305
	else
306
	{
307 308 309
		/* very old way */
		pq_putemptymessage('B');
		/* grottiness needed for old COPY OUT protocol */
310
		pq_startcopyout();
311
		cstate->copy_dest = COPY_OLD_FE;
312
	}
M
 
Marc G. Fournier 已提交
313
}
B
Bruce Momjian 已提交
314

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

		pq_beginmessage(&buf, 'G');
B
Bruce Momjian 已提交
327
		pq_sendbyte(&buf, format);		/* overall format */
328 329
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
330
			pq_sendint(&buf, format, 2);		/* per-column formats */
331
		pq_endmessage(&buf);
332 333
		cstate->copy_dest = COPY_NEW_FE;
		cstate->fe_msgbuf = makeStringInfo();
334 335 336
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
337 338
		/* old way */
		pq_putemptymessage('G');
339
		cstate->copy_dest = COPY_OLD_FE;
340 341 342
	}
	else
	{
343 344
		/* very old way */
		pq_putemptymessage('D');
345
		cstate->copy_dest = COPY_OLD_FE;
346 347 348
	}
	/* We *must* flush here to ensure FE knows it can send. */
	pq_flush();
M
 
Marc G. Fournier 已提交
349 350
}

351
static void
352
SendCopyEnd(CopyState cstate)
B
Bruce Momjian 已提交
353
{
354
	if (cstate->copy_dest == COPY_NEW_FE)
355
	{
356 357
		/* Shouldn't have any unsent data */
		Assert(cstate->fe_msgbuf->len == 0);
358

359 360 361 362 363
		/* Send Copy Done message */
		pq_putemptymessage('c');
	}
	else
	{
364 365
		CopySendData(cstate, "\\.", 2);
		/* Need to flush out the trailer (this also appends a newline) */
366
 	 	CopySendEndOfRow(cstate);
367
		pq_endcopyout(false);
368
	}
M
 
Marc G. Fournier 已提交
369 370
}

371

372
/*----------
373 374 375
 * 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
376
 * CopySendEndOfRow does the appropriate thing at end of each data row
377
 *  (data is not actually flushed except by CopySendEndOfRow)
378 379
 *
 * NB: no data conversion is applied by these functions
380
 *----------
M
 
Marc G. Fournier 已提交
381
 */
382
static void
383
CopySendData(CopyState cstate, const void *databuf, int datasize)
B
Bruce Momjian 已提交
384
{
385 386 387 388 389 390 391 392 393 394 395 396 397
	if (!cstate->is_copy_in) /* copy out */
	{
		appendBinaryStringInfo(cstate->fe_msgbuf, (char *) databuf, datasize);
	}
	else /* hack for: copy in */
	{
		/* we call copySendData in copy-in to handle results
		 * of default functions that we wish to send from the
		 * dispatcher to the executor primary and mirror segments.
		 * we do so by concatenating the results to line buffer.
		 */
		appendBinaryStringInfo(&cstate->line_buf, (char *) databuf, datasize);
	}
M
 
Marc G. Fournier 已提交
398 399
}

400
static void
401
CopySendString(CopyState cstate, const char *str)
402
{
403
	CopySendData(cstate, (void *) str, strlen(str));
404 405 406
}

static void
407
CopySendChar(CopyState cstate, char c)
408
{
409
	CopySendData(cstate, &c, 1);
410 411
}

412 413 414 415 416 417
/* AXG: Note that this will both add a newline AND flush the data.
 * For the dispatcher COPY TO we don't want to use this method since
 * our newlines already exist. We use another new method similar to
 * this one to flush the data
 */
void
418
CopySendEndOfRow(CopyState cstate)
419
{
420 421
	StringInfo	fe_msgbuf = cstate->fe_msgbuf;

422
	switch (cstate->copy_dest)
423 424
	{
		case COPY_FILE:
425
			/* Default line termination depends on platform */
426
#ifndef WIN32
427
			CopySendChar(cstate, '\n');
428
#else
429
			CopySendString(cstate, "\r\n");
430
#endif
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

			(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")));
				break;
		case COPY_OLD_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
			CopySendChar(cstate, '\n');

			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")));
449
			}
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
				break;
		case COPY_NEW_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
			CopySendChar(cstate, '\n');

			/* Dump the accumulated row as one CopyData message */
			(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
			break;
		case COPY_EXTERNAL_SOURCE:
			/* we don't actually do the write here, we let the caller do it */
#ifndef WIN32
			CopySendChar(cstate, '\n');
#else
			CopySendString(cstate, "\r\n");
#endif
			return; /* don't want to reset msgbug quite yet */
	}

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

/*
 * AXG: This one is equivalent to CopySendEndOfRow() besides that
 * it doesn't send end of row - it just flushed the data. We need
 * this method for the dispatcher COPY TO since it already has data
 * with newlines (from the executors).
 */
static void
CopyToDispatchFlush(CopyState cstate)
{
	StringInfo	fe_msgbuf = cstate->fe_msgbuf;

	switch (cstate->copy_dest)
	{
		case COPY_FILE:
487 488 489 490 491 492 493

			(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")));
494 495
			break;
		case COPY_OLD_FE:
496 497 498 499 500 501 502 503

			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")));
			}
504 505
			break;
		case COPY_NEW_FE:
506

507
			/* Dump the accumulated row as one CopyData message */
508
			(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
509
			break;
510 511 512 513
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* internal error */
			break;

514
	}
515 516 517 518

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

521

522 523
/*
 * CopyGetData reads data from the source (file or frontend)
524
 * CopyGetChar does the same for single characters
525
 *
526
 * CopyGetEof checks if EOF was detected by previous Get operation.
527 528 529 530 531
 *
 * 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.
 *
532 533 534 535
 * NB: no data conversion is applied by these functions
 *
 * Returns: the number of bytes that were successfully read
 * into the data buffer.
536
 */
537
static int
538
CopyGetData(CopyState cstate, void *databuf, int datasize)
B
Bruce Momjian 已提交
539
{
540
	size_t		bytesread = 0;
541 542

	switch (cstate->copy_dest)
B
Bruce Momjian 已提交
543
	{
544
		case COPY_FILE:
545 546 547
			bytesread = fread(databuf, 1, datasize, cstate->copy_file);
			if (feof(cstate->copy_file))
				cstate->fe_eof = true;
548 549
			break;
		case COPY_OLD_FE:
550
			if (pq_getbytes((char *) databuf, datasize))
551 552
			{
				/* Only a \. terminator is legal EOF in old protocol */
553 554 555
				ereport(ERROR,
						(errcode(ERRCODE_CONNECTION_FAILURE),
						 errmsg("unexpected EOF on client connection")));
556
			}
557 558
			bytesread += datasize;		/* update the count of bytes that were
										 * read so far */
559 560
			break;
		case COPY_NEW_FE:
561
			while (datasize > 0 && !cstate->fe_eof)
562
			{
B
Bruce Momjian 已提交
563
				int			avail;
B
Bruce Momjian 已提交
564

565
				while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
566 567 568 569
				{
					/* Try to receive another message */
					int			mtype;

B
Bruce Momjian 已提交
570
			readmessage:
571 572
					mtype = pq_getbyte();
					if (mtype == EOF)
573 574
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
575
							 errmsg("unexpected EOF on client connection")));
576
					if (pq_getmessage(cstate->fe_msgbuf, 0))
577 578
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
579
							 errmsg("unexpected EOF on client connection")));
580 581
					switch (mtype)
					{
B
Bruce Momjian 已提交
582
						case 'd':		/* CopyData */
583
							break;
B
Bruce Momjian 已提交
584
						case 'c':		/* CopyDone */
585
							/* COPY IN correctly terminated by frontend */
586 587
							cstate->fe_eof = true;
							return bytesread;
B
Bruce Momjian 已提交
588
						case 'f':		/* CopyFail */
589 590 591
							ereport(ERROR,
									(errcode(ERRCODE_QUERY_CANCELED),
									 errmsg("COPY from stdin failed: %s",
592
											pq_getmsgstring(cstate->fe_msgbuf))));
593
							break;
594 595
						case 'H':		/* Flush */
						case 'S':		/* Sync */
B
Bruce Momjian 已提交
596

597
							/*
598 599 600 601
							 * 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.
602 603
							 */
							goto readmessage;
604
						default:
605 606 607 608
							ereport(ERROR,
									(errcode(ERRCODE_PROTOCOL_VIOLATION),
									 errmsg("unexpected message type 0x%02X during COPY from stdin",
											mtype)));
609 610 611
							break;
					}
				}
612
				avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
613 614
				if (avail > datasize)
					avail = datasize;
615
				pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
616
				databuf = (void *) ((char *) databuf + avail);
617 618 619
				bytesread += avail;		/* update the count of bytes that were
										 * read so far */
				datasize -= avail;
B
Bruce Momjian 已提交
620
			}
621
			break;
622 623 624 625
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* RET read their own data with external_senddata() */
			break;

626
	}
B
Bruce Momjian 已提交
627

628
	
629
	return bytesread;
M
 
Marc G. Fournier 已提交
630
}
B
Bruce Momjian 已提交
631

632
/*
633
 * ValidateControlChars
634
 *
635 636 637 638 639 640 641 642 643 644
 * These routine is common for COPY and external tables. It validates the
 * control characters (delimiter, quote, etc..) and enforces the given rules.
 *
 * bool copy
 *  - pass true if you're COPY
 *  - pass false if you're an exttab
 *
 * bool load
 *  - pass true for inbound data (COPY FROM, SELECT FROM exttab)
 *  - pass false for outbound data (COPY TO, INSERT INTO exttab)
645
 */
646 647 648 649 650
void ValidateControlChars(bool copy, bool load, bool csv_mode, char *delim,
						char *null_print, char *quote, char *escape,
						List *force_quote, List *force_notnull,
						bool header_line, bool fill_missing, char *newline,
						int num_columns)
651
{
652
	bool	delim_off = (pg_strcasecmp(delim, "off") == 0);
653

654 655 656 657 658 659 660 661 662
	/*
	 * DELIMITER
	 *
	 * Only single-byte delimiter strings are supported. In addition, if the
	 * server encoding is a multibyte character encoding we only allow the
	 * delimiter to be an ASCII character (like postgresql. For more info
	 * on this see discussion and comments in MPP-3756).
	 */
	if (pg_database_encoding_max_length() == 1)
663
	{
664 665 666 667 668 669 670 671 672 673 674 675 676
		/* single byte encoding such as ascii, latinx and other */
		if (strlen(delim) != 1 && !delim_off)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("delimiter must be a single byte character, or \'off\'")));
	}
	else
	{
		/* multi byte encoding such as utf8 */
		if ((strlen(delim) != 1 || IS_HIGHBIT_SET(delim[0])) && !delim_off )
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("delimiter must be a single ASCII character, or \'off\'")));
677
	}
678

679 680 681 682 683
	if (strchr(delim, '\r') != NULL ||
		strchr(delim, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be newline or carriage return")));
684

685 686 687 688 689
	if (strchr(null_print, '\r') != NULL ||
		strchr(null_print, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("null representation cannot use newline or carriage return")));
690

691 692 693 694
	if (!csv_mode && strchr(delim, '\\') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be backslash")));
695

696 697 698 699
	if (strchr(null_print, delim[0]) != NULL && !delim_off)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
		errmsg("delimiter must not appear in the NULL specification")));
700

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715
	/*
	 * Disallow unsafe delimiter characters in non-CSV mode.  We can't allow
	 * backslash because it would be ambiguous.  We can't allow the other
	 * cases because data characters matching the delimiter must be
	 * backslashed, and certain backslash combinations are interpreted
	 * non-literally by COPY IN.  Disallowing all lower case ASCII letters
	 * is more than strictly necessary, but seems best for consistency and
	 * future-proofing.  Likewise we disallow all digits though only octal
	 * digits are actually dangerous.
	 */
	if (!csv_mode && !delim_off &&
		strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789", delim[0]) != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be \"%s\"", delim)));
716

717
	if (delim_off)
718
	{
719

720 721 722 723 724 725 726 727 728 729 730
		/*
		 * We don't support delimiter 'off' for COPY because the QD COPY
		 * sometimes internally adds columns to the data that it sends to
		 * the QE COPY modules, and it uses the delimiter for it. There
		 * are ways to work around this but for now it's not important and
		 * we simply don't support it.
		 */
		if (copy)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("Using no delimiter is only supported for external tables")));
M
 
Marc G. Fournier 已提交
731

732 733 734 735
		if (num_columns != 1)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("Using no delimiter is only possible for a single column table")));
736

737
	}
738

739 740 741 742
	/*
	 * HEADER
	 */
	if(header_line)
743
	{
744
		if(!copy && Gp_role == GP_ROLE_DISPATCH)
745
		{
746 747 748 749 750 751 752 753 754 755 756
			/* (exttab) */
			if(load)
			{
				/* RET */
				ereport(NOTICE,
						(errmsg("HEADER means that each one of the data files "
								"has a header row.")));				
			}
			else
			{
				/* WET */
757
				ereport(ERROR,
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925
						(errcode(ERRCODE_GP_FEATURE_NOT_YET),
						errmsg("HEADER is not yet supported for writable external tables")));				
			}
		}
	}

	/*
	 * QUOTE
	 */
	if (!csv_mode && quote != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("quote available only in CSV mode")));

	if (csv_mode && strlen(quote) != 1)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("quote must be a single character")));

	if (csv_mode && strchr(null_print, quote[0]) != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("CSV quote character must not appear in the NULL specification")));

	if (csv_mode && delim[0] == quote[0])
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter and quote must be different")));

	/*
	 * ESCAPE
	 */
	if (csv_mode && strlen(escape) != 1)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("escape in CSV format must be a single character")));

	if (!csv_mode &&
		(strchr(escape, '\r') != NULL ||
		strchr(escape, '\n') != NULL))
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("escape representation in text format cannot use newline or carriage return")));

	if (!csv_mode && strlen(escape) != 1)
	{
		if (pg_strcasecmp(escape, "off"))
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("escape must be a single character, or [OFF/off] to disable escapes")));
	}

	/*
	 * FORCE QUOTE
	 */
	if (!csv_mode && force_quote != NIL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("force quote available only in CSV mode")));
	if (force_quote != NIL && load)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("force quote only available for data unloading, not loading")));

	/*
	 * FORCE NOT NULL
	 */
	if (!csv_mode && force_notnull != NIL)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("force not null available only in CSV mode")));
	if (force_notnull != NIL && !load)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("force not null only available for data loading, not unloading")));

	if (fill_missing && !load)
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("fill missing fields only available for data loading, not unloading")));

	/*
	 * NEWLINE
	 */
	if (newline)
	{
		if (!load)
		{
			ereport(ERROR,
					(errcode(ERRCODE_GP_FEATURE_NOT_YET),
					errmsg("newline currently available for data loading only, not unloading")));
		}
		else
		{
			if(pg_strcasecmp(newline, "lf") != 0 &&
			   pg_strcasecmp(newline, "cr") != 0 &&
			   pg_strcasecmp(newline, "crlf") != 0)
				ereport(ERROR,
						(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
						errmsg("invalid value for NEWLINE (%s)", newline),
						errhint("valid options are: 'LF', 'CRLF', 'CR'")));
		}
	}
}



/*
 *	 DoCopy executes the SQL COPY statement
 *
 * Either unload or reload contents of table <relation>, depending on <from>.
 * (<from> = TRUE means we are inserting into the table.) In the "TO" case
 * we also support copying the output of an arbitrary SELECT query.
 *
 * If <pipe> is false, transfer is between the table and the file named
 * <filename>.	Otherwise, transfer is between the table and our regular
 * input/output stream. The latter could be either stdin/stdout or a
 * socket, depending on whether we're running under Postmaster control.
 *
 * 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>.
 *
 * When loading in the text format from an input stream (as opposed to
 * a file), recognize a "\." on a line by itself as EOF. Also recognize
 * a stream EOF.  When unloading in the text format to an output stream,
 * write a "." on a line by itself at the end of the data.
 *
 * 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.
 */
uint64
DoCopyInternal(const CopyStmt *stmt, const char *queryString, CopyState cstate)
{
	bool		is_from = stmt->is_from;
	bool		pipe = (stmt->filename == NULL || Gp_role == GP_ROLE_EXECUTE);
	List	   *attnamelist = stmt->attlist;
	List	   *force_quote = NIL;
	List	   *force_notnull = NIL;
	AclMode		required_access = (is_from ? ACL_INSERT : ACL_SELECT);
	AclResult	aclresult;
	ListCell   *option;
	TupleDesc   tupDesc;
	int         num_phys_attrs;
	uint64      processed;
	bool        qe_copy_from = (is_from && (Gp_role == GP_ROLE_EXECUTE));
    /* save relationOid for auto-stats */
	Oid         relationOid = InvalidOid;


	/* Extract options from the statement node tree */
	foreach(option, stmt->options)
	{
		DefElem    *defel = (DefElem *) lfirst(option);

		if (strcmp(defel->defname, "binary") == 0)
		{
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("BINARY is not supported")));
926 927 928
		}
		else if (strcmp(defel->defname, "oids") == 0)
		{
929
			if (cstate->oids)
930 931 932
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
933
			cstate->oids = intVal(defel->arg);
934 935 936
		}
		else if (strcmp(defel->defname, "delimiter") == 0)
		{
937
			if (cstate->delim)
938 939 940
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
941
			cstate->delim = strVal(defel->arg);
942 943 944
		}
		else if (strcmp(defel->defname, "null") == 0)
		{
945
			if (cstate->null_print)
946 947 948
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
949
			cstate->null_print = strVal(defel->arg);
950 951 952 953 954 955 956 957 958

			/*
			 * MPP-2010: unfortunately serialization function doesn't
			 * distinguish between 0x0 and empty string. Therefore we
			 * must assume that if NULL AS was indicated and has no value
			 * the actual value is an empty string.
			 */
			if(!cstate->null_print)
				cstate->null_print = "";
959
		}
B
Bruce Momjian 已提交
960 961
		else if (strcmp(defel->defname, "csv") == 0)
		{
962
			if (cstate->csv_mode)
B
Bruce Momjian 已提交
963 964 965
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
966
			cstate->csv_mode = intVal(defel->arg);
B
Bruce Momjian 已提交
967
		}
968 969
		else if (strcmp(defel->defname, "header") == 0)
		{
970
			if (cstate->header_line)
971 972 973
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
974
			cstate->header_line = intVal(defel->arg);
975
		}
B
Bruce Momjian 已提交
976 977
		else if (strcmp(defel->defname, "quote") == 0)
		{
978
			if (cstate->quote)
B
Bruce Momjian 已提交
979 980 981
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
982
			cstate->quote = strVal(defel->arg);
B
Bruce Momjian 已提交
983 984 985
		}
		else if (strcmp(defel->defname, "escape") == 0)
		{
986
			if (cstate->escape)
B
Bruce Momjian 已提交
987 988 989
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
990
			cstate->escape = strVal(defel->arg);
B
Bruce Momjian 已提交
991
		}
B
Bruce Momjian 已提交
992
		else if (strcmp(defel->defname, "force_quote") == 0)
B
Bruce Momjian 已提交
993
		{
B
Bruce Momjian 已提交
994
			if (force_quote)
B
Bruce Momjian 已提交
995 996 997
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
998
			force_quote = (List *) defel->arg;
B
Bruce Momjian 已提交
999
		}
B
Bruce Momjian 已提交
1000
		else if (strcmp(defel->defname, "force_notnull") == 0)
B
Bruce Momjian 已提交
1001
		{
B
Bruce Momjian 已提交
1002
			if (force_notnull)
B
Bruce Momjian 已提交
1003 1004 1005
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
1006
			force_notnull = (List *) defel->arg;
B
Bruce Momjian 已提交
1007
		}
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
		else if (strcmp(defel->defname, "fill_missing_fields") == 0)
		{
			if (cstate->fill_missing)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			cstate->fill_missing = intVal(defel->arg);
		}
		else if (strcmp(defel->defname, "newline") == 0)
		{
			if (cstate->eol_str)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			cstate->eol_str = strVal(defel->arg);
		}
1024
		else
1025
			elog(ERROR, "option \"%s\" not recognized",
1026 1027 1028
				 defel->defname);
	}

1029
	/* Set defaults */
B
Bruce Momjian 已提交
1030

1031 1032 1033
	cstate->err_loc_type = ROWNUM_ORIGINAL;
	cstate->eol_type = EOL_UNKNOWN;
	cstate->escape_off = false;
B
Bruce Momjian 已提交
1034

1035 1036
	if (!cstate->delim)
		cstate->delim = cstate->csv_mode ? "," : "\t";
B
Bruce Momjian 已提交
1037

1038 1039
	if (!cstate->null_print)
		cstate->null_print = cstate->csv_mode ? "" : "\\N";
B
Bruce Momjian 已提交
1040

1041
	if (cstate->csv_mode)
B
Bruce Momjian 已提交
1042
	{
1043 1044 1045 1046
		if (!cstate->quote)
			cstate->quote = "\"";
		if (!cstate->escape)
			cstate->escape = cstate->quote;
B
Bruce Momjian 已提交
1047
	}
B
Bruce Momjian 已提交
1048

1049 1050
	if (!cstate->csv_mode && !cstate->escape)
		cstate->escape = "\\";			/* default escape for text mode */
B
Bruce Momjian 已提交
1051

1052 1053 1054 1055 1056 1057 1058 1059
	/*
	 * Error handling setup
	 */
	if(stmt->sreh)
	{
		/* Single row error handling requested */
		SingleRowErrorDesc *sreh;
		bool		log_to_file = false;
B
Bruce Momjian 已提交
1060

1061
		sreh = (SingleRowErrorDesc *)stmt->sreh;
B
Bruce Momjian 已提交
1062

1063 1064 1065 1066
		if (!is_from)
			ereport(ERROR,
					(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY single row error handling only available using COPY FROM")));
B
Bruce Momjian 已提交
1067

1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
		if (sreh->errtable)
		{
			cstate->errMode = SREH_LOG;
		}
		else if (sreh->into_file)
		{
			cstate->errMode = SREH_LOG;
			if (sreh->is_keep)
				ereport(ERROR,
						(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
						 errmsg("KEEP may only be specified with an error table")));
			log_to_file = true;
		}
		else
		{
			cstate->errMode = SREH_IGNORE;
			if (sreh->is_keep)
				ereport(ERROR,
						(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
						errmsg("KEEP may only be specified with a LOG INTO errortable clause")));
		}
		cstate->cdbsreh = makeCdbSreh(sreh->is_keep,
									  sreh->reusing_existing_errtable,
									  sreh->rejectlimit,
									  sreh->is_limit_in_rows,
									  sreh->errtable,
									  stmt->filename,
									  stmt->relation->relname,
									  log_to_file);

		/* if necessary warn the user of the risk of table getting dropped */
		if(sreh->errtable && Gp_role == GP_ROLE_DISPATCH && !sreh->reusing_existing_errtable)
			emitSameTxnWarning();
	}
	else
	{
		/* No single row error handling requested. Use "all or nothing" */
		cstate->cdbsreh = NULL; /* default - no SREH */
		cstate->errMode = ALL_OR_NOTHING; /* default */
	}
B
Bruce Momjian 已提交
1108

1109
	cstate->skip_ext_partition = stmt->skip_ext_partition;
B
Bruce Momjian 已提交
1110

1111 1112 1113 1114 1115 1116
	/* We must be a QE if we received the partitioning config */
	if (stmt->partitions)
	{
		Assert(Gp_role == GP_ROLE_EXECUTE);
		cstate->partitions = stmt->partitions;
	}
B
Bruce Momjian 已提交
1117

1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
	/*
	 * Validate our control characters and their combination
	 */
	ValidateControlChars(true,
						 is_from,
						 cstate->csv_mode,
						 cstate->delim,
						 cstate->null_print,
						 cstate->quote,
						 cstate->escape,
						 force_quote,
						 force_notnull,
						 cstate->header_line,
						 cstate->fill_missing,
						 cstate->eol_str,
						 0 /* pass correct value when COPY supports no delim */);

	if (!pg_strcasecmp(cstate->escape, "off"))
		cstate->escape_off = true;

	/* set end of line type if NEWLINE keyword was specified */
	if (cstate->eol_str)
		CopyEolStrToType(cstate);
	
1142
	/* Disallow file COPY except to superusers. */
1143
	if (!pipe && !superuser())
1144 1145 1146 1147
		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 已提交
1148
						 "psql's \\copy command also works for anyone.")));
B
Bruce Momjian 已提交
1149

1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
	cstate->copy_dest = COPY_FILE;		/* default */
	cstate->filename = (Gp_role == GP_ROLE_EXECUTE ? NULL : stmt->filename); /* QE COPY always uses STDIN */
	cstate->copy_file = NULL;
	cstate->fe_msgbuf = NULL;
	cstate->fe_eof = false;
	cstate->missing_bytes = 0;
	
	if(!is_from)
	{
		if (pipe)
		{
			if (whereToSendOutput == DestRemote)
				cstate->fe_copy = true;
			else
				cstate->copy_file = stdout;
		}
		else
		{
			mode_t		oumask; /* Pre-existing umask value */
			struct stat st;

			/*
			 * Prevent write to relative path ... too easy to shoot oneself in the
			 * foot by overwriting a database file ...
			 */
			if (!is_absolute_path(cstate->filename))
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_NAME),
						 errmsg("relative path not allowed for COPY to file")));

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

			if (cstate->copy_file == NULL)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not open file \"%s\" for writing: %m",
								cstate->filename)));

			// Increase buffer size to improve performance  (cmcdevitt)
			setvbuf(cstate->copy_file, NULL, _IOFBF, 393216); // 384 Kbytes

			fstat(fileno(cstate->copy_file), &st);
			if (S_ISDIR(st.st_mode))
			{
				FreeFile(cstate->copy_file);
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("\"%s\" is a directory", cstate->filename)));
			}
		}

	}

	elog(DEBUG1,"DoCopy starting");
1206 1207
	if (stmt->relation)
	{
1208 1209
		LOCKMODE lockmode = (is_from ? RowExclusiveLock : AccessShareLock);

1210 1211 1212 1213
		Assert(!stmt->query);
		cstate->queryDesc = NULL;

		/* Open and lock the relation, using the appropriate lock type. */
1214 1215 1216 1217
		cstate->rel = heap_openrv(stmt->relation, lockmode);

		/* save relation oid for auto-stats call later */
		relationOid = RelationGetRelid(cstate->rel);
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241

		/* Check relation permissions. */
		aclresult = pg_class_aclcheck(RelationGetRelid(cstate->rel),
									  GetUserId(),
									  required_access);
		if (aclresult != ACLCHECK_OK)
			aclcheck_error(aclresult, ACL_KIND_CLASS,
						   RelationGetRelationName(cstate->rel));

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

		/* Don't allow COPY w/ OIDs to or from a table without them */
		if (cstate->oids && !cstate->rel->rd_rel->relhasoids)
			ereport(ERROR,
					(errcode(ERRCODE_UNDEFINED_COLUMN),
					 errmsg("table \"%s\" does not have OIDs",
							RelationGetRelationName(cstate->rel))));

		tupDesc = RelationGetDescr(cstate->rel);
1242 1243 1244 1245

		/* Update error log info */
		if (cstate->cdbsreh)
			cstate->cdbsreh->relid = RelationGetRelid(cstate->rel);
1246 1247 1248 1249 1250
	}
	else
	{
		Query	   *query = stmt->query;
		List	   *rewritten;
1251
		PlannedStmt	 *plannedstmt;
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
		DestReceiver *dest;

		Assert(query);
		Assert(!is_from);
		cstate->rel = NULL;

		/* Don't allow COPY w/ OIDs from a select */
		if (cstate->oids)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY (SELECT) WITH OIDS is not supported")));

1264
		if (query->intoClause)
1265 1266 1267 1268
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY (SELECT INTO) is not supported")));

1269

1270 1271 1272 1273 1274
		/*
		 * The query has already been through parse analysis, but not
		 * rewriting or planning.  Do that now.
		 *
		 * Because the planner is not cool about not scribbling on its input,
1275
		 * we make a preliminary copy of the source querytree.  This prevents
1276 1277
		 * problems in the case that the COPY is in a portal or plpgsql
		 * function and is executed repeatedly.  (See also the same hack in
1278
												  * EXPLAIN, DECLARE CURSOR and PREPARE.)  XXX the planner really
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
		 * shouldn't modify its input ... FIXME someday.
		 */
		query = copyObject(query);
		Assert(query->commandType == CMD_SELECT);

		/*
		 * Must acquire locks in case we didn't come fresh from the parser.
		 * XXX this also scribbles on query, another reason for copyObject
		 */
		AcquireRewriteLocks(query);

		/* Rewrite through rule system */
		rewritten = QueryRewrite(query);

		/* We don't expect more or less than one result query */
		if (list_length(rewritten) != 1)
			elog(ERROR, "unexpected rewrite result");

		query = (Query *) linitial(rewritten);
		Assert(query->commandType == CMD_SELECT);

		/* plan the query */
1301
		plannedstmt = planner(query, 0, NULL);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316

		/*
		 * Update snapshot command ID to ensure this query sees results of any
		 * previously executed queries.  (It's a bit cheesy to modify
		 * ActiveSnapshot without making a copy, but for the limited ways in
		 * which COPY can be invoked, I think it's OK, because the active
		 * snapshot shouldn't be shared with anything else anyway.)
		 */
		ActiveSnapshot->curcid = GetCurrentCommandId();

		/* Create dest receiver for COPY OUT */
		dest = CreateDestReceiver(DestCopyOut, NULL);
		((DR_copy *) dest)->cstate = cstate;

		/* Create a QueryDesc requesting no output */
1317
		cstate->queryDesc = CreateQueryDesc(plannedstmt, queryString,
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329
											ActiveSnapshot, InvalidSnapshot,
											dest, NULL, false);

		/*
		 * Call ExecutorStart to prepare the plan for execution.
		 *
		 * ExecutorStart computes a result tupdesc for us
		 */
		ExecutorStart(cstate->queryDesc, 0);

		tupDesc = cstate->queryDesc->tupDesc;
	}
B
Bruce Momjian 已提交
1330

1331
	cstate->attnamelist = attnamelist;
1332
	/* Generate or convert list of attributes to process */
1333 1334 1335
	cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);

	num_phys_attrs = tupDesc->natts;
1336

1337 1338
	/* Convert FORCE QUOTE name list to per-column flags, check validity */
	cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
B
Bruce Momjian 已提交
1339
	if (force_quote)
B
Bruce Momjian 已提交
1340
	{
1341
		List	   *attnums;
1342
		ListCell   *cur;
B
Bruce Momjian 已提交
1343

1344
		attnums = CopyGetAttnums(tupDesc, cstate->rel, force_quote);
B
Bruce Momjian 已提交
1345

1346
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1347
		{
1348
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1349

1350
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1351 1352
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1353 1354
						 errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
								NameStr(tupDesc->attrs[attnum - 1]->attname))));
1355
			cstate->force_quote_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1356 1357
		}
	}
B
Bruce Momjian 已提交
1358

1359 1360
	/* Convert FORCE NOT NULL name list to per-column flags, check validity */
	cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
B
Bruce Momjian 已提交
1361
	if (force_notnull)
B
Bruce Momjian 已提交
1362
	{
1363
		List	   *attnums;
1364
		ListCell   *cur;
B
Bruce Momjian 已提交
1365

1366
		attnums = CopyGetAttnums(tupDesc, cstate->rel, force_notnull);
B
Bruce Momjian 已提交
1367

1368
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1369
		{
1370
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1371

1372
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1373 1374
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1375 1376
						 errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
								NameStr(tupDesc->attrs[attnum - 1]->attname))));
1377
			cstate->force_notnull_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1378
		}
B
Bruce Momjian 已提交
1379

1380 1381 1382 1383 1384 1385
		/* keep the raw version too, we will need it later */
		cstate->force_notnull = force_notnull;
	}
	/*
	 * Set up variables to avoid per-attribute overhead.
	 */
1386 1387
	initStringInfo(&cstate->attribute_buf);
	initStringInfo(&cstate->line_buf);
1388
	cstate->processed = 0;
1389

1390 1391
	/*
	 * Set up encoding conversion info.  Even if the client and server
1392 1393 1394 1395 1396 1397
	 * encodings are the same, we must apply pg_client_to_server() to
	 * validate data in multibyte encodings. However, transcoding must
	 * be skipped for COPY FROM in executor mode since data already arrived
	 * in server encoding (was validated and trancoded by dispatcher mode
	 * COPY). For this same reason encoding_embeds_ascii can never be true
	 * for COPY FROM in executor mode.
1398
	 */
1399
	cstate->client_encoding = pg_get_client_encoding();
1400
	cstate->need_transcoding =
1401 1402
		((cstate->client_encoding != GetDatabaseEncoding() ||
		  pg_database_encoding_max_length() > 1) && !qe_copy_from);
1403

1404 1405 1406
	cstate->encoding_embeds_ascii = (qe_copy_from ? false : PG_ENCODING_IS_CLIENT_ONLY(cstate->client_encoding));
	cstate->line_buf_converted = (Gp_role == GP_ROLE_EXECUTE ? true : false);
	setEncodingConversionProc(cstate, pg_get_client_encoding(), !is_from);
1407

1408
	/*
1409
	 * some greenplum db specific vars
1410
	 */
1411 1412
	cstate->is_copy_in = (is_from ? true : false);
	if (is_from)
1413
	{
1414 1415
		cstate->error_on_executor = false;
		initStringInfo(&(cstate->executor_err_context));
1416
	}
1417

1418 1419 1420 1421 1422 1423
	if (is_from)				/* copy from file to database */
	{
		bool		pipe = (cstate->filename == NULL);
		bool		shouldDispatch = (Gp_role == GP_ROLE_DISPATCH &&
									  cstate->rel->rd_cdbpolicy != NULL);
		char		relkind;
1424

1425
		Assert(cstate->rel);
1426

1427
		relkind = cstate->rel->rd_rel->relkind;
1428

1429
		if (relkind != RELKIND_RELATION)
1430
		{
1431
			if (relkind == RELKIND_VIEW)
1432 1433
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1434 1435 1436
						 errmsg("cannot copy to view \"%s\"",
								RelationGetRelationName(cstate->rel))));
			else if (relkind == RELKIND_SEQUENCE)
1437 1438
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1439
						 errmsg("cannot copy to sequence \"%s\"",
1440
								RelationGetRelationName(cstate->rel))));
1441
			else
1442 1443
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1444
						 errmsg("cannot copy to non-table relation \"%s\"",
B
Bruce Momjian 已提交
1445
								RelationGetRelationName(cstate->rel))));
1446
		}
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561

		if(stmt->sreh && Gp_role != GP_ROLE_EXECUTE && !cstate->rel->rd_cdbpolicy)
			ereport(ERROR,
					(errcode(ERRCODE_GP_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY single row error handling only available for distributed user tables")));

		if (pipe)
		{
			if (whereToSendOutput == DestRemote)
				ReceiveCopyBegin(cstate);
			else
				cstate->copy_file = stdin;
		}
		else
		{
			struct stat st;

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

			if (cstate->copy_file == NULL)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not open file \"%s\" for reading: %m",
								cstate->filename)));

			// Increase buffer size to improve performance  (cmcdevitt)
            setvbuf(cstate->copy_file, NULL, _IOFBF, 393216); // 384 Kbytes

			fstat(fileno(cstate->copy_file), &st);
			if (S_ISDIR(st.st_mode))
			{
				FreeFile(cstate->copy_file);
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("\"%s\" is a directory", cstate->filename)));
			}
		}


		/*
		 * Append Only Tables.
		 *
		 * If QD, build a list of all the relations (relids) that may get data
		 * inserted into them as a part of this operation. This includes
		 * the relation specified in the COPY command, plus any partitions
		 * that it may have. Then, call assignPerRelSegno to assign a segfile
		 * number to insert into each of the Append Only relations that exists
		 * in this global list. We generate the list now and save it in cstate.
		 *
		 * If QE - get the QD generated list from CopyStmt and each relation can
		 * find it's assigned segno by looking at it (during CopyFrom).
		 *
		 * Utility mode always builds a one single mapping.
		 */
		if(shouldDispatch)
		{
			Oid relid = RelationGetRelid(cstate->rel);
			List *all_relids = NIL;

			all_relids = lappend_oid(all_relids, relid);

			if (rel_is_partitioned(relid))
			{
				PartitionNode *pn = RelationBuildPartitionDesc(cstate->rel, false);
				all_relids = list_concat(all_relids, all_partition_relids(pn));
			}

			cstate->ao_segnos = assignPerRelSegno(all_relids);
		}
		else
		{
			if (stmt->ao_segnos)
			{
				/* We must be a QE if we received the aosegnos config */
				Assert(Gp_role == GP_ROLE_EXECUTE);
				cstate->ao_segnos = stmt->ao_segnos;
			}
			else
			{
				/*
				 * utility mode (or dispatch mode for no policy table).
				 * create a one entry map for our one and only relation
				 */
				if(RelationIsAoRows(cstate->rel) || RelationIsAoCols(cstate->rel))
				{
					SegfileMapNode *n = makeNode(SegfileMapNode);
					n->relid = RelationGetRelid(cstate->rel);
					n->segno = SetSegnoForWrite(InvalidFileSegNumber, n->relid);
					cstate->ao_segnos = lappend(cstate->ao_segnos, n);
				}
			}
		}

		/*
		 * Set up is done. Get to work!
		 */
		if (shouldDispatch)
		{
			/* data needs to get dispatched to segment databases */
			CopyFromDispatch(cstate);
		}
		else
		{
			/* data needs to get inserted locally */
			CopyFrom(cstate);
		}

		if (!pipe)
		{
			if (FreeFile(cstate->copy_file))
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not write to file \"%s\": %m",
								cstate->filename)));
		}
1562
	}
1563 1564
	else		/* copy from database to file */
		DoCopyTo(cstate);
1565

1566 1567 1568 1569 1570 1571 1572 1573 1574
	/*
	 * Close the relation or query.  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.
	 */
	if (cstate->rel)
		heap_close(cstate->rel, (is_from ? NoLock : AccessShareLock));
	if (cstate->queryDesc)
1575
	{
1576 1577 1578 1579
		/* Close down the query and free resources. */
		ExecutorEnd(cstate->queryDesc);
		FreeQueryDesc(cstate->queryDesc);
		cstate->queryDesc = NULL;
1580
	}
1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593

	/* Clean up single row error handling related memory */
	if(cstate->cdbsreh)
		destroyCdbSreh(cstate->cdbsreh);

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

    /* MPP-4407. Logging number of tuples copied */
	if (Gp_role == GP_ROLE_DISPATCH
			&& is_from
			&& relationOid != InvalidOid
			&& GetCommandLogLevel((Node *) stmt) <= log_statement)
1594
	{
1595 1596 1597 1598 1599 1600
		elog(DEBUG1, "type_of_statement = %s dboid = %d tableoid = %d num_tuples_modified = %u",
				autostats_cmdtype_to_string(AUTOSTATS_CMDTYPE_COPY),
				MyDatabaseId,
				relationOid,
				(unsigned int) processed);
	}
1601

1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614
    /* 	 Fix for MPP-4082. Issue automatic ANALYZE if conditions are satisfied. */
	if (Gp_role == GP_ROLE_DISPATCH && is_from)
	{
		auto_stats(AUTOSTATS_CMDTYPE_COPY, relationOid, processed, false /* inFunction */);
	} /*end auto-stats block*/

	if(cstate->force_quote_flags)
		pfree(cstate->force_quote_flags);
	if(cstate->force_notnull_flags)
		pfree(cstate->force_notnull_flags);
		
	pfree(cstate->attribute_buf.data);
	pfree(cstate->line_buf.data);
1615

1616 1617
	return processed;
}
1618

1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
uint64
DoCopy(const CopyStmt *stmt, const char *queryString)
{
	uint64 result = -1;
	/* Allocate workspace and zero all fields */
	CopyState cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
	PG_TRY();
	{
		result = DoCopyInternal(stmt, queryString, cstate);
	}
	PG_CATCH();
	{
		if (cstate->queryDesc)
		{
			/* should shutdown the mpp stuff such as interconnect and dispatch thread */
			mppExecutorCleanup(cstate->queryDesc);
		}
		PG_RE_THROW();
	}
	PG_END_TRY();
	pfree(cstate);
	return result;
}

/*
 * This intermediate routine exists mainly to localize the effects of setjmp
 * so we don't need to plaster a lot of variables with "volatile".
 */
static void
DoCopyTo(CopyState cstate)
{
	bool		pipe = (cstate->filename == NULL);

	if (cstate->rel)
	{
		char		relkind = cstate->rel->rd_rel->relkind;
1655

1656
		if (relkind != RELKIND_RELATION)
1657
		{
1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695
			if (relkind == RELKIND_VIEW)
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from view \"%s\"",
								RelationGetRelationName(cstate->rel)),
						 errhint("Try the COPY (SELECT ...) TO variant.")));
			else if (relkind == RELKIND_SEQUENCE)
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from sequence \"%s\"",
								RelationGetRelationName(cstate->rel))));
			else
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from non-table relation \"%s\"",
								RelationGetRelationName(cstate->rel))));
		}
		else if (RelationIsExternal(cstate->rel))
		{
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from external relation \"%s\"",
								RelationGetRelationName(cstate->rel)),
						 errhint("Try the COPY (SELECT ...) TO variant.")));
		}
		else if (rel_has_external_partition(cstate->rel->rd_id))
		{
			if (!cstate->skip_ext_partition)
			{
				ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
					 errmsg("cannot copy from relation \"%s\" which has external partition(s)",
							RelationGetRelationName(cstate->rel)),
					 errhint("Try the COPY (SELECT ...) TO variant.")));
			}
			else
			{
				ereport(NOTICE,
1696
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1697 1698
					 errmsg("COPY ignores external partition(s)")));
			}
1699 1700
		}
	}
1701

1702 1703
	PG_TRY();
	{
1704 1705
		if (cstate->fe_copy)
			SendCopyBegin(cstate);
1706

1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
		/*
		 * We want to dispatch COPY TO commands only in the case that
		 * we are the dispatcher and we are copying from a user relation
		 * (a relation where data is distributed in the segment databases).
		 * Otherwize, if we are not the dispatcher *or* if we are
		 * doing COPY (SELECT) we just go straight to work, without
		 * dispatching COPY commands to executors.
		 */
		if (Gp_role == GP_ROLE_DISPATCH && cstate->rel && cstate->rel->rd_cdbpolicy)
			CopyToDispatch(cstate);
		else
			CopyTo(cstate);
1719

1720 1721
		if (cstate->fe_copy)
			SendCopyEnd(cstate);
1722 1723 1724 1725
	}
	PG_CATCH();
	{
		/*
B
Bruce Momjian 已提交
1726
		 * Make sure we turn off old-style COPY OUT mode upon error. It is
B
Bruce Momjian 已提交
1727 1728
		 * okay to do this in all cases, since it does nothing if the mode is
		 * not on.
1729 1730 1731 1732 1733
		 */
		pq_endcopyout(true);
		PG_RE_THROW();
	}
	PG_END_TRY();
1734 1735 1736 1737 1738 1739 1740 1741 1742

	if (!pipe)
	{
		if (FreeFile(cstate->copy_file))
			ereport(ERROR,
					(errcode_for_file_access(),
					 errmsg("could not write to file \"%s\": %m",
							cstate->filename)));
	}
1743 1744
}

1745
/*
1746 1747 1748
 * CopyToCreateDispatchCommand
 *
 * Create the COPY command that will get dispatched to the QE's.
1749
 */
1750 1751 1752 1753 1754 1755 1756 1757
static void CopyToCreateDispatchCommand(CopyState cstate,
										StringInfo cdbcopy_cmd,
										AttrNumber	num_phys_attrs,
										Form_pg_attribute *attr)

{
	ListCell   *cur;
	bool		is_first_col = true;
1758
	int			i;
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807

	/* append schema and tablename */
	appendStringInfo(cdbcopy_cmd, "COPY %s.%s",
					 quote_identifier(get_namespace_name(RelationGetNamespace(cstate->rel))),
					 quote_identifier(RelationGetRelationName(cstate->rel)));
	/*
	 * append column list. NOTE: if not specified originally, attnumlist will
	 * include all non-dropped columns of the table by default
	 */
	if(num_phys_attrs > 0) /* don't append anything for zero column table */
	{
		foreach(cur, cstate->attnumlist)
		{
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;

			/* We don't add dropped attributes */
			if (attr[m]->attisdropped)
				continue;

			/* append column string. quote it if needed */
			appendStringInfo(cdbcopy_cmd, (is_first_col ? "(%s" : ",%s"),
							 quote_identifier(NameStr(attr[m]->attname)));

			is_first_col = false;
		}

		if (!is_first_col)
			appendStringInfo(cdbcopy_cmd, ")");
	}

	appendStringInfo(cdbcopy_cmd, " TO STDOUT WITH");

	if (cstate->oids)
		appendStringInfo(cdbcopy_cmd, " OIDS");

	appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
	appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));

	/* if default escape in text format ("\") leave expression out */
	if (!cstate->csv_mode && strcmp(cstate->escape, "\\") != 0)
		appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));

	if (cstate->csv_mode)
	{
		appendStringInfo(cdbcopy_cmd, " CSV");
		appendStringInfo(cdbcopy_cmd, " QUOTE AS E'%s'", escape_quotes(cstate->quote));
		appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));

1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824
		/* Create list of FORCE QUOTE columns */
		is_first_col = true;
		for (i = 0; i < num_phys_attrs; i++)
		{
			if (cstate->force_quote_flags[i])
			{
				if (is_first_col)
					appendStringInfoString(cdbcopy_cmd, "FORCE QUOTE ");
				else
					appendStringInfoString(cdbcopy_cmd, ", ");
				is_first_col = false;

				appendStringInfoString(cdbcopy_cmd,
									   quote_identifier(NameStr(attr[i]->attname)));
			}
		}

1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
		/* do NOT include HEADER. Header row is created by dispatcher COPY */
	}

}


/*
 * Copy from relation TO file. Starts a COPY TO command on each of
 * the executors and gathers all the results and writes it out.
 */
 void
CopyToDispatch(CopyState cstate)
1837
{
1838
	TupleDesc	tupDesc;
1839
	int			num_phys_attrs;
1840
	int			attr_count;
1841
	Form_pg_attribute *attr;
1842 1843 1844
	CdbCopy    *cdbCopy;
	StringInfoData cdbcopy_err;
	StringInfoData cdbcopy_cmd;
1845

1846
	tupDesc = cstate->rel->rd_att;
1847 1848
	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
1849
	attr_count = list_length(cstate->attnumlist);
1850

1851 1852 1853
	/* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
	cstate->fe_msgbuf = makeStringInfo();

1854 1855 1856 1857 1858 1859
	/*
	 * prepare to get COPY data from segDBs:
	 * 1 - re-construct the orignial COPY command sent from the client.
	 * 2 - execute a BEGIN DTM transaction.
	 * 3 - send the COPY command to all segment databases.
	 */
B
Bruce Momjian 已提交
1860

1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
	cdbCopy = makeCdbCopy(false);

	cdbCopy->partitions = RelationBuildPartitionDesc(cstate->rel, false);
	cdbCopy->skip_ext_partition = cstate->skip_ext_partition;

	/* XXX: lock all partitions */

	/* allocate memory for error and copy strings */
	initStringInfo(&cdbcopy_err);
	initStringInfo(&cdbcopy_cmd);

	/* create the command to send to QE's and store it in cdbcopy_cmd */
	CopyToCreateDispatchCommand(cstate,
								&cdbcopy_cmd,
								num_phys_attrs,
								attr);
1877

1878
	/*
1879 1880 1881 1882 1883 1884 1885
	 * Start a COPY command in every db of every segment in Greenplum Database.
	 *
	 * From this point in the code we need to be extra careful
	 * about error handling. ereport() must not be called until
	 * the COPY command sessions are closed on the executors.
	 * Calling ereport() will leave the executors hanging in
	 * COPY state.
1886
	 */
1887
	elog(DEBUG5, "COPY command sent to segdbs: %s", cdbcopy_cmd.data);
1888

1889 1890 1891 1892 1893
	PG_TRY();
	{
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data);
	}
	PG_CATCH();
1894
	{
1895 1896
		/* get error message from CopyStart */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
1897

1898 1899 1900 1901 1902 1903 1904
		/* TODO: end COPY in all the segdbs in progress */
		cdbCopyEnd(cdbCopy);

		ereport(LOG,
				(errcode(ERRCODE_CDB_INTERNAL_ERROR),
				 errmsg("%s", cdbcopy_err.data)));
		PG_RE_THROW();
1905
	}
1906 1907 1908 1909
	PG_END_TRY();

	/* if a header has been requested send the line */
	if (cstate->header_line)
1910
	{
1911 1912 1913
		ListCell   *cur;
		bool		hdr_delim = false;

1914 1915 1916
		/*
		 * For non-binary copy, we need to convert null_print to client
		 * encoding, because it will be sent directly with CopySendString.
1917 1918 1919 1920
		 *
		 * MPP: in here we only care about this if we need to print the
		 * header. We rely on the segdb server copy out to do the conversion
		 * before sending the data rows out. We don't need to repeat it here
1921
		 */
1922
		if (cstate->need_transcoding)
1923 1924 1925 1926 1927
			cstate->null_print = (char *)
				pg_server_to_custom(cstate->null_print,
									strlen(cstate->null_print),
									cstate->client_encoding,
									cstate->enc_conversion_proc);
1928

1929
		foreach(cur, cstate->attnumlist)
1930
		{
1931 1932
			int			attnum = lfirst_int(cur);
			char	   *colname;
B
Bruce Momjian 已提交
1933

1934 1935 1936
			if (hdr_delim)
				CopySendChar(cstate, cstate->delim[0]);
			hdr_delim = true;
1937

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

1940 1941 1942
			CopyAttributeOutCSV(cstate, colname, false,
								list_length(cstate->attnumlist) == 1);
		}
1943

1944 1945 1946
		/* add a newline and flush the data */
		CopySendEndOfRow(cstate);
	}
1947

1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
	/*
	 * This is the main work-loop. In here we keep collecting data from the
	 * COPY commands on the segdbs, until no more data is available. We
	 * keep writing data out a chunk at a time.
	 */
	while(true)
	{

		bool done;
		bool copy_cancel = (QueryCancelPending ? true : false);

		/* get a chunk of data rows from the QE's */
		done = cdbCopyGetData(cdbCopy, copy_cancel, &cstate->processed);

		/* send the chunk of data rows to destination (file or stdout) */
		if(cdbCopy->copy_out_buf.len > 0) /* conditional is important! */
		{
			/*
			 * in the dispatcher we receive chunks of whole rows with row endings.
			 * We don't want to use CopySendEndOfRow() b/c it adds row endings and
			 * also b/c it's intended for a single row at a time. Therefore we need
			 * to fill in the out buffer and just flush it instead.
			 */
			CopySendData(cstate, (void *) cdbCopy->copy_out_buf.data, cdbCopy->copy_out_buf.len);
			CopyToDispatchFlush(cstate);
		}

		if(done)
		{
			if(cdbCopy->remote_data_err || cdbCopy->io_errors)
				appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);

			break;
1981
		}
1982
	}
1983

1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
	/* we can throw the error now if QueryCancelPending was set previously */
	CHECK_FOR_INTERRUPTS();

	/*
	 * report all accumulated errors back to the client.
	 */
	if (cdbCopy->remote_data_err)
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("%s", cdbcopy_err.data)));
	if (cdbCopy->io_errors)
		ereport(ERROR,
				(errcode(ERRCODE_IO_ERROR),
				 errmsg("%s", cdbcopy_err.data)));

	pfree(cdbcopy_cmd.data);
	pfree(cdbcopy_err.data);
	pfree(cdbCopy);
}


/*
 * Copy from relation or query TO file.
 */
static void
CopyTo(CopyState cstate)
{
	TupleDesc	tupDesc;
	int			num_phys_attrs;
	Form_pg_attribute *attr;
	ListCell   *cur;
	List *target_rels = NIL;
	ListCell *lc;

2018
	if (cstate->rel)
2019
	{
2020 2021 2022 2023 2024 2025 2026 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
		if (cstate->partitions)
		{
			ListCell *lc;
			List *relids = all_partition_relids(cstate->partitions);

			foreach(lc, relids)
			{
				Oid relid = lfirst_oid(lc);
				Relation rel = heap_open(relid, AccessShareLock);

				target_rels = lappend(target_rels, rel);
			}
		}
		else
			target_rels = lappend(target_rels, cstate->rel);

		tupDesc = RelationGetDescr(cstate->rel);
	}
	else
		tupDesc = cstate->queryDesc->tupDesc;

	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
	cstate->null_print_client = cstate->null_print;		/* default */

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

	cstate->out_functions =
		(FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));

	/* Get info about the columns we need to process. */
	foreach(cur, cstate->attnumlist)
	{
		int			attnum = lfirst_int(cur);
		Oid			out_func_oid;
		bool		isvarlena;

		getTypeOutputInfo(attr[attnum - 1]->atttypid,
						  &out_func_oid,
						  &isvarlena);
		fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
	}
B
Bruce Momjian 已提交
2063

2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074
	/*
	 * Create a temporary memory context that we can reset once per row to
	 * 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.)
	 */
	cstate->rowcontext = AllocSetContextCreate(CurrentMemoryContext,
											   "COPY TO",
											   ALLOCSET_DEFAULT_MINSIZE,
											   ALLOCSET_DEFAULT_INITSIZE,
											   ALLOCSET_DEFAULT_MAXSIZE);
2075

2076 2077 2078 2079 2080 2081 2082 2083 2084
	/*
	 * we need to convert null_print to client
	 * encoding, because it will be sent directly with CopySendString.
	 */
	if (cstate->need_transcoding)
		cstate->null_print_client = pg_server_to_custom(cstate->null_print,
														cstate->null_print_len,
														cstate->client_encoding,
														cstate->enc_conversion_proc);
2085

2086 2087 2088 2089 2090
	/* if a header has been requested send the line */
	if (cstate->header_line)
	{
		/* header should not be printed in execute mode. */
		if (Gp_role != GP_ROLE_EXECUTE)
2091
		{
2092 2093 2094 2095 2096 2097
			bool		hdr_delim = false;

			foreach(cur, cstate->attnumlist)
			{
				int			attnum = lfirst_int(cur);
				char	   *colname;
2098

2099 2100 2101 2102 2103 2104 2105 2106 2107
				if (hdr_delim)
					CopySendChar(cstate, cstate->delim[0]);
				hdr_delim = true;

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

				CopyAttributeOutCSV(cstate, colname, false,
									list_length(cstate->attnumlist) == 1);
			}
2108

2109
			CopySendEndOfRow(cstate);
2110
		}
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182
	}

	if (cstate->rel)
	{
		foreach(lc, target_rels)
		{
			Relation rel = lfirst(lc);
			Datum	   *values;
			bool	   *nulls;
			HeapScanDesc scandesc = NULL;			/* used if heap table */
			AppendOnlyScanDesc aoscandesc = NULL;	/* append only table */

			tupDesc = RelationGetDescr(rel);
			attr = tupDesc->attrs;
			num_phys_attrs = tupDesc->natts;

			/*
			 * We need to update attnumlist because different partition
			 * entries might have dropped tables.
			 */
			cstate->attnumlist =
				CopyGetAttnums(tupDesc, rel, cstate->attnamelist);

			pfree(cstate->out_functions);
			cstate->out_functions =
				(FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));

			/* Get info about the columns we need to process. */
			foreach(cur, cstate->attnumlist)
			{
				int			attnum = lfirst_int(cur);
				Oid			out_func_oid;
				bool		isvarlena;

				getTypeOutputInfo(attr[attnum - 1]->atttypid,
								  &out_func_oid,
								  &isvarlena);
				fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
			}

			values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
			nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));

			if (RelationIsHeap(rel))
			{
				HeapTuple	tuple;

				scandesc = heap_beginscan(rel, ActiveSnapshot, 0, NULL);
				while ((tuple = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
				{
					CHECK_FOR_INTERRUPTS();

					/* Deconstruct the tuple ... faster than repeated heap_getattr */
					heap_deform_tuple(tuple, tupDesc, values, nulls);

					/* Format and send the data */
					CopyOneRowTo(cstate, HeapTupleGetOid(tuple), values, nulls);
				}

				heap_endscan(scandesc);
			}
			else if(RelationIsAoRows(rel))
			{
				MemTuple		tuple;
				TupleTableSlot	*slot = MakeSingleTupleTableSlot(tupDesc);
				MemTupleBinding *mt_bind = create_memtuple_binding(tupDesc);

				aoscandesc = appendonly_beginscan(rel, ActiveSnapshot, ActiveSnapshot, 0, NULL);

				while ((tuple = appendonly_getnext(aoscandesc, ForwardScanDirection, slot)) != NULL)
				{
					CHECK_FOR_INTERRUPTS();
2183

2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
					/* Extract all the values of the  tuple */
					slot_getallattrs(slot);
					values = slot_get_values(slot);
					nulls = slot_get_isnull(slot);

					/* Format and send the data */
					CopyOneRowTo(cstate, MemTupleGetOid(tuple, mt_bind), values, nulls);
				}

				ExecDropSingleTupleTableSlot(slot);

				appendonly_endscan(aoscandesc);
			}
			else if(RelationIsAoCols(rel))
			{
				AOCSScanDesc scan = NULL;
				TupleTableSlot *slot = MakeSingleTupleTableSlot(tupDesc);
				bool *proj = NULL;

				int nvp = tupDesc->natts;
				int i;

				if (tupDesc->tdhasoid)
				{
				    elog(ERROR, "OIDS=TRUE is not allowed on tables that use column-oriented storage. Use OIDS=FALSE");
				}

				proj = palloc(sizeof(bool) * nvp);
				for(i=0; i<nvp; ++i)
				    proj[i] = true;

				scan = aocs_beginscan(rel, ActiveSnapshot, ActiveSnapshot, NULL /* relationTupleDesc */, proj);
				for(;;)
				{
				    CHECK_FOR_INTERRUPTS();

				    aocs_getnext(scan, ForwardScanDirection, slot);
				    if (TupIsNull(slot))
				        break;

				    slot_getallattrs(slot);
				    values = slot_get_values(slot);
				    nulls = slot_get_isnull(slot);

					CopyOneRowTo(cstate, InvalidOid, values, nulls);
				}

				ExecDropSingleTupleTableSlot(slot);
				aocs_endscan(scan);

				pfree(proj);
			}
			else if(RelationIsExternal(rel))
			{
				/* should never get here */
				if (!cstate->skip_ext_partition)
				{
				    elog(ERROR, "internal error");
				}
			}
			else
			{
				/* should never get here */
				Assert(false);
			}

			/* partition table, so close */
			if (cstate->partitions)
				heap_close(rel, NoLock);
		}
2254 2255 2256
	}
	else
	{
2257 2258
		Assert(Gp_role != GP_ROLE_EXECUTE);

2259 2260 2261 2262 2263 2264 2265
		/* run the plan --- the dest receiver will send tuples */
		ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L);
	}

	MemoryContextDelete(cstate->rowcontext);
}

2266 2267 2268 2269 2270 2271 2272 2273
void
CopyOneCustomRowTo(CopyState cstate, bytea *value)
{	
	appendBinaryStringInfo(cstate->fe_msgbuf, 
						   VARDATA_ANY((void *) value), 
						   VARSIZE_ANY_EXHDR((void *) value));
}

2274 2275 2276
/*
 * Emit one row during CopyTo().
 */
2277 2278
void
CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *isnulls)
2279 2280 2281 2282 2283 2284 2285 2286 2287 2288
{
	bool		need_delim = false;
	FmgrInfo   *out_functions = cstate->out_functions;
	MemoryContext oldcontext;
	ListCell   *cur;
	char	   *string;

	MemoryContextReset(cstate->rowcontext);
	oldcontext = MemoryContextSwitchTo(cstate->rowcontext);

2289 2290 2291
	/* Text format has no per-tuple header, but send OID if wanted */
	/* Assume digits don't need any quoting or encoding conversion */
	if (cstate->oids)
2292
	{
2293 2294 2295 2296
		string = DatumGetCString(DirectFunctionCall1(oidout,
													 ObjectIdGetDatum(tupleOid)));
		CopySendString(cstate, string);
		need_delim = true;
2297 2298 2299 2300 2301
	}

	foreach(cur, cstate->attnumlist)
	{
		int			attnum = lfirst_int(cur);
2302

2303 2304 2305 2306 2307 2308 2309
		bool		isnull = isnulls[attnum-1];
		Datum		value = values[attnum-1];

		if (need_delim)
			CopySendChar(cstate, cstate->delim[0]);

		need_delim = true;
2310

2311 2312
		if (isnull)
		{
2313
			CopySendString(cstate, cstate->null_print_client);
2314 2315 2316
		}
		else
		{
2317 2318
			char		quotec = cstate->quote ? cstate->quote[0] : '\0';

2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335
			/* int2out or int4out ? */
			if (out_functions[attnum -1].fn_oid == 39 ||  /* int2out or int4out */
				out_functions[attnum -1].fn_oid == 43 )
			{
				char tmp[33];
				/*
				 * The standard postgres way is to call the output function, but that involves one or more pallocs,
				 * and a call to sprintf, followed by a conversion to client charset.
				 * Do a fast conversion to string instead.
				 */

				if (out_functions[attnum -1].fn_oid ==  39)
					pg_itoa(DatumGetInt16(value),tmp);
				else
					pg_ltoa(DatumGetInt32(value),tmp);

				/*
2336 2337
				 * Integers don't need quoting, or transcoding to client char
				 * set. We still quote them if FORCE QUOTE was used, though.
2338
				 */
2339 2340
				if (cstate->force_quote_flags[attnum - 1])
					CopySendChar(cstate, quotec);
2341
				CopySendData(cstate, tmp, strlen(tmp));
2342 2343
				if (cstate->force_quote_flags[attnum - 1])
					CopySendChar(cstate, quotec);
2344 2345 2346 2347 2348 2349
			}
			else if (out_functions[attnum -1].fn_oid == 1702)   /* numeric_out */
			{
				string = OutputFunctionCall(&out_functions[attnum - 1],
																value);
				/*
2350 2351
				 * Numerics don't need quoting, or transcoding to client char
				 * set. We still quote them if FORCE QUOTE was used, though.
2352
				 */
2353 2354
				if (cstate->force_quote_flags[attnum - 1])
					CopySendChar(cstate, quotec);
2355
				CopySendData(cstate, string, strlen(string));
2356 2357
				if (cstate->force_quote_flags[attnum - 1])
					CopySendChar(cstate, quotec);
2358 2359
			}
			else
2360
			{
2361 2362 2363 2364 2365 2366
				string = OutputFunctionCall(&out_functions[attnum - 1],
											value);
				if (cstate->csv_mode)
					CopyAttributeOutCSV(cstate, string,
										cstate->force_quote_flags[attnum - 1],
										list_length(cstate->attnumlist) == 1);
2367
				else
2368
					CopyAttributeOutText(cstate, string);
2369
			}
2370 2371 2372
		}
	}

2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384
	/*
	 * Finish off the row: write it to the destination, and update the count.
	 * However, if we're in the context of a writable external table, we let 
	 * the caller do it - send the data to its local external source (see
	 * external_insert() ).
	 */
	if(cstate->copy_dest != COPY_EXTERNAL_SOURCE)
	{
		CopySendEndOfRow(cstate);
		cstate->processed++;
	}
	
2385
	MemoryContextSwitchTo(oldcontext);
2386 2387
}

2388

2389
/*
2390 2391 2392 2393 2394 2395
 * CopyFromCreateDispatchCommand
 *
 * The COPY command that needs to get dispatched to the QE's isn't necessarily
 * the same command that arrived from the parser to the QD. For example, we
 * always change filename to STDIN, we may pre-evaluate constant values or
 * functions on the QD and send them to the QE with an extended column list.
2396
 */
2397 2398 2399 2400 2401 2402 2403 2404 2405 2406
static void CopyFromCreateDispatchCommand(CopyState cstate,
										  StringInfo cdbcopy_cmd,
										  GpPolicy  *policy,
										  AttrNumber	num_phys_attrs,
										  AttrNumber	num_defaults,
										  AttrNumber	p_nattrs,
										  AttrNumber	h_attnum,
										  int *defmap,
										  ExprState **defexprs,
										  Form_pg_attribute *attr)
2407
{
2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425
	ListCell   *cur;
	bool		is_first_col;
	int			i,
				p_index = 0;
	AttrNumber	extra_attr_count = 0; /* count extra attributes we add in the dispatcher COPY
										 usually non constant defaults we pre-evaluate in here */

	Assert(Gp_role == GP_ROLE_DISPATCH);

	/* append schema and tablename */
	appendStringInfo(cdbcopy_cmd, "COPY %s.%s",
					 quote_identifier(get_namespace_name(RelationGetNamespace(cstate->rel))),
					 quote_identifier(RelationGetRelationName(cstate->rel)));
	/*
	 * append column list. NOTE: if not specified originally, attnumlist will
	 * include all non-dropped columns of the table by default
	 */
	if(num_phys_attrs > 0) /* don't append anything for zero column table */
2426
	{
2427 2428
		is_first_col = true;
		foreach(cur, cstate->attnumlist)
2429
		{
2430 2431
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
2432

2433 2434 2435 2436 2437 2438 2439 2440 2441
			/* We don't add dropped attributes */
			if (attr[m]->attisdropped)
				continue;

			/* append column string. quote it if needed */
			appendStringInfo(cdbcopy_cmd, (is_first_col ? "(%s" : ",%s"),
							 quote_identifier(NameStr(attr[m]->attname)));

			is_first_col = false;
2442
		}
2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459

		/*
		 * In order to maintain consistency between the primary and mirror segment data, we
		 * want to evaluate all table columns that are not participating in this COPY command
		 * and have a non-constant default values on the dispatcher. If we let them evaluate
		 * on the primary and mirror executors separately - they will get different values.
		 * Also, if the distribution column is not participating and it has any default value,
		 * we have to evaluate it on the dispatcher only too, so that it wouldn't hash as a null
		 * and inserted as a default value on the segment databases.
		 *
		 * Therefore, we include these columns in the column list for the executor COPY.
		 * The default values will be evaluated on the dispatcher COPY and the results for
		 * the added columns will be appended to each data row that is shipped to the segments.
		 */
		extra_attr_count = 0;

		for (i = 0; i < num_defaults; i++)
2460
		{
2461 2462 2463 2464
			bool add_to_list = false;

			/* check 1: is this default for a distribution column? */
			for (p_index = 0; p_index < p_nattrs; p_index++)
2465
			{
2466
				h_attnum = policy->attrs[p_index];
2467

2468 2469
				if(h_attnum - 1 == defmap[i])
					add_to_list = true;
2470
			}
2471 2472 2473 2474 2475 2476

			/* check 2: is this a non constant default? */
			if(defexprs[i]->expr->type != T_Const)
				add_to_list = true;

			if(add_to_list)
2477
			{
2478 2479 2480 2481 2482 2483 2484 2485 2486 2487
				/* We don't add dropped attributes */
				if (attr[defmap[i]]->attisdropped)
					continue;

				/* append column string. quote it if needed */
				appendStringInfo(cdbcopy_cmd, (is_first_col ? "(%s" : ",%s"),
								 quote_identifier(NameStr(attr[defmap[i]]->attname)));

				extra_attr_count++;
				is_first_col = false;
2488 2489
			}
		}
2490 2491 2492

		if (!is_first_col)
			appendStringInfo(cdbcopy_cmd, ")");
2493
	}
2494

2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506
	/*
	 * NOTE: we used to always pass STDIN here to the QEs. But since we want
	 * the QEs to know the original file name for recording it in an error table
	 * (if they use one) we actually pass the filename here, and in the QE COPY
	 * we get it, save it, and then always revert back to actually using STDIN.
	 * (if we originally use STDIN we just pass it along and record that in the
	 * error table).
	 */
	if(cstate->filename)
		appendStringInfo(cdbcopy_cmd, " FROM %s WITH", quote_literal_internal(cstate->filename));
	else
		appendStringInfo(cdbcopy_cmd, " FROM STDIN WITH");
2507

2508 2509
	if (cstate->oids)
		appendStringInfo(cdbcopy_cmd, " OIDS");
2510

2511 2512
	appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
	appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));
2513

2514 2515 2516
	/* if default escape in text format ("\") leave expression out */
	if (!cstate->csv_mode && strcmp(cstate->escape, "\\") != 0)
		appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));
2517

2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575
	/* if EOL is already defined it means that NEWLINE was declared. pass it along */
	if (cstate->eol_type != EOL_UNKNOWN)
	{
		Assert(cstate->eol_str);
		appendStringInfo(cdbcopy_cmd, " NEWLINE AS '%s'", escape_quotes(cstate->eol_str));
	}
		
	if (cstate->csv_mode)
	{
		appendStringInfo(cdbcopy_cmd, " CSV");
		appendStringInfo(cdbcopy_cmd, " QUOTE AS E'%s'", escape_quotes(cstate->quote));
		appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));

		if(cstate->force_notnull)
		{
			ListCell   *l;

			is_first_col = true;
			appendStringInfo(cdbcopy_cmd, " FORCE NOT NULL");

			foreach(l, cstate->force_notnull)
			{
				const char	   *col_name = strVal(lfirst(l));

				appendStringInfo(cdbcopy_cmd, (is_first_col ? " %s" : ",%s"),
								 quote_identifier(col_name));
				is_first_col = false;
			}
		}
		/* do NOT include HEADER. Header row is "swallowed" by dispatcher COPY */
	}

	if (cstate->fill_missing)
		appendStringInfo(cdbcopy_cmd, " FILL MISSING FIELDS");

	/* add single row error handling clauses if necessary */
	if (cstate->errMode != ALL_OR_NOTHING)
	{
		if (cstate->errMode == SREH_LOG)
		{
			if (cstate->cdbsreh->errtbl)
			{
				Relation	errtbl = cstate->cdbsreh->errtbl;
				char	   *namespace, *relname;

				namespace = get_namespace_name(RelationGetNamespace(errtbl));
				relname = RelationGetRelationName(errtbl);
				appendStringInfo(cdbcopy_cmd, " LOG ERRORS INTO %s.%s",
								 quote_identifier(namespace),
								 quote_identifier(relname));
			}
			else
				appendStringInfoString(cdbcopy_cmd, " LOG ERRORS");
		}

		appendStringInfo(cdbcopy_cmd, " SEGMENT REJECT LIMIT %d %s",
						 cstate->cdbsreh->rejectlimit, (cstate->cdbsreh->is_limit_in_rows ? "ROWS" : "PERCENT"));
	}
2576

2577
}
2578

2579 2580 2581
/*
 * Copy FROM file to relation.
 */
2582 2583
void
CopyFromDispatch(CopyState cstate)
2584
{
2585
	TupleDesc	tupDesc;
2586
	Form_pg_attribute *attr;
B
Bruce Momjian 已提交
2587 2588 2589
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
2590
	FmgrInfo   *in_functions;
2591
	FmgrInfo   *out_functions; /* for handling defaults in Greenplum Database */
2592
	Oid		   *typioparams;
2593
	int			attnum;
B
Bruce Momjian 已提交
2594
	int			i;
2595
	int			p_index;
2596
	Oid			in_func_oid;
2597
	Oid			out_func_oid;
2598
	Datum	   *values;
2599 2600 2601
	bool	   *nulls;
	int		   *attr_offsets;
	int			total_rejeted_from_qes = 0;
2602
	bool		isnull;
2603
	bool	   *isvarlena;
2604
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
2605
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
2606
	bool		file_has_oids = false;
2607
	int		   *defmap;
2608
	ExprState **defexprs;		/* array of default att expressions */
B
Bruce Momjian 已提交
2609
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
2610
	MemoryContext oldcontext = CurrentMemoryContext;
2611
	ErrorContextCallback errcontext;
2612 2613 2614 2615
	bool		no_more_data = false;
	ListCell   *cur;
	bool		cur_row_rejected = false;
	CdbCopy    *cdbCopy;
2616

2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630
	/*
	 * This stringInfo will contain 2 types of error messages:
	 *
	 * 1) Data errors refer to errors that are a result of inappropriate
	 *	  input data or constraint violations. All data error messages
	 *	  from the segment databases will be added to this variable and
	 *	  reported back to the client at the end of the copy command
	 *	  execution on the dispatcher.
	 * 2) Any command execution error that occurs during this COPY session.
	 *	  Such errors will usually be failure to send data over the network,
	 *	  a COPY command that was rejected by the segment databases or any I/O
	 *	  error.
	 */
	StringInfoData cdbcopy_err;
2631

2632 2633 2634 2635
	/*
	 * a reconstructed and modified COPY command that is dispatched to segments.
	 */
	StringInfoData cdbcopy_cmd;
2636

2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650
	/*
	 * Variables for cdbpolicy
	 */
	GpPolicy  *policy; /* the partitioning policy for this table */
	AttrNumber	p_nattrs; /* num of attributes in the distribution policy */
	Oid       *p_attr_types;	/* types for each policy attribute */

	/* variables for partitioning */
	Datum      *part_values = NULL;
	Oid		   *part_attr_types = NULL; /* types for partitioning */
	Oid		   *part_typio = NULL;
	FmgrInfo   *part_infuncs = NULL;
	AttrNumber *part_attnum = NULL;
	int			part_attnums = 0;
2651

2652 2653 2654 2655 2656
	/*
	 * Variables for original row number tracking
	 */
	StringInfoData line_buf_with_lineno;
	int			original_lineno_for_qe;
2657

2658 2659 2660
	/*
	 * Variables for cdbhash
	 */
2661

2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682
	/*
	 * In the case of partitioned tables with children that have different
	 * distribution policies, we maintain a hash table of CdbHashs and
	 * GpPolicies for each child table. We lazily add them to the hash --
	 * when a partition is returned which we haven't seen before, we makeCdbHash
	 * and copy the policy over.
	 */
	typedef struct
	{
		Oid			relid;
		CdbHash    *cdbHash;		/* a CdbHash API object		 */
		GpPolicy   *policy;			/* policy for this cdb hash */
	} cdbhashdata;

	/* The actually hash table. Only initialised if we need it. */
	HTAB *hashmap = NULL;

	CdbHash *cdbHash = NULL;
	AttrNumber	h_attnum;		/* hash key attribute number */
	Datum		h_key;			/* hash key value			 */
	unsigned int target_seg = 0;	/* result segment of cdbhash */
2683

2684
	tupDesc = RelationGetDescr(cstate->rel);
2685
	attr = tupDesc->attrs;
2686
	num_phys_attrs = tupDesc->natts;
2687
	attr_count = list_length(cstate->attnumlist);
2688
	num_defaults = 0;
2689 2690 2691 2692 2693 2694 2695
	h_attnum = 0;

	/*
	 * Init original row number tracking vars
	 */
	initStringInfo(&line_buf_with_lineno);
	original_lineno_for_qe = 1;
2696 2697

	/*
2698
	 * We need a ResultRelInfo so we can use the regular executor's
2699 2700
	 * index-entry-making machinery.  (There used to be a huge amount of
	 * code here that basically duplicated execUtils.c ...)
2701
	 */
2702
	resultRelInfo = makeNode(ResultRelInfo);
B
Bruce Momjian 已提交
2703
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
2704 2705
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
2706 2707
	if (resultRelInfo->ri_TrigDesc)
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
2708 2709 2710
            palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
    resultRelInfo->ri_TrigInstrument = NULL;
    ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
2711

2712
	ExecOpenIndices(resultRelInfo);
2713

2714 2715 2716
	estate->es_result_relations = resultRelInfo;
	estate->es_num_result_relations = 1;
	estate->es_result_relation_info = resultRelInfo;
2717

2718 2719
	econtext = GetPerTupleExprContext(estate);

2720
	/*
2721
	 * Pick up the required catalog information for each attribute in the
2722 2723
	 * relation, including the input function, the element type (to pass
	 * to the input function), and info about defaults and constraints.
2724
	 */
2725
	in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2726
	out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2727
	typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
2728 2729
	defmap = (int *) palloc(num_phys_attrs * sizeof(int));
	defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
2730 2731
	isvarlena = (bool *) palloc(num_phys_attrs * sizeof(bool));

2732

2733
	for (attnum = 1; attnum <= num_phys_attrs; attnum++)
2734
	{
2735
		/* We don't need info for dropped attributes */
2736
		if (attr[attnum - 1]->attisdropped)
2737
			continue;
B
Bruce Momjian 已提交
2738

2739
		/* Fetch the input function and typioparam info */
2740 2741
		getTypeInputInfo(attr[attnum - 1]->atttypid,
						 &in_func_oid, &typioparams[attnum - 1]);
2742
		fmgr_info(in_func_oid, &in_functions[attnum - 1]);
B
Bruce Momjian 已提交
2743

2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755
		/*
		 * Fetch the output function and typioparam info. We need it
		 * for handling default functions on the dispatcher COPY, if
		 * there are any.
		 */
		getTypeOutputInfo(attr[attnum - 1]->atttypid,
						  &out_func_oid,
						  &isvarlena[attnum - 1]);
		fmgr_info(out_func_oid, &out_functions[attnum - 1]);

		/* TODO: is force quote array necessary for default conversion */

2756
		/* Get default info if needed */
2757
		if (!list_member_int(cstate->attnumlist, attnum))
2758
		{
2759
			/* attribute is NOT to be copied from input */
2760
			/* use default value if one exists */
2761
			Node	   *defexpr = build_column_default(cstate->rel, attnum);
2762 2763

			if (defexpr != NULL)
B
Bruce Momjian 已提交
2764
			{
2765 2766
				defexprs[num_defaults] = ExecPrepareExpr((Expr *) defexpr,
														 estate);
2767
				defmap[num_defaults] = attnum - 1;
2768
				num_defaults++;
2769
			}
2770
		}
2771 2772
	}

2773
	/*
2774 2775 2776 2777 2778 2779 2780
	 * prepare to COPY data into segDBs:
	 * - set table partitioning information
	 * - set append only table relevant info for dispatch.
	 * - get the distribution policy for this table.
	 * - build a COPY command to dispatch to segdbs.
	 * - dispatch the modified COPY command to all segment databases.
	 * - prepare cdbhash for hashing on row values.
2781
	 */
2782
	cdbCopy = makeCdbCopy(true);
2783

2784 2785
	estate->es_result_partitions = cdbCopy->partitions =
		RelationBuildPartitionDesc(cstate->rel, false);
2786

2787
	CopyInitPartitioningState(estate);
2788

2789 2790
	if (list_length(cstate->ao_segnos) > 0)
		cdbCopy->ao_segnos = cstate->ao_segnos;
2791

2792 2793 2794
	/* add cdbCopy reference to cdbSreh (if needed) */
	if (cstate->errMode != ALL_OR_NOTHING)
		cstate->cdbsreh->cdbcopy = cdbCopy;
2795

2796 2797 2798 2799
	/* get the CDB policy for this table and prepare for hashing */
	if (estate->es_result_partitions &&
		!partition_policies_equal(cstate->rel->rd_cdbpolicy,
								  estate->es_result_partitions))
2800
	{
2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831
		/*
		 * This is a partitioned table that has multiple, different
		 * distribution policies.
		 *
		 * We build up a fake policy comprising the set of all columns used
		 * to distribute all children in the partition configuration. That way
		 * we're sure to parse all necessary columns in the input data and we
		 * have all column types handy.
		 */
		List *cols = NIL;
		ListCell *lc;
		HASHCTL hash_ctl;

		partition_get_policies_attrs(estate->es_result_partitions,
									 cstate->rel->rd_cdbpolicy,
									 &cols);
        MemSet(&hash_ctl, 0, sizeof(hash_ctl));
        hash_ctl.keysize = sizeof(Oid);
        hash_ctl.entrysize = sizeof(cdbhashdata);
        hash_ctl.hash = oid_hash;
        hash_ctl.hcxt = CurrentMemoryContext;

        hashmap = hash_create("partition cdb hash map",
                              100 /* XXX: need a better value, but what? */,
                              &hash_ctl,
                              HASH_ELEM | HASH_FUNCTION | HASH_CONTEXT);
		p_nattrs = list_length(cols);
		policy = palloc(sizeof(GpPolicy) + sizeof(AttrNumber) * p_nattrs);
		i = 0;
		foreach(lc, cols)
			policy->attrs[i++] = lfirst_int(lc);
2832

2833 2834
	}
	else
2835
	{
2836
		policy = GpPolicyCopy(CurrentMemoryContext, cstate->rel->rd_cdbpolicy);
2837

2838 2839 2840 2841 2842 2843 2844
		if (policy)
			p_nattrs = policy->nattrs;	/* number of partitioning keys */
		else
			p_nattrs = 0;
		/* Create hash API reference */
		cdbHash = makeCdbHash(cdbCopy->total_segs, HASH_FNV_1);
	}
2845

2846

2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
	/*
	 * Extract types for each partition key from the tuple descriptor,
	 * and convert them when necessary. We don't want to do this
	 * for each tuple since get_typtype() is quite expensive when called
	 * lots of times.
	 *
	 * The array key for p_attr_types is the attribute number of the attribute
	 * in question.
	 */
	p_attr_types = (Oid *)palloc0(num_phys_attrs * sizeof(Oid));
	for (i = 0; i < p_nattrs; i++)
	{
		h_attnum = policy->attrs[i];
2860

2861 2862 2863 2864 2865 2866 2867
		/*
		 * get the data type of this attribute. If it's an
		 * array type use anyarray, or else just use as is.
		 */
		if (attr[h_attnum - 1]->attndims > 0)
			p_attr_types[h_attnum - 1] = ANYARRAYOID;
		else
2868
		{
2869 2870 2871 2872 2873 2874 2875
			/* If this type is a domain type, get its base type. */
			p_attr_types[h_attnum - 1] = attr[h_attnum - 1]->atttypid;
			if (get_typtype(p_attr_types[h_attnum - 1]) == 'd')
			    p_attr_types[h_attnum - 1] =
					getBaseType(p_attr_types[h_attnum - 1]);
		}
	}
2876

2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891
	/* allocate memory for error and copy strings */
	initStringInfo(&cdbcopy_err);
	initStringInfo(&cdbcopy_cmd);

	/* store the COPY command string in cdbcopy_cmd */
	CopyFromCreateDispatchCommand(cstate,
								  &cdbcopy_cmd,
								  policy,
								  num_phys_attrs,
								  num_defaults,
								  p_nattrs,
								  h_attnum,
								  defmap,
								  defexprs,
								  attr);
2892

2893 2894 2895 2896 2897 2898 2899 2900
	/*
	 * for optimized parsing - get the last field number in the
	 * file that we need to parse to have all values for the hash keys.
	 * (If the table has an empty distribution policy, then we don't need
	 * to parse any attributes really... just send the row away using
	 * a special cdbhash function designed for this purpose).
	 */
	cstate->last_hash_field = 0;
2901

2902 2903 2904
	for (p_index = 0; p_index < p_nattrs; p_index++)
	{
		i = 1;
2905

2906 2907 2908 2909 2910 2911 2912
		/*
		 * for this partitioning key, search for its location in the attr list.
		 * (note that fields may be out of order).
		 */
		foreach(cur, cstate->attnumlist)
		{
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
2913

2914 2915 2916 2917
			if (attnum == policy->attrs[p_index])
			{
				if (i > cstate->last_hash_field)
					cstate->last_hash_field = i;
2918
			}
B
Bruce Momjian 已提交
2919

2920
			if (estate->es_result_partitions)
2921
			{
2922
				if (attnum == estate->es_partition_state->max_partition_attr)
B
Bruce Momjian 已提交
2923
				{
2924 2925 2926
					if (i > cstate->last_hash_field)
						cstate->last_hash_field = i;
				}				
2927
			}
B
Bruce Momjian 已提交
2928

2929
			i++;
2930
		}
2931
	}
2932

2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956
	/*
	 * Dispatch the COPY command.
	 *
	 * From this point in the code we need to be extra careful about error
	 * handling. ereport() must not be called until the COPY command sessions
	 * are closed on the executors. Calling ereport() will leave the executors
	 * hanging in COPY state.
	 *
	 * For errors detected by the dispatcher, we save the error message in
	 * cdbcopy_err StringInfo, move on to closing all COPY sessions on the
	 * executors and only then raise an error. We need to make sure to TRY/CATCH
	 * all other errors that may be raised from elsewhere in the backend. All
	 * error during COPY on the executors will be detected only when we end the
	 * COPY session there, so we are fine there.
	 */
	elog(DEBUG5, "COPY command sent to segdbs: %s", cdbcopy_cmd.data);
	PG_TRY();
	{
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data);
	}
	PG_CATCH();
	{
		/* get error message from CopyStart */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
2957

2958 2959
		/* end COPY in all the segdbs in progress */
		cdbCopyEnd(cdbCopy);
2960

2961 2962
		/* get error message from CopyEnd */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
2963

2964 2965 2966 2967 2968 2969
		ereport(LOG,
				(errcode(ERRCODE_CDB_INTERNAL_ERROR),
				 errmsg("%s", cdbcopy_err.data)));
		PG_RE_THROW();
	}
	PG_END_TRY();
2970

2971 2972 2973 2974
	/*
	 * Prepare to catch AFTER triggers.
	 */
	//AfterTriggerBeginQuery();
2975

2976 2977 2978 2979 2980 2981 2982 2983
	/*
	 * 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.
	 */
	//ExecBSInsertTriggers(estate, resultRelInfo);
B
Bruce Momjian 已提交
2984

2985
	file_has_oids = cstate->oids;	/* must rely on user to tell us this... */
2986

2987 2988 2989
	values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
	nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
	attr_offsets = (int *) palloc(num_phys_attrs * sizeof(int));
2990

2991 2992 2993 2994 2995 2996
	/* Set up callback to identify error line number */
	errcontext.callback = copy_in_error_callback;
	errcontext.arg = (void *) cstate;
	errcontext.previous = error_context_stack;
	error_context_stack = &errcontext;
	cstate->err_loc_type = ROWNUM_ORIGINAL;
2997

2998
	CopyInitDataParser(cstate);
2999

3000 3001 3002
	do
	{
		size_t		bytesread = 0;
3003

3004 3005 3006 3007
		/* read a chunk of data into the buffer */
		PG_TRY();
		{
			bytesread = CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);
3008
		}
3009
		PG_CATCH();
3010
		{
3011
			/*
3012 3013 3014 3015
			 * If we are here, we got some kind of communication error
			 * with the client or a bad protocol message. clean up and
			 * re-throw error. Note that we don't handle this error in
			 * any special way in SREH mode as it's not a data error.
3016
			 */
3017 3018
			cdbCopyEnd(cdbCopy);
			PG_RE_THROW();
3019
		}
3020
		PG_END_TRY();
3021

3022
		cstate->raw_buf_done = false;
3023

3024 3025 3026
		/* set buffer pointers to beginning of the buffer */
		cstate->begloc = cstate->raw_buf;
		cstate->raw_buf_index = 0;
3027

3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049
		/*
		 * continue if some bytes were read or if we didn't reach EOF. if we
		 * both reached EOF _and_ no bytes were read, quit the loop we are
		 * done
		 */
		if (bytesread > 0 || !cstate->fe_eof)
		{
			/* on first time around just throw the header line away */
			if (cstate->header_line)
			{
				PG_TRY();
				{
					cstate->line_done = cstate->csv_mode ?
						CopyReadLineCSV(cstate, bytesread) :
						CopyReadLineText(cstate, bytesread);
				}
				PG_CATCH();
				{
					/*
					 * TODO: use COPY_HANDLE_ERROR here, but make sure to
					 * ignore this error per the "note:" below.
					 */
3050

3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
					/*
					 * got here? encoding conversion error occured on the
					 * header line (first row).
					 */
					if(cstate->errMode == ALL_OR_NOTHING)
					{
						/* re-throw error and abort */
						cdbCopyEnd(cdbCopy);
						PG_RE_THROW();
					}
					else
					{
						/* SREH - release error state */
						if(!elog_dismiss(DEBUG5))
							PG_RE_THROW(); /* hope to never get here! */
3066

3067 3068 3069 3070 3071 3072 3073 3074
						/*
						 * note: we don't bother doing anything special here.
						 * we are never interested in logging a header line
						 * error. just continue the workflow.
						 */
					}
				}
				PG_END_TRY();
B
Bruce Momjian 已提交
3075

3076 3077
				cstate->cur_lineno++;
				RESET_LINEBUF;
V
Vadim B. Mikheev 已提交
3078

3079 3080
				cstate->header_line = false;
			}
3081

3082 3083 3084 3085 3086 3087
			while (!cstate->raw_buf_done)
			{
				Oid			loaded_oid = InvalidOid;
				GpPolicy   *part_policy = NULL; /* policy for specific part */
				AttrNumber	part_p_nattrs = 0; /* partition policy max attno */
				CdbHash	   *part_hash = NULL; /* hash for the part policy */
3088

3089 3090 3091 3092 3093 3094
				if (QueryCancelPending)
				{
					/* quit processing loop */
					no_more_data = true;
					break;
				}
3095

3096 3097
				/* Reset the per-tuple exprcontext */
				ResetPerTupleExprContext(estate);
3098

3099 3100
				/* Switch into its memory context */
				MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3101

3102 3103 3104 3105
				/* Initialize all values for row to NULL */
				MemSet(values, 0, num_phys_attrs * sizeof(Datum));
				MemSet(nulls, true, num_phys_attrs * sizeof(bool));
				MemSet(attr_offsets, 0, num_phys_attrs * sizeof(int));
3106

3107 3108
				/* Get the line number of the first line of this data row */
				original_lineno_for_qe = cstate->cur_lineno + 1;
3109

3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
				PG_TRY();
				{
					/* Actually read the line into memory here */
					cstate->line_done = cstate->csv_mode ?
						CopyReadLineCSV(cstate, bytesread) :
						CopyReadLineText(cstate, bytesread);
				}
				PG_CATCH();
				{
					/* got here? encoding conversion/check error occurred */
					COPY_HANDLE_ERROR;
				}
				PG_END_TRY();
3123

3124 3125 3126 3127 3128
				if(cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
				}
3129 3130


3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
				if(!cstate->line_done)
				{
					/*
					 * if eof reached, and no data in line_buf,
					 * we don't need to do att parsing
					 */
					if (cstate->fe_eof && cstate->line_buf.len == 0)
					{
						break;
					}
					/*
					 * We did not finish reading a complete data line.
					 *
					 * If eof is not yet reached, we skip att parsing
					 * and read more data. But if eof _was_ reached it means
					 * that the original last data line is defective and
					 * we want to catch that error later on.
					 */
					if (!cstate->fe_eof || cstate->end_marker)
						break;
				}
3152

3153 3154 3155
				if (file_has_oids)
				{
					char	   *oid_string;
3156

3157 3158
					/* can't be in CSV mode here */
					oid_string = CopyReadOidAttr(cstate, &isnull);
3159

3160 3161 3162
					if (isnull)
					{
						/* got here? null in OID column error */
3163

3164 3165 3166 3167
						if(cstate->errMode == ALL_OR_NOTHING)
						{
							/* report error and abort */
							cdbCopyEnd(cdbCopy);
3168

3169 3170 3171 3172 3173 3174 3175 3176 3177 3178
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("null OID in COPY data.")));
						}
						else
						{
							/* SREH */
							cstate->cdbsreh->rejectcount++;
							cur_row_rejected = true;
						}
3179

3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
					}
					else
					{
						PG_TRY();
						{
							cstate->cur_attname = "oid";
							loaded_oid = DatumGetObjectId(DirectFunctionCall1(oidin,
										   CStringGetDatum(oid_string)));
						}
						PG_CATCH();
						{
							/* got here? oid column conversion failed */
							COPY_HANDLE_ERROR;
						}
						PG_END_TRY();
3195

3196 3197 3198 3199 3200 3201
						if (loaded_oid == InvalidOid)
						{
							if(cstate->errMode == ALL_OR_NOTHING)
							{
								/* report error and abort */
								cdbCopyEnd(cdbCopy);
3202

3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213
								ereport(ERROR,
										(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
										 errmsg("invalid OID in COPY data.")));
							}
							else
							{
								/* SREH */
								cstate->cdbsreh->rejectcount++;
								cur_row_rejected = true;
							}
						}
3214

3215 3216
						cstate->cur_attname = NULL;
					}
B
Bruce Momjian 已提交
3217

3218 3219 3220 3221 3222 3223
					if(cur_row_rejected)
					{
						ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
						QD_GOTO_NEXT_ROW;
					}
				}
B
Bruce Momjian 已提交
3224

3225

3226 3227 3228 3229 3230 3231 3232 3233 3234
				PG_TRY();
				{
					/*
					 * parse and convert the data line attributes.
					 */
					if (cstate->csv_mode)
						CopyReadAttributesCSV(cstate, nulls, attr_offsets, num_phys_attrs, attr);
					else
						CopyReadAttributesText(cstate, nulls, attr_offsets, num_phys_attrs, attr);
3235

3236 3237 3238 3239 3240 3241 3242
					attr_get_key(cstate, cdbCopy,
								 original_lineno_for_qe,
								 target_seg,
								 p_nattrs, policy->attrs,
								 attr, attr_offsets, nulls,
							   	 in_functions, typioparams,
								 values);
3243

3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254
					/*
					 * Now compute defaults for only:
					 * 1 - the distribution column,
					 * 2 - any other column with a non-constant default expression
					 * (such as a function) that is, of course, if these columns
					 * not provided by the input data.
					 * Anything not processed here or above will remain NULL.
					 */
					for (i = 0; i < num_defaults; i++)
					{
						bool compute_default = false;
B
Bruce Momjian 已提交
3255

3256 3257 3258 3259
						/* check 1: is this default for a distribution column? */
						for (p_index = 0; p_index < p_nattrs; p_index++)
						{
							h_attnum = policy->attrs[p_index];
3260

3261 3262 3263
							if(h_attnum - 1 == defmap[i])
								compute_default = true;
						}
B
Bruce Momjian 已提交
3264

3265 3266 3267
						/* check 2: is this a default function? (non-constant default) */
						if(defexprs[i]->expr->type != T_Const)
							compute_default = true;
3268

3269 3270 3271
						if(compute_default)
						{
							char *string;
B
Bruce Momjian 已提交
3272

3273 3274
							values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
															 &isnull, NULL);
3275

3276 3277 3278 3279 3280
							/*
							 * prepare to concatinate next value:
							 * remove eol characters from end of line buf
							 */
							truncateEol(&cstate->line_buf, cstate->eol_type);
3281

3282 3283 3284 3285 3286 3287 3288
							if (isnull)
							{
								appendStringInfo(&cstate->line_buf, "%c%s", cstate->delim[0], cstate->null_print);
							}
							else
							{
								nulls[defmap[i]] = false;
3289

3290
								appendStringInfo(&cstate->line_buf, "%c", cstate->delim[0]); /* write the delimiter */
3291

3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304
								string = DatumGetCString(FunctionCall3(&out_functions[defmap[i]],
																	   values[defmap[i]],
																	   ObjectIdGetDatum(typioparams[defmap[i]]),
																	   Int32GetDatum(attr[defmap[i]]->atttypmod)));
								if (cstate->csv_mode)
								{
									CopyAttributeOutCSV(cstate, string,
														false, /*force_quote[attnum - 1],*/
														list_length(cstate->attnumlist) == 1);
								}
								else
									CopyAttributeOutText(cstate, string);
							}
3305

3306 3307 3308
							/* re-add the eol characters */
							concatenateEol(cstate);
						}
3309

3310
					}
B
Bruce Momjian 已提交
3311

3312 3313
					/* lock partition */
					if (estate->es_result_partitions)
B
Bruce Momjian 已提交
3314
					{
3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406
						PartitionNode *n = estate->es_result_partitions;
						MemoryContext cxt_save;
						/* lazily initialised */
						if (part_values == NULL)
						{
							List *pattnums = get_partition_attrs(n);
							ListCell *lc;
							int ii = 0;

							cxt_save = MemoryContextSwitchTo(oldcontext);

							part_values = palloc0(num_phys_attrs * sizeof(Datum));
							part_attr_types = palloc(num_phys_attrs * sizeof(Oid));
							part_typio = palloc(num_phys_attrs * sizeof(Oid));
							part_infuncs =
								palloc(num_phys_attrs * sizeof(FmgrInfo));
							part_attnum = palloc(num_phys_attrs *
												 sizeof(AttrNumber));
							part_attnums = list_length(pattnums);
							MemoryContextSwitchTo(cxt_save);

							foreach(lc, pattnums)
							{
								AttrNumber attnum = (AttrNumber)lfirst_int(lc);
								Oid in_func_oid;

								getTypeInputInfo(attr[attnum - 1]->atttypid,
												 &in_func_oid,
												 &part_typio[attnum - 1]);
								fmgr_info(in_func_oid, &part_infuncs[attnum - 1]);
								part_attnum[ii++] = attnum;
							}
						}
						MemSet(part_values, 0, num_phys_attrs * sizeof(Datum));

						attr_get_key(cstate, cdbCopy,
									 original_lineno_for_qe,
									 target_seg,
									 part_attnums,
									 part_attnum,
									 attr, attr_offsets, nulls,
									 part_infuncs, part_typio,
									 part_values);

						/* values_get_partition() calls palloc() */
						cxt_save = MemoryContextSwitchTo(oldcontext);

						resultRelInfo = values_get_partition(part_values,
															 nulls,
															 tupDesc, estate);

						MemoryContextSwitchTo(cxt_save);

						/*
						 * If we a partition set with differing policies,
						 * get the policy for this particular child partition.
						 */
						if (hashmap)
						{
							bool found;
							cdbhashdata *d;
							Oid relid = resultRelInfo->ri_RelationDesc->rd_id;

							d = hash_search(hashmap, &(relid), HASH_ENTER,
											&found);
							if (found)
							{
								part_policy = d->policy;
								part_p_nattrs = part_policy->nattrs;
								part_hash = d->cdbHash;
							}
							else
							{
								Relation rel = heap_open(relid, NoLock);
								MemoryContext save_cxt;

								/*
								 * Make sure this all persists the current
								 * iteration.
								 */
								save_cxt = MemoryContextSwitchTo(oldcontext);
								d->relid = relid;
								part_hash = d->cdbHash =
									makeCdbHash(cdbCopy->total_segs, HASH_FNV_1);
								part_policy = d->policy =
									GpPolicyCopy(oldcontext,
												 rel->rd_cdbpolicy);
								part_p_nattrs = part_policy->nattrs;
								heap_close(rel, NoLock);
								MemoryContextSwitchTo(save_cxt);
							}
						}
B
Bruce Momjian 已提交
3407
					}
3408 3409 3410 3411 3412 3413

					/*
					 * The the usual case or a partitioned table
					 * with non-divergent child table policies.
					 */
					if (!part_hash)
B
Bruce Momjian 已提交
3414
					{
3415 3416 3417
						part_hash = cdbHash;
						part_policy = policy;
						part_p_nattrs = p_nattrs;
B
Bruce Momjian 已提交
3418 3419
					}

3420 3421 3422 3423 3424 3425 3426 3427 3428 3429
					/*
					 * policy should be PARTITIONED (normal tables) or
					 * ENTRY
					 */
					if (!part_policy || part_policy->ptype == POLICYTYPE_UNDEFINED)
					{
						elog(FATAL, "Bad or undefined policy. (%p)", part_policy);
					}
				}
				PG_CATCH();
B
Bruce Momjian 已提交
3430
				{
3431
					COPY_HANDLE_ERROR;
B
Bruce Momjian 已提交
3432
				}
3433
				PG_END_TRY();
B
Bruce Momjian 已提交
3434

3435
				if(cur_row_rejected)
B
Bruce Momjian 已提交
3436
				{
3437 3438
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
B
Bruce Momjian 已提交
3439
				}
3440 3441

				/*
3442 3443 3444 3445 3446 3447 3448 3449
				 * At this point in the code, values[x] is final for this
				 * data row -- either the input data, a null or a default
				 * value is in there, and constraints applied.
				 *
				 * Perform a cdbhash on this data row. Perform a hash operation
				 * on each attribute that is included in CDB policy (partitioning
				 * key columns). Send COPY data line to the target segment
				 * database executors. Data row will not be inserted locally.
3450
				 */
3451 3452
				Assert(PointerIsValid(part_hash));
				cdbhashinit(part_hash);
B
Bruce Momjian 已提交
3453

3454 3455 3456 3457
				for (i = 0; i < part_p_nattrs; i++)
				{
					/* current attno from the policy */
					h_attnum = part_policy->attrs[i];
3458

3459
					h_key = values[h_attnum - 1];	/* value of this attr */
B
Bruce Momjian 已提交
3460

3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082
					if (!nulls[h_attnum - 1])
						cdbhash(part_hash, h_key, p_attr_types[h_attnum - 1]);
					else
						cdbhashnull(part_hash);
				}

				/*
				 * If this is a relation with an empty policy, there is no
				 * hash key to use, therefore use cdbhashnokey() to pick a
				 * hash value for us.
				 */
				if (part_p_nattrs == 0)
					cdbhashnokey(part_hash);

				target_seg = cdbhashreduce(part_hash);	/* hash result segment */


				/*
				 * Send data row to all databases for this segment.
				 * Also send the original row number with the data.
				 * modify the data to look like:
				 *    "<lineno>^<linebuf_converted>^<data>"
				 */
				appendStringInfo(&line_buf_with_lineno, "%d%c%d%c%s",
								 original_lineno_for_qe,
								 COPY_METADATA_DELIM,
								 cstate->line_buf_converted, \
								 COPY_METADATA_DELIM, \
								 cstate->line_buf.data);
				
				/* send modified data */
				cdbCopySendData(cdbCopy,
								target_seg,
								line_buf_with_lineno.data,
								line_buf_with_lineno.len);

				RESET_LINEBUF_WITH_LINENO;

				cstate->processed++;
				if (estate->es_result_partitions)
					resultRelInfo->ri_aoprocessed++;

				if (cdbCopy->io_errors)
				{
					appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
					no_more_data = true;
					break;
				}

				RESET_LINEBUF;

			}					/* end while(!raw_buf_done) */
		}						/* end if (bytesread > 0 || !cstate->fe_eof) */
		else
			/* no bytes read, end of data */
		{
			no_more_data = true;
		}
	} while (!no_more_data);

	/* Free p_attr_types */
	pfree(p_attr_types);

	/*
	 * Done reading input data and sending it off to the segment
	 * databases Now we would like to end the copy command on
	 * all segment databases across the cluster.
	 */
	total_rejeted_from_qes = cdbCopyEnd(cdbCopy);

	/*
	 * If we quit the processing loop earlier due to a
	 * cancel query signal, we now throw an error.
	 * (Safe to do only after cdbCopyEnd).
	 */
	CHECK_FOR_INTERRUPTS();


	if (cdbCopy->remote_data_err || cdbCopy->io_errors)
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);

	if (cdbCopy->remote_data_err)
	{
		cstate->error_on_executor = true;
		if(cdbCopy->err_context.len > 0)
			appendBinaryStringInfo(&cstate->executor_err_context, cdbCopy->err_context.data, cdbCopy->err_context.len);
	}

	/*
	 * report all accumulated errors back to the client. We get here if an error
	 * happened in all-or-nothing error handling mode or if reject limit was
	 * reached in single-row error handling mode.
	 */
	if (cdbCopy->remote_data_err)
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("%s", cdbcopy_err.data)));
	if (cdbCopy->io_errors)
		ereport(ERROR,
				(errcode(ERRCODE_IO_ERROR),
				 errmsg("%s", cdbcopy_err.data)));

	/*
	 * switch back away from COPY error context callback. don't want line
	 * error information anymore
	 */
	error_context_stack = errcontext.previous;

	/*
	 * If we got here it means that either all the data was loaded or some rows
	 * were rejected in SREH mode. In other words - nothing caused an abort.
	 * We now want to report the actual number of rows loaded and rejected.
	 * If any rows were rejected from the QE COPY processes subtract this number
	 * from the number of rows that were successfully processed on the QD COPY
	 * so that we can report the correct number.
	 */
	if(cstate->cdbsreh)
	{
		int total_rejected = 0;
		int total_rejected_from_qd = cstate->cdbsreh->rejectcount;
		
		/* if used errtable, QD bad rows were sent to QEs and counted there. ignore QD count */
		if (cstate->cdbsreh->errtbl)
			total_rejected_from_qd = 0;
		
		total_rejected = total_rejected_from_qd + total_rejeted_from_qes;
		cstate->processed -= total_rejected;

		/* emit a NOTICE with number of rejected rows */
		ReportSrehResults(cstate->cdbsreh, total_rejected);

		/* See if we want to DROP error table when destroying cdbsreh */
		if(cstate->cdbsreh->errtbl)
			SetErrorTableVerdict(cstate->cdbsreh, total_rejected);
	}


	/*
	 * Done, clean up
	 */
	MemoryContextSwitchTo(oldcontext);

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

	/*
	 * Handle queued AFTER triggers
	 */
	//AfterTriggerEndQuery(estate);

	resultRelInfo = estate->es_result_relations;
	for (i = estate->es_num_result_relations; i > 0; i--)
	{
		/* update AO tuple counts */
		char relstorage = RelinfoGetStorage(resultRelInfo);
		if (relstorage_is_ao(relstorage))
		{
			if (cdbCopy->aotupcounts)
			{
				HTAB *ht = cdbCopy->aotupcounts;
				struct {
					Oid relid;
					int64 tupcount;
				} *ao;
				bool found;
				Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);

				ao = hash_search(ht, &relid, HASH_FIND, &found);
				if (found)
				{
   	 				/* find out which segnos the result rels in the QE's used */
    			    ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);

    				UpdateMasterAosegTotals(resultRelInfo->ri_RelationDesc,
											resultRelInfo->ri_aosegno,
											ao->tupcount, 1);
				}
			}
			else
			{
				ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
				UpdateMasterAosegTotals(resultRelInfo->ri_RelationDesc,
										resultRelInfo->ri_aosegno,
										cstate->processed, 1);
			}
		}

		/* Close indices and then the relation itself */
		ExecCloseIndices(resultRelInfo);
		heap_close(resultRelInfo->ri_RelationDesc, NoLock);
		resultRelInfo++;
	}

	/*
	 * free all resources besides ones that are needed for error reporting
	 */
	if (cdbHash)
		pfree(cdbHash);
	pfree(values);
	pfree(nulls);
	pfree(attr_offsets);
	pfree(in_functions);
	pfree(out_functions);
	pfree(isvarlena);
	pfree(typioparams);
	pfree(defmap);
	pfree(defexprs);
	pfree(cdbcopy_cmd.data);
	pfree(cdbcopy_err.data);
	pfree(line_buf_with_lineno.data);
	pfree(cdbCopy);

	if (policy)
		pfree(policy);

	/* free the hash table allocated by values_get_partition(), if any */
	if(estate->es_result_partitions && estate->es_partition_state->result_partition_hash != NULL)
		hash_destroy(estate->es_partition_state->result_partition_hash);

	/*
	 * Don't worry about the partition table hash map, that will be
	 * freed when our current memory context is freed. And that will be
	 * quite soon.
	 */
	
	cstate->rel = NULL; /* closed above */
	FreeExecutorState(estate);
}

/*
 * Copy FROM file to relation.
 */
static void
CopyFrom(CopyState cstate)
{
	void		*tuple;
	TupleDesc	tupDesc;
	Form_pg_attribute *attr;
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
	FmgrInfo   *in_functions;
	Oid		   *typioparams;
	int			attnum;
	int			i;
	Oid			in_func_oid;
	Datum	   *values;
	bool	   *nulls;
	bool		isnull;
	ResultRelInfo *resultRelInfo;
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
	TupleTableSlot *slot;
	bool		file_has_oids;
	int		   *defmap;
	ExprState **defexprs;		/* array of default att expressions */
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
	MemoryContext oldcontext = CurrentMemoryContext;
	ErrorContextCallback errcontext;
	int		   *attr_offsets;
	bool		no_more_data = false;
	ListCell   *cur;
	bool		cur_row_rejected = false;
	int			original_lineno_for_qe = 0; /* keep compiler happy (var referenced by macro) */
	CdbCopy    *cdbCopy = NULL; /* never used... for compiling COPY_HANDLE_ERROR */
	tupDesc = RelationGetDescr(cstate->rel);
	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
	attr_count = list_length(cstate->attnumlist);
	num_defaults = 0;

	/*
	 * We need a ResultRelInfo so we can use the regular executor's
	 * index-entry-making machinery.  (There used to be a huge amount of
	 * code here that basically duplicated execUtils.c ...)
	 */
	resultRelInfo = makeNode(ResultRelInfo);
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
	if (resultRelInfo->ri_TrigDesc)
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
                        palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
        resultRelInfo->ri_TrigInstrument = NULL;
        ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);

        ExecOpenIndices(resultRelInfo);

	estate->es_result_relations = resultRelInfo;
	estate->es_num_result_relations = 1;
	estate->es_result_relation_info = resultRelInfo;
	estate->es_result_partitions = cstate->partitions;

	CopyInitPartitioningState(estate);

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

	econtext = GetPerTupleExprContext(estate);

	/*
	 * Pick up the required catalog information for each attribute in the
	 * relation, including the input function, the element type (to pass
	 * to the input function), and info about defaults and constraints.
	 */
	in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
	typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
	defmap = (int *) palloc(num_phys_attrs * sizeof(int));
	defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));

	for (attnum = 1; attnum <= num_phys_attrs; attnum++)
	{
		/* We don't need info for dropped attributes */
		if (attr[attnum - 1]->attisdropped)
			continue;

		/* Fetch the input function and typioparam info */
		getTypeInputInfo(attr[attnum - 1]->atttypid,
						 &in_func_oid, &typioparams[attnum - 1]);
		fmgr_info(in_func_oid, &in_functions[attnum - 1]);

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

			if (defexpr != NULL)
			{
				defexprs[num_defaults] = ExecPrepareExpr((Expr *) defexpr,
														 estate);
				defmap[num_defaults] = attnum - 1;
				num_defaults++;
			}
		}

	}

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

	/*
	 * 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.
	 */
	ExecBSInsertTriggers(estate, resultRelInfo);

	file_has_oids = cstate->oids;	/* must rely on user to tell us this... */

	values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
	nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
	attr_offsets = (int *) palloc(num_phys_attrs * sizeof(int));

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

	if (Gp_role == GP_ROLE_EXECUTE)
		cstate->err_loc_type = ROWNUM_EMBEDDED; /* get original row num from QD COPY */
	else
		cstate->err_loc_type = ROWNUM_ORIGINAL; /* we can count rows by ourselves */

	CopyInitDataParser(cstate);

	do
	{
		size_t		bytesread = 0;

		/* read a chunk of data into the buffer */
		bytesread = CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);
		cstate->raw_buf_done = false;

		/* set buffer pointers to beginning of the buffer */
		cstate->begloc = cstate->raw_buf;
		cstate->raw_buf_index = 0;

		/*
		 * continue if some bytes were read or if we didn't reach EOF. if we
		 * both reached EOF _and_ no bytes were read, quit the loop we are
		 * done
		 */
		if (bytesread > 0 || !cstate->fe_eof)
		{
			/* handle HEADER, but only if we're in utility mode */
			if (cstate->header_line)
			{
				cstate->line_done = cstate->csv_mode ?
					CopyReadLineCSV(cstate, bytesread) :
					CopyReadLineText(cstate, bytesread);
				cstate->cur_lineno++;
				cstate->header_line = false;

				RESET_LINEBUF;
			}

			while (!cstate->raw_buf_done)
			{
				bool		skip_tuple;
				Oid			loaded_oid = InvalidOid;
				char		relstorage;
				
				CHECK_FOR_INTERRUPTS();

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

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

				/* Initialize all values for row to NULL */
				MemSet(values, 0, num_phys_attrs * sizeof(Datum));
				MemSet(nulls, true, num_phys_attrs * sizeof(bool));
				/* reset attribute pointers */
				MemSet(attr_offsets, 0, num_phys_attrs * sizeof(int));

				PG_TRY();
				{
					/* Actually read the line into memory here */
					cstate->line_done = cstate->csv_mode ?
					CopyReadLineCSV(cstate, bytesread) :
					CopyReadLineText(cstate, bytesread);
				}
				PG_CATCH();
				{
					/* got here? encoding conversion/check error occurred */
					COPY_HANDLE_ERROR;
				}
				PG_END_TRY();

				if(cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QE_GOTO_NEXT_ROW;
				}

				if(!cstate->line_done)
				{
					/*
					 * if eof reached, and no data in line_buf,
					 * we don't need to do att parsing.
					 */
					if (cstate->fe_eof && cstate->line_buf.len == 0)
					{
						break;
					}
					/*
					 * We did not finish reading a complete date line
					 *
					 * If eof is not yet reached, we skip att parsing
					 * and read more data. But if eof _was_ reached it means
					 * that the original last data line is defective and
					 * we want to catch that error later on.
					 */
					if (!cstate->fe_eof || cstate->end_marker)
						break;
				}

				if (file_has_oids)
				{
					char	   *oid_string;

					/* can't be in CSV mode here */
					oid_string = CopyReadOidAttr(cstate, &isnull);

					if (isnull)
					{
						/* got here? null in OID column error */

						if(cstate->errMode == ALL_OR_NOTHING)
						{
							/* report error and abort */
							cdbCopyEnd(cdbCopy);

							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("null OID in COPY data.")));
						}
						else
						{
							/* SREH */
							cstate->cdbsreh->rejectcount++;
							cur_row_rejected = true;
						}

					}
					else
					{
						PG_TRY();
						{
							cstate->cur_attname = "oid";
							loaded_oid = DatumGetObjectId(DirectFunctionCall1(oidin,
																			  CStringGetDatum(oid_string)));
						}
						PG_CATCH();
						{
							/* got here? oid column conversion failed */
							COPY_HANDLE_ERROR;
						}
						PG_END_TRY();

						if (loaded_oid == InvalidOid)
						{
							if(cstate->errMode == ALL_OR_NOTHING)
								ereport(ERROR,
										(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
										 errmsg("invalid OID in COPY data.")));
							else /* SREH */
							{
								cstate->cdbsreh->rejectcount++;
								cur_row_rejected = true;
							}
						}
						cstate->cur_attname = NULL;
					}

					if(cur_row_rejected)
					{
						ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
						QE_GOTO_NEXT_ROW;
					}

				}

				PG_TRY();
				{
					if (cstate->csv_mode)
						CopyReadAttributesCSV(cstate, nulls, attr_offsets, num_phys_attrs, attr);
					else
						CopyReadAttributesText(cstate, nulls, attr_offsets, num_phys_attrs, attr);

					/*
					 * Loop to read the user attributes on the line.
					 */
					foreach(cur, cstate->attnumlist)
					{
						int			attnum = lfirst_int(cur);
						int			m = attnum - 1;
						char	   *string;

						string = cstate->attribute_buf.data + attr_offsets[m];

						if (nulls[m])
							isnull = true;
						else
							isnull = false;

						if (cstate->csv_mode && isnull && cstate->force_notnull_flags[m])
						{
							string = cstate->null_print;		/* set to NULL string */
							isnull = false;
						}

						cstate->cur_attname = NameStr(attr[m]->attname);

						values[m] = InputFunctionCall(&in_functions[m],
													  isnull ? NULL : string,
													  typioparams[m],
													  attr[m]->atttypmod);
						nulls[m] = isnull;
						cstate->cur_attname = NULL;
					}

					/*
					 * 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.
					 */
					for (i = 0; i < num_defaults; i++)
					{
						values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
														 &isnull, NULL);

						if (!isnull)
							nulls[defmap[i]] = false;
					}
				}
				PG_CATCH();
				{
					COPY_HANDLE_ERROR; /* SREH */
				}
				PG_END_TRY();

				if(cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QE_GOTO_NEXT_ROW;
				}

				/*
				 * We might create a ResultRelInfo which needs to persist
				 * the per tuple context.
				 */
				PG_TRY();
				{
					MemoryContextSwitchTo(oldcontext);
					if (estate->es_result_partitions)
					{
						resultRelInfo = values_get_partition(values, nulls,
															 tupDesc, estate);
						estate->es_result_relation_info = resultRelInfo;
					}
				}
				PG_CATCH();
				{
					COPY_HANDLE_ERROR;
				}
				PG_END_TRY();

				if (cur_row_rejected)
				{
					MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QE_GOTO_NEXT_ROW;
				}

				relstorage = RelinfoGetStorage(resultRelInfo);
				if (relstorage == RELSTORAGE_AOROWS &&
					resultRelInfo->ri_aoInsertDesc == NULL)
				{
					ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
					resultRelInfo->ri_aoInsertDesc =
						appendonly_insert_init(resultRelInfo->ri_RelationDesc,
											   SnapshotNow,
											   resultRelInfo->ri_aosegno, false);
				}
				else if (relstorage == RELSTORAGE_AOCOLS &&
						 resultRelInfo->ri_aocsInsertDesc == NULL)
				{
					ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
                    resultRelInfo->ri_aocsInsertDesc =
                        aocs_insert_init(resultRelInfo->ri_RelationDesc,
                        				 resultRelInfo->ri_aosegno, false);
				}
				else if (relstorage == RELSTORAGE_EXTERNAL &&
						 resultRelInfo->ri_extInsertDesc == NULL)
				{
					resultRelInfo->ri_extInsertDesc =
						external_insert_init(resultRelInfo->ri_RelationDesc);
				}

				MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));

				/*
				 * And now we can form the input tuple.
				 */
				if (relstorage == RELSTORAGE_AOROWS)
				{
					/* form a mem tuple */
					tuple = (MemTuple)
						memtuple_form_to(resultRelInfo->ri_aoInsertDesc->mt_bind,
														values, nulls,
														NULL, NULL, false);

					if (cstate->oids && file_has_oids)
						MemTupleSetOid(tuple, resultRelInfo->ri_aoInsertDesc->mt_bind, loaded_oid);
				}
				else if (relstorage == RELSTORAGE_AOCOLS)
				{
                    tuple = NULL;
				}
				else
				{
					/* form a regular heap tuple */
					tuple = (HeapTuple) heap_form_tuple(tupDesc, values, nulls);

					if (cstate->oids && file_has_oids)
						HeapTupleSetOid((HeapTuple)tuple, loaded_oid);
				}


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

				/* Partitions don't support triggers yet */
				Assert(!(estate->es_result_partitions &&
						 resultRelInfo->ri_TrigDesc));

				skip_tuple = false;

				/* BEFORE ROW INSERT Triggers */
				if (resultRelInfo->ri_TrigDesc &&
					resultRelInfo->ri_TrigDesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
				{
					HeapTuple	newtuple;

					if(relstorage == RELSTORAGE_AOCOLS)
					{
						Assert(!tuple);
						elog(ERROR, "triggers are not supported on tables that use column-oriented storage");
					}

					Assert(resultRelInfo->ri_TrigFunctions != NULL);
					newtuple = ExecBRInsertTriggers(estate, resultRelInfo, tuple);

					if (newtuple == NULL)		/* "do nothing" */
						skip_tuple = true;
					else if (newtuple != tuple) /* modified by Trigger(s) */
					{
						heap_freetuple(tuple);
						tuple = newtuple;
					}
				}

				if (!skip_tuple)
				{
					char relstorage = RelinfoGetStorage(resultRelInfo);
					
					if (relstorage != RELSTORAGE_AOCOLS)
					{
						/* Place tuple in tuple slot */
						ExecStoreGenericTuple(tuple, slot, false);
					}

					else
					{
						ExecClearTuple(slot);
						slot->PRIVATE_tts_values = values;
						slot->PRIVATE_tts_isnull = nulls;
						ExecStoreVirtualTuple(slot);
					}

					/*
					 * Check the constraints of the tuple
					 */
					if (resultRelInfo->ri_RelationDesc->rd_att->constr)
							ExecConstraints(resultRelInfo, slot, estate);

					/*
					 * OK, store the tuple and create index entries for it
					 */
					if (relstorage == RELSTORAGE_AOROWS)
					{
						Oid			tupleOid;
						AOTupleId	aoTupleId;
						
						/* inserting into an append only relation */
						appendonly_insert(resultRelInfo->ri_aoInsertDesc, tuple, &tupleOid, &aoTupleId);
						
						if (resultRelInfo->ri_NumIndices > 0)
							ExecInsertIndexTuples(slot, (ItemPointer)&aoTupleId, estate, false);
					}
					else if (relstorage == RELSTORAGE_AOCOLS)
					{
						AOTupleId aoTupleId;
						
                        aocs_insert_values(resultRelInfo->ri_aocsInsertDesc, values, nulls, &aoTupleId);
						if (resultRelInfo->ri_NumIndices > 0)
							ExecInsertIndexTuples(slot, (ItemPointer)&aoTupleId, estate, false);
					}
					else if (relstorage == RELSTORAGE_EXTERNAL)
					{
						external_insert(resultRelInfo->ri_extInsertDesc, tuple);
					}
					else
					{
						simple_heap_insert(resultRelInfo->ri_RelationDesc, tuple);

						if (resultRelInfo->ri_NumIndices > 0)
							ExecInsertIndexTuples(slot, &(((HeapTuple)tuple)->t_self), estate, false);
					}


					/* AFTER ROW INSERT Triggers */
					ExecARInsertTriggers(estate, resultRelInfo, tuple);

					/*
					 * 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.
					 *
					 * MPP: incrementing this counter here only matters for utility
					 * mode. in dispatch mode only the dispatcher COPY collects row
					 * count, so this counter is meaningless.
					 */
					cstate->processed++;
					if (relstorage_is_ao(relstorage))
						resultRelInfo->ri_aoprocessed++;
				}

				RESET_LINEBUF;
			}					/* end while(!raw_buf_done) */
		}						/* end if (bytesread > 0 || !cstate->fe_eof) */
		else
			/* no bytes read, end of data */
		{
			no_more_data = true;
		}
	} while (!no_more_data);


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

	MemoryContextSwitchTo(oldcontext);

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

	/*
	 * Handle queued AFTER triggers
	 */
	AfterTriggerEndQuery(estate);

	/*
	 * If SREH and in executor mode send the number of rejected
	 * rows to the client (QD COPY).
	 */
	if(cstate->errMode != ALL_OR_NOTHING && Gp_role == GP_ROLE_EXECUTE)
		SendNumRowsRejected(cstate->cdbsreh->rejectcount);

	if (estate->es_result_partitions && Gp_role == GP_ROLE_EXECUTE)
		SendAOTupCounts(estate);

	/* free the hash table allocated by values_get_partition(), if any */
	if(estate->es_result_partitions && estate->es_partition_state->result_partition_hash != NULL)
		hash_destroy(estate->es_partition_state->result_partition_hash);
		
	pfree(attr_offsets);

	pfree(in_functions);
	pfree(typioparams);
	pfree(defmap);
	pfree(defexprs);

	ExecDropSingleTupleTableSlot(slot);

	/*
	 * Finalize appends and close relations we opened.
	 */
	resultRelInfo = estate->es_result_relations;
	for (i = estate->es_num_result_relations; i > 0; i--)
	{
			if (resultRelInfo->ri_aoInsertDesc)
					appendonly_insert_finish(resultRelInfo->ri_aoInsertDesc);

			if (resultRelInfo->ri_aocsInsertDesc)
					aocs_insert_finish(resultRelInfo->ri_aocsInsertDesc);

			if (resultRelInfo->ri_extInsertDesc)
					external_insert_finish(resultRelInfo->ri_extInsertDesc);
			
			/* Close indices and then the relation itself */
			ExecCloseIndices(resultRelInfo);
			heap_close(resultRelInfo->ri_RelationDesc, NoLock);
			resultRelInfo++;
	}
	
	cstate->rel = NULL; /* closed above */
	FreeExecutorState(estate);
}

/*
 * Finds the next TEXT line that is in the input buffer and loads
 * it into line_buf. Returns an indication if the line that was read
 * is complete (if an unescaped line-end was encountered). If we
 * reached the end of buffer before the whole line was written into the
 * line buffer then returns false.
 */
bool
CopyReadLineText(CopyState cstate, size_t bytesread)
{
	int			linesize;
	char		escapec = '\0';

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

	/*
	 * set the escape char for text format ('\\' by default).
	 */
	escapec = cstate->escape[0];

	if (cstate->raw_buf_index >= bytesread)
	{
		cstate->raw_buf_done = true;
		cstate->line_done = CopyCheckIsLastLine(cstate);
		return false;
	}

	/*
	 * Detect end of line type if not already detected.
	 */
	if (cstate->eol_type == EOL_UNKNOWN)
	{
		cstate->quote = NULL;

		if (!DetectLineEnd(cstate, bytesread))
		{
			/* load entire input buffer into line buf, and quit */
			appendBinaryStringInfo(&cstate->line_buf, cstate->raw_buf, bytesread);
			cstate->raw_buf_done = true;
			cstate->line_done = CopyCheckIsLastLine(cstate);

			if (cstate->line_done)
				preProcessDataLine(cstate);

			return cstate->line_done;
		}
	}

	/*
	 * Special case: eol is CRNL, last byte of previous buffer was an
	 * unescaped CR and 1st byte of current buffer is NL. We check for
	 * that here.
	 */
	if (cstate->eol_type == EOL_CRLF)
	{
		/* if we started scanning from the 1st byte of the buffer */
		if (cstate->begloc == cstate->raw_buf)
		{
			/* and had a CR in last byte of prev buf */
			if (cstate->cr_in_prevbuf)
			{
				/*
				 * if this 1st byte in buffer is 2nd byte of line end sequence
				 * (linefeed)
				 */
				if (*(cstate->begloc) == cstate->eol_ch[1])
				{
					/*
					* load that one linefeed byte and indicate we are done
					* with the data line
					*/
					appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, 1);
					cstate->raw_buf_index++;
					cstate->begloc++;
					cstate->cr_in_prevbuf = false;
					preProcessDataLine(cstate);

					if (cstate->raw_buf_index >= bytesread)
					{
						cstate->raw_buf_done = true;
					}
					return true;
				}
			}

			cstate->cr_in_prevbuf = false;
		}
	}

	/*
	 * (we need a loop so that if eol_ch is found, but prev ch is backslash,
	 * we can search for the next eol_ch)
	 */
	while (true)
	{
		/* reached end of buffer */
		if ((cstate->endloc = scanTextLine(cstate, cstate->begloc, cstate->eol_ch[0], bytesread - cstate->raw_buf_index)) == NULL)
		{
			linesize = bytesread - (cstate->begloc - cstate->raw_buf);
			appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, linesize);

			if (cstate->eol_type == EOL_CRLF && cstate->line_buf.len > 1)
			{
				char	   *last_ch = cstate->line_buf.data + cstate->line_buf.len - 1; /* before terminating \0 */

				if (*last_ch == '\r')
					cstate->cr_in_prevbuf = true;
			}

			cstate->line_done = CopyCheckIsLastLine(cstate);
			cstate->raw_buf_done = true;

			break;
		}
		else
			/* found the 1st eol ch in raw_buf. */
		{
			bool		eol_found = true;

			/*
			 * Load that piece of data (potentially a data line) into the line buffer,
			 * and update the pointers for the next scan.
			 */
			linesize = cstate->endloc - cstate->begloc + 1;
			appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, linesize);
			cstate->raw_buf_index += linesize;
			cstate->begloc = cstate->endloc + 1;

			if (cstate->eol_type == EOL_CRLF)
			{
				/* check if there is a '\n' after the '\r' */
				if (cstate->raw_buf_index < bytesread && *(cstate->endloc + 1) == '\n')
				{
					/* this is a line end */
					appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, 1);		/* load that '\n' */
					cstate->raw_buf_index++;
					cstate->begloc++;
				}
				/* no data left, may in next buf*/
				else if (cstate->raw_buf_index >= bytesread)
				{
					cstate->cr_in_prevbuf = true;
					eol_found = false;
				}
				else
				{
					/* just a CR, not a line end */
					eol_found = false;
				}
			}

			/*
			 * in some cases, this end of line char happens to be the
			 * last character in the buffer. we need to catch that.
			 */
			if (cstate->raw_buf_index >= bytesread)
				cstate->raw_buf_done = true;

			/*
			 * if eol was found, and it isn't escaped, line is done
			 */
			if (eol_found)
			{
				cstate->line_done = true;
				break;
			}
			else
			{
				/* stay in the loop and process some more data. */
				cstate->line_done = false;

				/* no data left, retuen false */
				if (cstate->raw_buf_done)
				{
					return false;
				}

				if (eol_found)
					cstate->cur_lineno++;		/* increase line index for error
												 * reporting */
			}

		}						/* end of found eol_ch */
	}

	/* Done reading a complete line. Do pre processing of the raw input data */
	if (cstate->line_done)
		preProcessDataLine(cstate);

	/*
	 * check if this line is an end marker -- "\."
	 */
	cstate->end_marker = false;

	switch (cstate->eol_type)
	{
		case EOL_LF:
			if (!strcmp(cstate->line_buf.data, "\\.\n"))
				cstate->end_marker = true;
			break;
		case EOL_CR:
			if (!strcmp(cstate->line_buf.data, "\\.\r"))
				cstate->end_marker = true;
			break;
		case EOL_CRLF:
			if (!strcmp(cstate->line_buf.data, "\\.\r\n"))
				cstate->end_marker = true;
			break;
		case EOL_UNKNOWN:
			break;
	}

	if (cstate->end_marker)
	{
		/*
		 * Reached end marker. In protocol version 3 we
		 * should ignore anything after \. up to protocol
		 * end of copy data.
		 */
		if (cstate->copy_dest == COPY_NEW_FE)
		{
			while (!cstate->fe_eof)
			{
				CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);	/* eat data */
			}
		}

		cstate->fe_eof = true;
		/* we don't want to process a \. as data line, want to quit. */
		cstate->line_done = false;
		cstate->raw_buf_done = true;
	}

	return cstate->line_done;
}

/*
 * Finds the next CSV line that is in the input buffer and loads
 * it into line_buf. Returns an indication if the line that was read
 * is complete (if an unescaped line-end was encountered). If we
 * reached the end of buffer before the whole line was written into the
 * line buffer then returns false.
 */
bool
CopyReadLineCSV(CopyState cstate, size_t bytesread)
{
	int			linesize;
	char		quotec = '\0',
				escapec = '\0';
	bool		csv_is_invalid = false;

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

	escapec = cstate->escape[0];
	quotec = cstate->quote[0];

	/* ignore special escape processing if it's the same as quotec */
	if (quotec == escapec)
		escapec = '\0';

	if (cstate->raw_buf_index >= bytesread)
	{
		cstate->raw_buf_done = true;
		cstate->line_done = CopyCheckIsLastLine(cstate);
		return false;
	}

	/*
	 * Detect end of line type if not already detected.
	 */
	if (cstate->eol_type == EOL_UNKNOWN)
	{
		if (!DetectLineEnd(cstate, bytesread))
		{
			/* EOL not found. load entire input buffer into line buf, and return */
			appendBinaryStringInfo(&cstate->line_buf, cstate->raw_buf, bytesread);
			cstate->line_done = CopyCheckIsLastLine(cstate);;
			cstate->raw_buf_done = true;

			if (cstate->line_done)
				preProcessDataLine(cstate);

			return cstate->line_done;
		}
	}

	/*
	 * Special case: eol is CRNL, last byte of previous buffer was an
	 * unescaped CR and 1st byte of current buffer is NL. We check for
	 * that here.
	 */
	if (cstate->eol_type == EOL_CRLF)
	{
		/* if we started scanning from the 1st byte of the buffer */
		if (cstate->begloc == cstate->raw_buf)
		{
			/* and had a CR in last byte of prev buf */
			if (cstate->cr_in_prevbuf)
			{
				/*
				 * if this 1st byte in buffer is 2nd byte of line end sequence
				 * (linefeed)
				 */
				if (*(cstate->begloc) == cstate->eol_ch[1])
				{
					/*
					 * load that one linefeed byte and indicate we are done
					 * with the data line
					 */
					appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, 1);
					cstate->raw_buf_index++;
					cstate->begloc++;
					cstate->line_done = true;
					preProcessDataLine(cstate);
					cstate->cr_in_prevbuf = false;

					if (cstate->raw_buf_index >= bytesread)
					{
						cstate->raw_buf_done = true;
					}
					return true;
				}
			}

			cstate->cr_in_prevbuf = false;
		}
	}

	/*
	 * (we need a loop so that if eol_ch is found, but we are in quotes,
	 * we can search for the next eol_ch)
	 */
	while (true)
	{
		/* reached end of buffer */
		if ((cstate->endloc = scanCSVLine(cstate, cstate->begloc, cstate->eol_ch[0], escapec, quotec, bytesread - cstate->raw_buf_index)) == NULL)
		{
			linesize = bytesread - (cstate->begloc - cstate->raw_buf);
			appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, linesize);

			if (cstate->line_buf.len > 1)
			{
				char	   *last_ch = cstate->line_buf.data + cstate->line_buf.len - 1; /* before terminating \0 */

				if (*last_ch == '\r')
				{
					if (cstate->eol_type == EOL_CRLF)
						cstate->cr_in_prevbuf = true;
				}
			}

			cstate->line_done = CopyCheckIsLastLine(cstate);
			cstate->raw_buf_done = true;
			break;
		}
		else
			/* found 1st eol char in raw_buf. */
		{
			bool		eol_found = true;

			/*
			 * Load that piece of data (potentially a data line) into the line buffer,
			 * and update the pointers for the next scan.
			 */
			linesize = cstate->endloc - cstate->begloc + 1;
			appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, linesize);
			cstate->raw_buf_index += linesize;
			cstate->begloc = cstate->endloc + 1;

			/* end of line only if not in quotes */
			if (cstate->in_quote)
			{
				/* buf done, but still in quote */
				if (cstate->raw_buf_index >= bytesread)
					cstate->raw_buf_done = true;

				cstate->line_done = false;

				/* update file line for error message */

				/*
				 * TODO: for dos line end we need to do check before
				 * incrementing!
				 */
				cstate->cur_lineno++;

				/*
				 * If we are still in quotes and linebuf len is extremely large
				 * then this file has bad csv and we have to stop the rolling
				 * snowball from getting bigger.
				 */
				if(cstate->line_buf.len >= gp_max_csv_line_length)
				{
					csv_is_invalid = true;
					cstate->in_quote = false;
					cstate->line_done = true;
					cstate->num_consec_csv_err++;
					break;
				}

				if (cstate->raw_buf_done)
					break;
			}
			else
			{
				/* if dos eol, check for '\n' after the '\r' */
				if (cstate->eol_type == EOL_CRLF)
				{
					if (cstate->raw_buf_index < bytesread && *(cstate->endloc + 1) == '\n')
					{
						/* this is a line end */
						appendBinaryStringInfo(&cstate->line_buf, cstate->begloc, 1);	/* load that '\n' */
						cstate->raw_buf_index++;
						cstate->begloc++;
					}
					else if (cstate->raw_buf_index >= bytesread)
					{
						cstate->cr_in_prevbuf = true;
						eol_found = false;
					}
					else
					{
						/* just a CR, not a line end */
						eol_found = false;
					}
				}

				/*
				 * in some cases, this end of line char happens to be the
				 * last character in the buffer. we need to catch that.
				 */
				if (cstate->raw_buf_index >= bytesread)
					cstate->raw_buf_done = true;

				/*
				 * if eol was found line is done
				 */
				if (eol_found)
				{
					cstate->line_done = true;
					break;
				}
				else
				{
					cstate->line_done = false;
					/* no data left, return false */
					if (cstate->raw_buf_done)
					{
						return false;
					}
				}
			}
		}						/* end of found eol_ch */
	}


	/* Done reading a complete line. Do pre processing of the raw input data */
	if (cstate->line_done)
		preProcessDataLine(cstate);

	/*
	 * We have a corrupted csv format case. It is already converted to server
	 * encoding, *which is necessary*. Ok, we can report an error now.
	 */
	if(csv_is_invalid)
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("data line too long. likely due to invalid csv data")));
	else
		cstate->num_consec_csv_err = 0; /* reset consecutive count */

	/*
	 * check if this line is an end marker -- "\."
	 */
	cstate->end_marker = false;

	switch (cstate->eol_type)
	{
		case EOL_LF:
			if (!strcmp(cstate->line_buf.data, "\\.\n"))
				cstate->end_marker = true;
			break;
		case EOL_CR:
			if (!strcmp(cstate->line_buf.data, "\\.\r"))
				cstate->end_marker = true;
			break;
		case EOL_CRLF:
			if (!strcmp(cstate->line_buf.data, "\\.\r\n"))
				cstate->end_marker = true;
			break;
		case EOL_UNKNOWN:
			break;
	}

	if (cstate->end_marker)
	{
		/*
		 * Reached end marker. In protocol version 3 we
		 * should ignore anything after \. up to protocol
		 * end of copy data.
		 */
		if (cstate->copy_dest == COPY_NEW_FE)
		{
			while (!cstate->fe_eof)
			{
				CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);	/* eat data */
			}
		}

		cstate->fe_eof = true;
		/* we don't want to process a \. as data line, want to quit. */
		cstate->line_done = false;
		cstate->raw_buf_done = true;
	}

	return cstate->line_done;
}

/*
 * Detected the eol type by looking at the first data row.
 * Possible eol types are NL, CR, or CRNL. If eol type was
 * detected, it is set and a boolean true is returned to
 * indicated detection was successful. If the first data row
 * is longer than the input buffer, we return false and will
 * try again in the next buffer.
 */
static bool
DetectLineEnd(CopyState cstate, size_t bytesread  __attribute__((unused)))
{
	int			index = 0;
	int			lineno = 0;
	char		c;
	char		quotec = '\0',
				escapec = '\0';
	bool		csv = false;
	
	/*
	 * CSV special case. See MPP-7819.
	 * 
	 * this functions may change the in_quote value while processing.
	 * this is ok as we need to keep state in case we don't find EOL
	 * in this buffer and need to be called again to continue searching.
	 * BUT if EOL *was* found we must reset to the state we had since 
	 * we are about to reprocess this buffer again in CopyReadLineCSV
	 * from the same starting point as we are in right now. 
	 */
	bool save_inquote = cstate->in_quote;
	bool save_lastwas = cstate->last_was_esc;

	/* if user specified NEWLINE we should never be here */
	Assert(!cstate->eol_str);

	if (cstate->quote)					/* CSV format */
	{
		csv = true;
		quotec = cstate->quote[0];
		escapec = cstate->escape[0];
		/* ignore special escape processing if it's the same as quotec */
		if (quotec == escapec)
			escapec = '\0';
	}

	while (index < RAW_BUF_SIZE)
	{
		c = cstate->raw_buf[index];

		if (csv)
		{
			if (cstate->in_quote && c == escapec)
				cstate->last_was_esc = !cstate->last_was_esc;
			if (c == quotec && !cstate->last_was_esc)
				cstate->in_quote = !cstate->in_quote;
			if (c != escapec)
				cstate->last_was_esc = false;
		}

		if (c == '\n')
		{
			lineno++;
			
			if (!csv || (csv && !cstate->in_quote))
			{
				cstate->eol_type = EOL_LF;
				cstate->eol_ch[0] = '\n';
				cstate->eol_ch[1] = '\0';

				cstate->in_quote = save_inquote; /* see comment at declaration */
				cstate->last_was_esc = save_lastwas;
				return true;
			}
			else if(csv && cstate->in_quote && cstate->line_buf.len + index >= gp_max_csv_line_length)
			{	
				/* we do a "line too long" CSV check for the first row as well (MPP-7869) */
				cstate->in_quote = false;
				cstate->line_done = true;
				cstate->num_consec_csv_err++;
				cstate->cur_lineno += lineno;
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
								errmsg("data line too long. likely due to invalid csv data")));
			}

		}
		if (c == '\r')
		{
			lineno++;
			
			if (!csv || (csv && !cstate->in_quote))
			{
				if (cstate->raw_buf[index + 1] == '\n')		/* always safe */
				{
					cstate->eol_type = EOL_CRLF;
					cstate->eol_ch[0] = '\r';
					cstate->eol_ch[1] = '\n';
				}
				else
				{
					cstate->eol_type = EOL_CR;
					cstate->eol_ch[0] = '\r';
					cstate->eol_ch[1] = '\0';
				}

				cstate->in_quote = save_inquote; /* see comment at declaration */
				cstate->last_was_esc = save_lastwas;
				return true;
			}
		}

		index++;
	}

	/* since we're yet to find the EOL this buffer will never be 
	 * re-processed so add the number of rows we found so we don't lose it */
	cstate->cur_lineno += lineno;
	
	return false;
}

/*
 *  Return decimal value for a hexadecimal digit
 */
static
int GetDecimalFromHex(char hex)
{
	if (isdigit((unsigned char)hex))
		return hex - '0';
	else
		return tolower((unsigned char)hex) - 'a' + 10;
}

/*
 * Read all TEXT attributes. Attributes are parsed from line_buf and
 * inserted (all at once) to attribute_buf, while saving pointers to
 * each attribute's starting position.
 *
 * When this routine finishes execution both the nulls array and
 * the attr_offsets array are updated. The attr_offsets will include
 * the offset from the beginning of the attribute array of which
 * each attribute begins. If a specific attribute is not used for this
 * COPY command (ommitted from the column list), a value of 0 will be assigned.
 * For example: for table foo(a,b,c,d,e) and COPY foo(a,b,e)
 * attr_offsets may look something like this after this routine
 * returns: [0,20,0,0,55]. That means that column "a" value starts
 * at byte offset 0, "b" in 20 and "e" in 55, in attribute_buf.
 *
 * In the attribute buffer (attribute_buf) each attribute
 * is terminated with a '\0', and therefore by using the attr_offsets
 * array we could point to a beginning of an attribute and have it
 * behave as a C string, much like previously done in COPY.
 *
 * Another aspect to improving performance is reducing the frequency
 * of data load into buffers. The original COPY read attribute code
 * loaded a character at a time. In here we try to load a chunk of data
 * at a time. Usually a chunk will include a full data row
 * (unless we have an escaped delim). That effectively reduces the number of
 * loads by a factor of number of bytes per row. This improves performance
 * greatly, unfortunately it add more complexity to the code.
 *
 * Global participants in parsing logic:
 *
 * line_buf.cursor -- an offset from beginning of the line buffer
 * that indicates where we are about to begin the next scan. Note that
 * if we have WITH OIDS or if we ran CopyExtractRowMetaData this cursor is
 * already shifted and is not in the beginning of line buf anymore.
 *
 * attribute_buf.cursor -- an offset from the beginning of the
 * attribute buffer that indicates where the current attribute begins.
 */

static inline uint64 uint64_has_nullbyte(uint64 w) {
return ((w - 0x0101010101010101ull) & ~w & 0x8080808080808080ull); }
static inline uint64 uint64_has_byte(uint64 w, unsigned char b) {
	w ^= b * 0x0101010101010101ull;
	return ((w - 0x0101010101010101ull) & ~w & 0x8080808080808080ull);}

void
CopyReadAttributesText(CopyState cstate, bool * __restrict nulls,
					   int * __restrict attr_offsets, int num_phys_attrs, Form_pg_attribute * __restrict attr)
{
	char		delimc = cstate->delim[0];		/* delimiter character */
	char		escapec = cstate->escape[0];	/* escape character    */
	char	   *scan_start;		/* pointer to line buffer for scan start. */
	char	   *scan_end;		/* pointer to line buffer where char was found */
	char	   *stop;
	char	   *scanner;
	int			attr_pre_len = 0;/* attr raw len, before processing escapes */
	int			attr_post_len = 0;/* current attr len after escaping */
	int			m;				/* attribute index being parsed */
	int			bytes_remaining;/* num bytes remaining to be scanned in line
								 * buf */
	int			chunk_start;	/* offset to beginning of line chunk to load */
	int			chunk_len = 0;	/* length of chunk of data to load to attr buf */
	int			oct_val;		/* byte value for octal escapes */
	int			hex_val;
	int			attnum = 0;		/* attribute number being parsed */
	int			attribute = 1;
	bool		saw_high_bit = false;
	ListCell   *cur;			/* cursor to attribute list used for this COPY */

	/* init variables for attribute scan */
	RESET_ATTRBUF;

	/* cursor is now > 0 if we copy WITH OIDS */
	scan_start = cstate->line_buf.data + cstate->line_buf.cursor;
	chunk_start = cstate->line_buf.cursor;

	cur = list_head(cstate->attnumlist);

	/* check for zero column table case */
	if(num_phys_attrs > 0)
	{
		attnum = lfirst_int(cur);
		m = attnum - 1;
	}

	if (cstate->escape_off)
		escapec = delimc;		/* look only for delimiters, escapes are
								 * disabled */

	/* have a single column only and no delim specified? take the fast track */
	if (cstate->delimiter_off)
    {
		CopyReadAttributesTextNoDelim(cstate, nulls, num_phys_attrs,
											 attnum);
        return;
    }

	/*
	 * Scan through the line buffer to read all attributes data
	 */
	while (cstate->line_buf.cursor < cstate->line_buf.len)
	{
		bytes_remaining = cstate->line_buf.len - cstate->line_buf.cursor;
		stop = scan_start + bytes_remaining;
B
Bruce Momjian 已提交
5083
		/*
5084 5085 5086
		 * We can eliminate one test (for length) in the loop by replacing the
		 * last byte with the delimiter.  We need to remember what it was so we
		 * can replace it later.
5087
		 */
5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589
		char  endchar = *(stop-1);
		*(stop-1) = delimc;

		/* Find the next of: delimiter, or escape, or end of buffer */
		for (scanner = scan_start; *scanner != delimc && *scanner != escapec; scanner++)
			;
		if (scanner == (stop-1) && endchar != delimc)
		{
			if (endchar != escapec)
				scanner++;
		}
		*(stop-1) = endchar;

		scan_end = (*scanner != '\0' ? (char *) scanner : NULL);

		if (scan_end == NULL)
		{
			/* GOT TO END OF LINE BUFFER */

			if (cur == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));

			attnum = lfirst_int(cur);
			m = attnum - 1;

			/* don't count eol char(s) in attr and chunk len calculation */
			if (cstate->eol_type == EOL_CRLF)
			{
				attr_pre_len += bytes_remaining - 2;
				chunk_len = cstate->line_buf.len - chunk_start - 2;
			}
			else
			{
				attr_pre_len += bytes_remaining - 1;
				chunk_len = cstate->line_buf.len - chunk_start - 1;
			}

			/* check if this is a NULL value or data value (assumed NULL) */
			if (attr_pre_len == cstate->null_print_len
				&&
				strncmp(cstate->line_buf.data + cstate->line_buf.len - attr_pre_len - 1, cstate->null_print, attr_pre_len)
				== 0)
				nulls[m] = true;
			else
				nulls[m] = false;

			attr_offsets[m] = cstate->attribute_buf.cursor;


			/* load the last chunk, the whole buffer in most cases */
			appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data + chunk_start, chunk_len);

			cstate->line_buf.cursor += attr_pre_len + 2;		/* skip eol char and
														 * '\0' to exit loop */

			/*
			 * line is done, but do we have more attributes to process?
			 *
			 * normally, remaining attributes that have no data means ERROR,
			 * however, with FILL MISSING FIELDS remaining attributes become
			 * NULL. since attrs are null by default we leave unchanged and
			 * avoid throwing an error, with the exception of empty data lines
			 * for multiple attributes, which we intentionally don't support.
			 */
			if (lnext(cur) != NULL)
			{
				if (!cstate->fill_missing)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for column \"%s\"",
									 NameStr(attr[lfirst_int(lnext(cur)) - 1]->attname))));

				else if (attribute == 1 && attr_pre_len == 0)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for column \"%s\", found empty data line",
									 NameStr(attr[lfirst_int(lnext(cur)) - 1]->attname))));
			}
		}
		else
			/* FOUND A DELIMITER OR ESCAPE */
		{
			if (cur == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));

			if (*scan_end == delimc)	/* found a delimiter */
			{
				attnum = lfirst_int(cur);
				m = attnum - 1;

				/* (we don't include the delimiter ch in length) */
				attr_pre_len += scan_end - scan_start;
				attr_post_len += scan_end - scan_start;

				/* check if this is a null print or data (assumed NULL) */
				if (attr_pre_len == cstate->null_print_len &&
					strncmp(scan_end - attr_pre_len, cstate->null_print, attr_pre_len) == 0)
					nulls[m] = true;
				else
					nulls[m] = false;

				/* set the pointer to next attribute position */
				attr_offsets[m] = cstate->attribute_buf.cursor;

				/*
				 * update buffer cursors to our current location, +1 to skip
				 * the delimc
				 */
				cstate->line_buf.cursor = scan_end - cstate->line_buf.data + 1;
				cstate->attribute_buf.cursor += attr_post_len + 1;

				/* prepare scan for next attr */
				scan_start = cstate->line_buf.data + cstate->line_buf.cursor;
				cur = lnext(cur);
				attr_pre_len = 0;
				attr_post_len = 0;

				/*
				 * for the dispatcher - stop parsing once we have
				 * all the hash field values. We don't need the rest.
				 */
				if (Gp_role == GP_ROLE_DISPATCH)
				{
					if (attribute == cstate->last_hash_field)
					{
						/*
						 * load the chunk from chunk_start to end of current
						 * attribute, not including delimiter
						 */
						chunk_len = cstate->line_buf.cursor - chunk_start - 1;
						appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data + chunk_start, chunk_len);
						break;
					}
				}

				attribute++;
			}
			else
				/* found an escape character */
			{
				char		nextc = *(scan_end + 1);
				char		newc;
				int			skip = 2;

				chunk_len = (scan_end - cstate->line_buf.data) - chunk_start + 1;

				/* load a chunk of data */
				appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data + chunk_start, chunk_len);

				switch (nextc)
				{
					case '0':
					case '1':
					case '2':
					case '3':
					case '4':
					case '5':
					case '6':
					case '7':
						/* handle \013 */
						oct_val = OCTVALUE(nextc);
						nextc = *(scan_end + 2);

						/*
						 * (no need for out bad access check since line if
						 * buffered)
						 */
						if (ISOCTAL(nextc))
						{
							skip++;
							oct_val = (oct_val << 3) + OCTVALUE(nextc);
							nextc = *(scan_end + 3);
							if (ISOCTAL(nextc))
							{
								skip++;
								oct_val = (oct_val << 3) + OCTVALUE(nextc);
							}
						}
						newc = oct_val & 0377;	/* the escaped byte value */
						if (IS_HIGHBIT_SET(newc))
							saw_high_bit = true;
						break;
					case 'x':
						/* Handle \x3F */
						hex_val = 0; /* init */
						nextc = *(scan_end + 2); /* get char after 'x' */

						if (isxdigit((unsigned char)nextc))
						{
							skip++;
							hex_val = GetDecimalFromHex(nextc);
							nextc = *(scan_end + 3); /* get second char */

							if (isxdigit((unsigned char)nextc))
							{
								skip++;
								hex_val = (hex_val << 4) + GetDecimalFromHex(nextc);
							}
							newc = hex_val & 0xff;
							if (IS_HIGHBIT_SET(newc))
								saw_high_bit = true;
						}
						else
						{
							newc = 'x';
						}
						break;

					case 'b':
						newc = '\b';
						break;
					case 'f':
						newc = '\f';
						break;
					case 'n':
						newc = '\n';
						break;
					case 'r':
						newc = '\r';
						break;
					case 't':
						newc = '\t';
						break;
					case 'v':
						newc = '\v';
						break;
					default:
						if (nextc == delimc)
							newc = delimc;
						else if (nextc == escapec)
							newc = escapec;
						else
						{
							/* no escape sequence found. it's a lone escape */
							
							bool next_is_eol = ((nextc == '\n' && cstate->eol_type == EOL_LF) ||
											    (nextc == '\r' && (cstate->eol_type == EOL_CR || 
																   cstate->eol_type == EOL_CRLF)));
							
							if(!next_is_eol)
							{
								/* take next char literally */
								newc = nextc;
							}
							else
							{
								/* there isn't a next char (end of data in line). we keep the 
								 * backslash as a literal character. We don't skip over the EOL,
								 * since we don't support escaping it anymore (unlike PG).
								 */
								newc = escapec;
								skip--;
							}
						}

						break;
				}

				/* update to current length, add escape and escaped chars  */
				attr_pre_len += scan_end - scan_start + 2;
				/* update to current length, escaped char */
				attr_post_len += scan_end - scan_start + 1;

				/*
				 * Need to get rid of the escape character. This is done by
				 * loading the chunk up to including the escape character
				 * into the attribute buffer. Then overwriting the escape char
				 * with the escaped sequence or char, and continuing to scan
				 * from *after* the char than is after the escape in line_buf.
				 */
				*(cstate->attribute_buf.data + cstate->attribute_buf.len - 1) = newc;
				cstate->line_buf.cursor = scan_end - cstate->line_buf.data + skip;
				scan_start = scan_end + skip;
				chunk_start = cstate->line_buf.cursor;
				chunk_len = 0;
			}

		}						/* end delimiter/backslash */

	}							/* end line buffer scan. */

	/*
	 * Replace all delimiters with NULL for string termination.
	 * NOTE: only delimiters (NOT necessarily all delimc) are replaced.
	 * Example (delimc = '|'):
	 * - Before:  f  1	|  f  \|  2  |	f  3
	 * - After :  f  1 \0  f   |  2 \0	f  3
	 */
	for (attribute = 0; attribute < num_phys_attrs; attribute++)
	{
		if (attr_offsets[attribute] != 0)
			*(cstate->attribute_buf.data + attr_offsets[attribute] - 1) = '\0';
	}

	/* 
	 * MPP-6816 
	 * If any attribute has a de-escaped octal or hex sequence with a
	 * high bit set, we check that the changed attribute text is still
	 * valid WRT encoding. We run the check on all attributes since 
	 * such octal sequences are so rare in client data that it wouldn't
	 * affect performance at all anyway.
	 */
	if(saw_high_bit)
	{
		for (attribute = 0; attribute < num_phys_attrs; attribute++)
		{
			char *fld = cstate->attribute_buf.data + attr_offsets[attribute];
			pg_verifymbstr(fld, strlen(fld), false);
		}
	}
}

/*
 * Read all the attributes of the data line in CSV mode,
 * performing de-escaping as needed. Escaping does not follow the normal
 * PostgreSQL text mode, but instead "standard" (i.e. common) CSV usage.
 *
 * Quoted fields can span lines, in which case the line end is embedded
 * in the returned string.
 *
 * null_print is the null marker string.  Note that this is compared to
 * the pre-de-escaped input string (thus if it is quoted it is not a NULL).
 *----------
 */
void
CopyReadAttributesCSV(CopyState cstate, bool *nulls, int *attr_offsets,
					  int num_phys_attrs, Form_pg_attribute *attr)
{
	char		delimc = cstate->delim[0];
	char		quotec = cstate->quote[0];
	char		escapec = cstate->escape[0];
	char		c;
	int			start_cursor = cstate->line_buf.cursor;
	int			end_cursor = start_cursor;
	int			input_len = 0;
	int			attnum;			/* attribute number being parsed */
	int			m = 0;			/* attribute index being parsed */
	int			attribute = 1;
	bool		in_quote = false;
	bool		saw_quote = false;
	ListCell   *cur;			/* cursor to attribute list used for this COPY */

	/* init variables for attribute scan */
	RESET_ATTRBUF;

	cur = list_head(cstate->attnumlist);

	if(num_phys_attrs > 0)
	{
		attnum = lfirst_int(cur);
		m = attnum - 1;
	}

	for (;;)
	{
		end_cursor = cstate->line_buf.cursor;

		/* finished processing attributes in line */
		if (cstate->line_buf.cursor >= cstate->line_buf.len - 1)
		{
			input_len = end_cursor - start_cursor;

			if (cstate->eol_type == EOL_CRLF)
			{
				/* ignore the leftover CR */
				input_len--;
				cstate->attribute_buf.data[cstate->attribute_buf.cursor - 1] = '\0';
			}

			/* check whether raw input matched null marker */
			if(num_phys_attrs > 0)
			{
				if (!saw_quote && input_len == cstate->null_print_len &&
					strncmp(&cstate->line_buf.data[start_cursor], cstate->null_print, input_len) == 0)
					nulls[m] = true;
				else
					nulls[m] = false;
			}

			/* if zero column table and data is trying to get in */
			if(num_phys_attrs == 0 && input_len > 0)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));
			if (cur == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));

			if (in_quote)
			{
				/* next c will usually be LF, but it could also be a quote
				 * char if the last line of the file has no LF, and we don't
				 * want to error out in this case.
				 */
				c = cstate->line_buf.data[cstate->line_buf.cursor];
				if(c != quotec)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("unterminated CSV quoted field")));
			}

			/*
			 * line is done, but do we have more attributes to process?
			 *
			 * normally, remaining attributes that have no data means ERROR,
			 * however, with FILL MISSING FIELDS remaining attributes become
			 * NULL. since attrs are null by default we leave unchanged and
			 * avoid throwing an error, with the exception of empty data lines
			 * for multiple attributes, which we intentionally don't support.
			 */
			if (lnext(cur) != NULL)
			{
				if (!cstate->fill_missing)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for column \"%s\"",
									NameStr(attr[lfirst_int(lnext(cur)) - 1]->attname))));

				else if (attribute == 1 && input_len == 0)
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("missing data for column \"%s\", found empty data line",
									NameStr(attr[lfirst_int(lnext(cur)) - 1]->attname))));
			}

			break;
		}

		c = cstate->line_buf.data[cstate->line_buf.cursor++];

		/* unquoted field delimiter  */
		if (!in_quote && c == delimc && !cstate->delimiter_off)
		{
			/* check whether raw input matched null marker */
			input_len = end_cursor - start_cursor;

			if (cur == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));

			if(num_phys_attrs > 0)
			{
				if (!saw_quote && input_len == cstate->null_print_len &&
				strncmp(&cstate->line_buf.data[start_cursor], cstate->null_print, input_len) == 0)
					nulls[m] = true;
				else
					nulls[m] = false;
			}

			/* terminate attr string with '\0' */
			appendStringInfoCharMacro(&cstate->attribute_buf, '\0');
			cstate->attribute_buf.cursor++;

			/* setup next attribute scan */
			cur = lnext(cur);

			if (cur == NULL)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						 errmsg("extra data after last expected column")));

			saw_quote = false;

			if(num_phys_attrs > 0)
			{
				attnum = lfirst_int(cur);
				m = attnum - 1;
				attr_offsets[m] = cstate->attribute_buf.cursor;
			}

			start_cursor = cstate->line_buf.cursor;

			/*
			 * for the dispatcher - stop parsing once we have
			 * all the hash field values. We don't need the rest.
			 */
			if (Gp_role == GP_ROLE_DISPATCH)
			{
				if (attribute == cstate->last_hash_field)
					break;
			}

			attribute++;
			continue;
		}

		/* start of quoted field (or part of field) */
		if (!in_quote && c == quotec)
		{
			saw_quote = true;
			in_quote = true;
			continue;
		}

		/* escape within a quoted field */
		if (in_quote && c == escapec)
5590
		{
5591 5592 5593 5594 5595 5596 5597
			/*
			 * peek at the next char if available, and escape it if it is
			 * an escape char or a quote char
			 */
			if (cstate->line_buf.cursor <= cstate->line_buf.len)
			{
				char		nextc = cstate->line_buf.data[cstate->line_buf.cursor];
5598

5599 5600 5601 5602 5603 5604 5605 5606
				if (nextc == escapec || nextc == quotec)
				{
					appendStringInfoCharMacro(&cstate->attribute_buf, nextc);
					cstate->line_buf.cursor++;
					cstate->attribute_buf.cursor++;
					continue;
				}
			}
5607 5608
		}

5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621
		/*
		 * 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 (in_quote && c == quotec)
		{
			in_quote = false;
			continue;
		}
		appendStringInfoCharMacro(&cstate->attribute_buf, c);
		cstate->attribute_buf.cursor++;
	}
5622

5623 5624
}

5625
/*
5626 5627 5628 5629 5630 5631 5632
 * Read a single attribute line when delimiter is 'off'. This is a fast track -
 * we copy the entire line buf into the attribute buf, check for null value,
 * and we're done.
 *
 * Note that no equivalent function exists for CSV, as in CSV we still may
 * need to parse quotes etc. so the functionality of delimiter_off is inlined
 * inside of CopyReadAttributesCSV
5633
 */
5634 5635 5636
static void
CopyReadAttributesTextNoDelim(CopyState cstate, bool *nulls, int num_phys_attrs,
							  int attnum)
5637
{
5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651
	int 	len = 0;

	Assert(num_phys_attrs == 1);

	/* don't count eol char(s) in attr len calculation */
	len = cstate->line_buf.len - 1;

	if (cstate->eol_type == EOL_CRLF)
		len--;

	/* check if this is a NULL value or data value (assumed NULL) */
	if (len == cstate->null_print_len &&
		strncmp(cstate->line_buf.data, cstate->null_print, len) == 0)
		nulls[attnum - 1] = true;
5652
	else
5653 5654 5655
		nulls[attnum - 1] = false;

	appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data, len);
5656 5657
}

5658
/*
5659 5660 5661
 * Read the first attribute. This is mainly used to maintain support
 * for an OID column. All the rest of the columns will be read at once with
 * CopyReadAttributesText.
5662
 */
5663 5664
static char *
CopyReadOidAttr(CopyState cstate, bool *isnull)
5665
{
5666
	char		delimc = cstate->delim[0];
5667 5668 5669 5670
	char	   *start_loc = cstate->line_buf.data + cstate->line_buf.cursor;
	char	   *end_loc;
	int			attr_len = 0;
	int			bytes_remaining;
5671

5672 5673 5674 5675 5676 5677 5678 5679
	/* reset attribute buf to empty */
	RESET_ATTRBUF;

	/* # of bytes that were not yet processed in this line */
	bytes_remaining = cstate->line_buf.len - cstate->line_buf.cursor;

	/* got to end of line */
	if ((end_loc = scanTextLine(cstate, start_loc, delimc, bytes_remaining)) == NULL)
5680
	{
5681 5682 5683
		attr_len = bytes_remaining - 1; /* don't count '\n' in len calculation */
		appendBinaryStringInfo(&cstate->attribute_buf, start_loc, attr_len);
		cstate->line_buf.cursor += attr_len + 2;		/* skip '\n' and '\0' */
5684
	}
5685 5686 5687 5688 5689 5690 5691
	else
		/* found a delimiter */
	{
		/*
		 * (we don't care if delim was preceded with a backslash, because it's
		 * an invalid OID anyway)
		 */
5692

5693
		attr_len = end_loc - start_loc; /* we don't include the delimiter ch */
5694

5695 5696 5697
		appendBinaryStringInfo(&cstate->attribute_buf, start_loc, attr_len);
		cstate->line_buf.cursor += attr_len + 1;
	}
5698

5699

5700 5701 5702 5703 5704
	/* check whether raw input matched null marker */
	if (attr_len == cstate->null_print_len && strncmp(start_loc, cstate->null_print, attr_len) == 0)
		*isnull = true;
	else
		*isnull = false;
5705

5706 5707
	return cstate->attribute_buf.data;
}
5708

5709 5710 5711 5712 5713 5714 5715 5716
/*
 * Send text representation of one attribute, with conversion and escaping
 */
#define DUMPSOFAR() \
	do { \
		if (ptr > start) \
			CopySendData(cstate, start, ptr - start); \
	} while (0)
5717

5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728
/*
 * Send text representation of one attribute, with conversion and escaping
 */
static void
CopyAttributeOutText(CopyState cstate, char *string)
{
	char	   *ptr;
	char	   *start;
	char		c;
	char		delimc = cstate->delim[0];
	char		escapec = cstate->escape[0];
5729

5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764
	if (cstate->need_transcoding)
		ptr = pg_server_to_custom(string, 
								  strlen(string), 
								  cstate->client_encoding, 
								  cstate->enc_conversion_proc);
	else
		ptr = string;


	if (cstate->escape_off)
	{
		CopySendData(cstate, ptr, strlen(ptr));
		return;
	}

	/*
	 * 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 escaped 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.
	 *
	 * 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.  This loop is sufficiently performance-critical that
	 * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
	 * of the normal safe-encoding path.
	 */
	if (cstate->encoding_embeds_ascii)
	{
		start = ptr;
		while ((c = *ptr) != '\0')
		{
			if ((unsigned char) c < (unsigned char) 0x20)
5765
			{
5766 5767 5768 5769 5770 5771 5772
				/*
				 * \r and \n must be escaped, the others are traditional. We
				 * prefer to dump these using the C-like notation, rather than
				 * a backslash and the literal character, because it makes the
				 * dump file a bit more proof against Microsoftish data
				 * mangling.
				 */
5773 5774
				switch (c)
				{
5775 5776
					case '\b':
						c = 'b';
B
Bruce Momjian 已提交
5777
						break;
5778 5779
					case '\f':
						c = 'f';
5780
						break;
5781 5782
					case '\n':
						c = 'n';
5783
						break;
5784 5785
					case '\r':
						c = 'r';
5786
						break;
5787 5788
					case '\t':
						c = 't';
5789
						break;
5790 5791
					case '\v':
						c = 'v';
5792
						break;
5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836
					default:
						/* If it's the delimiter, must backslash it */
						if (c == delimc)
							break;
						/* All ASCII control chars are length 1 */
						ptr++;
						continue;		/* fall to end of loop */
				}
				/* if we get here, we need to convert the control char */
				DUMPSOFAR();
				CopySendChar(cstate, escapec);
				CopySendChar(cstate, c);
				start = ++ptr;	/* do not include char in next run */
			}
			else if (c == escapec || c == delimc)
			{
				DUMPSOFAR();
				CopySendChar(cstate, escapec);
				start = ptr++;	/* we include char in next run */
			}
			else if (IS_HIGHBIT_SET(c))
				ptr += pg_encoding_mblen(cstate->client_encoding, ptr);
			else
				ptr++;
		}
	}
	else
	{
		start = ptr;
		while ((c = *ptr) != '\0')
		{
			if ((unsigned char) c < (unsigned char) 0x20)
			{
				/*
				 * \r and \n must be escaped, the others are traditional. We
				 * prefer to dump these using the C-like notation, rather than
				 * a backslash and the literal character, because it makes the
				 * dump file a bit more proof against Microsoftish data
				 * mangling.
				 */
				switch (c)
				{
					case '\b':
						c = 'b';
5837
						break;
5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851
					case '\f':
						c = 'f';
						break;
					case '\n':
						c = 'n';
						break;
					case '\r':
						c = 'r';
						break;
					case '\t':
						c = 't';
						break;
					case '\v':
						c = 'v';
5852
						break;
5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876
					default:
						/* If it's the delimiter, must backslash it */
						if (c == delimc)
							break;
						/* All ASCII control chars are length 1 */
						ptr++;
						continue;		/* fall to end of loop */
				}
				/* if we get here, we need to convert the control char */
				DUMPSOFAR();
				CopySendChar(cstate, escapec);
				CopySendChar(cstate, c);
				start = ++ptr;	/* do not include char in next run */
			}
			else if (c == escapec || c == delimc)
			{
				DUMPSOFAR();
				CopySendChar(cstate, escapec);
				start = ptr++;	/* we include char in next run */
			}
			else
				ptr++;
		}
	}
5877

5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940
	DUMPSOFAR();
}

/*
 * Send text representation of one attribute, with conversion and
 * CSV-style escaping
 */
static void
CopyAttributeOutCSV(CopyState cstate, char *string,
					bool use_quote, bool single_attr)
{
	char	   *ptr;
	char	   *start;
	char		c;
	char		delimc = cstate->delim[0];
	char		quotec;
	char		escapec = cstate->escape[0];

	/*
	 * MPP-8075. We may get called with cstate->quote == NULL.
	 */
	if (cstate->quote == NULL)
	{
		quotec = '"';
	}
	else
	{
		quotec = cstate->quote[0];
	}

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

	if (cstate->need_transcoding)
		ptr = pg_server_to_custom(string, 
								  strlen(string),
								  cstate->client_encoding,
								  cstate->enc_conversion_proc);
	else
		ptr = string;

	/*
	 * Make a preliminary pass to discover if it needs quoting
	 */
	if (!use_quote)
	{
		/*
		 * 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.
		 */
		if (single_attr && strcmp(ptr, "\\.") == 0)
			use_quote = true;
		else
		{
			char	   *tptr = ptr;

			while ((c = *tptr) != '\0')
			{
				if (c == delimc || c == quotec || c == '\n' || c == '\r')
				{
					use_quote = true;
					break;
5941
				}
5942 5943 5944 5945
				if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
					tptr += pg_encoding_mblen(cstate->client_encoding, tptr);
				else
					tptr++;
5946 5947
			}
		}
5948
	}
5949

5950 5951 5952
	if (use_quote)
	{
		CopySendChar(cstate, quotec);
5953

5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971
		/*
		 * 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();
5972

5973 5974 5975 5976 5977 5978
		CopySendChar(cstate, quotec);
	}
	else
	{
		/* If it doesn't need quoting, we can just dump it as-is */
		CopySendString(cstate, ptr);
5979
	}
5980 5981
}

B
Bruce Momjian 已提交
5982
/*
5983 5984 5985 5986 5987 5988 5989
 * 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).
 *
 * rel can be NULL ... it's only used for error reports.
B
Bruce Momjian 已提交
5990
 */
5991 5992
List *
CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
B
Bruce Momjian 已提交
5993
{
5994
	List	   *attnums = NIL;
5995

5996
	if (attnamelist == NIL)
5997
	{
5998 5999 6000 6001
		/* Generate default column list */
		Form_pg_attribute *attr = tupDesc->attrs;
		int			attr_count = tupDesc->natts;
		int			i;
B
Bruce Momjian 已提交
6002

6003 6004 6005 6006 6007 6008 6009 6010
		for (i = 0; i < attr_count; i++)
		{
			if (attr[i]->attisdropped)
				continue;
			attnums = lappend_int(attnums, i + 1);
		}
	}
	else
B
Bruce Momjian 已提交
6011
	{
6012 6013
		/* Validate the user-supplied list and extract attnums */
		ListCell   *l;
B
Bruce Momjian 已提交
6014

6015
		foreach(l, attnamelist)
B
Bruce Momjian 已提交
6016
		{
6017 6018 6019
			char	   *name = strVal(lfirst(l));
			int			attnum;
			int			i;
B
Bruce Momjian 已提交
6020

6021 6022 6023
			/* Lookup column name */
			attnum = InvalidAttrNumber;
			for (i = 0; i < tupDesc->natts; i++)
6024
			{
6025 6026 6027
				if (tupDesc->attrs[i]->attisdropped)
					continue;
				if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
B
Bruce Momjian 已提交
6028
				{
6029 6030
					attnum = tupDesc->attrs[i]->attnum;
					break;
B
Bruce Momjian 已提交
6031 6032
				}
			}
6033
			if (attnum == InvalidAttrNumber)
6034
			{
6035 6036 6037 6038 6039 6040 6041 6042 6043 6044
				if (rel != NULL)
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column \"%s\" of relation \"%s\" does not exist",
									name, RelationGetRelationName(rel))));
				else
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column \"%s\" does not exist",
									name)));
6045
			}
6046 6047 6048 6049 6050 6051 6052
			/* Check for duplicates */
			if (list_member_int(attnums, attnum))
				ereport(ERROR,
						(errcode(ERRCODE_DUPLICATE_COLUMN),
						 errmsg("column \"%s\" specified more than once",
								name)));
			attnums = lappend_int(attnums, attnum);
B
Bruce Momjian 已提交
6053
		}
6054
	}
B
Bruce Momjian 已提交
6055

6056
	return attnums;
B
Bruce Momjian 已提交
6057 6058
}

6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135
#define COPY_FIND_MD_DELIM \
md_delim = memchr(line_start, COPY_METADATA_DELIM, Min(32, cstate->line_buf.len)); \
if(md_delim && (md_delim != line_start)) \
{ \
	value_len = md_delim - line_start + 1; \
	*md_delim = '\0'; \
} \
else \
{ \
	cstate->md_error = true; \
}	

/*
 * CopyExtractRowMetaData - extract embedded row number from data.
 *
 * If data is being parsed in execute mode the parser (QE) doesn't
 * know the original line number (in the original file) of the current
 * row. Therefore the QD sends this information along with the data.
 * other metadata that the QD sends includes whether the data was
 * converted to server encoding (should always be the case, unless
 * encoding error happened and we're in error table mode).
 *
 * in:
 *    line_buf: <original_num>^<buf_converted>^<data for this row>
 *    lineno: ?
 *    line_buf_converted: ?
 *
 * out:
 *    line_buf: <data for this row>
 *    lineno: <original_num>
 *    line_buf_converted: <t/f>
 */
static
void CopyExtractRowMetaData(CopyState cstate)
{
	char *md_delim = NULL; /* position of the metadata delimiter */
	
	/*
	 * Line_buf may have already skipped an OID column if WITH OIDS defined,
	 * so we need to start from cursor not always from beginning of linebuf.
	 */
	char *line_start = cstate->line_buf.data + cstate->line_buf.cursor;
	int  value_len = 0;

	cstate->md_error = false;
	
	/* look for the first delimiter, and extract lineno */
	COPY_FIND_MD_DELIM;
	
	/* 
	 * make sure MD exists. that should always be the case
	 * unless we run into an edge case - see MPP-8052. if that 
	 * happens md_error is now set. we raise an error. 
	 */
	if(cstate->md_error)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
				 errmsg("COPY metadata not found. This probably means that there is a "
						"mixture of newline types in the data. Use the NEWLINE keyword "
						"in order to resolve this reliably.")));

	cstate->cur_lineno = atoi(line_start);

	*md_delim = COPY_METADATA_DELIM; /* restore the line_buf byte after setting it to \0 */

	/* reposition line buf cursor to see next metadata value (skip lineno) */
	cstate->line_buf.cursor += value_len;
	line_start = cstate->line_buf.data + cstate->line_buf.cursor;

	/* look for the second delimiter, and extract line_buf_converted */
	COPY_FIND_MD_DELIM;
	Assert(*line_start == '0' || *line_start == '1'); 
	cstate->line_buf_converted = atoi(line_start);
	
	*md_delim = COPY_METADATA_DELIM;
	cstate->line_buf.cursor += value_len;
}
6136

6137
/*
6138
 * error context callback for COPY FROM
6139
 */
6140 6141
static void
copy_in_error_callback(void *arg)
6142
{
6143 6144
	CopyState	cstate = (CopyState) arg;
	char buffer[20];
6145

6146 6147 6148 6149
	/*
	 * If we saved the error context from a QE in cdbcopy.c append it here.
	 */
	if (Gp_role == GP_ROLE_DISPATCH && cstate->executor_err_context.len > 0)
6150
	{
6151 6152
		errcontext("%s", cstate->executor_err_context.data);
		return;
6153 6154
	}

6155 6156 6157
	/* don't need to print out context if error wasn't local */
	if (cstate->error_on_executor)
		return;
6158

6159 6160 6161 6162
	if (cstate->cur_attname)
	{
		/* error is relevant to a particular column */
		char	   *att_buf;
6163

6164
		att_buf = limit_printout_length(cstate->attribute_buf.data);
6165

6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177
		errcontext("COPY %s, line %s, column %s",
				   cstate->cur_relname,
				   linenumber_atoi(buffer, cstate->cur_lineno),
				   att_buf);
		pfree(att_buf);
	}
	else
	{
		/* error is relevant to a particular line */
		if (cstate->line_buf_converted || !cstate->need_transcoding)
		{
			char	   *line_buf;
6178

6179 6180
			line_buf = extract_line_buf(cstate);
			truncateEolStr(line_buf, cstate->eol_type);
6181

6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202
			errcontext("COPY %s, line %s: \"%s\"",
					   cstate->cur_relname,
					   linenumber_atoi(buffer, cstate->cur_lineno),
					   line_buf);
			pfree(line_buf);
		}
		else
		{
			/*
			 * 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.
			 */
			errcontext("COPY %s, line %s",
					   cstate->cur_relname,
					   linenumber_atoi(buffer, cstate->cur_lineno));
		}
	}
6203 6204 6205
}

/*
6206 6207 6208 6209 6210 6211 6212 6213
 * If our (copy of) linebuf has the embedded original row number and other
 * row-specific metadata, remove it. It is not part of the actual data, and
 * should not be displayed.
 *
 * we skip this step, however, if md_error was previously set by
 * CopyExtractRowMetaData. That should rarely happen, though.
 *
 * Returned value is a palloc'ed string to print.  The caller should pfree it.
6214
 */
6215 6216
static char *
extract_line_buf(CopyState cstate)
6217
{
6218
	char	   *line_buf = cstate->line_buf.data;
6219

6220
	if (cstate->err_loc_type == ROWNUM_EMBEDDED && !cstate->md_error)
6221
	{
6222 6223 6224 6225 6226 6227 6228
		/* the following is a compacted mod of CopyExtractRowMetaData */
		int value_len = 0;
		char *line_start = cstate->line_buf.data;
		char *lineno_delim = memchr(line_start, COPY_METADATA_DELIM,
									Min(32, cstate->line_buf.len));

		if (lineno_delim && (lineno_delim != line_start))
6229
		{
6230 6231 6232 6233 6234 6235 6236 6237 6238
			/*
			 * we only continue parsing metadata if the first extraction above
			 * succeeded. there are some edge cases where we may not have a line
			 * with MD to parse, for example if some non-copy related error
			 * propagated here and we don't yet have a proper data line.
			 * see MPP-11328
			 */
			value_len = lineno_delim - line_start + 1;
			line_start += value_len;
6239

6240 6241 6242 6243 6244 6245
			lineno_delim = memchr(line_start, COPY_METADATA_DELIM,
								  Min(32, cstate->line_buf.len));

			value_len = lineno_delim - line_start + 1;
			line_start += value_len;
			line_buf = line_start;
6246
		}
6247
	}
6248

6249 6250 6251 6252 6253 6254
	/*
	 * Finally allocate a new buffer and trim the string to a reasonable
	 * length.  We need a copy since this might be called from non-ERROR
	 * context like NOTICE, and we should preserve the original.
	 */
	return limit_printout_length(line_buf);
6255
}
6256

B
Bruce Momjian 已提交
6257
/*
6258 6259 6260 6261 6262 6263 6264
 * 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.
 * So, do our own truncation.  We return a pstrdup'd copy of the input.
B
Bruce Momjian 已提交
6265
 */
6266 6267
char *
limit_printout_length(const char *str)
B
Bruce Momjian 已提交
6268
{
6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287
#define MAX_COPY_DATA_DISPLAY 100

	int			slen = strlen(str);
	int			len;
	char	   *res;

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

	/* Apply encoding-dependent truncation */
	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, "...");
B
Bruce Momjian 已提交
6288

6289 6290
	return res;
}
6291

6292 6293 6294 6295 6296 6297 6298 6299 6300

static void
attr_get_key(CopyState cstate, CdbCopy *cdbCopy, int original_lineno_for_qe,
			 unsigned int target_seg,
			 AttrNumber p_nattrs, AttrNumber *attrs,
			 Form_pg_attribute *attr_descs, int *attr_offsets, bool *attr_nulls,
			 FmgrInfo *in_functions, Oid *typioparams, Datum *values)
{
	AttrNumber p_index;
B
Bruce Momjian 已提交
6301

B
Bruce Momjian 已提交
6302
	/*
6303 6304 6305
	 * Since we only need the internal format of values that
	 * we want to hash on (partitioning keys only), we want to
	 * skip converting the other values so we can run faster.
B
Bruce Momjian 已提交
6306
	 */
6307
	for (p_index = 0; p_index < p_nattrs; p_index++)
B
Bruce Momjian 已提交
6308
	{
6309 6310
		ListCell *cur;

6311
		/*
6312 6313
		 * For this partitioning key, search for its location in the attr list.
		 * (note that fields may be out of order, so this is necessary).
6314
		 */
6315
		foreach(cur, cstate->attnumlist)
B
Bruce Momjian 已提交
6316
		{
6317 6318 6319 6320
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
			char	   *string;
			bool		isnull;
6321

6322
			if (attnum == attrs[p_index])
6323
			{
6324 6325 6326 6327 6328 6329 6330 6331 6332
				string = cstate->attribute_buf.data + attr_offsets[m];

				if (attr_nulls[m])
					isnull = true;
				else
					isnull = false;

				if (cstate->csv_mode && isnull &&
					cstate->force_notnull_flags[m])
6333
				{
6334 6335
					string = cstate->null_print;		/* set to NULL string */
					isnull = false;
6336
				}
6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353

				/* we read an SQL NULL, no need to do anything */
				if (!isnull)
				{
					cstate->cur_attname = NameStr(attr_descs[m]->attname);

					values[m] = InputFunctionCall(&in_functions[m],
												  string,
												  typioparams[m],
												  attr_descs[m]->atttypmod);

					attr_nulls[m] = false;
					cstate->cur_attname = NULL;
				}		/* end if (!isnull) */

				break;	/* go to next partitioning key
						 * attribute */
6354
			}
6355 6356 6357
		}		/* end foreach */
	}			/* end for partitioning indexes */
}
B
Bruce Momjian 已提交
6358

6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382
/*
 * The following are custom versions of the string function strchr().
 * As opposed to the original strchr which searches through
 * a string until the target character is found, or a NULL is
 * found, this version will not return when a NULL is found.
 * Instead it will search through a pre-defined length of
 * bytes and will return only if the target character(s) is reached.
 *
 * If our client encoding is not a supported server encoding, we
 * know that it is not safe to look at each character as trailing
 * byte in a multibyte character may be a 7-bit ASCII equivalent.
 * Therefore we use pg_encoding_mblen to skip to the end of the
 * character.
 *
 * returns:
 *	 pointer to c - if c is located within the string.
 *	 NULL - if c was not found in specified length of search. Note:
 *			this DOESN'T mean that a '\0' was reached.
 */
char *
scanTextLine(CopyState cstate, const char *s, char eol, size_t len)
{
		
	if (cstate->encoding_embeds_ascii && !cstate->line_buf_converted)
6383
	{
6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398
		int			mblen;
		const char *end = s + len;
		
		/* we may need to skip the end of a multibyte char from the previous buffer */
		s += cstate->missing_bytes;
		
		mblen = pg_encoding_mblen(cstate->client_encoding, s);

		for (; *s != eol && s < end; s += mblen)
			mblen = pg_encoding_mblen(cstate->client_encoding, s);

		/* 
		 * MPP-10802
		 * if last char is a partial mb char (the rest of its bytes are in the next 
		 * buffer) save # of missing bytes for this char and skip them next time around 
6399
		 */
6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424
		cstate->missing_bytes = (s > end ? s - end : 0);
			
		return ((*s == eol) ? (char *) s : NULL);
	}
	else
		return memchr(s, eol, len);
}


char *
scanCSVLine(CopyState cstate, const char *s, char eol, char escapec, char quotec, size_t len)
{
	const char *start = s;
	const char *end = start + len;
	
	if (cstate->encoding_embeds_ascii && !cstate->line_buf_converted)
	{
		int			mblen;
		
		/* we may need to skip the end of a multibyte char from the previous buffer */
		s += cstate->missing_bytes;
		
		mblen = pg_encoding_mblen(cstate->client_encoding, s);
		
		for ( ; *s != eol && s < end ; s += mblen)
6425
		{
6426 6427 6428 6429 6430 6431 6432 6433
			if (cstate->in_quote && *s == escapec)
				cstate->last_was_esc = !cstate->last_was_esc;
			if (*s == quotec && !cstate->last_was_esc)
				cstate->in_quote = !cstate->in_quote;
			if (*s != escapec)
				cstate->last_was_esc = false;

			mblen = pg_encoding_mblen(cstate->client_encoding, s);
6434
		}
6435 6436 6437 6438 6439 6440 6441
		
		/* 
		 * MPP-10802
		 * if last char is a partial mb char (the rest of its bytes are in the next 
		 * buffer) save # of missing bytes for this char and skip them next time around 
		 */
		cstate->missing_bytes = (s > end ? s - end : 0);
6442 6443
	}
	else
6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454
		/* safe to scroll byte by byte */
	{	
		for ( ; *s != eol && s < end ; s++)
		{
			if (cstate->in_quote && *s == escapec)
				cstate->last_was_esc = !cstate->last_was_esc;
			if (*s == quotec && !cstate->last_was_esc)
				cstate->in_quote = !cstate->in_quote;
			if (*s != escapec)
				cstate->last_was_esc = false;
		}
6455
	}
6456 6457 6458 6459 6460 6461 6462 6463

	if (s == end)
		return NULL;
	
	if (*s == eol)
		cstate->last_was_esc = false;

	return ((*s == eol) ? (char *) s : NULL);
B
Bruce Momjian 已提交
6464 6465
}

6466 6467
/* remove end of line chars from end of a buffer */
void truncateEol(StringInfo buf, EolType eol_type)
6468
{
6469 6470
	int one_back = buf->len - 1;
	int two_back = buf->len - 2;
B
Bruce Momjian 已提交
6471

6472
	if(eol_type == EOL_CRLF)
B
Bruce Momjian 已提交
6473
	{
6474 6475
		if(buf->len < 2)
			return;
B
Bruce Momjian 已提交
6476

6477 6478
		if(buf->data[two_back] == '\r' &&
		   buf->data[one_back] == '\n')
B
Bruce Momjian 已提交
6479
		{
6480 6481 6482
			buf->data[two_back] = '\0';
			buf->data[one_back] = '\0';
			buf->len -= 2;
6483 6484 6485 6486
		}
	}
	else
	{
6487 6488
		if(buf->len < 1)
			return;
6489

6490 6491
		if(buf->data[one_back] == '\r' ||
		   buf->data[one_back] == '\n')
6492
		{
6493 6494
			buf->data[one_back] = '\0';
			buf->len--;
B
Bruce Momjian 已提交
6495 6496
		}
	}
6497
}
6498

6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534
/* wrapper for truncateEol */
void
truncateEolStr(char *str, EolType eol_type)
{
	StringInfoData buf;

	buf.data = str;
	buf.len = strlen(str);
	buf.maxlen = buf.len;
	truncateEol(&buf, eol_type);
}

/*
 * concatenateEol
 *
 * add end of line chars to end line buf.
 *
 */
static void concatenateEol(CopyState cstate)
{
	switch (cstate->eol_type)
	{
		case EOL_LF:
			appendStringInfo(&cstate->line_buf, "\n");
			break;
		case EOL_CR:
			appendStringInfo(&cstate->line_buf, "\r");
			break;
		case EOL_CRLF:
			appendStringInfo(&cstate->line_buf, "\r\n");
			break;
		case EOL_UNKNOWN:
			appendStringInfo(&cstate->line_buf, "\n");
			break;

	}
6535
}
6536

6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556
/*
 * Escape any single quotes or backslashes in given string (from initdb.c)
 */
static char *
escape_quotes(const char *src)
{
	int			len = strlen(src),
				i,
				j;
	char	   *result = palloc(len * 2 + 1);

	for (i = 0, j = 0; i < len; i++)
	{
		if ((src[i]) == '\'' || (src[i]) == '\\')
			result[j++] = src[i];
		result[j++] = src[i];
	}
	result[j] = '\0';
	return result;
}
6557 6558 6559 6560 6561

/*
 * copy_dest_startup --- executor startup
 */
static void
6562
copy_dest_startup(DestReceiver *self __attribute__((unused)), int operation __attribute__((unused)), TupleDesc typeinfo __attribute__((unused)))
6563 6564 6565 6566 6567 6568 6569 6570 6571 6572
{
	/* no-op */
}

/*
 * copy_dest_receive --- receive one tuple
 */
static void
copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
{
B
Bruce Momjian 已提交
6573
	DR_copy    *myState = (DR_copy *) self;
6574 6575 6576 6577 6578 6579
	CopyState	cstate = myState->cstate;

	/* Make sure the tuple is fully deconstructed */
	slot_getallattrs(slot);

	/* And send the data */
6580
	CopyOneRowTo(cstate, InvalidOid, slot_get_values(slot), slot_get_isnull(slot));
6581 6582 6583 6584 6585 6586
}

/*
 * copy_dest_shutdown --- executor end
 */
static void
6587
copy_dest_shutdown(DestReceiver *self __attribute__((unused)))
6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606
{
	/* no-op */
}

/*
 * copy_dest_destroy --- release DestReceiver object
 */
static void
copy_dest_destroy(DestReceiver *self)
{
	pfree(self);
}

/*
 * CreateCopyDestReceiver -- create a suitable DestReceiver object
 */
DestReceiver *
CreateCopyDestReceiver(void)
{
B
Bruce Momjian 已提交
6607
	DR_copy    *self = (DR_copy *) palloc(sizeof(DR_copy));
6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618

	self->pub.receiveSlot = copy_dest_receive;
	self->pub.rStartup = copy_dest_startup;
	self->pub.rShutdown = copy_dest_shutdown;
	self->pub.rDestroy = copy_dest_destroy;
	self->pub.mydest = DestCopyOut;

	self->cstate = NULL;		/* will be set later */

	return (DestReceiver *) self;
}
6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820


static void CopyInitPartitioningState(EState *estate)
{
	if (estate->es_result_partitions)
	{
		estate->es_partition_state =
 			createPartitionState(estate->es_result_partitions,
								 estate->es_num_result_relations);
	}
}

/*
 * Initialize data loader parsing state
 */
static void CopyInitDataParser(CopyState cstate)
{
	cstate->fe_eof = false;
	cstate->cur_relname = RelationGetRelationName(cstate->rel);
	cstate->cur_lineno = 0;
	cstate->cur_attname = NULL;
	cstate->null_print_len = strlen(cstate->null_print);

	if (cstate->csv_mode)
	{
		cstate->in_quote = false;
		cstate->last_was_esc = false;
		cstate->num_consec_csv_err = 0;
	}

	/* Set up data buffer to hold a chunk of data */
	MemSet(cstate->raw_buf, ' ', RAW_BUF_SIZE * sizeof(char));
	cstate->raw_buf[RAW_BUF_SIZE] = '\0';
	cstate->line_done = true;
	cstate->raw_buf_done = false;
}

/*
 * CopyCheckIsLastLine
 *
 * This routine checks if the line being looked at is the last line of data.
 * If it is, it makes sure that this line is terminated with an EOL. We must
 * do this check in order to support files that don't end up EOL before EOF,
 * because we want to treat that last line as normal - and be able to pre
 * process it like the other lines (remove metadata chars, encoding conversion).
 *
 * See MPP-4406 for an example of why this is needed.
 *
 * Notice: if line_buf is empty, no need to add EOL
 */
static bool CopyCheckIsLastLine(CopyState cstate)
{
	if (cstate->fe_eof && cstate->line_buf.len > 0)
	{
		concatenateEol(cstate);
		return true;
	}
	
	return false;
}

/*
 * setEncodingConversionProc
 *
 * COPY and External tables use a custom path to the encoding conversion
 * API because external tables have their own encoding (which is not
 * necessarily client_encoding). We therefore have to set the correct
 * encoding conversion function pointer ourselves, to be later used in
 * the conversion engine.
 *
 * The code here mimics a part of SetClientEncoding() in mbutils.c
 */
void setEncodingConversionProc(CopyState cstate, int client_encoding, bool iswritable)
{
	Oid		conversion_proc;
	
	/*
	 * COPY FROM and RET: convert from client to server
	 * COPY TO   and WET: convert from server to client
	 */
	if (iswritable)
		conversion_proc = FindDefaultConversionProc(GetDatabaseEncoding(),
													client_encoding);
	else		
		conversion_proc = FindDefaultConversionProc(client_encoding,
												    GetDatabaseEncoding());
	
	if (OidIsValid(conversion_proc))
	{
		/* conversion proc found */
		cstate->enc_conversion_proc = palloc(sizeof(FmgrInfo));
		fmgr_info(conversion_proc, cstate->enc_conversion_proc);
	}
	else
	{
		/* no conversion function (both encodings are probably the same) */
		cstate->enc_conversion_proc = NULL;
	}
}

/*
 * preProcessDataLine
 *
 * When Done reading a complete data line set input row number for error report
 * purposes (this also removes any metadata that was concatenated to the data
 * by the QD during COPY) and convert it to server encoding if transcoding is
 * needed.
 */
static
void preProcessDataLine(CopyState cstate)
{
	char	   *cvt;
	bool		force_transcoding = false;

	/*
	 * Increment line count by 1 if we have access to all the original
	 * data rows and can count them reliably (ROWNUM_ORIGINAL). However
	 * if we have ROWNUM_EMBEDDED the original row number for this row
	 * was sent to us with the data (courtesy of the data distributor), so
	 * get that number instead.
	 */
	if(cstate->err_loc_type == ROWNUM_ORIGINAL)
	{
		cstate->cur_lineno++;
	}
	else if(cstate->err_loc_type == ROWNUM_EMBEDDED)
	{
		Assert(Gp_role == GP_ROLE_EXECUTE);
		
		/*
		 * Extract various metadata sent to us from the QD COPY about this row:
		 * 1) the original line number of the row.
		 * 2) if the row was converted to server encoding or not
		 */
		CopyExtractRowMetaData(cstate); /* sets cur_lineno internally */
		
		/* check if QD sent us a badly encoded row, still in client_encoding, 
		 * in order to catch the encoding error ourselves. if line_buf_converted
		 * is false after CopyExtractRowMetaData then we must transcode and catch
		 * the error. Verify that we are indeed in SREH error table mode. that's
		 * the only valid path for receiving an unconverted data row.
		 */
		if (!cstate->line_buf_converted)
		{
			Assert(cstate->errMode == SREH_LOG);
			force_transcoding = true; 
		}
			
	}
	else
	{
		Assert(false); /* byte offset not yet supported */
	}
	
	if (cstate->need_transcoding || force_transcoding)
	{
		cvt = (char *) pg_custom_to_server(cstate->line_buf.data,
										   cstate->line_buf.len,
										   cstate->client_encoding,
										   cstate->enc_conversion_proc);
		
		Assert(!force_transcoding); /* if force is 't' we must have failed in the conversion */
		
		if (cvt != cstate->line_buf.data)
		{
			/* transfer converted data back to line_buf */
			RESET_LINEBUF;
			appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
			pfree(cvt);
		}
	}
	/* indicate that line buf is in server encoding */
	cstate->line_buf_converted = true;
}

void CopyEolStrToType(CopyState cstate)
{
	if (pg_strcasecmp(cstate->eol_str, "lf") == 0)
	{
		cstate->eol_type = EOL_LF;
		cstate->eol_ch[0] = '\n';
		cstate->eol_ch[1] = '\0';
	}
	else if (pg_strcasecmp(cstate->eol_str, "cr") == 0)
	{
		cstate->eol_type = EOL_CR;
		cstate->eol_ch[0] = '\r';
		cstate->eol_ch[1] = '\0';		
	}
	else if (pg_strcasecmp(cstate->eol_str, "crlf") == 0)
	{
		cstate->eol_type = EOL_CRLF;
		cstate->eol_ch[0] = '\r';
		cstate->eol_ch[1] = '\n';		
		
	}
	else /* error. must have been validated in CopyValidateControlChars() ! */
		ereport(ERROR,
				(errcode(ERRCODE_CDB_INTERNAL_ERROR),
				 errmsg("internal error in CopySetEolType. Trying to set NEWLINE %s", 
						 cstate->eol_str)));
}