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

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

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

56 57 58
#include "cdb/cdbvars.h"
#include "cdb/cdbcopy.h"
#include "cdb/cdbsreh.h"
59
#include "postmaster/autostats.h"
60

61 62 63 64 65 66 67
/* DestReceiver for COPY (SELECT) TO */
typedef struct
{
	DestReceiver pub;			/* publicly-known function pointers */
	CopyState	cstate;			/* CopyStateData for the command */
} DR_copy;

A
alldefector 已提交
68 69
static const char BinarySignature[11] = "PGCOPY\n\377\r\n\0";

70

71
/* non-export function prototypes */
72
static void DoCopyTo(CopyState cstate);
73
extern void CopyToDispatch(CopyState cstate);
74
static void CopyTo(CopyState cstate);
75
extern void CopyFromDispatch(CopyState cstate);
76
static void CopyFrom(CopyState cstate);
77
static void CopyFromProcessDataFileHeader(CopyState cstate, CdbCopy *cdbCopy, bool *pfile_has_oids);
78
static char *CopyReadOidAttr(CopyState cstate, bool *isnull);
79 80
static void CopyAttributeOutText(CopyState cstate, char *string);
static void CopyAttributeOutCSV(CopyState cstate, char *string,
81 82 83 84
								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);
A
alldefector 已提交
85 86 87 88
static Datum CopyReadBinaryAttribute(CopyState cstate,
									 int column_no, FmgrInfo *flinfo,
									 Oid typioparam, int32 typmod,
									 bool *isnull, bool skip_parsing);
89 90 91 92 93

/* Low-level communications functions */
static void SendCopyBegin(CopyState cstate);
static void ReceiveCopyBegin(CopyState cstate);
static void SendCopyEnd(CopyState cstate);
94
static void CopySendData(CopyState cstate, const void *databuf, int datasize);
95 96
static void CopySendString(CopyState cstate, const char *str);
static void CopySendChar(CopyState cstate, char c);
97 98
static int	CopyGetData(CopyState cstate, void *databuf, int datasize);

A
alldefector 已提交
99 100 101 102 103 104 105
static void CopySendInt16(CopyState cstate, int16 val);
static void CopySendInt32(CopyState cstate, int32 val);
static bool CopyGetInt16(CopyState cstate, int16 *val);
static bool CopyGetInt32(CopyState cstate, int32 *val);
static bool CopyGetInt64(CopyState cstate, int64 *val);


106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
/* 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);

/* ==========================================================================
D
Daniel Gustafsson 已提交
127
 * The following macros aid in major refactoring of data processing code (in
128 129 130 131 132 133 134 135
 * 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 已提交
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
#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! */ \
\
196
	if (Gp_role == GP_ROLE_DISPATCH || cstate->on_segment)\
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 273
	{\
		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\
	{\
		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 */
274

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

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

324
static void
325
ReceiveCopyBegin(CopyState cstate)
B
Bruce Momjian 已提交
326
{
327 328
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
329 330
		/* new way */
		StringInfoData buf;
331
		int			natts = list_length(cstate->attnumlist);
A
alldefector 已提交
332
		int16		format = (cstate->binary ? 1 : 0);
B
Bruce Momjian 已提交
333
		int			i;
334 335

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

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

387
/*----------
388 389 390
 * 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
391
 * CopySendEndOfRow does the appropriate thing at end of each data row
392
 *	(data is not actually flushed except by CopySendEndOfRow)
393 394
 *
 * NB: no data conversion is applied by these functions
395
 *----------
M
 
Marc G. Fournier 已提交
396
 */
397
static void
398
CopySendData(CopyState cstate, const void *databuf, int datasize)
B
Bruce Momjian 已提交
399
{
400 401 402 403 404 405 406 407 408 409 410 411 412
	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 已提交
413 414
}

415
static void
416
CopySendString(CopyState cstate, const char *str)
417
{
418
	CopySendData(cstate, (void *) str, strlen(str));
419 420 421
}

static void
422
CopySendChar(CopyState cstate, char c)
423
{
424
	CopySendData(cstate, &c, 1);
425 426
}

427 428 429 430 431 432
/* 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
433
CopySendEndOfRow(CopyState cstate)
434
{
435 436
	StringInfo	fe_msgbuf = cstate->fe_msgbuf;

437
	switch (cstate->copy_dest)
438 439
	{
		case COPY_FILE:
A
alldefector 已提交
440 441
			if (!cstate->binary)
			{
442
				/* Default line termination depends on platform */
443
#ifndef WIN32
444
				CopySendChar(cstate, '\n');
445
#else
446
				CopySendString(cstate, "\r\n");
447
#endif
A
alldefector 已提交
448
			}
449 450 451 452 453 454 455

			(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")));
A
Adam Lee 已提交
456

457
			break;
458 459
		case COPY_OLD_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
A
alldefector 已提交
460
			if (!cstate->binary)
461
				CopySendChar(cstate, '\n');
462 463 464 465 466 467 468

			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")));
469
			}
470
			break;
471 472
		case COPY_NEW_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
A
alldefector 已提交
473
			if (!cstate->binary)
474
				CopySendChar(cstate, '\n');
475 476 477 478 479 480 481 482 483 484 485

			/* 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
486
			return; /* don't want to reset msgbuf quite yet */
487 488
	}

489
	resetStringInfo(fe_msgbuf);
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
}

/*
 * 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:
506 507 508 509 510 511 512

			(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")));
513 514
			break;
		case COPY_OLD_FE:
515 516 517 518 519 520 521 522

			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")));
			}
523 524
			break;
		case COPY_NEW_FE:
525

526
			/* Dump the accumulated row as one CopyData message */
527
			(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
528
			break;
529 530 531 532
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* internal error */
			break;

533
	}
534

535
	resetStringInfo(fe_msgbuf);
536 537
}

538 539
/*
 * CopyGetData reads data from the source (file or frontend)
540
 * CopyGetChar does the same for single characters
541
 *
542
 * CopyGetEof checks if EOF was detected by previous Get operation.
543 544 545 546 547
 *
 * 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.
 *
548 549 550 551
 * NB: no data conversion is applied by these functions
 *
 * Returns: the number of bytes that were successfully read
 * into the data buffer.
552
 */
553
static int
554
CopyGetData(CopyState cstate, void *databuf, int datasize)
B
Bruce Momjian 已提交
555
{
556
	size_t		bytesread = 0;
557 558

	switch (cstate->copy_dest)
B
Bruce Momjian 已提交
559
	{
560
		case COPY_FILE:
561 562 563
			bytesread = fread(databuf, 1, datasize, cstate->copy_file);
			if (feof(cstate->copy_file))
				cstate->fe_eof = true;
564 565
			break;
		case COPY_OLD_FE:
566
			if (pq_getbytes((char *) databuf, datasize))
567 568
			{
				/* Only a \. terminator is legal EOF in old protocol */
569 570 571
				ereport(ERROR,
						(errcode(ERRCODE_CONNECTION_FAILURE),
						 errmsg("unexpected EOF on client connection")));
572
			}
573 574
			bytesread += datasize;		/* update the count of bytes that were
										 * read so far */
575 576
			break;
		case COPY_NEW_FE:
577
			while (datasize > 0 && !cstate->fe_eof)
578
			{
B
Bruce Momjian 已提交
579
				int			avail;
B
Bruce Momjian 已提交
580

581
				while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
582 583 584 585
				{
					/* Try to receive another message */
					int			mtype;

B
Bruce Momjian 已提交
586
			readmessage:
587 588
					mtype = pq_getbyte();
					if (mtype == EOF)
589 590
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
591
							 errmsg("unexpected EOF on client connection")));
592
					if (pq_getmessage(cstate->fe_msgbuf, 0))
593 594
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
595
							 errmsg("unexpected EOF on client connection")));
596 597
					switch (mtype)
					{
B
Bruce Momjian 已提交
598
						case 'd':		/* CopyData */
599
							break;
B
Bruce Momjian 已提交
600
						case 'c':		/* CopyDone */
601
							/* COPY IN correctly terminated by frontend */
602 603
							cstate->fe_eof = true;
							return bytesread;
B
Bruce Momjian 已提交
604
						case 'f':		/* CopyFail */
605 606 607
							ereport(ERROR,
									(errcode(ERRCODE_QUERY_CANCELED),
									 errmsg("COPY from stdin failed: %s",
608
									   pq_getmsgstring(cstate->fe_msgbuf))));
609
							break;
610 611
						case 'H':		/* Flush */
						case 'S':		/* Sync */
B
Bruce Momjian 已提交
612

613
							/*
614 615 616 617
							 * 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.
618 619
							 */
							goto readmessage;
620
						default:
621 622 623 624
							ereport(ERROR,
									(errcode(ERRCODE_PROTOCOL_VIOLATION),
									 errmsg("unexpected message type 0x%02X during COPY from stdin",
											mtype)));
625 626 627
							break;
					}
				}
628
				avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
629 630
				if (avail > datasize)
					avail = datasize;
631
				pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
632
				databuf = (void *) ((char *) databuf + avail);
633 634 635
				bytesread += avail;		/* update the count of bytes that were
										 * read so far */
				datasize -= avail;
B
Bruce Momjian 已提交
636
			}
637
			break;
638 639 640 641
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* RET read their own data with external_senddata() */
			break;

642
	}
B
Bruce Momjian 已提交
643

644
	return bytesread;
M
 
Marc G. Fournier 已提交
645
}
B
Bruce Momjian 已提交
646

647 648 649 650
/*
 * These functions do apply some data conversion
 */

A
alldefector 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
/*
 * CopySendInt32 sends an int32 in network byte order
 */
static void
CopySendInt32(CopyState cstate, int32 val)
{
	uint32		buf;

	buf = htonl((uint32) val);
	CopySendData(cstate, &buf, sizeof(buf));
}

/*
 * CopyGetInt32 reads an int32 that appears in network byte order
 *
 * Returns true if OK, false if EOF
 */
static bool
CopyGetInt32(CopyState cstate, int32 *val)
{
	uint32		buf;

	if (CopyGetData(cstate, &buf, sizeof(buf)) != sizeof(buf))
	{
		*val = 0;				/* suppress compiler warning */
		return false;
	}
	*val = (int32) ntohl(buf);
	return true;
}

/*
 * CopyGetInt64 reads an int64 that appears in network byte order
 *
 * Returns true if OK, false if EOF
 */
static bool
CopyGetInt64(CopyState cstate, int64 *val)
{
	uint64		buf;

	if (CopyGetData(cstate, &buf, sizeof(buf)) != sizeof(buf))
	{
		*val = 0;				/* suppress compiler warning */
		return false;
	}
	*val = (int64) ntohll(buf);
	return true;
}

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

	buf = htons((uint16) val);
	CopySendData(cstate, &buf, sizeof(buf));
}

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

	if (CopyGetData(cstate, &buf, sizeof(buf)) != sizeof(buf))
	{
		*val = 0;				/* suppress compiler warning */
		return false;
	}
	*val = (int16) ntohs(buf);
	return true;
}


731
/*
732
 * ValidateControlChars
733
 *
734 735 736 737 738 739 740 741 742 743
 * 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)
744
 */
745 746 747 748 749
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)
750
{
751
	bool	delim_off = (pg_strcasecmp(delim, "off") == 0);
752

753 754 755 756 757 758 759 760 761
	/*
	 * 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)
762
	{
763 764 765 766 767 768 769 770 771 772 773 774 775
		/* 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\'")));
776
	}
777

778 779 780 781 782
	if (strchr(delim, '\r') != NULL ||
		strchr(delim, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be newline or carriage return")));
783

784 785 786 787 788
	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")));
789

790 791 792 793
	if (!csv_mode && strchr(delim, '\\') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be backslash")));
794

795 796 797 798
	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")));
799

800 801 802 803 804 805 806 807 808 809 810 811 812 813 814
	/*
	 * 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)));
815

816
	if (delim_off)
817
	{
818

819 820 821 822 823 824 825 826 827 828 829
		/*
		 * 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 已提交
830

831 832 833 834
		if (num_columns != 1)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("Using no delimiter is only possible for a single column table")));
835

836
	}
837

838 839 840 841
	/*
	 * HEADER
	 */
	if(header_line)
842
	{
843
		if(!copy && Gp_role == GP_ROLE_DISPATCH)
844
		{
845 846 847 848 849 850 851 852 853 854 855
			/* (exttab) */
			if(load)
			{
				/* RET */
				ereport(NOTICE,
						(errmsg("HEADER means that each one of the data files "
								"has a header row.")));				
			}
			else
			{
				/* WET */
856
				ereport(ERROR,
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 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
						(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.
 *
975 976 977
 * Iff <binary>, unload or reload in the binary format, as opposed to the
 * more wasteful but more robust and portable text format.
 *
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
 * 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;
1009 1010 1011 1012 1013 1014
	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;
1015 1016 1017 1018 1019 1020 1021 1022

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

		if (strcmp(defel->defname, "binary") == 0)
		{
A
alldefector 已提交
1023
			if (cstate->binary)
1024 1025
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
A
alldefector 已提交
1026 1027
						 errmsg("conflicting or redundant options")));
			cstate->binary = intVal(defel->arg);
1028 1029 1030
		}
		else if (strcmp(defel->defname, "oids") == 0)
		{
1031
			if (cstate->oids)
1032 1033 1034
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1035
			cstate->oids = intVal(defel->arg);
1036 1037 1038
		}
		else if (strcmp(defel->defname, "delimiter") == 0)
		{
1039
			if (cstate->delim)
1040 1041 1042
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1043
			cstate->delim = strVal(defel->arg);
1044 1045 1046
		}
		else if (strcmp(defel->defname, "null") == 0)
		{
1047
			if (cstate->null_print)
1048 1049 1050
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1051
			cstate->null_print = strVal(defel->arg);
1052 1053 1054 1055 1056 1057 1058 1059 1060

			/*
			 * 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 = "";
1061
		}
B
Bruce Momjian 已提交
1062 1063
		else if (strcmp(defel->defname, "csv") == 0)
		{
1064
			if (cstate->csv_mode)
B
Bruce Momjian 已提交
1065 1066 1067
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1068
			cstate->csv_mode = intVal(defel->arg);
B
Bruce Momjian 已提交
1069
		}
1070 1071
		else if (strcmp(defel->defname, "header") == 0)
		{
1072
			if (cstate->header_line)
1073 1074 1075
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1076
			cstate->header_line = intVal(defel->arg);
1077
		}
B
Bruce Momjian 已提交
1078 1079
		else if (strcmp(defel->defname, "quote") == 0)
		{
1080
			if (cstate->quote)
B
Bruce Momjian 已提交
1081 1082 1083
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1084
			cstate->quote = strVal(defel->arg);
B
Bruce Momjian 已提交
1085 1086 1087
		}
		else if (strcmp(defel->defname, "escape") == 0)
		{
1088
			if (cstate->escape)
B
Bruce Momjian 已提交
1089 1090 1091
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1092
			cstate->escape = strVal(defel->arg);
B
Bruce Momjian 已提交
1093
		}
B
Bruce Momjian 已提交
1094
		else if (strcmp(defel->defname, "force_quote") == 0)
B
Bruce Momjian 已提交
1095
		{
B
Bruce Momjian 已提交
1096
			if (force_quote)
B
Bruce Momjian 已提交
1097 1098 1099
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
1100
			force_quote = (List *) defel->arg;
B
Bruce Momjian 已提交
1101
		}
B
Bruce Momjian 已提交
1102
		else if (strcmp(defel->defname, "force_notnull") == 0)
B
Bruce Momjian 已提交
1103
		{
B
Bruce Momjian 已提交
1104
			if (force_notnull)
B
Bruce Momjian 已提交
1105 1106 1107
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
B
Bruce Momjian 已提交
1108
			force_notnull = (List *) defel->arg;
B
Bruce Momjian 已提交
1109
		}
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
		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);
		}
A
Adam Lee 已提交
1126 1127 1128 1129 1130 1131 1132 1133
		else if (strcmp(defel->defname, "on_segment") == 0)
		{
			if (cstate->on_segment)
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
			cstate->on_segment = TRUE;
		}
1134
		else
1135
			elog(ERROR, "option \"%s\" not recognized",
1136 1137 1138
				 defel->defname);
	}

1139
	/* Set defaults */
B
Bruce Momjian 已提交
1140

A
alldefector 已提交
1141 1142 1143 1144 1145 1146
	/* Check for incompatible options */
	if (cstate->binary && cstate->delim)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify DELIMITER in BINARY mode")));

1147 1148 1149 1150 1151
	if (cstate->on_segment && stmt->filename==NULL)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("STDIN and STDOUT are not supported by 'COPY ON SEGMENT'")));

1152 1153 1154 1155
	/*
	 * In PostgreSQL, HEADER is not allowed in text mode either, but in GPDB,
	 * only forbid it with BINARY.
	 */
A
alldefector 已提交
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
	if (cstate->binary && cstate->header_line)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify HEADER in BINARY mode")));

	if (cstate->binary && cstate->csv_mode)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify CSV in BINARY mode")));

	if (cstate->binary && cstate->null_print)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify NULL in BINARY mode")));

1171 1172 1173
	cstate->err_loc_type = ROWNUM_ORIGINAL;
	cstate->eol_type = EOL_UNKNOWN;
	cstate->escape_off = false;
B
Bruce Momjian 已提交
1174

1175 1176
	if (!cstate->delim)
		cstate->delim = cstate->csv_mode ? "," : "\t";
B
Bruce Momjian 已提交
1177

1178 1179
	if (!cstate->null_print)
		cstate->null_print = cstate->csv_mode ? "" : "\\N";
B
Bruce Momjian 已提交
1180

1181
	if (cstate->csv_mode)
B
Bruce Momjian 已提交
1182
	{
1183 1184 1185 1186
		if (!cstate->quote)
			cstate->quote = "\"";
		if (!cstate->escape)
			cstate->escape = cstate->quote;
B
Bruce Momjian 已提交
1187
	}
B
Bruce Momjian 已提交
1188

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

1192 1193 1194 1195 1196 1197 1198 1199
	/*
	 * Error handling setup
	 */
	if(stmt->sreh)
	{
		/* Single row error handling requested */
		SingleRowErrorDesc *sreh;
		bool		log_to_file = false;
B
Bruce Momjian 已提交
1200

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

1203 1204 1205 1206
		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 已提交
1207

1208
		if (sreh->into_file)
1209 1210 1211 1212 1213 1214 1215 1216
		{
			cstate->errMode = SREH_LOG;
			log_to_file = true;
		}
		else
		{
			cstate->errMode = SREH_IGNORE;
		}
1217
		cstate->cdbsreh = makeCdbSreh(sreh->rejectlimit,
1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228
									  sreh->is_limit_in_rows,
									  stmt->filename,
									  stmt->relation->relname,
									  log_to_file);
	}
	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 已提交
1229

1230
	cstate->skip_ext_partition = stmt->skip_ext_partition;
B
Bruce Momjian 已提交
1231

1232 1233 1234 1235 1236 1237
	/* 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 已提交
1238

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261
	/*
	 * 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);
1262

1263
	/* Disallow file COPY except to superusers. */
1264
	if (!pipe && !superuser())
1265 1266 1267 1268
		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 已提交
1269
						 "psql's \\copy command also works for anyone.")));
B
Bruce Momjian 已提交
1270

1271
	cstate->copy_dest = COPY_FILE;		/* default */
A
Adam Lee 已提交
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283
	if (Gp_role == GP_ROLE_EXECUTE)
	{
		if (cstate->on_segment) /* Save data to a local file */
		{
			StringInfoData filepath;
			initStringInfo(&filepath);
			appendStringInfoString(&filepath, stmt->filename);

			replaceStringInfoString(&filepath, "<SEG_DATA_DIR>", DataDir);

			if (strstr(stmt->filename, "<SEGID>") == NULL)
				ereport(ERROR,
1284 1285
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
					 errmsg("<SEGID> is required for file name")));
A
Adam Lee 已提交
1286 1287 1288 1289 1290 1291

			char segid_buf[8];
			snprintf(segid_buf, 8, "%d", GpIdentity.segindex);
			replaceStringInfoString(&filepath, "<SEGID>", segid_buf);

			cstate->filename = filepath.data;
1292 1293 1294 1295 1296 1297 1298
			/* Rename filename if error log needed */
			if (NULL != cstate->cdbsreh)
			{
				snprintf(cstate->cdbsreh->filename,
						 sizeof(cstate->cdbsreh->filename), "%s",
						 filepath.data);
			}
A
Adam Lee 已提交
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

			pipe = false;
		}
		else
		{
			cstate->filename = NULL; /* QE COPY always uses STDIN */
		}
	}
	else
	{
		cstate->filename = stmt->filename; /* Not on_segment, QD saves file to local */
	}
1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328
	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;
A
Adam Lee 已提交
1329 1330 1331 1332
			char *filename = cstate->filename;

			if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
				filename = "/dev/null";
1333 1334 1335 1336 1337

			/*
			 * Prevent write to relative path ... too easy to shoot oneself in the
			 * foot by overwriting a database file ...
			 */
A
Adam Lee 已提交
1338
			if (!is_absolute_path(filename))
1339 1340 1341 1342 1343
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_NAME),
						 errmsg("relative path not allowed for COPY to file")));

			oumask = umask((mode_t) 022);
A
Adam Lee 已提交
1344
			cstate->copy_file = AllocateFile(filename, PG_BINARY_W);
1345 1346 1347 1348 1349
			umask(oumask);

			if (cstate->copy_file == NULL)
				ereport(ERROR,
						(errcode_for_file_access(),
A
Adam Lee 已提交
1350
						 errmsg("could not open file \"%s\" for writing: %m", filename)));
1351 1352 1353 1354 1355 1356 1357 1358

			// 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))
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
A
Adam Lee 已提交
1359
						 errmsg("\"%s\" is a directory", filename)));
1360 1361 1362 1363 1364
		}

	}

	elog(DEBUG1,"DoCopy starting");
1365 1366 1367 1368 1369 1370
	if (stmt->relation)
	{
		Assert(!stmt->query);
		cstate->queryDesc = NULL;

		/* Open and lock the relation, using the appropriate lock type. */
1371 1372
		cstate->rel = heap_openrv(stmt->relation,
							 (is_from ? RowExclusiveLock : AccessShareLock));
1373 1374 1375

		/* save relation oid for auto-stats call later */
		relationOid = RelationGetRelid(cstate->rel);
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399

		/* 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);
1400 1401 1402 1403

		/* Update error log info */
		if (cstate->cdbsreh)
			cstate->cdbsreh->relid = RelationGetRelid(cstate->rel);
1404 1405 1406 1407
	}
	else
	{
		List	   *rewritten;
1408
		Query	   *query;
1409
		PlannedStmt *plan;
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
		DestReceiver *dest;

		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")));

		/*
B
Bruce Momjian 已提交
1422
		 * Run parse analysis and rewrite.	Note this also acquires sufficient
1423
		 * locks on the source table(s).
1424
		 *
1425 1426
		 * Because the parser and planner tend to scribble on their input, we
		 * make a preliminary copy of the source querytree.  This prevents
1427 1428
		 * problems in the case that the COPY is in a portal or plpgsql
		 * function and is executed repeatedly.  (See also the same hack in
1429
		 * DECLARE CURSOR and PREPARE.)  XXX FIXME someday.
1430
		 */
1431 1432
		rewritten = pg_analyze_and_rewrite((Node *) copyObject(stmt->query),
										   queryString, NULL, 0);
1433 1434 1435 1436 1437 1438 1439

		/* 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);
1440
		Assert(query->utilityStmt == NULL);
1441

1442
		/* Query mustn't use INTO, either */
1443
		if (query->intoClause)
1444 1445 1446
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY (SELECT INTO) is not supported")));
1447 1448

		/* plan the query */
1449
		plan = planner(query, 0, NULL);
1450 1451 1452 1453 1454 1455 1456 1457

		/*
		 * 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.)
		 */
1458
		ActiveSnapshot->curcid = GetCurrentCommandId(false);
1459 1460 1461 1462 1463 1464

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

		/* Create a QueryDesc requesting no output */
1465
		cstate->queryDesc = CreateQueryDesc(plan, queryString,
1466 1467 1468
											ActiveSnapshot, InvalidSnapshot,
											dest, NULL, false);

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
		if (gp_enable_gpperfmon && Gp_role == GP_ROLE_DISPATCH)
		{
			Assert(queryString);
			gpmon_qlog_query_submit(cstate->queryDesc->gpmon_pkt);
			gpmon_qlog_query_text(cstate->queryDesc->gpmon_pkt,
					queryString,
					application_name,
					GetResqueueName(GetResQueueId()),
					GetResqueuePriority(GetResQueueId()));
		}

1480 1481 1482 1483 1484 1485 1486 1487 1488
		/*
		 * 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 已提交
1489

1490
	cstate->attnamelist = attnamelist;
1491
	/* Generate or convert list of attributes to process */
1492 1493 1494
	cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);

	num_phys_attrs = tupDesc->natts;
1495

1496 1497
	/* 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 已提交
1498
	if (force_quote)
B
Bruce Momjian 已提交
1499
	{
1500
		List	   *attnums;
1501
		ListCell   *cur;
B
Bruce Momjian 已提交
1502

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

1505
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1506
		{
1507
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1508

1509
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1510 1511
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1512 1513
				   errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
						  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1514
			cstate->force_quote_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1515 1516
		}
	}
B
Bruce Momjian 已提交
1517

1518 1519
	/* 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 已提交
1520
	if (force_notnull)
B
Bruce Momjian 已提交
1521
	{
1522
		List	   *attnums;
1523
		ListCell   *cur;
B
Bruce Momjian 已提交
1524

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

1527
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1528
		{
1529
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1530

1531
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1532 1533
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1534 1535
				errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
					   NameStr(tupDesc->attrs[attnum - 1]->attname))));
1536
			cstate->force_notnull_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1537
		}
B
Bruce Momjian 已提交
1538

1539 1540 1541
		/* keep the raw version too, we will need it later */
		cstate->force_notnull = force_notnull;
	}
1542 1543

	/* Set up variables to avoid per-attribute overhead. */
1544 1545
	initStringInfo(&cstate->attribute_buf);
	initStringInfo(&cstate->line_buf);
1546
	cstate->processed = 0;
1547

1548 1549
	/*
	 * Set up encoding conversion info.  Even if the client and server
1550 1551 1552 1553 1554 1555
	 * 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.
1556
	 */
1557
	cstate->client_encoding = pg_get_client_encoding();
1558
	cstate->need_transcoding =
1559 1560
		((cstate->client_encoding != GetDatabaseEncoding() ||
		  pg_database_encoding_max_length() > 1) && !qe_copy_from);
1561

1562 1563 1564
	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);
1565

1566
	/*
1567
	 * some greenplum db specific vars
1568
	 */
1569 1570
	cstate->is_copy_in = (is_from ? true : false);
	if (is_from)
1571
	{
1572 1573
		cstate->error_on_executor = false;
		initStringInfo(&(cstate->executor_err_context));
1574
	}
1575

1576 1577 1578 1579 1580 1581
	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;
1582

1583
		Assert(cstate->rel);
1584

1585
		relkind = cstate->rel->rd_rel->relkind;
1586

1587
		if (relkind != RELKIND_RELATION)
1588
		{
1589
			if (relkind == RELKIND_VIEW)
1590 1591
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1592 1593 1594
						 errmsg("cannot copy to view \"%s\"",
								RelationGetRelationName(cstate->rel))));
			else if (relkind == RELKIND_SEQUENCE)
1595 1596
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1597
						 errmsg("cannot copy to sequence \"%s\"",
1598
								RelationGetRelationName(cstate->rel))));
1599
			else
1600 1601
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1602
						 errmsg("cannot copy to non-table relation \"%s\"",
B
Bruce Momjian 已提交
1603
								RelationGetRelationName(cstate->rel))));
1604
		}
1605 1606 1607 1608 1609 1610

		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")));

1611 1612 1613 1614 1615
		if (cstate->on_segment && Gp_role == GP_ROLE_EXECUTE)
		{
			pipe = true;
		}

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
		if (pipe)
		{
			if (whereToSendOutput == DestRemote)
				ReceiveCopyBegin(cstate);
			else
				cstate->copy_file = stdin;
		}
		else
		{
			struct stat st;
1626
			char *filename = cstate->filename;
1627

1628 1629 1630 1631 1632
			/* Use dummy file on master for COPY FROM ON SEGMENT */
			if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
				filename = "/dev/null";

			cstate->copy_file = AllocateFile(filename, PG_BINARY_R);
1633 1634 1635 1636 1637

			if (cstate->copy_file == NULL)
				ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not open file \"%s\" for reading: %m",
1638
								filename)));
1639 1640 1641 1642 1643 1644 1645 1646

			// 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))
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1647
						 errmsg("\"%s\" is a directory", filename)));
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
		}


		/*
		 * 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))
			{
1675
				if (cstate->on_segment && gp_enable_segment_copy_checking && !partition_policies_equal(cstate->rel->rd_cdbpolicy, RelationBuildPartitionDesc(cstate->rel, false)))
1676
				{
1677 1678 1679 1680
					ereport(ERROR,
							(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
							 errmsg("COPY FROM ON SEGMENT doesn't support checking distribution key restriction when the distribution policy of the partition table is different from the main table"),
							 errhint("\"SET gp_enable_segment_copy_checking=off\" can be used to disable distribution key checking.")));
1681 1682
					return cstate->processed;
				}
1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
				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);
1707
					n->segno = SetSegnoForWrite(cstate->rel, InvalidFileSegNumber);
1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
					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 */
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733
			if (cstate->on_segment)
			{
				MemoryContext oldcxt;
				oldcxt = MemoryContextSwitchTo(CacheMemoryContext);
				cstate->rel->rd_cdbpolicy = palloc(sizeof(GpPolicy) + sizeof(AttrNumber) * stmt->nattrs);
				cstate->rel->rd_cdbpolicy->nattrs = stmt->nattrs;
				cstate->rel->rd_cdbpolicy->ptype = stmt->ptype;
				memcpy(cstate->rel->rd_cdbpolicy->attrs, stmt->distribution_attrs, sizeof(AttrNumber) * stmt->nattrs);
				MemoryContextSwitchTo(oldcxt);
			}
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
			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)));
		}
1745
	}
1746
	else
1747
		DoCopyTo(cstate);		/* copy from database to file */
1748

1749 1750 1751 1752 1753 1754 1755 1756 1757
	/*
	 * 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)
1758
	{
1759 1760 1761 1762
		/* Close down the query and free resources. */
		ExecutorEnd(cstate->queryDesc);
		FreeQueryDesc(cstate->queryDesc);
		cstate->queryDesc = NULL;
1763
	}
1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776

	/* 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)
1777
	{
1778 1779 1780 1781 1782 1783
		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);
	}
1784

1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
    /* 	 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);
1795

1796 1797
	pfree(cstate->attribute_buf.data);
	pfree(cstate->line_buf.data);
1798

1799 1800
	return processed;
}
1801

1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836
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)
	{
1837
		if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
1838
		{
1839
			if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
1840 1841 1842 1843 1844
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from view \"%s\"",
								RelationGetRelationName(cstate->rel)),
						 errhint("Try the COPY (SELECT ...) TO variant.")));
1845
			else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
				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,
1877
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1878 1879
					 errmsg("COPY ignores external partition(s)")));
			}
1880 1881
		}
	}
1882

1883 1884
	PG_TRY();
	{
1885 1886
		if (cstate->fe_copy)
			SendCopyBegin(cstate);
A
Adam Lee 已提交
1887 1888 1889 1890 1891 1892 1893 1894 1895
		else if	(Gp_role == GP_ROLE_EXECUTE && cstate->on_segment)
		{
			SendCopyBegin(cstate);
			/*
			 * For COPY ON SEGMENT command, segment writes to file
			 * instead of front end. Switch to COPY_FILE
			 */
			cstate->copy_dest = COPY_FILE;
		}
1896

1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908
		/*
		 * 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);
1909

1910 1911
		if (cstate->fe_copy)
			SendCopyEnd(cstate);
A
Adam Lee 已提交
1912 1913 1914 1915 1916 1917 1918 1919 1920
		else if (Gp_role == GP_ROLE_EXECUTE && cstate->on_segment)
		{
			/*
			 * For COPY ON SEGMENT command, switch back to front end
			 * before sending copy end which is "\."
			 */
			cstate->copy_dest = COPY_NEW_FE;
			SendCopyEnd(cstate);
		}
1921 1922 1923 1924
	}
	PG_CATCH();
	{
		/*
B
Bruce Momjian 已提交
1925
		 * Make sure we turn off old-style COPY OUT mode upon error. It is
B
Bruce Momjian 已提交
1926 1927
		 * okay to do this in all cases, since it does nothing if the mode is
		 * not on.
1928 1929 1930 1931 1932
		 */
		pq_endcopyout(true);
		PG_RE_THROW();
	}
	PG_END_TRY();
1933 1934 1935 1936 1937 1938 1939 1940 1941

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

1944
/*
1945 1946 1947
 * CopyToCreateDispatchCommand
 *
 * Create the COPY command that will get dispatched to the QE's.
1948
 */
1949 1950 1951 1952 1953 1954 1955 1956
static void CopyToCreateDispatchCommand(CopyState cstate,
										StringInfo cdbcopy_cmd,
										AttrNumber	num_phys_attrs,
										Form_pg_attribute *attr)

{
	ListCell   *cur;
	bool		is_first_col = true;
1957
	int			i;
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988

	/* 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, ")");
	}

A
Adam Lee 已提交
1989 1990 1991 1992 1993 1994 1995 1996
	if (cstate->on_segment)
	{
		appendStringInfo(cdbcopy_cmd, " TO '%s' WITH ON SEGMENT", cstate->filename);
	}
	else
	{
		appendStringInfo(cdbcopy_cmd, " TO STDOUT WITH");
	}
1997 1998 1999 2000

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

A
alldefector 已提交
2001 2002 2003 2004
	if (cstate->binary)
		appendStringInfo(cdbcopy_cmd, " BINARY");
	else
	{
2005 2006
		appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
		appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));
2007

2008 2009 2010
		/* 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));
2011

2012
		if (cstate->csv_mode)
2013
		{
2014
			appendStringInfo(cdbcopy_cmd, " CSV");
A
Adam Lee 已提交
2015 2016 2017 2018 2019 2020 2021 2022

			/*
			 * If on_segment, QE needs to write their own CSV header. If not,
			 * only QD needs to, QE doesn't send CSV header to QD
			 */
			if (cstate->on_segment && cstate->header_line)
				appendStringInfo(cdbcopy_cmd, " HEADER");

2023 2024 2025 2026 2027 2028
			appendStringInfo(cdbcopy_cmd, " QUOTE AS E'%s'", escape_quotes(cstate->quote));
			appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));

			/* Create list of FORCE QUOTE columns */
			is_first_col = true;
			for (i = 0; i < num_phys_attrs; i++)
2029
			{
2030 2031 2032 2033 2034 2035 2036
				if (cstate->force_quote_flags[i])
				{
					if (is_first_col)
						appendStringInfoString(cdbcopy_cmd, "FORCE QUOTE ");
					else
						appendStringInfoString(cdbcopy_cmd, ", ");
					is_first_col = false;
2037

2038 2039 2040
					appendStringInfoString(cdbcopy_cmd,
										   quote_identifier(NameStr(attr[i]->attname)));
				}
2041 2042
			}

2043 2044
			/* do NOT include HEADER. Header row is created by dispatcher COPY */
		}
A
alldefector 已提交
2045
	}
2046 2047 2048 2049 2050 2051 2052 2053 2054
}


/*
 * 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)
2055
{
2056
	TupleDesc	tupDesc;
2057
	int			num_phys_attrs;
2058
	int			attr_count;
2059
	Form_pg_attribute *attr;
2060 2061 2062
	CdbCopy    *cdbCopy;
	StringInfoData cdbcopy_err;
	StringInfoData cdbcopy_cmd;
2063

2064
	tupDesc = cstate->rel->rd_att;
2065 2066
	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
2067
	attr_count = list_length(cstate->attnumlist);
2068

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

2072 2073 2074 2075 2076 2077
	/*
	 * 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 已提交
2078

2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094
	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);
2095

2096
	/*
2097 2098 2099 2100 2101 2102 2103
	 * 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.
2104
	 */
2105
	elog(DEBUG5, "COPY command sent to segdbs: %s", cdbcopy_cmd.data);
2106

2107 2108
	PG_TRY();
	{
2109
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data, NULL);
2110 2111
	}
	PG_CATCH();
2112
	{
2113 2114
		/* get error message from CopyStart */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
2115

2116 2117 2118 2119 2120 2121 2122
		/* 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();
2123
	}
2124 2125
	PG_END_TRY();

A
alldefector 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
	if (cstate->binary)
	{
		/* Generate header for a binary copy */
		int32		tmp;

		/* Signature */
		CopySendData(cstate, (char *) BinarySignature, 11);
		/* Flags field */
		tmp = 0;
		if (cstate->oids)
			tmp |= (1 << 16);
		CopySendInt32(cstate, tmp);
		/* No header extension */
		tmp = 0;
		CopySendInt32(cstate, tmp);
	}

2143 2144
	/* if a header has been requested send the line */
	if (cstate->header_line)
2145
	{
2146 2147 2148
		ListCell   *cur;
		bool		hdr_delim = false;

2149 2150 2151
		/*
		 * For non-binary copy, we need to convert null_print to client
		 * encoding, because it will be sent directly with CopySendString.
2152 2153 2154 2155
		 *
		 * 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
2156
		 */
2157
		if (cstate->need_transcoding)
2158 2159 2160 2161 2162
			cstate->null_print = (char *)
				pg_server_to_custom(cstate->null_print,
									strlen(cstate->null_print),
									cstate->client_encoding,
									cstate->enc_conversion_proc);
2163

2164
		foreach(cur, cstate->attnumlist)
2165
		{
2166 2167
			int			attnum = lfirst_int(cur);
			char	   *colname;
B
Bruce Momjian 已提交
2168

2169 2170 2171
			if (hdr_delim)
				CopySendChar(cstate, cstate->delim[0]);
			hdr_delim = true;
2172

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

2175 2176 2177
			CopyAttributeOutCSV(cstate, colname, false,
								list_length(cstate->attnumlist) == 1);
		}
2178

2179 2180 2181
		/* add a newline and flush the data */
		CopySendEndOfRow(cstate);
	}
2182

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
	/*
	 * 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;
2216
		}
2217
	}
2218

A
alldefector 已提交
2219 2220 2221 2222 2223 2224 2225 2226
	if (cstate->binary)
	{
		/* Generate trailer for a binary copy */
		CopySendInt16(cstate, -1);
		/* Need to flush out the trailer */
		CopySendEndOfRow(cstate);
	}

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 2254 2255 2256 2257 2258 2259 2260
	/* 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;

2261
	if (cstate->rel)
2262
	{
2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291
		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();

	/* Get info about the columns we need to process. */
2292
	cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2293 2294 2295 2296 2297 2298
	foreach(cur, cstate->attnumlist)
	{
		int			attnum = lfirst_int(cur);
		Oid			out_func_oid;
		bool		isvarlena;

A
alldefector 已提交
2299 2300 2301 2302 2303
		if (cstate->binary)
			getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
									&out_func_oid,
									&isvarlena);
		else
2304 2305 2306
			getTypeOutputInfo(attr[attnum - 1]->atttypid,
							  &out_func_oid,
							  &isvarlena);
2307 2308
		fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
	}
B
Bruce Momjian 已提交
2309

2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320
	/*
	 * 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);
2321

2322 2323 2324 2325 2326 2327 2328 2329 2330
	/*
	 * 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);
2331

A
alldefector 已提交
2332 2333 2334
	if (cstate->binary)
	{
		/* binary header should not be sent in execute mode. */
A
Adam Lee 已提交
2335
		if (Gp_role != GP_ROLE_EXECUTE || cstate->on_segment)
A
alldefector 已提交
2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353
		{
			/* Generate header for a binary copy */
			int32		tmp;

			/* Signature */
			CopySendData(cstate, (char *) BinarySignature, 11);
			/* Flags field */
			tmp = 0;
			if (cstate->oids)
				tmp |= (1 << 16);
			CopySendInt32(cstate, tmp);
			/* No header extension */
			tmp = 0;
			CopySendInt32(cstate, tmp);
		}
	}
	else
	{
2354 2355
		/* if a header has been requested send the line */
		if (cstate->header_line)
2356
		{
2357
			/* header should not be printed in execute mode. */
A
Adam Lee 已提交
2358
			if (Gp_role != GP_ROLE_EXECUTE || cstate->on_segment)
2359
			{
2360
				bool		hdr_delim = false;
2361

2362 2363 2364 2365
				foreach(cur, cstate->attnumlist)
				{
					int			attnum = lfirst_int(cur);
					char	   *colname;
2366

2367 2368 2369
					if (hdr_delim)
						CopySendChar(cstate, cstate->delim[0]);
					hdr_delim = true;
2370

2371 2372 2373 2374 2375 2376 2377
					colname = NameStr(attr[attnum - 1]->attname);

					CopyAttributeOutCSV(cstate, colname, false,
										list_length(cstate->attnumlist) == 1);
				}
				CopySendEndOfRow(cstate);
			}
2378
		}
2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412
	}

	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;

A
alldefector 已提交
2413 2414 2415 2416 2417
				if (cstate->binary)
					getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
											&out_func_oid,
											&isvarlena);
				else
2418 2419 2420
					getTypeOutputInfo(attr[attnum - 1]->atttypid,
									  &out_func_oid,
									  &isvarlena);
A
alldefector 已提交
2421

2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456
				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();
2457

2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
					/* 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);
		}
2528 2529 2530
	}
	else
	{
2531 2532
		Assert(Gp_role != GP_ROLE_EXECUTE);

2533 2534 2535 2536
		/* run the plan --- the dest receiver will send tuples */
		ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L);
	}

A
alldefector 已提交
2537
	/* binary trailer should not be sent in execute mode. */
A
Adam Lee 已提交
2538
	if (cstate->binary)
A
alldefector 已提交
2539
	{
A
Adam Lee 已提交
2540 2541 2542 2543 2544 2545 2546 2547
		if (Gp_role != GP_ROLE_EXECUTE || (Gp_role == GP_ROLE_EXECUTE && cstate->on_segment))
		{
			/* Generate trailer for a binary copy */
			CopySendInt16(cstate, -1);

			/* Need to flush out the trailer */
			CopySendEndOfRow(cstate);
		}
A
alldefector 已提交
2548 2549
	}

2550 2551 2552
	if (Gp_role == GP_ROLE_EXECUTE && cstate->on_segment)
		SendNumRows(0, cstate->processed);

2553 2554 2555
	MemoryContextDelete(cstate->rowcontext);
}

2556 2557
void
CopyOneCustomRowTo(CopyState cstate, bytea *value)
2558 2559 2560
{
	appendBinaryStringInfo(cstate->fe_msgbuf,
						   VARDATA_ANY((void *) value),
2561 2562 2563
						   VARSIZE_ANY_EXHDR((void *) value));
}

2564 2565 2566
/*
 * Emit one row during CopyTo().
 */
2567
void
2568
CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
2569 2570 2571 2572 2573 2574 2575 2576 2577 2578
{
	bool		need_delim = false;
	FmgrInfo   *out_functions = cstate->out_functions;
	MemoryContext oldcontext;
	ListCell   *cur;
	char	   *string;

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

A
alldefector 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592
	if (cstate->binary)
	{
		/* Binary per-tuple header */
		CopySendInt16(cstate, list_length(cstate->attnumlist));
		/* Send OID if wanted --- note attnumlist doesn't include it */
		if (cstate->oids)
		{
			/* Hack --- assume Oid is same size as int32 */
			CopySendInt32(cstate, sizeof(int32));
			CopySendInt32(cstate, tupleOid);
		}
	}
	else
	{
2593 2594 2595 2596 2597 2598 2599 2600 2601
		/* 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)
		{
			string = DatumGetCString(DirectFunctionCall1(oidout,
												ObjectIdGetDatum(tupleOid)));
			CopySendString(cstate, string);
			need_delim = true;
		}
A
alldefector 已提交
2602
	}
2603 2604 2605 2606

	foreach(cur, cstate->attnumlist)
	{
		int			attnum = lfirst_int(cur);
2607 2608
		Datum		value = values[attnum - 1];
		bool		isnull = nulls[attnum - 1];
2609

A
alldefector 已提交
2610 2611
		if (!cstate->binary)
		{
2612 2613 2614
			if (need_delim)
				CopySendChar(cstate, cstate->delim[0]);
			need_delim = true;
A
alldefector 已提交
2615
		}
2616

2617 2618
		if (isnull)
		{
A
alldefector 已提交
2619
			if (!cstate->binary)
2620
				CopySendString(cstate, cstate->null_print_client);
A
alldefector 已提交
2621 2622
			else
				CopySendInt32(cstate, -1);
2623 2624 2625
		}
		else
		{
A
alldefector 已提交
2626 2627
			if (!cstate->binary)
			{
2628
				char		quotec = cstate->quote ? cstate->quote[0] : '\0';
2629

2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
				/* 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.
					 */
2640

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

2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669
					/*
					 * Integers don't need quoting, or transcoding to client char
					 * set. We still quote them if FORCE QUOTE was used, though.
					 */
					if (cstate->force_quote_flags[attnum - 1])
						CopySendChar(cstate, quotec);
					CopySendData(cstate, tmp, strlen(tmp));
					if (cstate->force_quote_flags[attnum - 1])
						CopySendChar(cstate, quotec);
				}
				else if (out_functions[attnum -1].fn_oid == 1702)   /* numeric_out */
				{
					string = OutputFunctionCall(&out_functions[attnum - 1],
												value);
					/*
					 * Numerics don't need quoting, or transcoding to client char
					 * set. We still quote them if FORCE QUOTE was used, though.
					 */
					if (cstate->force_quote_flags[attnum - 1])
						CopySendChar(cstate, quotec);
					CopySendData(cstate, string, strlen(string));
					if (cstate->force_quote_flags[attnum - 1])
						CopySendChar(cstate, quotec);
				}
2670
				else
2671 2672 2673 2674 2675 2676 2677 2678 2679 2680
				{
					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);
					else
						CopyAttributeOutText(cstate, string);
				}
2681
			}
A
alldefector 已提交
2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
			else
			{
				bytea	   *outputbytes;

				outputbytes = SendFunctionCall(&out_functions[attnum - 1],
											   value);
				CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
				CopySendData(cstate, VARDATA(outputbytes),
							 VARSIZE(outputbytes) - VARHDRSZ);
			}
		}
2693 2694
	}

2695 2696
	/*
	 * Finish off the row: write it to the destination, and update the count.
2697
	 * However, if we're in the context of a writable external table, we let
2698 2699 2700 2701 2702 2703 2704 2705
	 * 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++;
	}
2706

2707
	MemoryContextSwitchTo(oldcontext);
2708 2709
}

2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
static void CopyFromProcessDataFileHeader(CopyState cstate, CdbCopy *cdbCopy, bool *pfile_has_oids)
{
	if (!cstate->binary)
	{
		*pfile_has_oids = cstate->oids;	/* must rely on user to tell us... */
	}
	else
	{
		/* Read and verify binary header */
		char		readSig[11];
		int32		tmp_flags, tmp_extension;
		int32		tmp;

		/* Signature */
		if (CopyGetData(cstate, readSig, 11) != 11 ||
			memcmp(readSig, BinarySignature, 11) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					errmsg("COPY file signature not recognized")));
		/* Flags field */
		if (!CopyGetInt32(cstate, &tmp_flags))
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					errmsg("invalid COPY file header (missing flags)")));
		*pfile_has_oids = (tmp_flags & (1 << 16)) != 0;
		tmp = tmp_flags & ~(1 << 16);
		if ((tmp >> 16) != 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				errmsg("unrecognized critical flags in COPY file header")));
		/* Header extension length */
		if (!CopyGetInt32(cstate, &tmp_extension) ||
			tmp_extension < 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					errmsg("invalid COPY file header (missing length)")));
		/* Skip extension header, if present */
		while (tmp_extension-- > 0)
		{
			if (CopyGetData(cstate, readSig, 1) != 1)
				ereport(ERROR,
						(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
						errmsg("invalid COPY file header (wrong length)")));
		}

		/* Send binary header to all segments except:
			* dummy file on master for COPY FROM ON SEGMENT
			*/
		if(Gp_role == GP_ROLE_DISPATCH && !cstate->on_segment)
		{
			uint32 buf;
			cdbCopySendDataToAll(cdbCopy, (char *) BinarySignature, 11);
			buf = htonl((uint32) tmp_flags);
			cdbCopySendDataToAll(cdbCopy, (char *) &buf, 4);
			buf = htonl((uint32) 0);
			cdbCopySendDataToAll(cdbCopy, (char *) &buf, 4);
		}
	}

	if (*pfile_has_oids && cstate->binary)
	{
		FmgrInfo	oid_in_function;
		Oid			oid_typioparam;
		Oid			in_func_oid;

		getTypeBinaryInputInfo(OIDOID,
							&in_func_oid, &oid_typioparam);
		fmgr_info(in_func_oid, &oid_in_function);
	}
}
2780

2781
/*
2782 2783 2784 2785 2786 2787
 * 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.
2788
 */
A
alldefector 已提交
2789
static int CopyFromCreateDispatchCommand(CopyState cstate,
2790 2791 2792 2793 2794 2795 2796 2797 2798
										  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)
2799
{
2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
	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 */
2818
	{
2819 2820
		is_first_col = true;
		foreach(cur, cstate->attnumlist)
2821
		{
2822 2823
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
2824

2825 2826 2827 2828 2829 2830 2831 2832 2833
			/* 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;
2834
		}
2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851

		/*
		 * 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++)
2852
		{
2853 2854 2855 2856
			bool add_to_list = false;

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

2860 2861
				if(h_attnum - 1 == defmap[i])
					add_to_list = true;
2862
			}
2863 2864 2865 2866 2867 2868

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

			if(add_to_list)
2869
			{
2870
				/* We don't add dropped attributes */
A
alldefector 已提交
2871
				/* XXXX: this check seems unnecessary given how CopyFromDispatch constructs defmap */
2872 2873 2874 2875 2876 2877 2878 2879 2880
				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;
2881 2882
			}
		}
2883 2884 2885

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

2888 2889
	/*
	 * NOTE: we used to always pass STDIN here to the QEs. But since we want
2890
	 * the QEs to know the original file name for recording it in an error log file
2891 2892 2893
	 * (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
2894
	 * error log file).
2895 2896 2897 2898 2899
	 */
	if(cstate->filename)
		appendStringInfo(cdbcopy_cmd, " FROM %s WITH", quote_literal_internal(cstate->filename));
	else
		appendStringInfo(cdbcopy_cmd, " FROM STDIN WITH");
2900

2901 2902 2903
	if (cstate->on_segment)
		appendStringInfo(cdbcopy_cmd, " ON SEGMENT");

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

A
alldefector 已提交
2907 2908 2909 2910 2911 2912
	if (cstate->binary)
	{
		appendStringInfo(cdbcopy_cmd, " BINARY");
	}
	else
	{
2913 2914
		appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
		appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));
2915

2916 2917 2918
		/* 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));
2919

2920 2921
		/* if EOL is already defined it means that NEWLINE was declared. pass it along */
		if (cstate->eol_type != EOL_UNKNOWN)
2922
		{
2923 2924 2925
			Assert(cstate->eol_str);
			appendStringInfo(cdbcopy_cmd, " NEWLINE AS '%s'", escape_quotes(cstate->eol_str));
		}
2926

2927 2928 2929
		if (cstate->csv_mode)
		{
			appendStringInfo(cdbcopy_cmd, " CSV");
2930 2931 2932 2933 2934 2935 2936 2937

			/*
			 * If on_segment, QE needs to write its own CSV header. If not,
			 * only QD needs to, QE doesn't send CSV header to QD
			 */
			if (cstate->on_segment && cstate->header_line)
				appendStringInfo(cdbcopy_cmd, " HEADER");

2938 2939
			appendStringInfo(cdbcopy_cmd, " QUOTE AS E'%s'", escape_quotes(cstate->quote));
			appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));
2940

2941
			if(cstate->force_notnull)
2942
			{
2943
				ListCell   *l;
2944

2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955
				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;
				}
2956
			}
2957
			/* do NOT include HEADER. Header row is "swallowed" by dispatcher COPY */
2958
		}
A
alldefector 已提交
2959
	}
2960 2961 2962 2963 2964 2965 2966 2967 2968

	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)
		{
2969
			appendStringInfoString(cdbcopy_cmd, " LOG ERRORS");
2970 2971 2972 2973 2974
		}

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

A
alldefector 已提交
2976
	return extra_attr_count;
2977
}
2978

2979 2980 2981
/*
 * Copy FROM file to relation.
 */
2982 2983
void
CopyFromDispatch(CopyState cstate)
2984
{
2985
	TupleDesc	tupDesc;
2986
	Form_pg_attribute *attr;
B
Bruce Momjian 已提交
2987 2988 2989
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
2990
	FmgrInfo   *in_functions;
A
alldefector 已提交
2991
	FmgrInfo	oid_in_function;
2992
	FmgrInfo   *out_functions; /* for handling defaults in Greenplum Database */
2993
	Oid		   *typioparams;
A
alldefector 已提交
2994
	Oid			oid_typioparam;
2995
	int			attnum;
B
Bruce Momjian 已提交
2996
	int			i;
2997
	int			p_index;
2998
	Oid			in_func_oid;
2999
	Oid			out_func_oid;
3000
	Datum	   *values;
3001 3002
	bool	   *nulls;
	int		   *attr_offsets;
3003
	int			total_rejected_from_qes = 0;
3004
	int			total_completed_from_qes = 0;
3005
	bool		isnull;
3006
	bool	   *isvarlena;
3007
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
3008
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
3009
	bool		file_has_oids = false;
3010
	int		   *defmap;
3011
	ExprState **defexprs;		/* array of default att expressions */
B
Bruce Momjian 已提交
3012
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
3013
	MemoryContext oldcontext = CurrentMemoryContext;
3014
	ErrorContextCallback errcontext;
3015 3016 3017 3018
	bool		no_more_data = false;
	ListCell   *cur;
	bool		cur_row_rejected = false;
	CdbCopy    *cdbCopy;
3019

3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033
	/*
	 * 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;
3034

3035 3036 3037 3038
	/*
	 * a reconstructed and modified COPY command that is dispatched to segments.
	 */
	StringInfoData cdbcopy_cmd;
3039

3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053
	/*
	 * 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;
3054

3055 3056 3057 3058 3059
	/*
	 * Variables for original row number tracking
	 */
	StringInfoData line_buf_with_lineno;
	int			original_lineno_for_qe;
3060

3061 3062 3063
	/*
	 * Variables for cdbhash
	 */
3064

3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085
	/*
	 * 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 */
3086

3087
	tupDesc = RelationGetDescr(cstate->rel);
3088
	attr = tupDesc->attrs;
3089
	num_phys_attrs = tupDesc->natts;
3090
	attr_count = list_length(cstate->attnumlist);
3091
	num_defaults = 0;
3092 3093 3094 3095 3096 3097 3098
	h_attnum = 0;

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

	/*
3101
	 * We need a ResultRelInfo so we can use the regular executor's
3102 3103
	 * index-entry-making machinery.  (There used to be a huge amount of
	 * code here that basically duplicated execUtils.c ...)
3104
	 */
3105
	resultRelInfo = makeNode(ResultRelInfo);
B
Bruce Momjian 已提交
3106
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
3107 3108
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
3109 3110
	if (resultRelInfo->ri_TrigDesc)
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
3111 3112 3113
            palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
    resultRelInfo->ri_TrigInstrument = NULL;
    ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
3114

3115
	ExecOpenIndices(resultRelInfo);
3116

3117 3118 3119
	estate->es_result_relations = resultRelInfo;
	estate->es_num_result_relations = 1;
	estate->es_result_relation_info = resultRelInfo;
3120

3121 3122
	econtext = GetPerTupleExprContext(estate);

3123
	/*
3124
	 * Pick up the required catalog information for each attribute in the
3125 3126
	 * relation, including the input function, the element type (to pass
	 * to the input function), and info about defaults and constraints.
3127
	 */
3128
	in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3129
	out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3130
	typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
3131 3132
	defmap = (int *) palloc(num_phys_attrs * sizeof(int));
	defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
3133 3134
	isvarlena = (bool *) palloc(num_phys_attrs * sizeof(bool));

3135

3136
	for (attnum = 1; attnum <= num_phys_attrs; attnum++)
3137
	{
3138
		/* We don't need info for dropped attributes */
3139
		if (attr[attnum - 1]->attisdropped)
3140
			continue;
B
Bruce Momjian 已提交
3141

3142
		/* Fetch the input function and typioparam info */
A
alldefector 已提交
3143 3144 3145 3146
		if (cstate->binary)
			getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
								   &in_func_oid, &typioparams[attnum - 1]);
		else
3147 3148
			getTypeInputInfo(attr[attnum - 1]->atttypid,
							 &in_func_oid, &typioparams[attnum - 1]);
3149
		fmgr_info(in_func_oid, &in_functions[attnum - 1]);
B
Bruce Momjian 已提交
3150

3151 3152 3153 3154 3155
		/*
		 * Fetch the output function and typioparam info. We need it
		 * for handling default functions on the dispatcher COPY, if
		 * there are any.
		 */
A
alldefector 已提交
3156 3157 3158 3159 3160
		if (cstate->binary)
			getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
									&out_func_oid,
									&isvarlena[attnum - 1]);
		else
3161 3162 3163
			getTypeOutputInfo(attr[attnum - 1]->atttypid,
							  &out_func_oid,
							  &isvarlena[attnum - 1]);
3164 3165 3166 3167
		fmgr_info(out_func_oid, &out_functions[attnum - 1]);

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

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

			if (defexpr != NULL)
B
Bruce Momjian 已提交
3176
			{
3177 3178
				defexprs[num_defaults] = ExecPrepareExpr((Expr *) defexpr,
														 estate);
3179
				defmap[num_defaults] = attnum - 1;
3180
				num_defaults++;
3181
			}
3182
		}
3183 3184
	}

3185
	/*
3186 3187 3188 3189 3190 3191 3192
	 * 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.
3193
	 */
3194
	cdbCopy = makeCdbCopy(true);
3195

3196 3197
	estate->es_result_partitions = cdbCopy->partitions =
		RelationBuildPartitionDesc(cstate->rel, false);
3198

3199
	CopyInitPartitioningState(estate);
3200 3201


3202 3203
	if (list_length(cstate->ao_segnos) > 0)
		cdbCopy->ao_segnos = cstate->ao_segnos;
3204

3205 3206 3207
	/* add cdbCopy reference to cdbSreh (if needed) */
	if (cstate->errMode != ALL_OR_NOTHING)
		cstate->cdbsreh->cdbcopy = cdbCopy;
3208

3209 3210 3211 3212
	/* 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))
3213
	{
3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
		/*
		 * 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);
	}
	else
3247
	{
3248
		policy = GpPolicyCopy(CurrentMemoryContext, cstate->rel->rd_cdbpolicy);
3249

3250 3251 3252 3253 3254
		if (policy)
			p_nattrs = policy->nattrs;	/* number of partitioning keys */
		else
			p_nattrs = 0;
		/* Create hash API reference */
3255
		cdbHash = makeCdbHash(cdbCopy->total_segs);
3256
	}
3257

3258

3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271
	/*
	 * 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];
3272

3273 3274 3275 3276 3277 3278 3279
		/*
		 * 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
3280
		{
3281 3282 3283 3284 3285 3286 3287
			/* 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]);
		}
	}
3288

3289 3290 3291 3292 3293
	/* allocate memory for error and copy strings */
	initStringInfo(&cdbcopy_err);
	initStringInfo(&cdbcopy_cmd);

	/* store the COPY command string in cdbcopy_cmd */
A
alldefector 已提交
3294
	int extra_attr_count = CopyFromCreateDispatchCommand(cstate,
3295 3296 3297 3298 3299 3300 3301 3302 3303
								  &cdbcopy_cmd,
								  policy,
								  num_phys_attrs,
								  num_defaults,
								  p_nattrs,
								  h_attnum,
								  defmap,
								  defexprs,
								  attr);
3304

3305 3306 3307 3308 3309 3310 3311 3312
	/*
	 * 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;
3313

3314 3315 3316
	for (p_index = 0; p_index < p_nattrs; p_index++)
	{
		i = 1;
3317

3318 3319 3320 3321 3322 3323 3324
		/*
		 * 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 已提交
3325

3326 3327 3328 3329
			if (attnum == policy->attrs[p_index])
			{
				if (i > cstate->last_hash_field)
					cstate->last_hash_field = i;
3330
			}
B
Bruce Momjian 已提交
3331

3332
			if (estate->es_result_partitions)
3333
			{
3334
				if (attnum == estate->es_partition_state->max_partition_attr)
B
Bruce Momjian 已提交
3335
				{
3336 3337 3338
					if (i > cstate->last_hash_field)
						cstate->last_hash_field = i;
				}				
3339
			}
B
Bruce Momjian 已提交
3340

3341
			i++;
3342
		}
3343
	}
3344

A
alldefector 已提交
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
	/* init partition routing data structure */
	if (estate->es_result_partitions)
	{
		PartitionNode *n = estate->es_result_partitions;
		MemoryContext cxt_save;

		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;
		}
	}

3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397
	/*
	 * 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();
	{
3398
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data, cstate->rel->rd_cdbpolicy);
3399 3400 3401 3402 3403
	}
	PG_CATCH();
	{
		/* get error message from CopyStart */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
3404

3405 3406
		/* end COPY in all the segdbs in progress */
		cdbCopyEnd(cdbCopy);
3407

3408 3409
		/* get error message from CopyEnd */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
3410

3411 3412 3413 3414 3415 3416
		ereport(LOG,
				(errcode(ERRCODE_CDB_INTERNAL_ERROR),
				 errmsg("%s", cdbcopy_err.data)));
		PG_RE_THROW();
	}
	PG_END_TRY();
3417

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

3421
	/*
3422 3423 3424 3425
	 * 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.
3426 3427
	 */
	//ExecBSInsertTriggers(estate, resultRelInfo);
B
Bruce Momjian 已提交
3428

3429 3430
	/* Skip header processing if dummy file on master for COPY FROM ON SEGMENT */
	if (!cstate->on_segment || Gp_role != GP_ROLE_DISPATCH)
A
alldefector 已提交
3431
	{
3432
		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
A
alldefector 已提交
3433
	}
3434

3435 3436 3437
	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));
3438

3439 3440 3441 3442 3443 3444
	/* 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;
3445

3446
	CopyInitDataParser(cstate);
3447

3448 3449 3450
	do
	{
		size_t		bytesread = 0;
3451

A
alldefector 已提交
3452 3453
		if (!cstate->binary)
		{
3454 3455 3456 3457
		/* read a chunk of data into the buffer */
		PG_TRY();
		{
			bytesread = CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);
3458
		}
3459
		PG_CATCH();
3460
		{
3461
			/*
3462 3463 3464 3465
			 * 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.
3466
			 */
3467 3468
			cdbCopyEnd(cdbCopy);
			PG_RE_THROW();
3469
		}
3470
		PG_END_TRY();
3471

3472
		cstate->raw_buf_done = false;
3473

3474 3475 3476
		/* set buffer pointers to beginning of the buffer */
		cstate->begloc = cstate->raw_buf;
		cstate->raw_buf_index = 0;
A
alldefector 已提交
3477
		}
3478

3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500
		/*
		 * 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.
					 */
3501

3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516
					/*
					 * 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! */
3517

3518 3519 3520 3521 3522 3523 3524 3525
						/*
						 * 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 已提交
3526

3527 3528
				cstate->cur_lineno++;
				RESET_LINEBUF;
V
Vadim B. Mikheev 已提交
3529

3530 3531
				cstate->header_line = false;
			}
3532

3533 3534 3535 3536 3537 3538
			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 */
3539

3540 3541 3542 3543 3544 3545
				if (QueryCancelPending)
				{
					/* quit processing loop */
					no_more_data = true;
					break;
				}
3546

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

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

3553 3554 3555 3556
				/* 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));
3557

3558 3559
				/* Get the line number of the first line of this data row */
				original_lineno_for_qe = cstate->cur_lineno + 1;
3560

A
alldefector 已提交
3561 3562
				if (!cstate->binary)
				{
3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575
				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();
3576

3577 3578 3579 3580 3581
				if(cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
				}
3582 3583


3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604
				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;
				}
3605

3606 3607 3608
				if (file_has_oids)
				{
					char	   *oid_string;
3609

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

3613 3614 3615
					if (isnull)
					{
						/* got here? null in OID column error */
3616

3617 3618 3619 3620
						if(cstate->errMode == ALL_OR_NOTHING)
						{
							/* report error and abort */
							cdbCopyEnd(cdbCopy);
3621

3622 3623 3624 3625 3626 3627 3628 3629 3630 3631
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("null OID in COPY data.")));
						}
						else
						{
							/* SREH */
							cstate->cdbsreh->rejectcount++;
							cur_row_rejected = true;
						}
3632

3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647
					}
					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();
3648

3649 3650 3651 3652 3653 3654
						if (loaded_oid == InvalidOid)
						{
							if(cstate->errMode == ALL_OR_NOTHING)
							{
								/* report error and abort */
								cdbCopyEnd(cdbCopy);
3655

3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666
								ereport(ERROR,
										(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
										 errmsg("invalid OID in COPY data.")));
							}
							else
							{
								/* SREH */
								cstate->cdbsreh->rejectcount++;
								cur_row_rejected = true;
							}
						}
3667

3668 3669
						cstate->cur_attname = NULL;
					}
B
Bruce Momjian 已提交
3670

3671 3672 3673 3674 3675 3676
					if(cur_row_rejected)
					{
						ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
						QD_GOTO_NEXT_ROW;
					}
				}
A
alldefector 已提交
3677 3678 3679 3680 3681 3682 3683 3684
				}
				else
				{
					/*
					 * Binary mode, not doing anything here;
					 * Deferring "line" segmenting and parsing to next code block.
					 */
				}
3685

3686 3687 3688 3689 3690
				PG_TRY();
				{
					/*
					 * parse and convert the data line attributes.
					 */
A
alldefector 已提交
3691 3692
					if (!cstate->binary)
					{
3693 3694 3695 3696
					if (cstate->csv_mode)
						CopyReadAttributesCSV(cstate, nulls, attr_offsets, num_phys_attrs, attr);
					else
						CopyReadAttributesText(cstate, nulls, attr_offsets, num_phys_attrs, attr);
3697

A
alldefector 已提交
3698
						/* Parse only partition attributes */
3699 3700 3701 3702 3703 3704 3705
					attr_get_key(cstate, cdbCopy,
								 original_lineno_for_qe,
								 target_seg,
								 p_nattrs, policy->attrs,
								 attr, attr_offsets, nulls,
							   	 in_functions, typioparams,
								 values);
A
alldefector 已提交
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
					}
					else
					{
						/* binary */
						int16		fld_count;
						int32		fld_size;
						char buffer[20];
						ListCell   *cur;

						resetStringInfo(&cstate->line_buf);

						if (!CopyGetInt16(cstate, &fld_count) ||
							fld_count == -1)
						{
							no_more_data = true;
							break;
						}

						cstate->cur_lineno++;

						/*
						 * copy to line_buf
						*/
						uint16 fld_count_be = htons((uint16) fld_count + extra_attr_count);
						appendBinaryStringInfo(&cstate->line_buf, &fld_count_be, 2);

						if (fld_count != attr_count)
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("QE: line %s: row field count is %d, expected %d",
									 		linenumber_atoi(buffer, cstate->cur_lineno),
											(int) fld_count, attr_count)));

						if (file_has_oids)
						{
							cstate->cur_attname = "oid";
							loaded_oid =
								DatumGetObjectId(CopyReadBinaryAttribute(cstate,
																		 0,
																		 &oid_in_function,
																		 oid_typioparam,
																		 -1,
																		 &isnull,
																		 false));
							fld_size = isnull ? -1 : cstate->attribute_buf.len;
							uint32 fld_size_be = htonl((uint32) fld_size);
							appendBinaryStringInfo(&cstate->line_buf,
												   &fld_size_be,
												   4);
							if (!isnull)
								appendBinaryStringInfo(&cstate->line_buf,
													   cstate->attribute_buf.data,
													   cstate->attribute_buf.len);
							if (isnull || loaded_oid == InvalidOid)
								ereport(ERROR,
										(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
										 errmsg("invalid OID in COPY data")));
							cstate->cur_attname = NULL;
						}

						i = 0;
						AttrNumber p_index;
						foreach(cur, cstate->attnumlist)
						{
							int			attnum = lfirst_int(cur);
							int			m = attnum - 1;

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

							bool skip_parsing = true;
							/* using same logic as the two invocations of attr_get_key */
							for (p_index = 0; p_index < p_nattrs; p_index++)
							{
								if (attnum == policy->attrs[p_index])
								{
									skip_parsing = false;
									break;
								}
							}
							if (skip_parsing && part_attnums > 0) {
								for (p_index = 0; p_index < p_nattrs; p_index++) {
									if (attnum == part_attnum[p_index])
									{
										skip_parsing = false;
										break;
									}
								}
							}
							values[m] = CopyReadBinaryAttribute(cstate,
																i,
																&in_functions[m],
																typioparams[m],
																attr[m]->atttypmod,
																&isnull,
																skip_parsing);
							fld_size = isnull ? -1 : cstate->attribute_buf.len;
							uint32 fld_size_be = htonl((uint32) fld_size);
							appendBinaryStringInfo(&cstate->line_buf,
												   &fld_size_be,
												   4);
							if (!isnull)
								appendBinaryStringInfo(&cstate->line_buf,
													   cstate->attribute_buf.data,
													   cstate->attribute_buf.len);
							nulls[m] = isnull;
							cstate->cur_attname = NULL;
						}
					}
3815

3816 3817 3818 3819 3820 3821 3822
					/*
					 * 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.
A
alldefector 已提交
3823 3824 3825 3826
					 *
					 * These are fields in addition to those specified in the original COPY command.
					 * They are computed by QD here and fed to the QEs.
					 * See same logic and comments in CopyFromCreateDispatchCommand
3827 3828 3829 3830
					 */
					for (i = 0; i < num_defaults; i++)
					{
						bool compute_default = false;
B
Bruce Momjian 已提交
3831

3832 3833 3834 3835
						/* 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];
3836

3837 3838 3839
							if(h_attnum - 1 == defmap[i])
								compute_default = true;
						}
B
Bruce Momjian 已提交
3840

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

3845 3846 3847 3848
						if(compute_default)
						{
							values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
															 &isnull, NULL);
3849

A
alldefector 已提交
3850 3851 3852 3853
							/* Extend line_buf for the QDs */
							if (!cstate->binary)
							{
								char *string;
3854 3855 3856 3857 3858
							/*
							 * prepare to concatinate next value:
							 * remove eol characters from end of line buf
							 */
							truncateEol(&cstate->line_buf, cstate->eol_type);
3859

3860 3861 3862 3863 3864 3865 3866
							if (isnull)
							{
								appendStringInfo(&cstate->line_buf, "%c%s", cstate->delim[0], cstate->null_print);
							}
							else
							{
								nulls[defmap[i]] = false;
3867

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

3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882
								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);
							}
3883

3884 3885 3886
							/* re-add the eol characters */
							concatenateEol(cstate);
						}
A
alldefector 已提交
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
							else
							{
								/* binary format */
								if (isnull) {
									uint32 fld_size_be = htonl((uint32) -1);
									appendBinaryStringInfo(&cstate->line_buf,
														   &fld_size_be,
														   4);
								} else {
									bytea	   *outputbytes;
									outputbytes = SendFunctionCall(&out_functions[defmap[i]],
																   FunctionCall3(&out_functions[defmap[i]],
																		   		 values[defmap[i]],
																		   		 ObjectIdGetDatum(typioparams[defmap[i]]),
																		   		 Int32GetDatum(attr[defmap[i]]->atttypmod)));
									int32 fld_size = VARSIZE(outputbytes) - VARHDRSZ;
									uint32 fld_size_be = htonl((uint32) fld_size);
									appendBinaryStringInfo(&cstate->line_buf,
														   &fld_size_be,
														   4);
									appendBinaryStringInfo(&cstate->line_buf,
														   VARDATA(outputbytes),
														   fld_size);
								}
							}
						}
3913

3914
					}
B
Bruce Momjian 已提交
3915

3916 3917
					/* lock partition */
					if (estate->es_result_partitions)
B
Bruce Momjian 已提交
3918
					{
A
alldefector 已提交
3919 3920 3921
						Datum *values_for_partition;

						if (!cstate->binary)
3922
							{
A
alldefector 已提交
3923 3924 3925 3926 3927 3928
							/*
							 * Text/CSV: Ensure we parse all partition attrs.
							 * Q: Wouldn't this potentially reparse values (and miss defaults)?
							 *    Why not merge with the other attr_get_key call
							 *    (replace part_values with values)?
							 */
3929 3930 3931 3932 3933 3934 3935 3936 3937
						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);
A
alldefector 已提交
3938 3939 3940 3941 3942 3943 3944 3945 3946
							values_for_partition = part_values;
						}
						else
						{
							/*
							 * Binary: We've made sure to parse partition attrs above.
							 */
							values_for_partition = values;
						}
3947 3948

						/* values_get_partition() calls palloc() */
A
alldefector 已提交
3949
						MemoryContext cxt_save = MemoryContextSwitchTo(oldcontext);
3950

A
alldefector 已提交
3951
						resultRelInfo = values_get_partition(values_for_partition,
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
															 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 =
3987
									makeCdbHash(cdbCopy->total_segs);
3988 3989 3990 3991 3992 3993 3994 3995
								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 已提交
3996
					}
3997 3998 3999 4000 4001 4002

					/*
					 * The the usual case or a partitioned table
					 * with non-divergent child table policies.
					 */
					if (!part_hash)
B
Bruce Momjian 已提交
4003
					{
4004 4005 4006
						part_hash = cdbHash;
						part_policy = policy;
						part_p_nattrs = p_nattrs;
B
Bruce Momjian 已提交
4007 4008
					}

4009 4010 4011 4012
					/*
					 * policy should be PARTITIONED (normal tables) or
					 * ENTRY
					 */
4013
					if (!part_policy)
4014 4015 4016 4017 4018
					{
						elog(FATAL, "Bad or undefined policy. (%p)", part_policy);
					}
				}
				PG_CATCH();
B
Bruce Momjian 已提交
4019
				{
4020
					COPY_HANDLE_ERROR;
B
Bruce Momjian 已提交
4021
				}
4022
				PG_END_TRY();
B
Bruce Momjian 已提交
4023

A
alldefector 已提交
4024 4025 4026
				if (no_more_data)
					break;

4027
				if(cur_row_rejected)
B
Bruce Momjian 已提交
4028
				{
4029 4030
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
B
Bruce Momjian 已提交
4031
				}
4032 4033

				/*
4034 4035 4036 4037 4038 4039 4040 4041
				 * 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.
4042
				 */
4043
				Assert(PointerIsValid(part_hash));
A
alldefector 已提交
4044 4045 4046 4047 4048
				/* Assert does not activate in production build */
				if (!part_hash)
				{
					elog(FATAL, "Bad part_hash: %p", part_hash);
				}
4049
				cdbhashinit(part_hash);
B
Bruce Momjian 已提交
4050

4051 4052 4053 4054
				for (i = 0; i < part_p_nattrs; i++)
				{
					/* current attno from the policy */
					h_attnum = part_policy->attrs[i];
4055

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

4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077
					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.
A
alldefector 已提交
4078 4079 4080 4081 4082
				 */
				if (!cstate->binary)
				{
					/*
					 * Text/CSV: modify the data to look like:
4083 4084 4085 4086 4087 4088 4089 4090
				 *    "<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);
A
alldefector 已提交
4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105
				}
				else
				{
					/*
					 * Binary: modify the data to look like:
					 *    "<lineno:int64><data:bytes>"
					 */
					uint64 lineno = htonll((uint64) original_lineno_for_qe);
					appendBinaryStringInfo(&line_buf_with_lineno,
										   &lineno,
										   sizeof(lineno));
					appendBinaryStringInfo(&line_buf_with_lineno,
										   cstate->line_buf.data,
										   cstate->line_buf.len);
				}
4106 4107
				
				/* send modified data */
4108 4109 4110 4111 4112 4113 4114
				if (!cstate->on_segment) {
					cdbCopySendData(cdbCopy,
									target_seg,
									line_buf_with_lineno.data,
									line_buf_with_lineno.len);
					RESET_LINEBUF_WITH_LINENO;
				}
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

				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.
	 */
4146
	total_rejected_from_qes = cdbCopyEndAndFetchRejectNum(cdbCopy, &total_completed_from_qes);
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

	/*
	 * 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;
4198 4199 4200 4201 4202 4203 4204 4205

		/*
		 * If error log has been requested, then we send the row to the segment
		 * so that it can be written in the error log file. The segment process
		 * counts it again as a rejected row. So we ignore the reject count
		 * from the master and only consider the reject count from segments.
		 */
		if (cstate->cdbsreh->log_to_file)
4206
			total_rejected_from_qd = 0;
4207 4208

		total_rejected = total_rejected_from_qd + total_rejected_from_qes;
4209 4210 4211 4212 4213 4214
		cstate->processed -= total_rejected;

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

4215
	cstate->processed += total_completed_from_qes;
4216 4217 4218 4219 4220 4221

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

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

4225
	/* Handle queued AFTER triggers */
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
	//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);

	/*
	 * 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);
}

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
static GpDistributionData
initDistributionData(CopyState cstate, Form_pg_attribute *attr,AttrNumber num_phys_attrs)
{
	/*
	 * 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 */

	CdbHash *cdbHash = NULL;
	AttrNumber h_attnum; /* hash key attribute number */
	int p_index;
	int total_segs = getgpsegmentCount();
	int i = 0;

	policy = GpPolicyCopy(CurrentMemoryContext, cstate->rel->rd_cdbpolicy);

	if (policy)
		p_nattrs = policy->nattrs; /* number of partitioning keys */
	else
		p_nattrs = 0;
	/* Create hash API reference */
	cdbHash = makeCdbHash(total_segs);

	/*
	 * 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];

		/*
		 * 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
		{
			/* 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]);
		}
	}

	/*
	 * 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;

	for (p_index = 0; p_index < p_nattrs; p_index++)
	{
		i = 1;

		/*
		 * for this partitioning key, search for its location in the attr list.
		 * (note that fields may be out of order).
		 */
		ListCell *cur;
		foreach (cur, cstate->attnumlist)
		{
			int attnum = lfirst_int(cur);

			if (attnum == policy->attrs[p_index])
			{
				if (i > cstate->last_hash_field)
					cstate->last_hash_field = i;
			}
			i++;
		}
	}
	GpDistributionData distData;
	distData.policy = policy;
	distData.p_nattrs = p_nattrs;
	distData.p_attr_types = p_attr_types;
	distData.cdbHash = cdbHash;
	return distData;
}

static unsigned int
get_target_seg(GpDistributionData distData, Datum *baseValues, bool *baseNulls)
{
	unsigned int target_seg = 0;
	CdbHash *cdbHash = distData.cdbHash;
	GpPolicy *policy = distData.policy;		 /* the partitioning policy for this table */
	AttrNumber p_nattrs = distData.p_nattrs; /* num of attributes in the distribution policy */
	Oid *p_attr_types = distData.p_attr_types;

	if (!policy)
	{
		elog(FATAL, "Bad or undefined policy. (%p)", policy);
	}

	/*
	 * At this point in the code, baseValues[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.
	 */
	Assert(PointerIsValid(cdbHash));
	/* Assert does not activate in production build */
	if (!cdbHash)
	{
		elog(FATAL, "Bad cdb_hash: %p", cdbHash);
	}
	cdbhashinit(cdbHash);

	AttrNumber h_attnum;
	Datum h_key;
	for (int i = 0; i < p_nattrs; i++)
	{
		/* current attno from the policy */
		h_attnum = policy->attrs[i];

		h_key = baseValues[h_attnum - 1]; /* value of this attr */
		if (!baseNulls[h_attnum - 1])
			cdbhash(cdbHash, h_key, p_attr_types[h_attnum - 1]);
		else
			cdbhashnull(cdbHash);
	}

	/*
	 * 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 (p_nattrs == 0)
		cdbhashnokey(cdbHash);

	target_seg = cdbhashreduce(cdbHash); /* hash result segment */
	return target_seg;
}

4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464
/*
 * 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;
A
alldefector 已提交
4465
	FmgrInfo	oid_in_function;
4466
	Oid		   *typioparams;
A
alldefector 已提交
4467
	Oid			oid_typioparam;
4468 4469 4470
	int			attnum;
	int			i;
	Oid			in_func_oid;
4471 4472 4473 4474 4475 4476
	Datum		*values = NULL;
	bool		*nulls = NULL;
	Datum		*partValues = NULL;
	bool		*partNulls = NULL;
	Datum		*baseValues = NULL;
	bool		*baseNulls = NULL;
4477 4478 4479
	bool		isnull;
	ResultRelInfo *resultRelInfo;
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
4480
	TupleTableSlot *baseSlot;
4481 4482 4483 4484 4485 4486 4487
	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;
4488
	CommandId	mycid = GetCurrentCommandId(true);
4489 4490
	bool		use_wal = true; /* by default, use WAL logging */
	bool		use_fsm = true; /* by default, use FSM for free space */
4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501
	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;
4502
	bool		is_segment_data_processed = (cstate->on_segment && Gp_role == GP_ROLE_EXECUTE) ? false : true;
4503
	bool is_check_distkey = (cstate->on_segment && Gp_role == GP_ROLE_EXECUTE && gp_enable_segment_copy_checking) ? true : false;
4504 4505
	GpDistributionData	distData; /* distribution data used to compute target seg */
	unsigned int	target_seg = 0; /* result segment of cdbhash */
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
	/*----------
	 * Check to see if we can avoid writing WAL
	 *
	 * If archive logging is not enabled *and* either
	 *	- table was created in same transaction as this COPY
	 *	- data is being written to relfilenode created in this transaction
	 * then we can skip writing WAL.  It's safe because if the transaction
	 * doesn't commit, we'll discard the table (or the new relfilenode file).
	 * If it does commit, we'll have done the heap_sync at the bottom of this
	 * routine first.
	 *
	 * As mentioned in comments in utils/rel.h, the in-same-transaction test
	 * is not completely reliable, since in rare cases rd_createSubid or
	 * rd_newRelfilenodeSubid can be cleared before the end of the transaction.
	 * However this is OK since at worst we will fail to make the optimization.
	 *
	 * Also, if the target file is new-in-transaction, we assume that checking
	 * FSM for free space is a waste of time, even if we must use WAL because
	 * of archiving.  This could possibly be wrong, but it's unlikely.
	 *
	 * The comments for heap_insert and RelationGetBufferForTuple specify that
	 * skipping WAL logging is only safe if we ensure that our tuples do not
	 * go into pages containing tuples from any other transactions --- but this
	 * must be the case if we have a new table or new relfilenode, so we need
	 * no additional work to enforce that.
	 *----------
	 */
	if (cstate->rel->rd_createSubid != InvalidSubTransactionId ||
		cstate->rel->rd_newRelfilenodeSubid != InvalidSubTransactionId)
	{
		use_fsm = false;
		if (!XLogArchivingActive())
			use_wal = false;
	}

4542 4543
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

4544 4545
	/*
	 * We need a ResultRelInfo so we can use the regular executor's
4546 4547
	 * index-entry-making machinery.  (There used to be a huge amount of code
	 * here that basically duplicated execUtils.c ...)
4548 4549 4550 4551 4552 4553 4554
	 */
	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 *)
4555 4556 4557
			palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
	resultRelInfo->ri_TrigInstrument = NULL;
	ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
4558

4559
	ExecOpenIndices(resultRelInfo);
4560 4561 4562 4563 4564 4565 4566 4567 4568

	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 */
4569
	baseSlot = MakeSingleTupleTableSlot(tupDesc);
4570 4571 4572 4573 4574

	econtext = GetPerTupleExprContext(estate);

	/*
	 * Pick up the required catalog information for each attribute in the
4575 4576
	 * relation, including the input function, the element type (to pass to
	 * the input function), and info about defaults and constraints.
4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589
	 */
	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 */
A
alldefector 已提交
4590 4591 4592 4593
		if (cstate->binary)
			getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
								   &in_func_oid, &typioparams[attnum - 1]);
		else
4594 4595
			getTypeInputInfo(attr[attnum - 1]->atttypid,
							 &in_func_oid, &typioparams[attnum - 1]);
4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614
		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++;
			}
		}
	}

4615 4616 4617 4618 4619 4620
	/* prepare distribuion data for computing target seg*/
	if (is_check_distkey)
	{
		distData = initDistributionData(cstate, attr,num_phys_attrs);
	}

4621
	/* Prepare to catch AFTER triggers. */
4622 4623 4624
	AfterTriggerBeginQuery();

	/*
4625 4626 4627 4628
	 * 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.
4629 4630 4631
	 */
	ExecBSInsertTriggers(estate, resultRelInfo);

4632 4633
	/* Skip header processing if dummy file get from master for COPY FROM ON SEGMENT */
	if(!cstate->on_segment || Gp_role != GP_ROLE_EXECUTE)
A
alldefector 已提交
4634
	{
4635
		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
A
alldefector 已提交
4636
	}
4637

4638 4639
	baseValues = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
	baseNulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
4640 4641
	attr_offsets = (int *) palloc(num_phys_attrs * sizeof(int));

4642 4643 4644
	partValues = (Datum *) palloc(attr_count * sizeof(Datum));
	partNulls = (bool *) palloc(attr_count * sizeof(bool));

4645 4646 4647 4648 4649 4650
	/* 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;

4651
	if (Gp_role == GP_ROLE_EXECUTE && (cstate->on_segment == false))
4652 4653 4654 4655 4656 4657
		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);

4658
PROCESS_SEGMENT_DATA:
4659 4660 4661 4662
	do
	{
		size_t		bytesread = 0;

A
alldefector 已提交
4663 4664
		if (!cstate->binary)
		{
4665 4666 4667 4668 4669 4670 4671
		/* 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;
A
alldefector 已提交
4672
		}
4673 4674 4675 4676 4677 4678 4679 4680

		/*
		 * 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)
		{
4681 4682
			/* handle HEADER, but only if COPY FROM ON SEGMENT */
			if (cstate->header_line && cstate->on_segment)
4683
			{
4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696
				/* on first time around just throw the header line away */
				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.
					 */
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
					/*
					 * 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! */

						/*
						 * 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();

				cstate->cur_lineno++;
4724
				RESET_LINEBUF;
4725 4726

				cstate->header_line = false;
4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742
			}

			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 */
4743 4744
				MemSet(baseValues, 0, num_phys_attrs * sizeof(Datum));
				MemSet(baseNulls, true, num_phys_attrs * sizeof(bool));
4745 4746 4747
				/* reset attribute pointers */
				MemSet(attr_offsets, 0, num_phys_attrs * sizeof(int));

A
alldefector 已提交
4748 4749
				if (!cstate->binary)
				{
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
				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)
4861
						CopyReadAttributesCSV(cstate, baseNulls, attr_offsets, num_phys_attrs, attr);
4862
					else
4863
						CopyReadAttributesText(cstate, baseNulls, attr_offsets, num_phys_attrs, attr);
4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875

					/*
					 * 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];

4876
						if (baseNulls[m])
4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888
							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);

4889
						baseValues[m] = InputFunctionCall(&in_functions[m],
4890 4891 4892
													  isnull ? NULL : string,
													  typioparams[m],
													  attr[m]->atttypmod);
4893
						baseNulls[m] = isnull;
4894 4895
						cstate->cur_attname = NULL;
					}
A
alldefector 已提交
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
					}
					PG_CATCH();
					{
						COPY_HANDLE_ERROR; /* SREH */
					}
					PG_END_TRY();

					if(cur_row_rejected)
					{
						ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
						QE_GOTO_NEXT_ROW;
					}
				}
				else
				{
					/* binary */
					if (cstate->err_loc_type == ROWNUM_EMBEDDED)
					{
						/**
						* Incoming data format:
						*     <original_line_num:uint64><data for this row:bytes>
						* We consume "original_line_num" before parsing the data.
						* See also CopyExtractRowMetaData(cstate) for text/csv formats.
						*/
						int64 line_num;
						if (!CopyGetInt64(cstate, &line_num))
						{
							no_more_data = true;
							break;
						}
						cstate->cur_lineno = line_num;
					}

					int16		fld_count;
					ListCell   *cur;
					char buffer[20];

					if (!CopyGetInt16(cstate, &fld_count) ||
						fld_count == -1)
					{
						no_more_data = true;
						break;
					}

					if (fld_count != attr_count)
						ereport(ERROR,
								(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
								 errmsg("QD: line %s: row field count is %d, expected %d",
								 		linenumber_atoi(buffer, cstate->cur_lineno),
										(int) fld_count, attr_count)));

					if (file_has_oids)
					{
						cstate->cur_attname = "oid";
						loaded_oid =
							DatumGetObjectId(CopyReadBinaryAttribute(cstate,
																	 0,
																	 &oid_in_function,
																	 oid_typioparam,
																	 -1,
																	 &isnull,
																	 false));
						if (isnull || loaded_oid == InvalidOid)
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("invalid OID in COPY data")));
						cstate->cur_attname = NULL;
					}

					i = 0;
					foreach(cur, cstate->attnumlist)
					{
						int			attnum = lfirst_int(cur);
						int			m = attnum - 1;

						cstate->cur_attname = NameStr(attr[m]->attname);
						i++;
						baseValues[m] = CopyReadBinaryAttribute(cstate,
															i,
															&in_functions[m],
															typioparams[m],
															attr[m]->atttypmod,
															&isnull,
															false);
						baseNulls[m] = isnull;
						cstate->cur_attname = NULL;
					}
				}
4984 4985 4986 4987 4988 4989 4990 4991

					/*
					 * 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++)
					{
4992
						baseValues[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
4993 4994 4995
														 &isnull, NULL);

						if (!isnull)
4996
							baseNulls[defmap[i]] = false;
4997 4998 4999 5000 5001 5002 5003 5004
					}

				/*
				 * We might create a ResultRelInfo which needs to persist
				 * the per tuple context.
				 */
				PG_TRY();
				{
5005
					MemoryContextSwitchTo(estate->es_query_cxt);
5006 5007
					if (estate->es_result_partitions)
					{
5008
						resultRelInfo = values_get_partition(baseValues, baseNulls,
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
															 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,
											   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.
				 */
5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075
				if (resultRelInfo->ri_partSlot != NULL)
				{
					AttrMap *map = resultRelInfo->ri_partInsertMap;
					Assert(map != NULL);


					MemSet(partValues, 0, attr_count * sizeof(Datum));
					MemSet(partNulls, true, attr_count * sizeof(bool));

					reconstructTupleValues(map, baseValues, baseNulls, (int) num_phys_attrs,
										   partValues, partNulls, (int) attr_count);

					values = partValues;
					nulls = partNulls;
				}
				else
				{
					values = baseValues;
					nulls = baseNulls;
				}

5076 5077 5078 5079 5080
				if (is_check_distkey)
				{
					target_seg = get_target_seg(distData, values, nulls);
					/*check distribution key if COPY FROM ON SEGMENT*/
					if (GpIdentity.segindex != target_seg)
5081 5082 5083 5084
						ereport(ERROR,
								(errcode(ERRCODE_INTEGRITY_CONSTRAINT_VIOLATION),
								 errmsg("value of distribution key doesn't belong to segment with ID %d, it belongs to segment with ID %d",
										GpIdentity.segindex, target_seg)));
5085 5086
				}

5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104
				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 */
5105
					tuple = (HeapTuple) heap_form_tuple(resultRelInfo->ri_RelationDesc->rd_att, values, nulls);
5106 5107 5108 5109 5110 5111 5112 5113 5114

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


				/*
				 * Triggers and stuff need to be invoked in query context.
				 */
5115
				MemoryContextSwitchTo(estate->es_query_cxt);
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

				/* 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);
					
5151 5152 5153 5154 5155 5156 5157 5158 5159 5160
					if (resultRelInfo->ri_partSlot != NULL)
					{
						Assert(resultRelInfo->ri_partInsertMap != NULL);
						slot = resultRelInfo->ri_partSlot;
					}
					else
					{
						slot = baseSlot;
					}

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
					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
					{
5209
						heap_insert(resultRelInfo->ri_RelationDesc, tuple, mycid, use_wal, use_fsm, GetCurrentTransactionId());
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

						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);

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
	/*
	 * After processed data from QD, which is empty and just for workflow, now
	 * to process the data on segment, only one shot if cstate->on_segment &&
	 * Gp_role == GP_ROLE_DISPATCH
	 */
	if (!is_segment_data_processed)
	{
		struct stat st;
		char *filename = cstate->filename;
		cstate->copy_file = AllocateFile(filename, PG_BINARY_R);

		if (cstate->copy_file == NULL)
			ereport(ERROR,
					(errcode_for_file_access(),
						errmsg("could not open file \"%s\" for reading: %m",
							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))
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						errmsg("\"%s\" is a directory", filename)));
		cstate->copy_dest = COPY_FILE;

		is_segment_data_processed = true;

		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
		CopyInitDataParser(cstate);
5274
		no_more_data = false;
5275 5276 5277 5278 5279

		goto PROCESS_SEGMENT_DATA;
	}

	elog(DEBUG1, "Segment %u, Copied %lu rows.", GpIdentity.segindex, cstate->processed);
5280

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

5284
	MemoryContextSwitchTo(estate->es_query_cxt);
5285

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

5289
	/* Handle queued AFTER triggers */
5290 5291 5292 5293 5294
	AfterTriggerEndQuery(estate);

	/*
	 * If SREH and in executor mode send the number of rejected
	 * rows to the client (QD COPY).
5295
	 * If COPY ... FROM ... ON SEGMENT, then need to send the number of completed
5296
	 */
5297 5298 5299 5300
	if ((cstate->errMode != ALL_OR_NOTHING && Gp_role == GP_ROLE_EXECUTE)
		|| cstate->on_segment)
		SendNumRows((cstate->errMode != ALL_OR_NOTHING) ? cstate->cdbsreh->rejectcount : 0,
				cstate->on_segment ? cstate->processed : 0);
5301 5302 5303 5304

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

5305 5306 5307
	/* NB: do not pfree baseValues/baseNulls and partValues/partNulls here, since
	 * there may be duplicate free in ExecDropSingleTupleTableSlot; if not, they
	 * would be freed by FreeExecutorState anyhow */
5308

5309
	ExecDropSingleTupleTableSlot(baseSlot);
5310

5311 5312 5313 5314 5315 5316 5317
	/*
	 * If we skipped writing WAL, then we need to sync the heap (but not
	 * indexes since those use WAL anyway)
	 */
	if (!use_wal)
		heap_sync(cstate->rel);

5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339
	/*
	 * 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 */
5340 5341

	MemoryContextSwitchTo(oldcontext);
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 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 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 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 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 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 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 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980
	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;
5981

5982 5983 5984 5985
	return false;
}

/*
5986
 *	Return decimal value for a hexadecimal digit
5987
 */
5988 5989
static int
GetDecimalFromHex(char hex)
5990
{
5991
	if (isdigit((unsigned char) hex))
5992 5993
		return hex - '0';
	else
5994
		return tolower((unsigned char) hex) - 'a' + 10;
5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 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
}

/*
 * 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.
 */

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 已提交
6095
		/*
6096 6097 6098
		 * 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.
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 6136 6137 6138 6139 6140 6141
		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
				&&
6142 6143 6144
				strncmp(cstate->line_buf.data + cstate->line_buf.len
					- attr_pre_len - (cstate->eol_type == EOL_CRLF ? 2 : 1),
					cstate->null_print, attr_pre_len) == 0)
6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 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 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 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 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 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 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602
				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)
6603
		{
6604 6605 6606 6607 6608 6609 6610
			/*
			 * 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];
6611

6612 6613 6614 6615 6616 6617 6618 6619
				if (nextc == escapec || nextc == quotec)
				{
					appendStringInfoCharMacro(&cstate->attribute_buf, nextc);
					cstate->line_buf.cursor++;
					cstate->attribute_buf.cursor++;
					continue;
				}
			}
6620 6621
		}

6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634
		/*
		 * 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++;
	}
6635

6636 6637
}

6638
/*
6639 6640 6641 6642 6643 6644 6645
 * 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
6646
 */
6647 6648 6649
static void
CopyReadAttributesTextNoDelim(CopyState cstate, bool *nulls, int num_phys_attrs,
							  int attnum)
6650
{
6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664
	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;
6665
	else
6666 6667 6668
		nulls[attnum - 1] = false;

	appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data, len);
6669 6670
}

6671
/*
6672 6673 6674
 * 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.
6675
 */
6676 6677
static char *
CopyReadOidAttr(CopyState cstate, bool *isnull)
6678
{
6679
	char		delimc = cstate->delim[0];
6680 6681 6682 6683
	char	   *start_loc = cstate->line_buf.data + cstate->line_buf.cursor;
	char	   *end_loc;
	int			attr_len = 0;
	int			bytes_remaining;
6684

6685 6686 6687 6688 6689 6690 6691 6692
	/* 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)
6693
	{
6694 6695 6696
		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' */
6697
	}
6698 6699 6700 6701 6702 6703 6704
	else
		/* found a delimiter */
	{
		/*
		 * (we don't care if delim was preceded with a backslash, because it's
		 * an invalid OID anyway)
		 */
6705

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

6708 6709 6710
		appendBinaryStringInfo(&cstate->attribute_buf, start_loc, attr_len);
		cstate->line_buf.cursor += attr_len + 1;
	}
6711

6712

6713 6714 6715 6716 6717
	/* 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;
6718

6719 6720
	return cstate->attribute_buf.data;
}
6721

A
alldefector 已提交
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
/*
 * Read a binary attribute.
 * skip_parsing is a hack for CopyFromDispatch (so we don't parse unneeded fields)
 */
static Datum
CopyReadBinaryAttribute(CopyState cstate,
						int column_no, FmgrInfo *flinfo,
						Oid typioparam, int32 typmod,
						bool *isnull, bool skip_parsing)
{
	int32		fld_size;
	Datum		result = 0;

	if (!CopyGetInt32(cstate, &fld_size))
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("unexpected EOF in COPY data")));
	if (fld_size == -1)
	{
		*isnull = true;
		return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
	}
	if (fld_size < 0)
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("invalid field size")));

	/* reset attribute_buf to empty, and load raw data in it */
	resetStringInfo(&cstate->attribute_buf);

	enlargeStringInfo(&cstate->attribute_buf, fld_size);
	if (CopyGetData(cstate, cstate->attribute_buf.data,
					fld_size) != fld_size)
		ereport(ERROR,
				(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
				 errmsg("unexpected EOF in COPY data")));

	cstate->attribute_buf.len = fld_size;
	cstate->attribute_buf.data[fld_size] = '\0';

	if (!skip_parsing)
	{
		/* Call the column type's binary input converter */
		result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
									 typioparam, typmod);

		/* Trouble if it didn't eat the whole buffer */
		if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
			ereport(ERROR,
					(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
					 errmsg("incorrect binary data format")));
	}

	*isnull = false;
	return result;
}

6779 6780 6781 6782 6783 6784 6785 6786
/*
 * Send text representation of one attribute, with conversion and escaping
 */
#define DUMPSOFAR() \
	do { \
		if (ptr > start) \
			CopySendData(cstate, start, ptr - start); \
	} while (0)
6787

6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798
/*
 * 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];
6799

6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834
	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)
6835
			{
6836
				/*
6837 6838 6839 6840 6841
				 * \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.
6842
				 */
6843 6844
				switch (c)
				{
6845 6846
					case '\b':
						c = 'b';
B
Bruce Momjian 已提交
6847
						break;
6848 6849
					case '\f':
						c = 'f';
6850
						break;
6851 6852
					case '\n':
						c = 'n';
6853
						break;
6854 6855
					case '\r':
						c = 'r';
6856
						break;
6857 6858
					case '\t':
						c = 't';
6859
						break;
6860 6861
					case '\v':
						c = 'v';
6862
						break;
6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906
					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';
6907
						break;
6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921
					case '\f':
						c = 'f';
						break;
					case '\n':
						c = 'n';
						break;
					case '\r':
						c = 'r';
						break;
					case '\t':
						c = 't';
						break;
					case '\v':
						c = 'v';
6922
						break;
6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946
					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++;
		}
	}
6947

6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010
	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;
7011
				}
7012 7013 7014 7015
				if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
					tptr += pg_encoding_mblen(cstate->client_encoding, tptr);
				else
					tptr++;
7016 7017
			}
		}
7018
	}
7019

7020 7021 7022
	if (use_quote)
	{
		CopySendChar(cstate, quotec);
7023

7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041
		/*
		 * 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();
7042

7043 7044 7045 7046 7047 7048
		CopySendChar(cstate, quotec);
	}
	else
	{
		/* If it doesn't need quoting, we can just dump it as-is */
		CopySendString(cstate, ptr);
7049
	}
7050 7051
}

B
Bruce Momjian 已提交
7052
/*
7053 7054 7055 7056 7057 7058 7059
 * 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 已提交
7060
 */
7061 7062
List *
CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
B
Bruce Momjian 已提交
7063
{
7064
	List	   *attnums = NIL;
7065

7066
	if (attnamelist == NIL)
7067
	{
7068 7069 7070 7071
		/* Generate default column list */
		Form_pg_attribute *attr = tupDesc->attrs;
		int			attr_count = tupDesc->natts;
		int			i;
B
Bruce Momjian 已提交
7072

7073 7074 7075 7076 7077 7078 7079 7080
		for (i = 0; i < attr_count; i++)
		{
			if (attr[i]->attisdropped)
				continue;
			attnums = lappend_int(attnums, i + 1);
		}
	}
	else
B
Bruce Momjian 已提交
7081
	{
7082 7083
		/* Validate the user-supplied list and extract attnums */
		ListCell   *l;
B
Bruce Momjian 已提交
7084

7085
		foreach(l, attnamelist)
B
Bruce Momjian 已提交
7086
		{
7087 7088 7089
			char	   *name = strVal(lfirst(l));
			int			attnum;
			int			i;
B
Bruce Momjian 已提交
7090

7091 7092 7093
			/* Lookup column name */
			attnum = InvalidAttrNumber;
			for (i = 0; i < tupDesc->natts; i++)
7094
			{
7095 7096 7097
				if (tupDesc->attrs[i]->attisdropped)
					continue;
				if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
B
Bruce Momjian 已提交
7098
				{
7099 7100
					attnum = tupDesc->attrs[i]->attnum;
					break;
B
Bruce Momjian 已提交
7101 7102
				}
			}
7103
			if (attnum == InvalidAttrNumber)
7104
			{
7105 7106 7107
				if (rel != NULL)
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
7108 7109
					errmsg("column \"%s\" of relation \"%s\" does not exist",
						   name, RelationGetRelationName(rel))));
7110 7111 7112 7113 7114
				else
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column \"%s\" does not exist",
									name)));
7115
			}
7116 7117 7118 7119 7120 7121 7122
			/* 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 已提交
7123
		}
7124
	}
B
Bruce Momjian 已提交
7125

7126
	return attnums;
B
Bruce Momjian 已提交
7127 7128
}

7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148
#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
7149
 * encoding error happened and we're in error log mode).
7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205
 *
 * 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;
}
7206

7207
/*
7208
 * error context callback for COPY FROM
7209
 */
7210 7211
static void
copy_in_error_callback(void *arg)
7212
{
7213 7214
	CopyState	cstate = (CopyState) arg;
	char buffer[20];
7215

7216 7217 7218 7219
	/*
	 * 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)
7220
	{
7221 7222
		errcontext("%s", cstate->executor_err_context.data);
		return;
7223 7224
	}

7225 7226 7227
	/* don't need to print out context if error wasn't local */
	if (cstate->error_on_executor)
		return;
7228

A
alldefector 已提交
7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243
	if (cstate->binary)
	{
		/* can't usefully display the data */
		if (cstate->cur_attname)
			errcontext("COPY %s, line %s, column %s",
					   cstate->cur_relname,
					   linenumber_atoi(buffer, cstate->cur_lineno),
					   cstate->cur_attname);
		else
			errcontext("COPY %s, line %s",
					   cstate->cur_relname,
					   linenumber_atoi(buffer, cstate->cur_lineno));
	}
	else
	{
7244 7245 7246 7247
	if (cstate->cur_attname)
	{
		/* error is relevant to a particular column */
		char	   *att_buf;
7248

7249
		att_buf = limit_printout_length(cstate->attribute_buf.data);
7250

7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262
		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;
7263

7264 7265
			line_buf = extract_line_buf(cstate);
			truncateEolStr(line_buf, cstate->eol_type);
7266

7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287
			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));
		}
	}
7288
}
A
alldefector 已提交
7289
}
7290 7291

/*
7292 7293 7294 7295 7296 7297 7298 7299
 * 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.
7300
 */
7301 7302
static char *
extract_line_buf(CopyState cstate)
7303
{
7304
	char	   *line_buf = cstate->line_buf.data;
7305

7306
	if (cstate->err_loc_type == ROWNUM_EMBEDDED && !cstate->md_error)
7307
	{
7308 7309 7310 7311 7312 7313 7314
		/* 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))
7315
		{
7316 7317 7318 7319 7320 7321 7322 7323 7324
			/*
			 * 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;
7325

7326 7327 7328 7329 7330 7331
			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;
7332
		}
7333
	}
7334

7335 7336 7337 7338 7339 7340
	/*
	 * 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);
7341
}
7342

B
Bruce Momjian 已提交
7343
/*
7344 7345 7346 7347 7348 7349 7350
 * 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 已提交
7351
 */
7352 7353
char *
limit_printout_length(const char *str)
B
Bruce Momjian 已提交
7354
{
7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373
#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 已提交
7374

7375 7376
	return res;
}
7377

7378 7379 7380 7381 7382 7383 7384 7385 7386

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 已提交
7387

B
Bruce Momjian 已提交
7388
	/*
7389 7390 7391
	 * 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 已提交
7392
	 */
7393
	for (p_index = 0; p_index < p_nattrs; p_index++)
B
Bruce Momjian 已提交
7394
	{
7395 7396
		ListCell *cur;

7397
		/*
7398 7399
		 * For this partitioning key, search for its location in the attr list.
		 * (note that fields may be out of order, so this is necessary).
7400
		 */
7401
		foreach(cur, cstate->attnumlist)
B
Bruce Momjian 已提交
7402
		{
7403 7404 7405 7406
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
			char	   *string;
			bool		isnull;
7407

7408
			if (attnum == attrs[p_index])
7409
			{
7410 7411 7412 7413 7414 7415 7416 7417 7418
				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])
7419
				{
7420 7421
					string = cstate->null_print;		/* set to NULL string */
					isnull = false;
7422
				}
7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439

				/* 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 */
7440
			}
7441 7442 7443
		}		/* end foreach */
	}			/* end for partitioning indexes */
}
B
Bruce Momjian 已提交
7444

7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 7468
/*
 * 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)
7469
	{
7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484
		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 
7485
		 */
7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502 7503 7504 7505 7506 7507 7508 7509 7510
		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)
7511
		{
7512 7513 7514 7515 7516 7517 7518 7519
			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);
7520
		}
7521 7522 7523 7524 7525 7526 7527
		
		/* 
		 * 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);
7528 7529
	}
	else
7530 7531 7532 7533 7534 7535 7536 7537 7538 7539 7540
		/* 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;
		}
7541
	}
7542 7543 7544 7545 7546 7547 7548 7549

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

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

7552 7553
/* remove end of line chars from end of a buffer */
void truncateEol(StringInfo buf, EolType eol_type)
7554
{
7555 7556
	int one_back = buf->len - 1;
	int two_back = buf->len - 2;
B
Bruce Momjian 已提交
7557

7558
	if(eol_type == EOL_CRLF)
B
Bruce Momjian 已提交
7559
	{
7560 7561
		if(buf->len < 2)
			return;
B
Bruce Momjian 已提交
7562

7563 7564
		if(buf->data[two_back] == '\r' &&
		   buf->data[one_back] == '\n')
B
Bruce Momjian 已提交
7565
		{
7566 7567 7568
			buf->data[two_back] = '\0';
			buf->data[one_back] = '\0';
			buf->len -= 2;
7569 7570 7571 7572
		}
	}
	else
	{
7573 7574
		if(buf->len < 1)
			return;
7575

7576 7577
		if(buf->data[one_back] == '\r' ||
		   buf->data[one_back] == '\n')
7578
		{
7579 7580
			buf->data[one_back] = '\0';
			buf->len--;
B
Bruce Momjian 已提交
7581 7582
		}
	}
7583
}
7584

7585 7586 7587 7588 7589 7590 7591 7592 7593 7594 7595 7596 7597 7598 7599 7600 7601 7602 7603 7604 7605 7606 7607 7608 7609 7610 7611 7612 7613 7614 7615 7616 7617 7618 7619 7620
/* 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;

	}
7621
}
7622

7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642
/*
 * 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;
}
7643 7644 7645 7646 7647

/*
 * copy_dest_startup --- executor startup
 */
static void
7648
copy_dest_startup(DestReceiver *self __attribute__((unused)), int operation __attribute__((unused)), TupleDesc typeinfo __attribute__((unused)))
7649 7650 7651 7652 7653 7654 7655 7656 7657 7658
{
	/* no-op */
}

/*
 * copy_dest_receive --- receive one tuple
 */
static void
copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
{
B
Bruce Momjian 已提交
7659
	DR_copy    *myState = (DR_copy *) self;
7660 7661 7662 7663 7664 7665
	CopyState	cstate = myState->cstate;

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

	/* And send the data */
7666
	CopyOneRowTo(cstate, InvalidOid, slot_get_values(slot), slot_get_isnull(slot));
7667 7668 7669 7670 7671 7672
}

/*
 * copy_dest_shutdown --- executor end
 */
static void
7673
copy_dest_shutdown(DestReceiver *self __attribute__((unused)))
7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692
{
	/* 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 已提交
7693
	DR_copy    *self = (DR_copy *) palloc(sizeof(DR_copy));
7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704

	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;
}
7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725 7726 7727 7728 7729 7730 7731 7732 7733 7734 7735 7736 7737 7738 7739 7740 7741 7742 7743 7744 7745 7746 7747 7748 7749 7750 7751 7752 7753 7754 7755 7756 7757 7758 7759 7760 7761 7762 7763 7764 7765 7766 7767 7768 7769 7770 7771 7772 7773 7774 7775 7776 7777 7778 7779 7780 7781 7782 7783 7784 7785 7786 7787 7788 7789 7790 7791 7792 7793 7794 7795 7796 7797 7798 7799 7800 7801 7802 7803 7804 7805 7806 7807 7808 7809 7810 7811 7812 7813 7814 7815 7816 7817 7818 7819 7820 7821 7822 7823 7824 7825 7826 7827 7828 7829 7830 7831 7832 7833 7834 7835 7836 7837 7838 7839 7840 7841 7842 7843


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
7844
		 * the error. Verify that we are indeed in SREH error log mode. that's
7845 7846 7847 7848 7849 7850 7851 7852 7853 7854 7855 7856 7857 7858 7859 7860 7861 7862 7863 7864 7865 7866 7867 7868 7869 7870 7871 7872 7873 7874 7875 7876 7877 7878 7879 7880 7881 7882 7883 7884 7885 7886 7887 7888 7889 7890 7891 7892 7893 7894 7895 7896 7897 7898 7899 7900 7901 7902 7903 7904 7905 7906
		 * 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)));
}