copy.c 228.1 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-2010, 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.327 2010/04/28 16:10:41 heikki 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/defrem.h"
36
#include "commands/tablecmds.h"
37
#include "commands/trigger.h"
38
#include "commands/queue.h"
B
Bruce Momjian 已提交
39
#include "executor/executor.h"
40
#include "executor/execDML.h"
41
#include "libpq/libpq.h"
42
#include "libpq/pqformat.h"
A
Adam Lee 已提交
43
#include "libpq/pqsignal.h"
44
#include "mb/pg_wchar.h"
B
Bruce Momjian 已提交
45
#include "miscadmin.h"
46
#include "optimizer/planner.h"
47
#include "parser/parse_relation.h"
48
#include "rewrite/rewriteHandler.h"
49
#include "storage/fd.h"
50
#include "tcop/tcopprot.h"
51
#include "tcop/utility.h"
B
Bruce Momjian 已提交
52 53
#include "utils/acl.h"
#include "utils/builtins.h"
54
#include "utils/lsyscache.h"
55
#include "utils/memutils.h"
56
#include "utils/snapmgr.h"
W
Wang Hao 已提交
57
#include "utils/metrics_utils.h"
58

59 60 61
#include "cdb/cdbvars.h"
#include "cdb/cdbcopy.h"
#include "cdb/cdbsreh.h"
62
#include "postmaster/autostats.h"
63
#include "utils/resscheduler.h"
64

A
Adam Lee 已提交
65 66 67 68
extern int popen_with_stderr(int *rwepipe, const char *exe, bool forwrite);
extern int pclose_with_stderr(int pid, int *rwepipe, StringInfo sinfo);
extern char *make_command(const char *cmd, extvar_t *ev);

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

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

78

79
/* non-export function prototypes */
80
static void DoCopyTo(CopyState cstate);
81
extern void CopyToDispatch(CopyState cstate);
82
static void CopyTo(CopyState cstate);
83
extern void CopyFromDispatch(CopyState cstate);
84
static void CopyFrom(CopyState cstate);
85
static void CopyFromProcessDataFileHeader(CopyState cstate, CdbCopy *cdbCopy, bool *pfile_has_oids);
86
static char *CopyReadOidAttr(CopyState cstate, bool *isnull);
87 88
static void CopyAttributeOutText(CopyState cstate, char *string);
static void CopyAttributeOutCSV(CopyState cstate, char *string,
89 90 91 92
								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 已提交
93 94 95 96
static Datum CopyReadBinaryAttribute(CopyState cstate,
									 int column_no, FmgrInfo *flinfo,
									 Oid typioparam, int32 typmod,
									 bool *isnull, bool skip_parsing);
97 98 99 100 101

/* Low-level communications functions */
static void SendCopyBegin(CopyState cstate);
static void ReceiveCopyBegin(CopyState cstate);
static void SendCopyEnd(CopyState cstate);
102
static void CopySendData(CopyState cstate, const void *databuf, int datasize);
103 104
static void CopySendString(CopyState cstate, const char *str);
static void CopySendChar(CopyState cstate, char c);
105 106
static int	CopyGetData(CopyState cstate, void *databuf, int datasize);

A
alldefector 已提交
107 108 109 110 111 112 113
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);


114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
/* 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);

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
static GpDistributionData *
InitDistributionData(CopyState cstate, Form_pg_attribute *attr,
                     AttrNumber num_phys_attrs,
                     EState *estate, bool multi_dist_policy);
static void
FreeDistributionData(GpDistributionData *distData);
static void
InitPartitionData(PartitionData *partitionData, EState *estate, Form_pg_attribute *attr,
                  AttrNumber num_phys_attrs, MemoryContext ctxt);
static void
FreePartitionData(PartitionData *partitionData);
static GpDistributionData *
GetDistributionPolicyForPartition(CopyState cstate, EState *estate,
                                  PartitionData *partitionData, HTAB *hashmap,
                                  Oid *p_attr_types,
                                  GetAttrContext *getAttrContext,
                                  MemoryContext ctxt);
static unsigned int
GetTargetSeg(GpDistributionData *distData, Datum *baseValues, bool *baseNulls);
A
Adam Lee 已提交
153
static ProgramPipes *open_program_pipes(char *command, bool forwrite);
154
static void close_program_pipes(CopyState cstate, bool ifThrow);
155

156
/* ==========================================================================
D
Daniel Gustafsson 已提交
157
 * The following macros aid in major refactoring of data processing code (in
158 159 160 161 162 163 164 165
 * 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 已提交
166

167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
#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! */ \
\
226
	if (Gp_role == GP_ROLE_DISPATCH || cstate->on_segment)\
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 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
	{\
		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 */
304

M
 
Marc G. Fournier 已提交
305
/*
306 307
 * Send copy start/stop messages for frontend copies.  These have changed
 * in past protocol redesigns.
M
 
Marc G. Fournier 已提交
308
 */
309
static void
310
SendCopyBegin(CopyState cstate)
B
Bruce Momjian 已提交
311
{
312 313
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
314 315
		/* new way */
		StringInfoData buf;
316
		int			natts = list_length(cstate->attnumlist);
A
alldefector 已提交
317
		int16		format = (cstate->binary ? 1 : 0);
B
Bruce Momjian 已提交
318
		int			i;
319 320

		pq_beginmessage(&buf, 'H');
B
Bruce Momjian 已提交
321
		pq_sendbyte(&buf, format);		/* overall format */
322 323
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
324
			pq_sendint(&buf, format, 2);		/* per-column formats */
325
		pq_endmessage(&buf);
326
		cstate->copy_dest = COPY_NEW_FE;
327 328
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
329
	{
330
		/* old way */
331 332 333 334
		if (cstate->binary)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
335 336
		pq_putemptymessage('H');
		/* grottiness needed for old COPY OUT protocol */
337
		pq_startcopyout();
338
		cstate->copy_dest = COPY_OLD_FE;
339
	}
B
Bruce Momjian 已提交
340
	else
341
	{
342
		/* very old way */
343 344 345 346
		if (cstate->binary)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
347 348
		pq_putemptymessage('B');
		/* grottiness needed for old COPY OUT protocol */
349
		pq_startcopyout();
350
		cstate->copy_dest = COPY_OLD_FE;
351
	}
M
 
Marc G. Fournier 已提交
352
}
B
Bruce Momjian 已提交
353

354
static void
355
ReceiveCopyBegin(CopyState cstate)
B
Bruce Momjian 已提交
356
{
357 358
	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
	{
359 360
		/* new way */
		StringInfoData buf;
361
		int			natts = list_length(cstate->attnumlist);
A
alldefector 已提交
362
		int16		format = (cstate->binary ? 1 : 0);
B
Bruce Momjian 已提交
363
		int			i;
364 365

		pq_beginmessage(&buf, 'G');
B
Bruce Momjian 已提交
366
		pq_sendbyte(&buf, format);		/* overall format */
367 368
		pq_sendint(&buf, natts, 2);
		for (i = 0; i < natts; i++)
B
Bruce Momjian 已提交
369
			pq_sendint(&buf, format, 2);		/* per-column formats */
370
		pq_endmessage(&buf);
371 372
		cstate->copy_dest = COPY_NEW_FE;
		cstate->fe_msgbuf = makeStringInfo();
373 374 375
	}
	else if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
	{
376
		/* old way */
377 378 379 380
		if (cstate->binary)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
381
		pq_putemptymessage('G');
382
		cstate->copy_dest = COPY_OLD_FE;
383 384 385
	}
	else
	{
386
		/* very old way */
387 388 389 390
		if (cstate->binary)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
			errmsg("COPY BINARY is not supported to stdout or from stdin")));
391
		pq_putemptymessage('D');
392
		cstate->copy_dest = COPY_OLD_FE;
393 394 395
	}
	/* We *must* flush here to ensure FE knows it can send. */
	pq_flush();
M
 
Marc G. Fournier 已提交
396 397
}

398
static void
399
SendCopyEnd(CopyState cstate)
B
Bruce Momjian 已提交
400
{
401
	if (cstate->copy_dest == COPY_NEW_FE)
402
	{
403 404
		/* Shouldn't have any unsent data */
		Assert(cstate->fe_msgbuf->len == 0);
405 406 407 408 409
		/* Send Copy Done message */
		pq_putemptymessage('c');
	}
	else
	{
410 411
		CopySendData(cstate, "\\.", 2);
		/* Need to flush out the trailer (this also appends a newline) */
412
		CopySendEndOfRow(cstate);
413
		pq_endcopyout(false);
414
	}
M
 
Marc G. Fournier 已提交
415 416
}

417
/*----------
418 419 420
 * 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
421
 * CopySendEndOfRow does the appropriate thing at end of each data row
422
 *	(data is not actually flushed except by CopySendEndOfRow)
423 424
 *
 * NB: no data conversion is applied by these functions
425
 *----------
M
 
Marc G. Fournier 已提交
426
 */
427
static void
428
CopySendData(CopyState cstate, const void *databuf, int datasize)
B
Bruce Momjian 已提交
429
{
430 431 432 433 434 435 436 437 438 439 440 441 442
	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 已提交
443 444
}

445
static void
446
CopySendString(CopyState cstate, const char *str)
447
{
448
	CopySendData(cstate, (void *) str, strlen(str));
449 450 451
}

static void
452
CopySendChar(CopyState cstate, char c)
453
{
454
	CopySendData(cstate, &c, 1);
455 456
}

457 458 459 460 461 462
/* 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
463
CopySendEndOfRow(CopyState cstate)
464
{
465 466
	StringInfo	fe_msgbuf = cstate->fe_msgbuf;

467
	switch (cstate->copy_dest)
468 469
	{
		case COPY_FILE:
A
alldefector 已提交
470 471
			if (!cstate->binary)
			{
472
				/* Default line termination depends on platform */
473
#ifndef WIN32
474
				CopySendChar(cstate, '\n');
475
#else
476
				CopySendString(cstate, "\r\n");
477
#endif
A
alldefector 已提交
478
			}
479 480 481 482

			(void) fwrite(fe_msgbuf->data, fe_msgbuf->len,
						  1, cstate->copy_file);
			if (ferror(cstate->copy_file))
483 484 485 486 487 488 489 490 491 492 493
			{
				if (cstate->is_program)
				{
					if (errno == EPIPE)
					{
						/*
						 * The pipe will be closed automatically on error at
						 * the end of transaction, but we might get a better
						 * error message from the subprocess' exit code than
						 * just "Broken Pipe"
						 */
494
						close_program_pipes(cstate, true);
495 496

						/*
A
Adam Lee 已提交
497
						 * If close_program_pipes() didn't throw an error,
498 499 500 501 502 503 504 505 506 507 508
						 * the program terminated normally, but closed the
						 * pipe first. Restore errno, and throw an error.
						 */
						errno = EPIPE;
					}
					ereport(ERROR,
							(errcode_for_file_access(),
							 errmsg("could not write to COPY program: %m")));
				}
				else
					ereport(ERROR,
509 510
						(errcode_for_file_access(),
						 errmsg("could not write to COPY file: %m")));
511
			}
A
Adam Lee 已提交
512

513
			break;
514 515
		case COPY_OLD_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
A
alldefector 已提交
516
			if (!cstate->binary)
517
				CopySendChar(cstate, '\n');
518 519 520 521 522 523 524

			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")));
525
			}
526
			break;
527 528
		case COPY_NEW_FE:
			/* The FE/BE protocol uses \n as newline for all platforms */
A
alldefector 已提交
529
			if (!cstate->binary)
530
				CopySendChar(cstate, '\n');
531 532 533 534 535 536 537 538 539 540 541

			/* 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
542
			return; /* don't want to reset msgbuf quite yet */
543 544
	}

545
	resetStringInfo(fe_msgbuf);
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
}

/*
 * 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:
562 563 564 565

			(void) fwrite(fe_msgbuf->data, fe_msgbuf->len,
						  1, cstate->copy_file);
			if (ferror(cstate->copy_file))
566 567 568 569 570 571 572 573 574 575 576
			{
				if (cstate->is_program)
				{
					if (errno == EPIPE)
					{
						/*
						 * The pipe will be closed automatically on error at
						 * the end of transaction, but we might get a better
						 * error message from the subprocess' exit code than
						 * just "Broken Pipe"
						 */
577
						close_program_pipes(cstate, true);
578 579

						/*
A
Adam Lee 已提交
580
						 * If close_program_pipes() didn't throw an error,
581 582 583 584 585 586 587 588 589 590 591
						 * the program terminated normally, but closed the
						 * pipe first. Restore errno, and throw an error.
						 */
						errno = EPIPE;
					}
					ereport(ERROR,
							(errcode_for_file_access(),
							 errmsg("could not write to COPY program: %m")));
				}
				else
					ereport(ERROR,
592 593
						(errcode_for_file_access(),
						 errmsg("could not write to COPY file: %m")));
594
			}
595 596
			break;
		case COPY_OLD_FE:
597 598 599 600 601 602 603 604

			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")));
			}
605 606
			break;
		case COPY_NEW_FE:
607

608
			/* Dump the accumulated row as one CopyData message */
609
			(void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
610
			break;
611 612 613 614
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* internal error */
			break;

615
	}
616

617
	resetStringInfo(fe_msgbuf);
618 619
}

620 621
/*
 * CopyGetData reads data from the source (file or frontend)
622
 * CopyGetChar does the same for single characters
623
 *
624
 * CopyGetEof checks if EOF was detected by previous Get operation.
625 626 627 628 629
 *
 * 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.
 *
630 631 632 633
 * NB: no data conversion is applied by these functions
 *
 * Returns: the number of bytes that were successfully read
 * into the data buffer.
634
 */
635
static int
636
CopyGetData(CopyState cstate, void *databuf, int datasize)
B
Bruce Momjian 已提交
637
{
638
	size_t		bytesread = 0;
639 640

	switch (cstate->copy_dest)
B
Bruce Momjian 已提交
641
	{
642
		case COPY_FILE:
643 644 645
			bytesread = fread(databuf, 1, datasize, cstate->copy_file);
			if (feof(cstate->copy_file))
				cstate->fe_eof = true;
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
			if (ferror(cstate->copy_file))
			{
				if (cstate->is_program)
				{
					int olderrno = errno;

					close_program_pipes(cstate, true);

					/*
					 * If close_program_pipes() didn't throw an error,
					 * the program terminated normally, but closed the
					 * pipe first. Restore errno, and throw an error.
					 */
					errno = olderrno;

					ereport(ERROR,
							(errcode_for_file_access(),
							 errmsg("could not read from COPY program: %m")));
				}
				else
					ereport(ERROR,
						(errcode_for_file_access(),
						 errmsg("could not read from COPY file: %m")));
			}
670 671
			break;
		case COPY_OLD_FE:
672
			if (pq_getbytes((char *) databuf, datasize))
673 674
			{
				/* Only a \. terminator is legal EOF in old protocol */
675 676 677
				ereport(ERROR,
						(errcode(ERRCODE_CONNECTION_FAILURE),
						 errmsg("unexpected EOF on client connection")));
678
			}
679 680
			bytesread += datasize;		/* update the count of bytes that were
										 * read so far */
681 682
			break;
		case COPY_NEW_FE:
683
			while (datasize > 0 && !cstate->fe_eof)
684
			{
B
Bruce Momjian 已提交
685
				int			avail;
B
Bruce Momjian 已提交
686

687
				while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
688 689 690 691
				{
					/* Try to receive another message */
					int			mtype;

B
Bruce Momjian 已提交
692
			readmessage:
693 694
					mtype = pq_getbyte();
					if (mtype == EOF)
695 696
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
697
							 errmsg("unexpected EOF on client connection")));
698
					if (pq_getmessage(cstate->fe_msgbuf, 0))
699 700
						ereport(ERROR,
								(errcode(ERRCODE_CONNECTION_FAILURE),
B
Bruce Momjian 已提交
701
							 errmsg("unexpected EOF on client connection")));
702 703
					switch (mtype)
					{
B
Bruce Momjian 已提交
704
						case 'd':		/* CopyData */
705
							break;
B
Bruce Momjian 已提交
706
						case 'c':		/* CopyDone */
707
							/* COPY IN correctly terminated by frontend */
708 709
							cstate->fe_eof = true;
							return bytesread;
B
Bruce Momjian 已提交
710
						case 'f':		/* CopyFail */
711 712 713
							ereport(ERROR,
									(errcode(ERRCODE_QUERY_CANCELED),
									 errmsg("COPY from stdin failed: %s",
714
									   pq_getmsgstring(cstate->fe_msgbuf))));
715
							break;
716 717
						case 'H':		/* Flush */
						case 'S':		/* Sync */
B
Bruce Momjian 已提交
718

719
							/*
720 721 722 723
							 * 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.
724 725
							 */
							goto readmessage;
726
						default:
727 728 729 730
							ereport(ERROR,
									(errcode(ERRCODE_PROTOCOL_VIOLATION),
									 errmsg("unexpected message type 0x%02X during COPY from stdin",
											mtype)));
731 732 733
							break;
					}
				}
734
				avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
735 736
				if (avail > datasize)
					avail = datasize;
737
				pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
738
				databuf = (void *) ((char *) databuf + avail);
739 740 741
				bytesread += avail;		/* update the count of bytes that were
										 * read so far */
				datasize -= avail;
B
Bruce Momjian 已提交
742
			}
743
			break;
744 745 746 747
		case COPY_EXTERNAL_SOURCE:
			Insist(false); /* RET read their own data with external_senddata() */
			break;

748
	}
B
Bruce Momjian 已提交
749

750
	return bytesread;
M
 
Marc G. Fournier 已提交
751
}
B
Bruce Momjian 已提交
752

753 754 755 756
/*
 * These functions do apply some data conversion
 */

A
alldefector 已提交
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
/*
 * 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;
}


837
/*
838
 * ValidateControlChars
839
 *
840 841 842 843 844 845 846 847 848 849
 * 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)
850
 */
851 852
void ValidateControlChars(bool copy, bool load, bool csv_mode, char *delim,
						char *null_print, char *quote, char *escape,
853
						  List *force_quote, bool force_quote_all, List *force_notnull,
854 855
						bool header_line, bool fill_missing, char *newline,
						int num_columns)
856
{
857
	bool	delim_off = (pg_strcasecmp(delim, "off") == 0);
858

859 860 861 862 863 864 865 866 867
	/*
	 * 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)
868
	{
869 870 871 872
		/* single byte encoding such as ascii, latinx and other */
		if (strlen(delim) != 1 && !delim_off)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
873
					errmsg("delimiter must be a single one-byte character, or \'off\'")));
874 875 876 877 878 879 880
	}
	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),
881
					errmsg("delimiter must be a single one-byte character, or \'off\'")));
882
	}
883

884 885 886 887 888
	if (strchr(delim, '\r') != NULL ||
		strchr(delim, '\n') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be newline or carriage return")));
889

890 891 892 893 894
	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")));
895

896 897 898 899
	if (!csv_mode && strchr(delim, '\\') != NULL)
		ereport(ERROR,
				(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
				errmsg("delimiter cannot be backslash")));
900

901 902 903 904
	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")));
905

906 907 908 909 910
	/*
	 * 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
911 912
	 * non-literally by COPY IN.  Disallowing all lower case ASCII letters is
	 * more than strictly necessary, but seems best for consistency and
913 914 915 916 917 918 919 920
	 * 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)));
921

922
	if (delim_off)
923
	{
924

925 926 927 928 929 930 931 932 933 934 935
		/*
		 * 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 已提交
936

937 938 939 940
		if (num_columns != 1)
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					errmsg("Using no delimiter is only possible for a single column table")));
941

942
	}
943

944 945 946 947
	/*
	 * HEADER
	 */
	if(header_line)
948
	{
949
		if(!copy && Gp_role == GP_ROLE_DISPATCH)
950
		{
951 952 953 954 955 956 957 958 959 960 961
			/* (exttab) */
			if(load)
			{
				/* RET */
				ereport(NOTICE,
						(errmsg("HEADER means that each one of the data files "
								"has a header row.")));				
			}
			else
			{
				/* WET */
962
				ereport(ERROR,
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 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 1009 1010 1011 1012 1013 1014 1015 1016 1017
						(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
	 */
1018
	if (!csv_mode && (force_quote != NIL || force_quote_all))
1019 1020 1021
		ereport(ERROR,
				(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
				errmsg("force quote available only in CSV mode")));
1022
	if ((force_quote != NIL || force_quote_all) && load)
1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
		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.
 *
1081 1082 1083
 * Iff <binary>, unload or reload in the binary format, as opposed to the
 * more wasteful but more robust and portable text format.
 *
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
 * 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
1102
 * the table or the specifically requested columns.
1103 1104 1105 1106 1107 1108 1109 1110 1111
 */
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;
1112 1113
	bool		force_quote_all = false;
	bool		format_specified = false;
1114
	AclMode		required_access = (is_from ? ACL_INSERT : ACL_SELECT);
1115 1116
	AclMode		relPerms;
	AclMode		remainingPerms;
1117
	ListCell   *option;
1118 1119 1120 1121 1122 1123
	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;
1124 1125 1126 1127 1128 1129

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

1130
		if (strcmp(defel->defname, "format") == 0)
1131
		{
1132
			char	   *fmt = defGetString(defel);
1133 1134

			if (format_specified)
1135 1136
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
A
alldefector 已提交
1137
						 errmsg("conflicting or redundant options")));
1138 1139
			format_specified = true;
			if (strcmp(fmt, "text") == 0)
B
Bruce Momjian 已提交
1140
				 /* default format */ ;
1141 1142 1143 1144 1145 1146 1147 1148
			else if (strcmp(fmt, "csv") == 0)
				cstate->csv_mode = true;
			else if (strcmp(fmt, "binary") == 0)
				cstate->binary = true;
			else
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("COPY format \"%s\" not recognized", fmt)));
1149 1150 1151
		}
		else if (strcmp(defel->defname, "oids") == 0)
		{
1152
			if (cstate->oids)
1153 1154 1155
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1156
			cstate->oids = defGetBoolean(defel);
1157 1158 1159
		}
		else if (strcmp(defel->defname, "delimiter") == 0)
		{
1160
			if (cstate->delim)
1161 1162 1163
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1164
			cstate->delim = defGetString(defel);
1165 1166 1167
		}
		else if (strcmp(defel->defname, "null") == 0)
		{
1168
			if (cstate->null_print)
1169 1170 1171
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1172
			cstate->null_print = defGetString(defel);
1173 1174 1175 1176 1177 1178 1179 1180 1181

			/*
			 * 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 = "";
1182
		}
1183 1184
		else if (strcmp(defel->defname, "header") == 0)
		{
1185
			if (cstate->header_line)
1186 1187 1188
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1189
			cstate->header_line = defGetBoolean(defel);
1190
		}
B
Bruce Momjian 已提交
1191 1192
		else if (strcmp(defel->defname, "quote") == 0)
		{
1193
			if (cstate->quote)
B
Bruce Momjian 已提交
1194 1195 1196
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1197
			cstate->quote = defGetString(defel);
B
Bruce Momjian 已提交
1198 1199 1200
		}
		else if (strcmp(defel->defname, "escape") == 0)
		{
1201
			if (cstate->escape)
B
Bruce Momjian 已提交
1202 1203 1204
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1205
			cstate->escape = defGetString(defel);
B
Bruce Momjian 已提交
1206
		}
B
Bruce Momjian 已提交
1207
		else if (strcmp(defel->defname, "force_quote") == 0)
B
Bruce Momjian 已提交
1208
		{
1209
			if (force_quote || force_quote_all)
B
Bruce Momjian 已提交
1210 1211 1212
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1213
			if (defel->arg && IsA(defel->arg, A_Star))
1214
				force_quote_all = true;
1215
			else if (defel->arg && IsA(defel->arg, List))
1216
				force_quote = (List *) defel->arg;
1217 1218
			else
				ereport(ERROR,
B
Bruce Momjian 已提交
1219 1220 1221
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("argument to option \"%s\" must be a list of column names",
								defel->defname)));
B
Bruce Momjian 已提交
1222
		}
1223
		else if (strcmp(defel->defname, "force_not_null") == 0)
B
Bruce Momjian 已提交
1224
		{
B
Bruce Momjian 已提交
1225
			if (force_notnull)
B
Bruce Momjian 已提交
1226 1227 1228
				ereport(ERROR,
						(errcode(ERRCODE_SYNTAX_ERROR),
						 errmsg("conflicting or redundant options")));
1229 1230 1231 1232
			if (defel->arg && IsA(defel->arg, List))
				force_notnull = (List *) defel->arg;
			else
				ereport(ERROR,
B
Bruce Momjian 已提交
1233 1234 1235
						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
						 errmsg("argument to option \"%s\" must be a list of column names",
								defel->defname)));
B
Bruce Momjian 已提交
1236
		}
1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252
		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 已提交
1253 1254 1255 1256 1257 1258 1259 1260
		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;
		}
1261
		else
1262 1263 1264 1265
			ereport(ERROR,
					(errcode(ERRCODE_SYNTAX_ERROR),
					 errmsg("option \"%s\" not recognized",
							defel->defname)));
1266 1267
	}

1268 1269 1270 1271
	/*
	 * Check for incompatible options (must do these two before inserting
	 * defaults)
	 */
A
alldefector 已提交
1272 1273 1274 1275 1276
	if (cstate->binary && cstate->delim)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify DELIMITER in BINARY mode")));

1277 1278 1279 1280 1281 1282
	if (stmt->is_program && stmt->filename == NULL)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("STDIN/STDOUT not allowed with PROGRAM")));

	if (cstate->on_segment && stmt->filename == NULL)
1283 1284 1285 1286
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("STDIN and STDOUT are not supported by 'COPY ON SEGMENT'")));

1287 1288 1289 1290
	/*
	 * In PostgreSQL, HEADER is not allowed in text mode either, but in GPDB,
	 * only forbid it with BINARY.
	 */
A
alldefector 已提交
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
	if (cstate->binary && cstate->header_line)
		ereport(ERROR,
				(errcode(ERRCODE_SYNTAX_ERROR),
				 errmsg("cannot specify HEADER in BINARY mode")));

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

1301 1302 1303
	cstate->err_loc_type = ROWNUM_ORIGINAL;
	cstate->eol_type = EOL_UNKNOWN;
	cstate->escape_off = false;
B
Bruce Momjian 已提交
1304

1305 1306
	if (!cstate->delim)
		cstate->delim = cstate->csv_mode ? "," : "\t";
B
Bruce Momjian 已提交
1307

1308 1309
	if (!cstate->null_print)
		cstate->null_print = cstate->csv_mode ? "" : "\\N";
B
Bruce Momjian 已提交
1310

1311
	if (cstate->csv_mode)
B
Bruce Momjian 已提交
1312
	{
1313 1314 1315 1316
		if (!cstate->quote)
			cstate->quote = "\"";
		if (!cstate->escape)
			cstate->escape = cstate->quote;
B
Bruce Momjian 已提交
1317
	}
B
Bruce Momjian 已提交
1318

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

1322 1323 1324 1325 1326 1327 1328 1329
	/*
	 * Error handling setup
	 */
	if(stmt->sreh)
	{
		/* Single row error handling requested */
		SingleRowErrorDesc *sreh;
		bool		log_to_file = false;
B
Bruce Momjian 已提交
1330

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

1333 1334 1335 1336
		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 已提交
1337

1338
		if (sreh->into_file)
1339 1340 1341 1342 1343 1344 1345 1346
		{
			cstate->errMode = SREH_LOG;
			log_to_file = true;
		}
		else
		{
			cstate->errMode = SREH_IGNORE;
		}
1347
		cstate->cdbsreh = makeCdbSreh(sreh->rejectlimit,
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
									  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 已提交
1359

1360
	cstate->skip_ext_partition = stmt->skip_ext_partition;
B
Bruce Momjian 已提交
1361

1362 1363 1364 1365 1366 1367
	/* 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 已提交
1368

1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379
	/*
	 * 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,
1380
						 force_quote_all,
1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
						 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);
1393

1394
	/* Disallow COPY to/from file or program except to superusers. */
1395
	if (!pipe && !superuser())
1396 1397 1398 1399 1400 1401 1402 1403 1404
	{
		if (stmt->is_program)
			ereport(ERROR,
					(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
					 errmsg("must be superuser to COPY to or from an external program"),
					 errhint("Anyone can COPY to stdout or from stdin. "
							 "psql's \\copy command also works for anyone.")));
		else
			ereport(ERROR,
1405 1406 1407
				(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 已提交
1408
						 "psql's \\copy command also works for anyone.")));
1409
	}
B
Bruce Momjian 已提交
1410

1411
	cstate->copy_dest = COPY_FILE;		/* default */
A
Adam Lee 已提交
1412 1413 1414 1415 1416 1417 1418 1419 1420 1421
	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);

1422
			if (strstr(stmt->filename, "<SEGID>") == NULL)
A
Adam Lee 已提交
1423
				ereport(ERROR,
1424
					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1425
					 errmsg("<SEGID> is required for file name")));
A
Adam Lee 已提交
1426 1427 1428

			char segid_buf[8];
			snprintf(segid_buf, 8, "%d", GpIdentity.segindex);
1429
			replaceStringInfoString(&filepath, "<SEGID>", segid_buf);
A
Adam Lee 已提交
1430 1431

			cstate->filename = filepath.data;
1432 1433 1434 1435 1436 1437 1438
			/* Rename filename if error log needed */
			if (NULL != cstate->cdbsreh)
			{
				snprintf(cstate->cdbsreh->filename,
						 sizeof(cstate->cdbsreh->filename), "%s",
						 filepath.data);
			}
A
Adam Lee 已提交
1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450

			pipe = false;
		}
		else
		{
			cstate->filename = NULL; /* QE COPY always uses STDIN */
		}
	}
	else
	{
		cstate->filename = stmt->filename; /* Not on_segment, QD saves file to local */
	}
1451 1452 1453 1454
	cstate->copy_file = NULL;
	cstate->fe_msgbuf = NULL;
	cstate->fe_eof = false;
	cstate->missing_bytes = 0;
1455
	cstate->is_program = stmt->is_program;
1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467
	
	if(!is_from)
	{
		if (pipe)
		{
			if (whereToSendOutput == DestRemote)
				cstate->fe_copy = true;
			else
				cstate->copy_file = stdout;
		}
		else
		{
1468 1469 1470
			if (cstate->is_program)
			{
				if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
A
Adam Lee 已提交
1471 1472 1473 1474
				{
					cstate->program_pipes = open_program_pipes("cat > /dev/null", true);
					cstate->copy_file = fdopen(cstate->program_pipes->pipes[0], PG_BINARY_W);
				}
1475
				else
A
Adam Lee 已提交
1476 1477 1478 1479
				{
					cstate->program_pipes = open_program_pipes(cstate->filename, true);
					cstate->copy_file = fdopen(cstate->program_pipes->pipes[0], PG_BINARY_W);
				}
A
Adam Lee 已提交
1480

1481 1482 1483 1484 1485 1486 1487 1488 1489 1490
				if (cstate->copy_file == NULL)
					ereport(ERROR,
							(errmsg("could not execute command \"%s\": %m",
									cstate->filename)));
			}
			else
			{
				mode_t		oumask; /* Pre-existing umask value */
				struct stat st;
				char *filename = cstate->filename;
1491

1492 1493
				if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
					filename = "/dev/null";
1494

1495 1496 1497 1498 1499 1500 1501 1502
				/*
				* Prevent write to relative path ... too easy to shoot oneself in the
				* foot by overwriting a database file ...
				*/
				if (!is_absolute_path(filename))
					ereport(ERROR,
							(errcode(ERRCODE_INVALID_NAME),
							errmsg("relative path not allowed for COPY to file")));
1503

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

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

1513 1514 1515 1516 1517 1518 1519 1520 1521
				// 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)));
			}
1522 1523 1524 1525 1526
		}

	}

	elog(DEBUG1,"DoCopy starting");
1527 1528 1529 1530 1531 1532
	if (stmt->relation)
	{
		Assert(!stmt->query);
		cstate->queryDesc = NULL;

		/* Open and lock the relation, using the appropriate lock type. */
1533 1534
		cstate->rel = heap_openrv(stmt->relation,
							 (is_from ? RowExclusiveLock : AccessShareLock));
1535 1536 1537

		/* save relation oid for auto-stats call later */
		relationOid = RelationGetRelid(cstate->rel);
1538

1539 1540
		tupDesc = RelationGetDescr(cstate->rel);

1541
		/* Check relation permissions. */
1542 1543 1544 1545 1546
		relPerms = pg_class_aclmask(RelationGetRelid(cstate->rel), GetUserId(),
									required_access, ACLMASK_ALL);
		remainingPerms = required_access & ~relPerms;
		if (remainingPerms != 0)
		{
1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
			/* We don't have table permissions, check per-column permissions */
			List	   *attnums;
			ListCell   *cur;

			attnums = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
			foreach(cur, attnums)
			{
				int			attnum = lfirst_int(cur);

				if (pg_attribute_aclcheck(RelationGetRelid(cstate->rel),
										  attnum,
										  GetUserId(),
										  remainingPerms) != ACLCHECK_OK)
					aclcheck_error(ACLCHECK_NO_PRIV, ACL_KIND_CLASS,
								   RelationGetRelationName(cstate->rel));
			}
		}
1564 1565

		/* check read-only transaction */
1566
		if (XactReadOnly && is_from && !cstate->rel->rd_islocaltemp)
1567
			PreventCommandIfReadOnly("COPY FROM");
1568 1569 1570 1571 1572 1573 1574 1575

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

1576 1577 1578
		/* Update error log info */
		if (cstate->cdbsreh)
			cstate->cdbsreh->relid = RelationGetRelid(cstate->rel);
1579 1580 1581 1582
	}
	else
	{
		List	   *rewritten;
1583
		Query	   *query;
1584
		PlannedStmt *plan;
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596
		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 已提交
1597
		 * Run parse analysis and rewrite.	Note this also acquires sufficient
1598
		 * locks on the source table(s).
1599
		 *
1600 1601
		 * Because the parser and planner tend to scribble on their input, we
		 * make a preliminary copy of the source querytree.  This prevents
1602 1603
		 * problems in the case that the COPY is in a portal or plpgsql
		 * function and is executed repeatedly.  (See also the same hack in
1604
		 * DECLARE CURSOR and PREPARE.)  XXX FIXME someday.
1605
		 */
1606 1607
		rewritten = pg_analyze_and_rewrite((Node *) copyObject(stmt->query),
										   queryString, NULL, 0);
1608 1609 1610 1611 1612 1613 1614

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

1617
		/* Query mustn't use INTO, either */
1618
		if (query->intoClause)
1619 1620 1621
			ereport(ERROR,
					(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
					 errmsg("COPY (SELECT INTO) is not supported")));
1622 1623

		/* plan the query */
1624
		plan = planner(query, 0, NULL);
1625 1626

		/*
1627 1628
		 * Use a snapshot with an updated command ID to ensure this query sees
		 * results of any previously executed queries.
1629
		 */
1630
		PushUpdatedSnapshot(GetActiveSnapshot());
1631 1632

		/* Create dest receiver for COPY OUT */
1633
		dest = CreateDestReceiver(DestCopyOut);
1634 1635 1636
		((DR_copy *) dest)->cstate = cstate;

		/* Create a QueryDesc requesting no output */
1637
		cstate->queryDesc = CreateQueryDesc(plan, queryString,
1638
											GetActiveSnapshot(),
1639
											InvalidSnapshot,
W
Wang Hao 已提交
1640 1641
											dest, NULL,
											GP_INSTRUMENT_OPTS);
1642

1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653
		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()));
		}

W
Wang Hao 已提交
1654 1655 1656 1657
		/* GPDB hook for collecting query info */
		if (query_info_collect_hook)
			(*query_info_collect_hook)(METRICS_QUERY_SUBMIT, cstate->queryDesc);

1658 1659 1660 1661 1662 1663 1664 1665 1666
		/*
		 * 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 已提交
1667

1668
	cstate->attnamelist = attnamelist;
1669
	/* Generate or convert list of attributes to process */
1670 1671 1672
	cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);

	num_phys_attrs = tupDesc->natts;
1673

1674 1675
	/* Convert FORCE QUOTE name list to per-column flags, check validity */
	cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1676
	if (force_quote_all)
1677
	{
B
Bruce Momjian 已提交
1678
		int			i;
1679 1680 1681 1682 1683

		for (i = 0; i < num_phys_attrs; i++)
			cstate->force_quote_flags[i] = true;
	}
	else if (force_quote)
B
Bruce Momjian 已提交
1684
	{
1685
		List	   *attnums;
1686
		ListCell   *cur;
B
Bruce Momjian 已提交
1687

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

1690
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1691
		{
1692
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1693

1694
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1695 1696
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1697 1698
				   errmsg("FORCE QUOTE column \"%s\" not referenced by COPY",
						  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1699
			cstate->force_quote_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1700 1701
		}
	}
B
Bruce Momjian 已提交
1702

1703 1704
	/* 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 已提交
1705
	if (force_notnull)
B
Bruce Momjian 已提交
1706
	{
1707
		List	   *attnums;
1708
		ListCell   *cur;
B
Bruce Momjian 已提交
1709

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

1712
		foreach(cur, attnums)
B
Bruce Momjian 已提交
1713
		{
1714
			int			attnum = lfirst_int(cur);
B
Bruce Momjian 已提交
1715

1716
			if (!list_member_int(cstate->attnumlist, attnum))
B
Bruce Momjian 已提交
1717 1718
				ereport(ERROR,
						(errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1719 1720
				errmsg("FORCE NOT NULL column \"%s\" not referenced by COPY",
					   NameStr(tupDesc->attrs[attnum - 1]->attname))));
1721
			cstate->force_notnull_flags[attnum - 1] = true;
B
Bruce Momjian 已提交
1722
		}
B
Bruce Momjian 已提交
1723

1724 1725 1726
		/* keep the raw version too, we will need it later */
		cstate->force_notnull = force_notnull;
	}
1727 1728

	/* Set up variables to avoid per-attribute overhead. */
1729 1730
	initStringInfo(&cstate->attribute_buf);
	initStringInfo(&cstate->line_buf);
1731
	cstate->processed = 0;
1732

1733 1734
	/*
	 * Set up encoding conversion info.  Even if the client and server
1735 1736 1737 1738 1739 1740
	 * 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.
1741
	 */
1742
	cstate->client_encoding = pg_get_client_encoding();
1743
	cstate->need_transcoding =
1744 1745
		((cstate->client_encoding != GetDatabaseEncoding() ||
		  pg_database_encoding_max_length() > 1) && !qe_copy_from);
1746

1747 1748 1749
	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);
1750

1751
	/*
1752
	 * some greenplum db specific vars
1753
	 */
1754 1755
	cstate->is_copy_in = (is_from ? true : false);
	if (is_from)
1756
	{
1757 1758
		cstate->error_on_executor = false;
		initStringInfo(&(cstate->executor_err_context));
1759
	}
1760

1761 1762
	if (is_from)				/* copy from file to database */
	{
1763
		bool		pipe = (cstate->filename == NULL || Gp_role == GP_ROLE_EXECUTE);
1764 1765 1766
		bool		shouldDispatch = (Gp_role == GP_ROLE_DISPATCH &&
									  cstate->rel->rd_cdbpolicy != NULL);
		char		relkind;
1767

1768
		Assert(cstate->rel);
1769

1770
		relkind = cstate->rel->rd_rel->relkind;
1771

1772
		if (relkind != RELKIND_RELATION)
1773
		{
1774
			if (relkind == RELKIND_VIEW)
1775 1776
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1777 1778 1779
						 errmsg("cannot copy to view \"%s\"",
								RelationGetRelationName(cstate->rel))));
			else if (relkind == RELKIND_SEQUENCE)
1780 1781
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1782
						 errmsg("cannot copy to sequence \"%s\"",
1783
								RelationGetRelationName(cstate->rel))));
1784
			else
1785 1786
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
1787
						 errmsg("cannot copy to non-table relation \"%s\"",
B
Bruce Momjian 已提交
1788
								RelationGetRelationName(cstate->rel))));
1789
		}
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804

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

		if (pipe)
		{
			if (whereToSendOutput == DestRemote)
				ReceiveCopyBegin(cstate);
			else
				cstate->copy_file = stdin;
		}
		else
		{
1805 1806 1807
			if (cstate->is_program)
			{
				if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
A
Adam Lee 已提交
1808 1809 1810 1811
				{
					cstate->program_pipes = open_program_pipes("cat /dev/null", false);
					cstate->copy_file = fdopen(cstate->program_pipes->pipes[0], PG_BINARY_R);
				}
1812
				else
A
Adam Lee 已提交
1813 1814 1815 1816
				{
					cstate->program_pipes = open_program_pipes(cstate->filename, false);
					cstate->copy_file = fdopen(cstate->program_pipes->pipes[0], PG_BINARY_R);
				}
1817

1818 1819 1820 1821 1822 1823 1824 1825 1826
				if (cstate->copy_file == NULL)
					ereport(ERROR,
							(errmsg("could not execute command \"%s\": %m",
									cstate->filename)));
			}
			else
			{
				struct stat st;
				char *filename = cstate->filename;
1827

1828 1829 1830
				/* Use dummy file on master for COPY FROM ON SEGMENT */
				if (cstate->on_segment && Gp_role == GP_ROLE_DISPATCH)
					filename = "/dev/null";
1831

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

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

1840 1841 1842 1843 1844 1845 1846 1847 1848
				// 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)));
			}
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
		}


		/*
		 * 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))
			{
1876
				if (cstate->on_segment && gp_enable_segment_copy_checking && !partition_policies_equal(cstate->rel->rd_cdbpolicy, RelationBuildPartitionDesc(cstate->rel, false)))
1877
				{
1878 1879 1880 1881
					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.")));
1882 1883
					return cstate->processed;
				}
1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
				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);
1908
					n->segno = SetSegnoForWrite(cstate->rel, InvalidFileSegNumber);
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924
					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 */
1925 1926
			if (cstate->on_segment)
			{
P
Pengzhou Tang 已提交
1927
				cstate->rel->rd_cdbpolicy = GpPolicyCopy(CacheMemoryContext, stmt->policy);
1928
			}
1929 1930 1931 1932 1933
			CopyFrom(cstate);
		}

		if (!pipe)
		{
1934 1935
			if (cstate->is_program)
			{
1936
				close_program_pipes(cstate, true);
1937 1938 1939 1940
			}
			else if (FreeFile(cstate->copy_file))
			{
					ereport(ERROR,
1941
						(errcode_for_file_access(),
1942
						 errmsg("could not close file \"%s\": %m",
1943
								cstate->filename)));
1944
			}
1945
		}
1946
	}
1947
	else
1948
		DoCopyTo(cstate);		/* copy from database to file */
1949

1950 1951 1952 1953 1954 1955 1956 1957 1958
	/*
	 * 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)
1959
	{
1960 1961 1962 1963
		/* Close down the query and free resources. */
		ExecutorEnd(cstate->queryDesc);
		FreeQueryDesc(cstate->queryDesc);
		cstate->queryDesc = NULL;
1964
		PopActiveSnapshot();
1965
	}
1966 1967

	/* Clean up single row error handling related memory */
1968
	if (cstate->cdbsreh)
1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
		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)
1979
	{
1980 1981 1982 1983 1984 1985
		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);
	}
1986

1987
    /* Issue automatic ANALYZE if conditions are satisfied (MPP-4082). */
1988 1989 1990
	if (Gp_role == GP_ROLE_DISPATCH && is_from)
		auto_stats(AUTOSTATS_CMDTYPE_COPY, relationOid, processed, false /* inFunction */);

1991
	if (cstate->force_quote_flags)
1992
		pfree(cstate->force_quote_flags);
1993
	if (cstate->force_notnull_flags)
1994
		pfree(cstate->force_notnull_flags);
1995

1996 1997
	pfree(cstate->attribute_buf.data);
	pfree(cstate->line_buf.data);
1998

1999 2000
	return processed;
}
2001

2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
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();
	{
2014 2015
		if (!(!cstate->on_segment && Gp_role == GP_ROLE_EXECUTE))
		{
A
Adam Lee 已提交
2016
			if (cstate->is_program && cstate->program_pipes)
2017
			{
A
Adam Lee 已提交
2018
				kill(cstate->program_pipes->pid, 9);
2019 2020 2021 2022
				close_program_pipes(cstate, false);
			}
		}

2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045
		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)
	{
2046
		if (cstate->rel->rd_rel->relkind != RELKIND_RELATION)
2047
		{
2048
			if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
2049 2050 2051 2052 2053
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						 errmsg("cannot copy from view \"%s\"",
								RelationGetRelationName(cstate->rel)),
						 errhint("Try the COPY (SELECT ...) TO variant.")));
2054
			else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
				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,
2086
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
2087 2088
					 errmsg("COPY ignores external partition(s)")));
			}
2089
		}
2090 2091 2092 2093 2094 2095 2096 2097 2098
	}else
	{
		/* Report error because COPY ON SEGMENT don't know the data location of the result of SELECT query.*/
		if(cstate->on_segment)
		{
			ereport(ERROR,
					(errcode(ERRCODE_WRONG_OBJECT_TYPE),
						errmsg("'COPY (SELECT ...) TO' doesn't support 'ON SEGMENT'.")));
		}
2099
	}
2100

2101 2102
	PG_TRY();
	{
2103 2104
		if (cstate->fe_copy)
			SendCopyBegin(cstate);
A
Adam Lee 已提交
2105 2106 2107 2108 2109 2110 2111 2112 2113
		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;
		}
2114

2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126
		/*
		 * 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);
2127

2128 2129
		if (cstate->fe_copy)
			SendCopyEnd(cstate);
A
Adam Lee 已提交
2130 2131 2132 2133 2134 2135 2136 2137 2138
		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);
		}
2139 2140 2141 2142
	}
	PG_CATCH();
	{
		/*
B
Bruce Momjian 已提交
2143
		 * Make sure we turn off old-style COPY OUT mode upon error. It is
B
Bruce Momjian 已提交
2144 2145
		 * okay to do this in all cases, since it does nothing if the mode is
		 * not on.
2146
		 */
A
Adam Lee 已提交
2147 2148 2149
		if (Gp_role == GP_ROLE_EXECUTE && cstate->on_segment)
			cstate->copy_dest = COPY_NEW_FE;

2150 2151 2152 2153
		pq_endcopyout(true);
		PG_RE_THROW();
	}
	PG_END_TRY();
2154 2155 2156

	if (!pipe)
	{
2157 2158
		if (cstate->is_program)
		{
2159
			close_program_pipes(cstate, true);
2160 2161 2162
		}
		else if (FreeFile(cstate->copy_file))
		{
2163 2164
			ereport(ERROR,
					(errcode_for_file_access(),
2165
					 errmsg("could not close file \"%s\": %m",
2166
							cstate->filename)));
2167
		}
2168
	}
2169 2170
}

2171
/*
2172 2173 2174
 * CopyToCreateDispatchCommand
 *
 * Create the COPY command that will get dispatched to the QE's.
2175
 */
2176 2177 2178 2179 2180 2181 2182
static void CopyToCreateDispatchCommand(CopyState cstate,
										StringInfo cdbcopy_cmd,
										AttrNumber	num_phys_attrs,
										Form_pg_attribute *attr)
{
	ListCell   *cur;
	bool		is_first_col = true;
2183
	int			i;
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

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

2215 2216 2217 2218 2219
	if (cstate->is_program)
		appendStringInfo(cdbcopy_cmd, " TO PROGRAM");
	else
		appendStringInfo(cdbcopy_cmd, " TO");

A
Adam Lee 已提交
2220 2221
	if (cstate->on_segment)
	{
2222 2223 2224 2225 2226
		appendStringInfo(cdbcopy_cmd, " '%s' WITH ON SEGMENT", cstate->filename);
	}
	else if (cstate->is_program)
	{
			appendStringInfo(cdbcopy_cmd, " '%s' WITH", cstate->filename);
A
Adam Lee 已提交
2227 2228 2229
	}
	else
	{
2230
			appendStringInfo(cdbcopy_cmd, " STDOUT WITH");
A
Adam Lee 已提交
2231
	}
2232 2233 2234 2235

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

A
alldefector 已提交
2236 2237 2238 2239
	if (cstate->binary)
		appendStringInfo(cdbcopy_cmd, " BINARY");
	else
	{
2240 2241
		appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
		appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));
2242

2243 2244 2245
		/* 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));
2246

2247
		if (cstate->csv_mode)
2248
		{
2249
			appendStringInfo(cdbcopy_cmd, " CSV");
A
Adam Lee 已提交
2250 2251 2252 2253 2254 2255 2256 2257

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

2258 2259 2260 2261 2262 2263
			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++)
2264
			{
2265 2266 2267 2268 2269 2270 2271
				if (cstate->force_quote_flags[i])
				{
					if (is_first_col)
						appendStringInfoString(cdbcopy_cmd, "FORCE QUOTE ");
					else
						appendStringInfoString(cdbcopy_cmd, ", ");
					is_first_col = false;
2272

2273 2274 2275
					appendStringInfoString(cdbcopy_cmd,
										   quote_identifier(NameStr(attr[i]->attname)));
				}
2276 2277
			}

2278 2279
			/* do NOT include HEADER. Header row is created by dispatcher COPY */
		}
A
alldefector 已提交
2280
	}
2281 2282 2283 2284 2285 2286 2287
}


/*
 * Copy from relation TO file. Starts a COPY TO command on each of
 * the executors and gathers all the results and writes it out.
 */
2288
void
2289
CopyToDispatch(CopyState cstate)
2290
{
2291
	TupleDesc	tupDesc;
2292
	int			num_phys_attrs;
2293
	int			attr_count;
2294
	Form_pg_attribute *attr;
2295 2296 2297
	CdbCopy    *cdbCopy;
	StringInfoData cdbcopy_err;
	StringInfoData cdbcopy_cmd;
2298

2299
	tupDesc = cstate->rel->rd_att;
2300 2301
	attr = tupDesc->attrs;
	num_phys_attrs = tupDesc->natts;
2302
	attr_count = list_length(cstate->attnumlist);
2303

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

2307 2308 2309 2310 2311 2312
	/*
	 * 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 已提交
2313

2314 2315 2316 2317
	cdbCopy = makeCdbCopy(false);

	cdbCopy->partitions = RelationBuildPartitionDesc(cstate->rel, false);
	cdbCopy->skip_ext_partition = cstate->skip_ext_partition;
P
Pengzhou Tang 已提交
2318
	cdbCopy->hasReplicatedTable = GpPolicyIsReplicated(cstate->rel->rd_cdbpolicy);
2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330

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

2332
	/*
2333 2334 2335 2336 2337 2338 2339
	 * 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.
2340
	 */
2341
	elog(DEBUG5, "COPY command sent to segdbs: %s", cdbcopy_cmd.data);
2342

2343 2344
	PG_TRY();
	{
2345
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data, NULL);
2346

A
Adam Lee 已提交
2347 2348 2349 2350
		if (cstate->binary)
		{
			/* Generate header for a binary copy */
			int32		tmp;
2351

A
Adam Lee 已提交
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
			/* 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);
		}
A
alldefector 已提交
2363

A
Adam Lee 已提交
2364 2365 2366 2367 2368
		/* if a header has been requested send the line */
		if (cstate->header_line)
		{
			ListCell   *cur;
			bool		hdr_delim = false;
A
alldefector 已提交
2369

A
Adam Lee 已提交
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383
			/*
			 * For non-binary copy, we need to convert null_print to client
			 * encoding, because it will be sent directly with CopySendString.
			 *
			 * 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
			 */
			if (cstate->need_transcoding)
				cstate->null_print = (char *)
					pg_server_to_custom(cstate->null_print,
										strlen(cstate->null_print),
										cstate->client_encoding,
										cstate->enc_conversion_proc);
2384

A
Adam Lee 已提交
2385 2386 2387 2388
			foreach(cur, cstate->attnumlist)
			{
				int			attnum = lfirst_int(cur);
				char	   *colname;
2389

A
Adam Lee 已提交
2390 2391 2392
				if (hdr_delim)
					CopySendChar(cstate, cstate->delim[0]);
				hdr_delim = true;
B
Bruce Momjian 已提交
2393

A
Adam Lee 已提交
2394
				colname = NameStr(attr[attnum - 1]->attname);
2395

A
Adam Lee 已提交
2396 2397 2398
				CopyAttributeOutCSV(cstate, colname, false,
									list_length(cstate->attnumlist) == 1);
			}
2399

A
Adam Lee 已提交
2400 2401
			/* add a newline and flush the data */
			CopySendEndOfRow(cstate);
2402
		}
2403

A
Adam Lee 已提交
2404 2405 2406 2407 2408 2409 2410
		/*
		 * 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)
		{
2411

A
Adam Lee 已提交
2412 2413
			bool done;
			bool copy_cancel = (QueryCancelPending ? true : false);
2414

A
Adam Lee 已提交
2415 2416
			/* get a chunk of data rows from the QE's */
			done = cdbCopyGetData(cdbCopy, copy_cancel, &cstate->processed);
2417

A
Adam Lee 已提交
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429
			/* 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);
			}
2430

A
Adam Lee 已提交
2431 2432 2433 2434 2435 2436 2437
			if(done)
			{
				if(cdbCopy->remote_data_err || cdbCopy->io_errors)
					appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);

				break;
			}
2438
		}
A
Adam Lee 已提交
2439 2440 2441 2442 2443
	}
    /* catch error from CopyStart, CopySendEndOfRow or CopyToDispatchFlush */
	PG_CATCH();
	{
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
2444

A
Adam Lee 已提交
2445
		cdbCopyEnd(cdbCopy);
2446

A
Adam Lee 已提交
2447
		ereport(LOG,
2448
				(errcode(ERRCODE_INTERNAL_ERROR),
A
Adam Lee 已提交
2449 2450
				 errmsg("%s", cdbcopy_err.data)));
		PG_RE_THROW();
2451
	}
A
Adam Lee 已提交
2452
	PG_END_TRY();
2453

A
alldefector 已提交
2454 2455 2456 2457 2458 2459 2460 2461
	if (cstate->binary)
	{
		/* Generate trailer for a binary copy */
		CopySendInt16(cstate, -1);
		/* Need to flush out the trailer */
		CopySendEndOfRow(cstate);
	}

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

2496
	if (cstate->rel)
2497
	{
2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511
		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
P
Pengzhou Tang 已提交
2512
		{
2513
			target_rels = lappend(target_rels, cstate->rel);
P
Pengzhou Tang 已提交
2514
		}
2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527
		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. */
2528
	cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2529 2530 2531 2532 2533 2534
	foreach(cur, cstate->attnumlist)
	{
		int			attnum = lfirst_int(cur);
		Oid			out_func_oid;
		bool		isvarlena;

A
alldefector 已提交
2535 2536 2537 2538 2539
		if (cstate->binary)
			getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
									&out_func_oid,
									&isvarlena);
		else
2540 2541 2542
			getTypeOutputInfo(attr[attnum - 1]->atttypid,
							  &out_func_oid,
							  &isvarlena);
2543 2544
		fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
	}
B
Bruce Momjian 已提交
2545

2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556
	/*
	 * 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);
2557

2558 2559 2560 2561 2562 2563 2564 2565 2566
	/*
	 * 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);
2567

A
alldefector 已提交
2568 2569 2570
	if (cstate->binary)
	{
		/* binary header should not be sent in execute mode. */
A
Adam Lee 已提交
2571
		if (Gp_role != GP_ROLE_EXECUTE || cstate->on_segment)
A
alldefector 已提交
2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589
		{
			/* 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
	{
2590 2591
		/* if a header has been requested send the line */
		if (cstate->header_line)
2592
		{
2593
			/* header should not be printed in execute mode. */
A
Adam Lee 已提交
2594
			if (Gp_role != GP_ROLE_EXECUTE || cstate->on_segment)
2595
			{
2596
				bool		hdr_delim = false;
2597

2598 2599 2600 2601
				foreach(cur, cstate->attnumlist)
				{
					int			attnum = lfirst_int(cur);
					char	   *colname;
2602

2603 2604 2605
					if (hdr_delim)
						CopySendChar(cstate, cstate->delim[0]);
					hdr_delim = true;
2606

2607 2608 2609 2610 2611 2612 2613
					colname = NameStr(attr[attnum - 1]->attname);

					CopyAttributeOutCSV(cstate, colname, false,
										list_length(cstate->attnumlist) == 1);
				}
				CopySendEndOfRow(cstate);
			}
2614
		}
2615 2616 2617 2618
	}

	if (cstate->rel)
	{
P
Pengzhou Tang 已提交
2619 2620 2621 2622 2623 2624 2625 2626 2627
		/* For replicated table, choose only one segment to scan data */
		if (Gp_role == GP_ROLE_EXECUTE && !cstate->on_segment &&
				GpPolicyIsReplicated(cstate->rel->rd_cdbpolicy) &&
				gp_session_id % GpIdentity.numsegments != GpIdentity.segindex)
		{
			MemoryContextDelete(cstate->rowcontext);
			return;
		}

2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
		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 已提交
2658 2659 2660 2661 2662
				if (cstate->binary)
					getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
											&out_func_oid,
											&isvarlena);
				else
2663 2664 2665
					getTypeOutputInfo(attr[attnum - 1]->atttypid,
									  &out_func_oid,
									  &isvarlena);
A
alldefector 已提交
2666

2667 2668 2669 2670 2671 2672 2673 2674 2675 2676
				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;

2677
				scandesc = heap_beginscan(rel, GetActiveSnapshot(), 0, NULL);
2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690
				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);
			}
2691
			else if (RelationIsAoRows(rel))
2692 2693 2694 2695 2696
			{
				MemTuple		tuple;
				TupleTableSlot	*slot = MakeSingleTupleTableSlot(tupDesc);
				MemTupleBinding *mt_bind = create_memtuple_binding(tupDesc);

2697 2698
				aoscandesc = appendonly_beginscan(rel, GetActiveSnapshot(),
												  GetActiveSnapshot(), 0, NULL);
2699 2700 2701 2702

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

2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716
					/* 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);
			}
2717
			else if (RelationIsAoCols(rel))
2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731
			{
				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);
2732
				for(i = 0; i < nvp; ++i)
2733 2734
				    proj[i] = true;

2735 2736 2737
				scan = aocs_beginscan(rel, GetActiveSnapshot(),
									  GetActiveSnapshot(),
									  NULL /* relationTupleDesc */, proj);
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
				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);
		}
2776 2777 2778
	}
	else
	{
2779 2780
		Assert(Gp_role != GP_ROLE_EXECUTE);

2781 2782 2783 2784
		/* run the plan --- the dest receiver will send tuples */
		ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L);
	}

A
alldefector 已提交
2785
	/* binary trailer should not be sent in execute mode. */
A
Adam Lee 已提交
2786
	if (cstate->binary)
A
alldefector 已提交
2787
	{
A
Adam Lee 已提交
2788 2789 2790 2791 2792 2793 2794 2795
		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 已提交
2796 2797
	}

2798 2799 2800
	if (Gp_role == GP_ROLE_EXECUTE && cstate->on_segment)
		SendNumRows(0, cstate->processed);

2801 2802 2803
	MemoryContextDelete(cstate->rowcontext);
}

2804 2805
void
CopyOneCustomRowTo(CopyState cstate, bytea *value)
2806 2807 2808
{
	appendBinaryStringInfo(cstate->fe_msgbuf,
						   VARDATA_ANY((void *) value),
2809 2810 2811
						   VARSIZE_ANY_EXHDR((void *) value));
}

2812 2813 2814
/*
 * Emit one row during CopyTo().
 */
2815
void
2816
CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
2817 2818 2819 2820 2821 2822 2823 2824 2825 2826
{
	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 已提交
2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
	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
	{
2841 2842 2843 2844 2845 2846 2847 2848 2849
		/* 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 已提交
2850
	}
2851 2852 2853 2854

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

A
alldefector 已提交
2858 2859
		if (!cstate->binary)
		{
2860 2861 2862
			if (need_delim)
				CopySendChar(cstate, cstate->delim[0]);
			need_delim = true;
A
alldefector 已提交
2863
		}
2864

2865 2866
		if (isnull)
		{
A
alldefector 已提交
2867
			if (!cstate->binary)
2868
				CopySendString(cstate, cstate->null_print_client);
A
alldefector 已提交
2869 2870
			else
				CopySendInt32(cstate, -1);
2871 2872 2873
		}
		else
		{
A
alldefector 已提交
2874 2875
			if (!cstate->binary)
			{
2876
				char		quotec = cstate->quote ? cstate->quote[0] : '\0';
2877

2878 2879 2880 2881 2882 2883 2884 2885 2886 2887
				/* 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.
					 */
2888

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

2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
					/*
					 * 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);
				}
2918
				else
2919 2920 2921 2922 2923 2924 2925 2926 2927 2928
				{
					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);
				}
2929
			}
A
alldefector 已提交
2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
			else
			{
				bytea	   *outputbytes;

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

2943 2944
	/*
	 * Finish off the row: write it to the destination, and update the count.
2945
	 * However, if we're in the context of a writable external table, we let
2946 2947 2948 2949 2950 2951 2952 2953
	 * 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++;
	}
2954

2955
	MemoryContextSwitchTo(oldcontext);
2956 2957
}

2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
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);
	}
}
3028

3029
/*
3030 3031 3032 3033 3034 3035
 * 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.
3036
 */
A
alldefector 已提交
3037
static int CopyFromCreateDispatchCommand(CopyState cstate,
3038 3039 3040 3041 3042 3043 3044 3045 3046
										  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)
3047
{
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065
	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 */
3066
	{
3067 3068
		is_first_col = true;
		foreach(cur, cstate->attnumlist)
3069
		{
3070 3071
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
3072

3073 3074 3075 3076 3077 3078 3079 3080 3081
			/* 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;
3082
		}
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099

		/*
		 * 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++)
3100
		{
3101 3102 3103 3104
			bool add_to_list = false;

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

3108 3109
				if(h_attnum - 1 == defmap[i])
					add_to_list = true;
3110
			}
3111 3112 3113 3114 3115 3116

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

			if(add_to_list)
3117
			{
3118
				/* We don't add dropped attributes */
A
alldefector 已提交
3119
				/* XXXX: this check seems unnecessary given how CopyFromDispatch constructs defmap */
3120 3121 3122 3123 3124 3125 3126 3127 3128
				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;
3129 3130
			}
		}
3131 3132 3133

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

3136 3137
	/*
	 * NOTE: we used to always pass STDIN here to the QEs. But since we want
3138
	 * the QEs to know the original file name for recording it in an error log file
3139 3140 3141
	 * (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
3142
	 * error log file).
3143 3144
	 */
	if(cstate->filename)
3145 3146 3147 3148 3149 3150
	{
		if (cstate->is_program)
			appendStringInfo(cdbcopy_cmd, " FROM PROGRAM %s WITH", quote_literal_internal(cstate->filename));
		else
			appendStringInfo(cdbcopy_cmd, " FROM %s WITH", quote_literal_internal(cstate->filename));
	}
3151 3152
	else
		appendStringInfo(cdbcopy_cmd, " FROM STDIN WITH");
3153

3154 3155 3156
	if (cstate->on_segment)
		appendStringInfo(cdbcopy_cmd, " ON SEGMENT");

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

A
alldefector 已提交
3160 3161 3162 3163 3164 3165
	if (cstate->binary)
	{
		appendStringInfo(cdbcopy_cmd, " BINARY");
	}
	else
	{
3166 3167
		appendStringInfo(cdbcopy_cmd, " DELIMITER AS E'%s'", escape_quotes(cstate->delim));
		appendStringInfo(cdbcopy_cmd, " NULL AS E'%s'", escape_quotes(cstate->null_print));
3168

3169 3170 3171
		/* 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));
3172

3173 3174
		/* if EOL is already defined it means that NEWLINE was declared. pass it along */
		if (cstate->eol_type != EOL_UNKNOWN)
3175
		{
3176 3177 3178
			Assert(cstate->eol_str);
			appendStringInfo(cdbcopy_cmd, " NEWLINE AS '%s'", escape_quotes(cstate->eol_str));
		}
3179

3180 3181 3182
		if (cstate->csv_mode)
		{
			appendStringInfo(cdbcopy_cmd, " CSV");
3183 3184 3185 3186 3187 3188 3189 3190

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

3191 3192
			appendStringInfo(cdbcopy_cmd, " QUOTE AS E'%s'", escape_quotes(cstate->quote));
			appendStringInfo(cdbcopy_cmd, " ESCAPE AS E'%s'", escape_quotes(cstate->escape));
3193

3194
			if(cstate->force_notnull)
3195
			{
3196
				ListCell   *l;
3197

3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208
				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;
				}
3209
			}
3210
			/* do NOT include HEADER. Header row is "swallowed" by dispatcher COPY */
3211
		}
A
alldefector 已提交
3212
	}
3213 3214 3215 3216 3217 3218 3219 3220 3221

	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)
		{
3222
			appendStringInfoString(cdbcopy_cmd, " LOG ERRORS");
3223 3224 3225 3226 3227
		}

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

A
alldefector 已提交
3229
	return extra_attr_count;
3230
}
3231

3232 3233 3234
/*
 * Copy FROM file to relation.
 */
3235 3236
void
CopyFromDispatch(CopyState cstate)
3237
{
3238
	TupleDesc	tupDesc;
3239
	Form_pg_attribute *attr;
B
Bruce Momjian 已提交
3240 3241 3242
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
3243
	FmgrInfo   *in_functions;
A
alldefector 已提交
3244
	FmgrInfo	oid_in_function;
3245
	FmgrInfo   *out_functions; /* for handling defaults in Greenplum Database */
3246
	Oid		   *typioparams;
A
Adam Lee 已提交
3247
	Oid			oid_typioparam = 0;
3248
	int			attnum;
B
Bruce Momjian 已提交
3249
	int			i;
3250
	int			p_index;
3251
	Oid			in_func_oid;
3252
	Oid			out_func_oid;
3253
	Datum	   *values;
3254 3255
	bool	   *nulls;
	int		   *attr_offsets;
3256
	int			total_rejected_from_qes = 0;
3257
	int64		total_completed_from_qes = 0;
3258
	bool		isnull;
3259
	bool	   *isvarlena;
3260
	ResultRelInfo *resultRelInfo;
B
Bruce Momjian 已提交
3261
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
3262
	bool		file_has_oids = false;
3263
	int		   *defmap;
3264
	ExprState **defexprs;		/* array of default att expressions */
B
Bruce Momjian 已提交
3265
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
3266
	MemoryContext oldcontext = CurrentMemoryContext;
3267
	ErrorContextCallback errcontext;
3268 3269 3270
	bool		no_more_data = false;
	bool		cur_row_rejected = false;
	CdbCopy    *cdbCopy;
3271

3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
	GpDistributionData *distData = NULL;		/*distribution policy for root table */
	GpDistributionData *part_distData = palloc(sizeof(GpDistributionData));		/* distribution policy for part table */
	GetAttrContext *getAttrContext = palloc(sizeof(GetAttrContext));		/* get attr values context */
	/* init partition data*/
	PartitionData *partitionData = palloc(sizeof(PartitionData));
	partitionData->part_values = NULL;
	partitionData->part_attr_types = NULL;
	partitionData->part_typio = NULL;
	partitionData->part_infuncs = NULL;
	partitionData->part_attnum = NULL;
	partitionData->part_attnums = 0;

3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297
	/*
	 * 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;
3298

3299 3300 3301 3302
	/*
	 * a reconstructed and modified COPY command that is dispatched to segments.
	 */
	StringInfoData cdbcopy_cmd;
3303

3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315
	/*
	 * 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 original row number tracking
	 */
	StringInfoData line_buf_with_lineno;
	int			original_lineno_for_qe;
3316

3317 3318 3319
	/*
	 * Variables for cdbhash
	 */
3320

3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331
	/*
	 * 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.
	 */

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

3333
	tupDesc = RelationGetDescr(cstate->rel);
3334
	attr = tupDesc->attrs;
3335
	num_phys_attrs = tupDesc->natts;
3336
	attr_count = list_length(cstate->attnumlist);
3337
	num_defaults = 0;
3338 3339 3340 3341 3342 3343 3344
	h_attnum = 0;

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

	/*
3347
	 * We need a ResultRelInfo so we can use the regular executor's
3348 3349
	 * index-entry-making machinery.  (There used to be a huge amount of
	 * code here that basically duplicated execUtils.c ...)
3350
	 */
3351
	resultRelInfo = makeNode(ResultRelInfo);
B
Bruce Momjian 已提交
3352
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
3353 3354
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
3355 3356
	if (resultRelInfo->ri_TrigDesc)
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
3357 3358 3359
            palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
    resultRelInfo->ri_TrigInstrument = NULL;
    ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
3360

3361
	ExecOpenIndices(resultRelInfo);
3362

3363 3364 3365
	estate->es_result_relations = resultRelInfo;
	estate->es_num_result_relations = 1;
	estate->es_result_relation_info = resultRelInfo;
3366

3367 3368
	econtext = GetPerTupleExprContext(estate);

3369
	/*
3370
	 * Pick up the required catalog information for each attribute in the
3371 3372
	 * relation, including the input function, the element type (to pass
	 * to the input function), and info about defaults and constraints.
3373
	 */
3374
	in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3375
	out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3376
	typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
3377 3378
	defmap = (int *) palloc(num_phys_attrs * sizeof(int));
	defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
3379 3380
	isvarlena = (bool *) palloc(num_phys_attrs * sizeof(bool));

3381

3382
	for (attnum = 1; attnum <= num_phys_attrs; attnum++)
3383
	{
3384
		/* We don't need info for dropped attributes */
3385
		if (attr[attnum - 1]->attisdropped)
3386
			continue;
B
Bruce Momjian 已提交
3387

3388
		/* Fetch the input function and typioparam info */
A
alldefector 已提交
3389 3390 3391 3392
		if (cstate->binary)
			getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
								   &in_func_oid, &typioparams[attnum - 1]);
		else
3393 3394
			getTypeInputInfo(attr[attnum - 1]->atttypid,
							 &in_func_oid, &typioparams[attnum - 1]);
3395
		fmgr_info(in_func_oid, &in_functions[attnum - 1]);
B
Bruce Momjian 已提交
3396

3397 3398 3399 3400 3401
		/*
		 * Fetch the output function and typioparam info. We need it
		 * for handling default functions on the dispatcher COPY, if
		 * there are any.
		 */
A
alldefector 已提交
3402 3403 3404 3405 3406
		if (cstate->binary)
			getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
									&out_func_oid,
									&isvarlena[attnum - 1]);
		else
3407 3408 3409
			getTypeOutputInfo(attr[attnum - 1]->atttypid,
							  &out_func_oid,
							  &isvarlena[attnum - 1]);
3410 3411 3412 3413
		fmgr_info(out_func_oid, &out_functions[attnum - 1]);

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

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

			if (defexpr != NULL)
B
Bruce Momjian 已提交
3422
			{
3423 3424
				defexprs[num_defaults] = ExecPrepareExpr((Expr *) defexpr,
														 estate);
3425
				defmap[num_defaults] = attnum - 1;
3426
				num_defaults++;
3427
			}
3428
		}
3429 3430
	}

3431
	/*
3432 3433 3434 3435 3436 3437 3438
	 * 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.
3439
	 */
3440
	cdbCopy = makeCdbCopy(true);
3441

3442 3443
	estate->es_result_partitions = cdbCopy->partitions =
		RelationBuildPartitionDesc(cstate->rel, false);
3444

3445
	CopyInitPartitioningState(estate);
3446 3447


3448 3449
	if (list_length(cstate->ao_segnos) > 0)
		cdbCopy->ao_segnos = cstate->ao_segnos;
3450

3451 3452 3453
	/* add cdbCopy reference to cdbSreh (if needed) */
	if (cstate->errMode != ALL_OR_NOTHING)
		cstate->cdbsreh->cdbcopy = cdbCopy;
3454

3455 3456 3457 3458 3459 3460 3461 3462 3463 3464
	/* get data for distribution */
	bool multi_dist_policy = estate->es_result_partitions
	        && !partition_policies_equal(cstate->rel->rd_cdbpolicy,
	                                     estate->es_result_partitions);
	distData = InitDistributionData(cstate, attr, num_phys_attrs,
	                                estate, multi_dist_policy);
	policy = distData->policy;
	cdbHash = distData->cdbHash;
	p_attr_types = distData->p_attr_types;
	p_nattrs = distData->p_nattrs;
3465 3466 3467 3468 3469
	/* allocate memory for error and copy strings */
	initStringInfo(&cdbcopy_err);
	initStringInfo(&cdbcopy_cmd);

	/* store the COPY command string in cdbcopy_cmd */
A
alldefector 已提交
3470
	int extra_attr_count = CopyFromCreateDispatchCommand(cstate,
3471 3472 3473 3474 3475 3476 3477 3478 3479
								  &cdbcopy_cmd,
								  policy,
								  num_phys_attrs,
								  num_defaults,
								  p_nattrs,
								  h_attnum,
								  defmap,
								  defexprs,
								  attr);
3480

A
alldefector 已提交
3481 3482 3483
	/* init partition routing data structure */
	if (estate->es_result_partitions)
	{
3484
		InitPartitionData(partitionData, estate, attr, num_phys_attrs, oldcontext);
A
alldefector 已提交
3485
	}
3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503
	/*
	 * 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();
	{
3504
		cdbCopyStart(cdbCopy, cdbcopy_cmd.data, cstate->rel->rd_cdbpolicy);
3505 3506 3507 3508 3509
	}
	PG_CATCH();
	{
		/* get error message from CopyStart */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
3510

3511 3512
		/* end COPY in all the segdbs in progress */
		cdbCopyEnd(cdbCopy);
3513

3514 3515
		/* get error message from CopyEnd */
		appendBinaryStringInfo(&cdbcopy_err, cdbCopy->err_msg.data, cdbCopy->err_msg.len);
3516

3517
		ereport(LOG,
3518
				(errcode(ERRCODE_INTERNAL_ERROR),
3519 3520 3521 3522
				 errmsg("%s", cdbcopy_err.data)));
		PG_RE_THROW();
	}
	PG_END_TRY();
3523

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

3527
	/*
3528 3529 3530 3531
	 * 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.
3532 3533
	 */
	//ExecBSInsertTriggers(estate, resultRelInfo);
B
Bruce Momjian 已提交
3534

3535 3536
	/* Skip header processing if dummy file on master for COPY FROM ON SEGMENT */
	if (!cstate->on_segment || Gp_role != GP_ROLE_DISPATCH)
A
alldefector 已提交
3537
	{
3538
		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
A
alldefector 已提交
3539
	}
3540

3541 3542 3543
	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));
3544

3545 3546 3547 3548 3549 3550
	/* 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;
3551

3552
	CopyInitDataParser(cstate);
3553

3554 3555 3556
	do
	{
		size_t		bytesread = 0;
3557

A
alldefector 已提交
3558 3559
		if (!cstate->binary)
		{
3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576
			/* read a chunk of data into the buffer */
			PG_TRY();
			{
				bytesread = CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);
			}
			PG_CATCH();
			{
				/*
				 * 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.
				 */
				cdbCopyEnd(cdbCopy);
				PG_RE_THROW();
			}
			PG_END_TRY();
3577

3578
			cstate->raw_buf_done = false;
3579

3580 3581 3582
			/* set buffer pointers to beginning of the buffer */
			cstate->begloc = cstate->raw_buf;
			cstate->raw_buf_index = 0;
A
alldefector 已提交
3583
		}
3584

3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606
		/*
		 * 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.
					 */
3607

3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622
					/*
					 * 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! */
3623

3624 3625 3626 3627 3628 3629 3630 3631
						/*
						 * 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 已提交
3632

3633 3634
				cstate->cur_lineno++;
				RESET_LINEBUF;
V
Vadim B. Mikheev 已提交
3635

3636 3637
				cstate->header_line = false;
			}
3638

3639 3640
			while (!cstate->raw_buf_done)
			{
3641 3642 3643
				part_distData->cdbHash = NULL;
				part_distData->policy = NULL;
				Oid loaded_oid = InvalidOid;
3644 3645 3646 3647 3648 3649
				if (QueryCancelPending)
				{
					/* quit processing loop */
					no_more_data = true;
					break;
				}
3650

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

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

3657 3658 3659 3660
				/* 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));
3661

3662 3663
				/* Get the line number of the first line of this data row */
				original_lineno_for_qe = cstate->cur_lineno + 1;
3664

A
alldefector 已提交
3665 3666
				if (!cstate->binary)
				{
3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679
				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();
3680

3681 3682 3683 3684 3685
				if(cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
				}
3686 3687


3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708
				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;
				}
3709

3710 3711 3712
				if (file_has_oids)
				{
					char	   *oid_string;
3713

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

3717 3718 3719
					if (isnull)
					{
						/* got here? null in OID column error */
3720

3721 3722 3723 3724
						if(cstate->errMode == ALL_OR_NOTHING)
						{
							/* report error and abort */
							cdbCopyEnd(cdbCopy);
3725

3726 3727 3728 3729 3730 3731 3732 3733 3734 3735
							ereport(ERROR,
									(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
									 errmsg("null OID in COPY data.")));
						}
						else
						{
							/* SREH */
							cstate->cdbsreh->rejectcount++;
							cur_row_rejected = true;
						}
3736

3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
					}
					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();
3752

3753 3754 3755 3756 3757 3758
						if (loaded_oid == InvalidOid)
						{
							if(cstate->errMode == ALL_OR_NOTHING)
							{
								/* report error and abort */
								cdbCopyEnd(cdbCopy);
3759

3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770
								ereport(ERROR,
										(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
										 errmsg("invalid OID in COPY data.")));
							}
							else
							{
								/* SREH */
								cstate->cdbsreh->rejectcount++;
								cur_row_rejected = true;
							}
						}
3771

3772 3773
						cstate->cur_attname = NULL;
					}
B
Bruce Momjian 已提交
3774

3775 3776 3777 3778 3779 3780
					if(cur_row_rejected)
					{
						ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
						QD_GOTO_NEXT_ROW;
					}
				}
A
alldefector 已提交
3781 3782 3783 3784 3785 3786 3787 3788
				}
				else
				{
					/*
					 * Binary mode, not doing anything here;
					 * Deferring "line" segmenting and parsing to next code block.
					 */
				}
3789

3790 3791 3792 3793 3794
				PG_TRY();
				{
					/*
					 * parse and convert the data line attributes.
					 */
A
alldefector 已提交
3795 3796
					if (!cstate->binary)
					{
3797 3798 3799 3800
					if (cstate->csv_mode)
						CopyReadAttributesCSV(cstate, nulls, attr_offsets, num_phys_attrs, attr);
					else
						CopyReadAttributesText(cstate, nulls, attr_offsets, num_phys_attrs, attr);
3801

A
alldefector 已提交
3802
						/* Parse only partition attributes */
3803 3804 3805 3806 3807 3808 3809
					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 已提交
3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889
					}
					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;
								}
							}
3890
							if (skip_parsing && partitionData->part_attnums > 0) {
A
alldefector 已提交
3891
								for (p_index = 0; p_index < p_nattrs; p_index++) {
3892
									if (attnum == partitionData->part_attnum[p_index])
A
alldefector 已提交
3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918
									{
										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;
						}
					}
3919

3920 3921 3922 3923 3924 3925 3926
					/*
					 * 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 已提交
3927 3928 3929 3930
					 *
					 * 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
3931 3932 3933 3934
					 */
					for (i = 0; i < num_defaults; i++)
					{
						bool compute_default = false;
B
Bruce Momjian 已提交
3935

3936 3937 3938 3939
						/* 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];
3940

3941 3942 3943
							if(h_attnum - 1 == defmap[i])
								compute_default = true;
						}
B
Bruce Momjian 已提交
3944

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

3949 3950 3951 3952
						if(compute_default)
						{
							values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
															 &isnull, NULL);
3953

A
alldefector 已提交
3954 3955 3956 3957
							/* Extend line_buf for the QDs */
							if (!cstate->binary)
							{
								char *string;
3958 3959 3960 3961 3962
							/*
							 * prepare to concatinate next value:
							 * remove eol characters from end of line buf
							 */
							truncateEol(&cstate->line_buf, cstate->eol_type);
3963

3964 3965 3966 3967 3968 3969 3970
							if (isnull)
							{
								appendStringInfo(&cstate->line_buf, "%c%s", cstate->delim[0], cstate->null_print);
							}
							else
							{
								nulls[defmap[i]] = false;
3971

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

3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986
								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);
							}
3987

3988 3989 3990
							/* re-add the eol characters */
							concatenateEol(cstate);
						}
A
alldefector 已提交
3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016
							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);
								}
							}
						}
4017

4018 4019 4020
					}
					/* lock partition */
					if (estate->es_result_partitions)
B
Bruce Momjian 已提交
4021
					{
4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034
						getAttrContext->tupDesc = tupDesc;
						getAttrContext->attr = attr;
						getAttrContext->num_phys_attrs = num_phys_attrs;
						getAttrContext->attr_offsets = attr_offsets;
						getAttrContext->nulls = nulls;
						getAttrContext->values = values;
						getAttrContext->cdbCopy = cdbCopy;
						getAttrContext->original_lineno_for_qe =
							original_lineno_for_qe;
						part_distData = GetDistributionPolicyForPartition(
							        cstate, estate, partitionData,
							        distData->hashmap, distData->p_attr_types,
							        getAttrContext, oldcontext);
B
Bruce Momjian 已提交
4035
					}
4036

4037
					if (!part_distData->cdbHash)
B
Bruce Momjian 已提交
4038
					{
4039 4040 4041 4042 4043
						part_distData->policy = distData->policy;
						part_distData->cdbHash = distData->cdbHash;
						part_distData->p_attr_types = distData->p_attr_types;
						part_distData->hashmap = distData->hashmap;
						part_distData->p_nattrs =distData->p_nattrs;
B
Bruce Momjian 已提交
4044
					}
4045 4046 4047 4048
					/*
					 * policy should be PARTITIONED (normal tables) or
					 * ENTRY
					 */
4049
					if (!part_distData->policy)
4050
					{
4051
						elog(FATAL, "Bad or undefined policy. (%p)", part_distData->policy);
4052 4053 4054
					}
				}
				PG_CATCH();
B
Bruce Momjian 已提交
4055
				{
4056
					COPY_HANDLE_ERROR;
B
Bruce Momjian 已提交
4057
				}
4058
				PG_END_TRY();
B
Bruce Momjian 已提交
4059

A
alldefector 已提交
4060 4061 4062
				if (no_more_data)
					break;

4063
				if(cur_row_rejected)
B
Bruce Momjian 已提交
4064
				{
4065 4066
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QD_GOTO_NEXT_ROW;
B
Bruce Momjian 已提交
4067
				}
4068

4069 4070 4071
				/*
				 * Send data row to all databases for this segment.
				 * Also send the original row number with the data.
A
alldefector 已提交
4072 4073 4074 4075 4076
				 */
				if (!cstate->binary)
				{
					/*
					 * Text/CSV: modify the data to look like:
4077 4078 4079 4080 4081 4082 4083 4084
				 *    "<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 已提交
4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099
				}
				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);
				}
4100
				
P
Pengzhou Tang 已提交
4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124
				/*
				 * 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.
				 */
				if (part_distData &&
					GpPolicyIsReplicated(part_distData->policy))
				{
					cdbCopySendDataToAll(cdbCopy,
							line_buf_with_lineno.data,
							line_buf_with_lineno.len);
					RESET_LINEBUF_WITH_LINENO;
				}
				else
				{
					target_seg  = GetTargetSeg(part_distData, values, nulls);

					if (!cstate->on_segment)
						cdbCopySendData(cdbCopy,
4125 4126 4127 4128 4129
									target_seg,
									line_buf_with_lineno.data,
									line_buf_with_lineno.len);
					RESET_LINEBUF_WITH_LINENO;
				}
4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157

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

	/*
	 * 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.
	 */
4158
	total_rejected_from_qes = cdbCopyEndAndFetchRejectNum(cdbCopy, &total_completed_from_qes);
4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209

	/*
	 * 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;
4210 4211 4212 4213 4214 4215 4216 4217

		/*
		 * 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)
4218
			total_rejected_from_qd = 0;
4219 4220

		total_rejected = total_rejected_from_qd + total_rejected_from_qes;
4221 4222 4223 4224 4225 4226
		cstate->processed -= total_rejected;

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

4227
	cstate->processed += total_completed_from_qes;
4228 4229 4230 4231 4232 4233

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

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

4237
	/* Handle queued AFTER triggers */
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
	//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
	 */
	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);
4299 4300 4301 4302
	pfree(part_distData);
	pfree(getAttrContext);
	FreePartitionData(partitionData);
	FreeDistributionData(distData);
4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313

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

4314 4315 4316 4317 4318
/*
 * Copy FROM file to relation.
 */
static void
CopyFrom(CopyState cstate)
4319 4320 4321 4322 4323 4324 4325
{
	TupleDesc	tupDesc;
	Form_pg_attribute *attr;
	AttrNumber	num_phys_attrs,
				attr_count,
				num_defaults;
	FmgrInfo   *in_functions;
A
alldefector 已提交
4326
	FmgrInfo	oid_in_function;
4327
	Oid		   *typioparams;
A
Adam Lee 已提交
4328
	Oid			oid_typioparam = 0;
4329 4330 4331
	int			attnum;
	int			i;
	Oid			in_func_oid;
4332 4333
	Datum		*partValues = NULL;
	bool		*partNulls = NULL;
4334 4335 4336
	bool		isnull;
	ResultRelInfo *resultRelInfo;
	EState	   *estate = CreateExecutorState(); /* for ExecConstraints() */
4337
	TupleTableSlot *baseSlot;
4338
	TupleTableSlot *slot;
4339
	bool		file_has_oids = false;
4340 4341 4342 4343 4344
	int		   *defmap;
	ExprState **defexprs;		/* array of default att expressions */
	ExprContext *econtext;		/* used for ExecEvalExpr for default atts */
	MemoryContext oldcontext = CurrentMemoryContext;
	ErrorContextCallback errcontext;
4345
	CommandId	mycid = GetCurrentCommandId(true);
4346
	int			hi_options = 0; /* start with default heap_insert options */
4347
	BulkInsertState bistate;
4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358
	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;
4359
	bool		is_segment_data_processed = (cstate->on_segment && Gp_role == GP_ROLE_EXECUTE) ? false : true;
4360
	bool is_check_distkey = (cstate->on_segment && Gp_role == GP_ROLE_EXECUTE && gp_enable_segment_copy_checking) ? true : false;
4361
	GpDistributionData	*distData = NULL; /* distribution data used to compute target seg */
4362
	unsigned int	target_seg = 0; /* result segment of cdbhash */
4363

4364 4365 4366
	/*----------
	 * Check to see if we can avoid writing WAL
	 *
A
Abhijit Subramanya 已提交
4367
	 * If archive logging/streaming is not enabled *and* either
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
	 *	- 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)
	{
4394
		hi_options |= HEAP_INSERT_SKIP_FSM;
4395
		if (!XLogIsNeeded())
4396
			hi_options |= HEAP_INSERT_SKIP_WAL;
4397 4398
	}

4399 4400
	oldcontext = MemoryContextSwitchTo(estate->es_query_cxt);

4401 4402
	/*
	 * We need a ResultRelInfo so we can use the regular executor's
4403 4404
	 * index-entry-making machinery.  (There used to be a huge amount of code
	 * here that basically duplicated execUtils.c ...)
4405 4406 4407 4408 4409 4410
	 */
	resultRelInfo = makeNode(ResultRelInfo);
	resultRelInfo->ri_RangeTableIndex = 1;		/* dummy */
	resultRelInfo->ri_RelationDesc = cstate->rel;
	resultRelInfo->ri_TrigDesc = CopyTriggerDesc(cstate->rel->trigdesc);
	if (resultRelInfo->ri_TrigDesc)
4411
	{
4412
		resultRelInfo->ri_TrigFunctions = (FmgrInfo *)
4413
			palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(FmgrInfo));
4414 4415 4416
		resultRelInfo->ri_TrigWhenExprs = (List **)
			palloc0(resultRelInfo->ri_TrigDesc->numtriggers * sizeof(List *));
	}
4417 4418
	resultRelInfo->ri_TrigInstrument = NULL;
	ResultRelInfoSetSegno(resultRelInfo, cstate->ao_segnos);
4419

4420
	ExecOpenIndices(resultRelInfo);
4421 4422 4423 4424 4425 4426 4427 4428 4429

	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 */
4430 4431
	baseSlot = ExecInitExtraTupleSlot(estate);
	ExecSetSlotDescriptor(baseSlot, tupDesc);
4432 4433 4434 4435 4436

	econtext = GetPerTupleExprContext(estate);

	/*
	 * Pick up the required catalog information for each attribute in the
4437 4438
	 * relation, including the input function, the element type (to pass to
	 * the input function), and info about defaults and constraints.
4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451
	 */
	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 已提交
4452 4453 4454 4455
		if (cstate->binary)
			getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
								   &in_func_oid, &typioparams[attnum - 1]);
		else
4456 4457
			getTypeInputInfo(attr[attnum - 1]->atttypid,
							 &in_func_oid, &typioparams[attnum - 1]);
4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476
		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++;
			}
		}
	}

4477 4478 4479
	/* prepare distribuion data for computing target seg*/
	if (is_check_distkey)
	{
4480
		distData = InitDistributionData(cstate, attr, num_phys_attrs, estate, false);
4481 4482
	}

4483
	/* Prepare to catch AFTER triggers. */
4484 4485 4486
	AfterTriggerBeginQuery();

	/*
4487 4488 4489 4490
	 * 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.
4491 4492 4493
	 */
	ExecBSInsertTriggers(estate, resultRelInfo);

4494 4495 4496 4497 4498
	/* 
	 * 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 已提交
4499
	{
4500
		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
A
alldefector 已提交
4501
	}
4502 4503 4504

	attr_offsets = (int *) palloc(num_phys_attrs * sizeof(int));

4505 4506 4507
	partValues = (Datum *) palloc(attr_count * sizeof(Datum));
	partNulls = (bool *) palloc(attr_count * sizeof(bool));

4508 4509
	bistate = GetBulkInsertState();

4510 4511 4512 4513 4514 4515
	/* 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;

4516
	if (Gp_role == GP_ROLE_EXECUTE && (cstate->on_segment == false))
4517 4518 4519 4520 4521 4522
		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);

4523
PROCESS_SEGMENT_DATA:
4524 4525 4526 4527
	do
	{
		size_t		bytesread = 0;

A
alldefector 已提交
4528 4529
		if (!cstate->binary)
		{
4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545
			PG_TRY();
			{
				/* read a chunk of data into the buffer */
				bytesread = CopyGetData(cstate, cstate->raw_buf, RAW_BUF_SIZE);
			}
			PG_CATCH();
			{
				/*
				 * 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.
				 */
				COPY_HANDLE_ERROR;
			}
			PG_END_TRY();
4546

4547 4548 4549 4550 4551
			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 已提交
4552
		}
4553 4554 4555 4556 4557 4558 4559 4560

		/*
		 * 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)
		{
4561 4562
			/* handle HEADER, but only if COPY FROM ON SEGMENT */
			if (cstate->header_line && cstate->on_segment)
4563
			{
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579
				/* 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();
				{
					/*
					 * got here? encoding conversion error occured on the
					 * header line (first row).
					 */
					if (cstate->errMode == ALL_OR_NOTHING)
					{
						/* re-throw error and abort */
4580
						COPY_HANDLE_ERROR;
4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597
					}
					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++;
4598
				RESET_LINEBUF;
4599 4600

				cstate->header_line = false;
4601 4602 4603 4604 4605 4606 4607
			}

			while (!cstate->raw_buf_done)
			{
				bool		skip_tuple;
				Oid			loaded_oid = InvalidOid;
				char		relstorage;
4608 4609 4610
				Datum	   *baseValues;
				bool	   *baseNulls;

4611 4612 4613 4614 4615 4616 4617 4618 4619
				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 */
4620 4621 4622 4623
				ExecClearTuple(baseSlot);
				baseValues = slot_get_values(baseSlot);
				baseNulls = slot_get_isnull(baseSlot);

4624 4625
				MemSet(baseValues, 0, num_phys_attrs * sizeof(Datum));
				MemSet(baseNulls, true, num_phys_attrs * sizeof(bool));
4626 4627 4628
				/* reset attribute pointers */
				MemSet(attr_offsets, 0, num_phys_attrs * sizeof(int));

A
alldefector 已提交
4629 4630
				if (!cstate->binary)
				{
4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738
				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)
						{
							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)
4739
						CopyReadAttributesCSV(cstate, baseNulls, attr_offsets, num_phys_attrs, attr);
4740
					else
4741
						CopyReadAttributesText(cstate, baseNulls, attr_offsets, num_phys_attrs, attr);
4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753

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

4754
						if (baseNulls[m])
4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766
							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);

4767
						baseValues[m] = InputFunctionCall(&in_functions[m],
4768 4769 4770
													  isnull ? NULL : string,
													  typioparams[m],
													  attr[m]->atttypmod);
4771
						baseNulls[m] = isnull;
4772 4773
						cstate->cur_attname = NULL;
					}
4774 4775 4776 4777 4778 4779
				}
				PG_CATCH();
				{
					COPY_HANDLE_ERROR; /* SREH */
				}
				PG_END_TRY();
A
alldefector 已提交
4780

4781 4782 4783 4784 4785
				if (cur_row_rejected)
				{
					ErrorIfRejectLimitReached(cstate->cdbsreh, cdbCopy);
					QE_GOTO_NEXT_ROW;
				}
A
alldefector 已提交
4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861
				}
				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;
					}
				}
4862 4863 4864 4865 4866 4867 4868 4869

					/*
					 * 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++)
					{
4870
						baseValues[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
4871 4872 4873
														 &isnull, NULL);

						if (!isnull)
4874
							baseNulls[defmap[i]] = false;
4875 4876 4877 4878 4879 4880 4881 4882
					}

				/*
				 * We might create a ResultRelInfo which needs to persist
				 * the per tuple context.
				 */
				PG_TRY();
				{
4883
					MemoryContextSwitchTo(estate->es_query_cxt);
4884 4885
					if (estate->es_result_partitions)
					{
4886
						resultRelInfo = values_get_partition(baseValues, baseNulls,
4887 4888
															 tupDesc, estate);
						estate->es_result_relation_info = resultRelInfo;
4889 4890
						FreeBulkInsertState(bistate);
						bistate = GetBulkInsertState();
4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931
					}
				}
				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));

4932 4933
				ExecStoreVirtualTuple(baseSlot);

4934 4935
				/*
				 * And now we can form the input tuple.
4936 4937
				 *
				 * The resulting tuple is stored in 'slot'
4938
				 */
4939 4940 4941 4942 4943
				if (resultRelInfo->ri_partSlot != NULL)
				{
					AttrMap *map = resultRelInfo->ri_partInsertMap;
					Assert(map != NULL);

4944 4945 4946 4947
					slot = resultRelInfo->ri_partSlot;
					ExecClearTuple(slot);
					partValues = slot_get_values(resultRelInfo->ri_partSlot);
					partNulls = slot_get_isnull(resultRelInfo->ri_partSlot);
4948 4949 4950 4951 4952
					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);
4953
					ExecStoreVirtualTuple(slot);
4954 4955 4956
				}
				else
				{
4957
					slot = baseSlot;
4958 4959
				}

4960
				if (is_check_distkey && distData->p_nattrs > 0)
4961
				{
4962
					target_seg = GetTargetSeg(distData, slot_get_values(slot), slot_get_isnull(slot));
4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977

					PG_TRY();
					{
						/* check distribution key if COPY FROM ON SEGMENT */
						if (GpIdentity.segindex != target_seg)
							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)));
					}
					PG_CATCH();
					{
						COPY_HANDLE_ERROR;
					}
					PG_END_TRY();
4978 4979
				}

4980 4981 4982
				/*
				 * Triggers and stuff need to be invoked in query context.
				 */
4983
				MemoryContextSwitchTo(estate->es_query_cxt);
4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995

				/* 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;
4996
					HeapTuple	tuple;
4997

4998
					tuple = ExecFetchSlotHeapTuple(slot);
4999 5000 5001 5002 5003 5004 5005 5006

					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) */
					{
5007
						ExecStoreHeapTuple(newtuple, slot, InvalidBuffer, false);
5008 5009 5010 5011 5012
					}
				}

				if (!skip_tuple)
				{
5013
					List	   *recheckIndexes = NIL;
5014
					char relstorage = RelinfoGetStorage(resultRelInfo);
5015
					ItemPointerData insertedTid;
5016 5017 5018 5019 5020

					/*
					 * Check the constraints of the tuple
					 */
					if (resultRelInfo->ri_RelationDesc->rd_att->constr)
5021
						ExecConstraints(resultRelInfo, slot, estate);
5022 5023 5024 5025 5026 5027

					/*
					 * OK, store the tuple and create index entries for it
					 */
					if (relstorage == RELSTORAGE_AOROWS)
					{
5028 5029 5030 5031
						MemTuple	mtuple;

						mtuple = ExecFetchSlotMemTuple(slot, false);

5032
						/* inserting into an append only relation */
5033
						appendonly_insert(resultRelInfo->ri_aoInsertDesc, mtuple, InvalidOid, (AOTupleId *) &insertedTid);
5034 5035 5036
					}
					else if (relstorage == RELSTORAGE_AOCOLS)
					{
5037 5038
                        aocs_insert(resultRelInfo->ri_aocsInsertDesc, slot);
						insertedTid = *slot_get_ctid(slot);
5039 5040 5041
					}
					else if (relstorage == RELSTORAGE_EXTERNAL)
					{
5042 5043 5044
						HeapTuple tuple;

						tuple = ExecFetchSlotHeapTuple(slot);
5045
						external_insert(resultRelInfo->ri_extInsertDesc, tuple);
5046
						ItemPointerSetInvalid(&insertedTid);
5047 5048 5049
					}
					else
					{
5050
						HeapTuple tuple;
5051

5052
						tuple = ExecFetchSlotHeapTuple(slot);
5053 5054
						heap_insert(resultRelInfo->ri_RelationDesc, tuple, mycid, hi_options, bistate,
									GetCurrentTransactionId());
5055
						insertedTid = tuple->t_self;
5056 5057
					}

5058
					if (resultRelInfo->ri_NumIndices > 0)
5059
						recheckIndexes = ExecInsertIndexTuples(slot, &insertedTid, estate);
5060 5061

					/* AFTER ROW INSERT Triggers */
5062 5063 5064 5065 5066 5067
					if (resultRelInfo->ri_TrigDesc &&
						resultRelInfo->ri_TrigDesc->n_after_row[TRIGGER_EVENT_INSERT] > 0)
					{
						HeapTuple tuple;

						tuple = ExecFetchSlotHeapTuple(slot);
5068 5069
						ExecARInsertTriggers(estate, resultRelInfo, tuple,
											 recheckIndexes);
5070
					}
5071

5072
					list_free(recheckIndexes);
5073

5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097
					/*
					 * 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);

5098 5099 5100 5101 5102 5103 5104
	/*
	 * 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)
	{
5105 5106
		if (cstate->is_program)
		{
A
Adam Lee 已提交
5107 5108
			cstate->program_pipes = open_program_pipes(cstate->filename, false);
			cstate->copy_file = fdopen(cstate->program_pipes->pipes[0], PG_BINARY_R);
5109

5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123
			if (cstate->copy_file == NULL)
				ereport(ERROR,
						(errmsg("could not execute command \"%s\": %m",
								cstate->filename)));
		}
		else
		{
			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(),
5124
						errmsg("could not open file \"%s\" for reading: %m",
5125
								filename)));
5126

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

5130 5131 5132 5133
			fstat(fileno(cstate->copy_file), &st);
			if (S_ISDIR(st.st_mode))
				ereport(ERROR,
						(errcode(ERRCODE_WRONG_OBJECT_TYPE),
5134
						errmsg("\"%s\" is a directory", filename)));
5135 5136
		}

5137 5138 5139 5140 5141 5142
		cstate->copy_dest = COPY_FILE;

		is_segment_data_processed = true;

		CopyFromProcessDataFileHeader(cstate, cdbCopy, &file_has_oids);
		CopyInitDataParser(cstate);
5143
		no_more_data = false;
5144 5145 5146 5147 5148

		goto PROCESS_SEGMENT_DATA;
	}

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

5150
	/* Done, clean up */
A
Adam Lee 已提交
5151 5152
	if (cstate->on_segment && cstate->is_program)
	{
5153
		close_program_pipes(cstate, true);
A
Adam Lee 已提交
5154 5155 5156 5157 5158 5159 5160 5161 5162
	}
	else if (cstate->on_segment && FreeFile(cstate->copy_file))
	{
			ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("could not close file \"%s\": %m",
						cstate->filename)));
	}

5163 5164
	error_context_stack = errcontext.previous;

5165 5166
	FreeBulkInsertState(bistate);

5167
	MemoryContextSwitchTo(estate->es_query_cxt);
5168

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

5172
	/* Handle queued AFTER triggers */
5173 5174 5175 5176 5177
	AfterTriggerEndQuery(estate);

	/*
	 * If SREH and in executor mode send the number of rejected
	 * rows to the client (QD COPY).
5178
	 * If COPY ... FROM ... ON SEGMENT, then need to send the number of completed
5179
	 */
5180 5181 5182 5183
	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);
5184 5185 5186 5187

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

5188 5189 5190
	/* 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 */
5191
	ExecResetTupleTable(estate->es_tupleTable, false);
5192

5193 5194 5195 5196
	/*
	 * If we skipped writing WAL, then we need to sync the heap (but not
	 * indexes since those use WAL anyway)
	 */
5197
	if (hi_options & HEAP_INSERT_SKIP_WAL)
5198 5199
		heap_sync(cstate->rel);

5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221
	/*
	 * 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 */
5222 5223

	MemoryContextSwitchTo(oldcontext);
5224 5225 5226 5227

	/* free distribution data after switching oldcontext */
	FreeDistributionData(distData);

5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 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
	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;
5867

5868 5869 5870 5871
	return false;
}

/*
5872
 *	Return decimal value for a hexadecimal digit
5873
 */
5874 5875
static int
GetDecimalFromHex(char hex)
5876
{
5877
	if (isdigit((unsigned char) hex))
5878 5879
		return hex - '0';
	else
5880
		return tolower((unsigned char) hex) - 'a' + 10;
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
}

/*
 * 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;
5943
	bool		saw_non_ascii = false;
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
	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 已提交
5981
		/*
5982 5983 5984
		 * 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.
5985
		 */
5986 5987 5988 5989 5990 5991 5992 5993 5994 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
		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
				&&
6028 6029 6030
				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)
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 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 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
				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 */
6170 6171
						if (newc == '\0' || IS_HIGHBIT_SET(newc))
							saw_non_ascii = true;
6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189
						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;
6190 6191
							if (newc == '\0' || IS_HIGHBIT_SET(newc))
								saw_non_ascii = true;
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
						}
						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.
	 */
6293
	if (saw_non_ascii)
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
	{
		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];
	int			attribute = 1;
	ListCell   *cur;			/* cursor to attribute list used for this COPY */
6324
	int 		attr_cursor;
6325 6326 6327 6328 6329

	/* init variables for attribute scan */
	RESET_ATTRBUF;

	cur = list_head(cstate->attnumlist);
6330
	attr_cursor = cstate->attribute_buf.cursor;
6331

6332 6333 6334 6335 6336 6337
	int line_len = cstate->line_buf.len;
	if (cstate->eol_type == EOL_CRLF)
		line_len--;

	/* if zero column table and data is trying to get in */
	if(num_phys_attrs == 0)
6338
	{
6339 6340 6341 6342 6343
		if (line_len > 0)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));
		return;
6344 6345
	}

6346 6347 6348 6349 6350
	if (cstate->delimiter_off)
		ereport(ERROR,
				(errcode(ERRCODE_INTERNAL_ERROR),
				 errmsg("delimiter 'OFF' is not supported by copy command")));

6351 6352
	for (;;)
	{
6353 6354 6355 6356 6357 6358 6359
		bool		found_delim = false;
		bool		saw_quote = false;
		int			input_len = 0;
		int			attnum;			/* attribute number being parsed */
		int			fieldno = 0;			/* attribute index being parsed */
		int			start_cursor = cstate->line_buf.cursor;
		int			end_cursor;
6360

6361 6362 6363 6364 6365 6366 6367 6368
		/*
		 * Scan data for field,
		 *
		 * The loop starts in "not quote" mode and then toggles between that
		 * and "in quote" mode. The loop exits normally if it is in "not
		 * quote" mode and a delimiter or line end is seen.
		 */
		for (;;)
6369
		{
6370
			char		c;
6371

6372 6373
			/* Not in quote */
			for (;;)
6374
			{
6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393
				end_cursor = cstate->line_buf.cursor;
				if (cstate->line_buf.cursor >= line_len - 1)
					goto endfield;
				c = cstate->line_buf.data[cstate->line_buf.cursor++];
				/* unquoted field delimiter */
				if (c == delimc)
				{
					found_delim = true;
					goto endfield;
				}
				/* start of quoted field (or part of field) */
				if (c == quotec)
				{
					saw_quote = true;
					break;
				}
				/* Add c to output string */
				appendStringInfoCharMacro(&cstate->attribute_buf, c);
				cstate->attribute_buf.cursor++;
6394 6395
			}

6396 6397
			/* In quote */
			for (;;)
6398
			{
6399 6400
				end_cursor = cstate->line_buf.cursor;
				if (cstate->line_buf.cursor >= line_len - 1)
6401 6402 6403
					ereport(ERROR,
							(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
							 errmsg("unterminated CSV quoted field")));
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

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

				/* escape within a quoted field */
				if (c == escapec)
				{
					/*
					 * 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 < line_len - 1)
					{
						char 		nextc = cstate->line_buf.data[cstate->line_buf.cursor];

						if (nextc == escapec || nextc == quotec)
						{
							appendStringInfoCharMacro(&cstate->attribute_buf, nextc);
							cstate->attribute_buf.cursor++;
							cstate->line_buf.cursor++;
							continue;
						}
					}
				}

				/*
				 * end of quoted field. Must do this test after testing for
				 * escape in case quote char and escape char are the same
				 * (which is the common case).
				 */
				if (c == quotec)
					break;

				/* Add c to output string */
				appendStringInfoCharMacro(&cstate->attribute_buf, c);
				cstate->attribute_buf.cursor++;
6439
			}
6440 6441 6442 6443 6444 6445
		}
endfield:
		if (cur == NULL)
			ereport(ERROR,
					(errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
					 errmsg("extra data after last expected column")));
6446

6447 6448 6449 6450 6451 6452
		/* Check whether raw input matched null marker */
		input_len = end_cursor - start_cursor;

		/* finished processing attributes in line */
		if (!found_delim)
		{
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
			/*
			 * 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))));
			}
		}

6478 6479 6480 6481 6482 6483 6484 6485 6486
		/* check whether raw input matched null marker */
		attnum = lfirst_int(cur);
		fieldno = attnum - 1;
		if (!saw_quote && input_len == cstate->null_print_len &&
			strncmp(&cstate->line_buf.data[start_cursor], cstate->null_print, input_len) == 0)
			nulls[fieldno] = true;
		else
			nulls[fieldno] = false;
		attr_offsets[fieldno] = attr_cursor;
6487

6488 6489 6490 6491
		/* Terminate attribute value in output area */
		appendStringInfoCharMacro(&cstate->attribute_buf, '\0');
		cstate->attribute_buf.cursor++;
		attr_cursor = cstate->attribute_buf.cursor;
6492

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

6496
		/*
6497 6498
		 * for the dispatcher - stop parsing once we have
		 * all the hash field values. We don't need the rest.
6499
		 */
6500
		if (Gp_role == GP_ROLE_DISPATCH)
6501
		{
6502 6503
			if (attribute == cstate->last_hash_field)
				break;
6504
		}
6505 6506 6507 6508 6509 6510

		attribute++;

		/* Done if we hit EOL instead of a delim */
		if (!found_delim)
			break;
6511
	}
6512

6513 6514
	if (cstate->eol_type == EOL_CRLF)
		cstate->line_buf.cursor++;
6515 6516
}

6517
/*
6518 6519 6520 6521 6522 6523 6524
 * 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
6525
 */
6526 6527 6528
static void
CopyReadAttributesTextNoDelim(CopyState cstate, bool *nulls, int num_phys_attrs,
							  int attnum)
6529
{
6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543
	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;
6544
	else
6545 6546 6547
		nulls[attnum - 1] = false;

	appendBinaryStringInfo(&cstate->attribute_buf, cstate->line_buf.data, len);
6548 6549
}

6550
/*
6551 6552 6553
 * 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.
6554
 */
6555 6556
static char *
CopyReadOidAttr(CopyState cstate, bool *isnull)
6557
{
6558
	char		delimc = cstate->delim[0];
6559 6560 6561 6562
	char	   *start_loc = cstate->line_buf.data + cstate->line_buf.cursor;
	char	   *end_loc;
	int			attr_len = 0;
	int			bytes_remaining;
6563

6564 6565 6566 6567 6568 6569 6570 6571
	/* 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)
6572
	{
6573 6574 6575
		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' */
6576
	}
6577 6578 6579 6580 6581 6582 6583
	else
		/* found a delimiter */
	{
		/*
		 * (we don't care if delim was preceded with a backslash, because it's
		 * an invalid OID anyway)
		 */
6584

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

6587 6588 6589
		appendBinaryStringInfo(&cstate->attribute_buf, start_loc, attr_len);
		cstate->line_buf.cursor += attr_len + 1;
	}
6590

6591

6592 6593 6594 6595 6596
	/* 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;
6597

6598 6599
	return cstate->attribute_buf.data;
}
6600

A
alldefector 已提交
6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657
/*
 * 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;
}

6658 6659 6660 6661 6662 6663 6664 6665
/*
 * Send text representation of one attribute, with conversion and escaping
 */
#define DUMPSOFAR() \
	do { \
		if (ptr > start) \
			CopySendData(cstate, start, ptr - start); \
	} while (0)
6666

6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677
/*
 * 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];
6678

6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713
	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)
6714
			{
6715
				/*
6716 6717 6718 6719 6720
				 * \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.
6721
				 */
6722 6723
				switch (c)
				{
6724 6725
					case '\b':
						c = 'b';
B
Bruce Momjian 已提交
6726
						break;
6727 6728
					case '\f':
						c = 'f';
6729
						break;
6730 6731
					case '\n':
						c = 'n';
6732
						break;
6733 6734
					case '\r':
						c = 'r';
6735
						break;
6736 6737
					case '\t':
						c = 't';
6738
						break;
6739 6740
					case '\v':
						c = 'v';
6741
						break;
6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785
					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';
6786
						break;
6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800
					case '\f':
						c = 'f';
						break;
					case '\n':
						c = 'n';
						break;
					case '\r':
						c = 'r';
						break;
					case '\t':
						c = 't';
						break;
					case '\v':
						c = 'v';
6801
						break;
6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825
					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++;
		}
	}
6826

6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 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
	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;
6890
				}
6891 6892 6893 6894
				if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
					tptr += pg_encoding_mblen(cstate->client_encoding, tptr);
				else
					tptr++;
6895 6896
			}
		}
6897
	}
6898

6899 6900 6901
	if (use_quote)
	{
		CopySendChar(cstate, quotec);
6902

6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920
		/*
		 * 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();
6921

6922 6923 6924 6925 6926 6927
		CopySendChar(cstate, quotec);
	}
	else
	{
		/* If it doesn't need quoting, we can just dump it as-is */
		CopySendString(cstate, ptr);
6928
	}
6929 6930
}

B
Bruce Momjian 已提交
6931
/*
6932 6933 6934 6935 6936 6937 6938
 * 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 已提交
6939
 */
6940 6941
List *
CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
B
Bruce Momjian 已提交
6942
{
6943
	List	   *attnums = NIL;
6944

6945
	if (attnamelist == NIL)
6946
	{
6947 6948 6949 6950
		/* Generate default column list */
		Form_pg_attribute *attr = tupDesc->attrs;
		int			attr_count = tupDesc->natts;
		int			i;
B
Bruce Momjian 已提交
6951

6952 6953 6954 6955 6956 6957 6958 6959
		for (i = 0; i < attr_count; i++)
		{
			if (attr[i]->attisdropped)
				continue;
			attnums = lappend_int(attnums, i + 1);
		}
	}
	else
B
Bruce Momjian 已提交
6960
	{
6961 6962
		/* Validate the user-supplied list and extract attnums */
		ListCell   *l;
B
Bruce Momjian 已提交
6963

6964
		foreach(l, attnamelist)
B
Bruce Momjian 已提交
6965
		{
6966 6967 6968
			char	   *name = strVal(lfirst(l));
			int			attnum;
			int			i;
B
Bruce Momjian 已提交
6969

6970 6971 6972
			/* Lookup column name */
			attnum = InvalidAttrNumber;
			for (i = 0; i < tupDesc->natts; i++)
6973
			{
6974 6975 6976
				if (tupDesc->attrs[i]->attisdropped)
					continue;
				if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
B
Bruce Momjian 已提交
6977
				{
6978 6979
					attnum = tupDesc->attrs[i]->attnum;
					break;
B
Bruce Momjian 已提交
6980 6981
				}
			}
6982
			if (attnum == InvalidAttrNumber)
6983
			{
6984 6985 6986
				if (rel != NULL)
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
6987 6988
					errmsg("column \"%s\" of relation \"%s\" does not exist",
						   name, RelationGetRelationName(rel))));
6989 6990 6991 6992 6993
				else
					ereport(ERROR,
							(errcode(ERRCODE_UNDEFINED_COLUMN),
							 errmsg("column \"%s\" does not exist",
									name)));
6994
			}
6995 6996 6997 6998 6999 7000 7001
			/* 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 已提交
7002
		}
7003
	}
B
Bruce Momjian 已提交
7004

7005
	return attnums;
B
Bruce Momjian 已提交
7006 7007
}

7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027
#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
7028
 * encoding error happened and we're in error log mode).
7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084
 *
 * 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;
}
7085

7086
/*
7087
 * error context callback for COPY FROM
7088
 */
7089 7090
static void
copy_in_error_callback(void *arg)
7091
{
7092 7093
	CopyState	cstate = (CopyState) arg;
	char buffer[20];
7094

7095 7096 7097 7098
	/*
	 * 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)
7099
	{
7100 7101
		errcontext("%s", cstate->executor_err_context.data);
		return;
7102 7103
	}

7104 7105 7106
	/* don't need to print out context if error wasn't local */
	if (cstate->error_on_executor)
		return;
7107

A
alldefector 已提交
7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122
	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
	{
7123 7124 7125 7126
	if (cstate->cur_attname)
	{
		/* error is relevant to a particular column */
		char	   *att_buf;
7127

7128
		att_buf = limit_printout_length(cstate->attribute_buf.data);
7129

7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141
		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;
7142

7143 7144
			line_buf = extract_line_buf(cstate);
			truncateEolStr(line_buf, cstate->eol_type);
7145

7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166
			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));
		}
	}
7167
}
A
alldefector 已提交
7168
}
7169 7170

/*
7171 7172 7173 7174 7175 7176 7177 7178
 * 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.
7179
 */
7180 7181
static char *
extract_line_buf(CopyState cstate)
7182
{
7183
	char	   *line_buf = cstate->line_buf.data;
7184

7185
	if (cstate->err_loc_type == ROWNUM_EMBEDDED && !cstate->md_error)
7186
	{
7187 7188 7189 7190 7191 7192 7193
		/* 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))
7194
		{
7195 7196 7197 7198 7199 7200 7201 7202 7203
			/*
			 * 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;
7204

7205 7206 7207
			lineno_delim = memchr(line_start, COPY_METADATA_DELIM,
								  Min(32, cstate->line_buf.len));

7208 7209 7210 7211 7212 7213
			if (lineno_delim && (lineno_delim != line_start))
			{
				value_len = lineno_delim - line_start + 1;
				line_start += value_len;
				line_buf = line_start;
			}
7214
		}
7215
	}
7216

7217 7218 7219 7220 7221 7222
	/*
	 * 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);
7223
}
7224

B
Bruce Momjian 已提交
7225
/*
7226 7227 7228 7229 7230 7231 7232
 * 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 已提交
7233
 */
7234 7235
char *
limit_printout_length(const char *str)
B
Bruce Momjian 已提交
7236
{
7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255
#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 已提交
7256

7257 7258
	return res;
}
7259

7260 7261 7262 7263 7264 7265 7266 7267 7268

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

B
Bruce Momjian 已提交
7270
	/*
7271 7272 7273
	 * 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 已提交
7274
	 */
7275
	for (p_index = 0; p_index < p_nattrs; p_index++)
B
Bruce Momjian 已提交
7276
	{
7277 7278
		ListCell *cur;

7279
		/*
7280 7281
		 * For this partitioning key, search for its location in the attr list.
		 * (note that fields may be out of order, so this is necessary).
7282
		 */
7283
		foreach(cur, cstate->attnumlist)
B
Bruce Momjian 已提交
7284
		{
7285 7286 7287 7288
			int			attnum = lfirst_int(cur);
			int			m = attnum - 1;
			char	   *string;
			bool		isnull;
7289

7290
			if (attnum == attrs[p_index])
7291
			{
7292 7293 7294 7295 7296 7297 7298 7299 7300
				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])
7301
				{
7302 7303
					string = cstate->null_print;		/* set to NULL string */
					isnull = false;
7304
				}
7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321

				/* 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 */
7322
			}
7323 7324 7325
		}		/* end foreach */
	}			/* end for partitioning indexes */
}
B
Bruce Momjian 已提交
7326

7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350
/*
 * 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)
7351
	{
7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366
		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 
7367
		 */
7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392
		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)
7393
		{
7394 7395 7396 7397 7398 7399 7400 7401
			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);
7402
		}
7403 7404 7405 7406 7407 7408 7409
		
		/* 
		 * 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);
7410 7411
	}
	else
7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422
		/* 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;
		}
7423
	}
7424 7425 7426 7427 7428 7429 7430 7431

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

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

7434 7435
/* remove end of line chars from end of a buffer */
void truncateEol(StringInfo buf, EolType eol_type)
7436
{
7437 7438
	int one_back = buf->len - 1;
	int two_back = buf->len - 2;
B
Bruce Momjian 已提交
7439

7440
	if(eol_type == EOL_CRLF)
B
Bruce Momjian 已提交
7441
	{
7442 7443
		if(buf->len < 2)
			return;
B
Bruce Momjian 已提交
7444

7445 7446
		if(buf->data[two_back] == '\r' &&
		   buf->data[one_back] == '\n')
B
Bruce Momjian 已提交
7447
		{
7448 7449 7450
			buf->data[two_back] = '\0';
			buf->data[one_back] = '\0';
			buf->len -= 2;
7451 7452 7453 7454
		}
	}
	else
	{
7455 7456
		if(buf->len < 1)
			return;
7457

7458 7459
		if(buf->data[one_back] == '\r' ||
		   buf->data[one_back] == '\n')
7460
		{
7461 7462
			buf->data[one_back] = '\0';
			buf->len--;
B
Bruce Momjian 已提交
7463 7464
		}
	}
7465
}
7466

7467 7468 7469 7470 7471 7472 7473 7474 7475 7476 7477 7478 7479 7480 7481 7482 7483 7484 7485 7486 7487 7488 7489 7490 7491 7492 7493 7494 7495 7496 7497 7498 7499 7500 7501 7502
/* 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;

	}
7503
}
7504

7505 7506 7507 7508 7509 7510 7511 7512 7513 7514 7515 7516 7517 7518 7519 7520 7521 7522 7523 7524
/*
 * 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;
}
7525 7526 7527 7528 7529

/*
 * copy_dest_startup --- executor startup
 */
static void
7530
copy_dest_startup(DestReceiver *self __attribute__((unused)), int operation __attribute__((unused)), TupleDesc typeinfo __attribute__((unused)))
7531 7532 7533 7534 7535 7536 7537 7538 7539 7540
{
	/* no-op */
}

/*
 * copy_dest_receive --- receive one tuple
 */
static void
copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
{
B
Bruce Momjian 已提交
7541
	DR_copy    *myState = (DR_copy *) self;
7542 7543 7544 7545 7546 7547
	CopyState	cstate = myState->cstate;

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

	/* And send the data */
7548
	CopyOneRowTo(cstate, InvalidOid, slot_get_values(slot), slot_get_isnull(slot));
7549 7550 7551 7552 7553 7554
}

/*
 * copy_dest_shutdown --- executor end
 */
static void
7555
copy_dest_shutdown(DestReceiver *self __attribute__((unused)))
7556 7557 7558 7559 7560 7561 7562 7563 7564 7565 7566 7567 7568 7569 7570 7571 7572 7573 7574
{
	/* 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 已提交
7575
	DR_copy    *self = (DR_copy *) palloc(sizeof(DR_copy));
7576 7577 7578 7579 7580 7581 7582 7583 7584 7585 7586

	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;
}
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 7621 7622 7623 7624 7625 7626 7627 7628 7629 7630 7631 7632 7633 7634 7635 7636 7637 7638 7639 7640 7641 7642 7643 7644 7645 7646 7647 7648 7649 7650 7651 7652 7653 7654 7655 7656 7657 7658 7659 7660 7661 7662 7663 7664 7665 7666 7667 7668 7669 7670 7671 7672 7673 7674 7675 7676 7677 7678 7679 7680 7681 7682 7683 7684 7685 7686 7687 7688 7689 7690 7691 7692 7693 7694 7695 7696 7697 7698 7699 7700 7701 7702 7703 7704 7705 7706 7707 7708 7709 7710 7711 7712 7713 7714 7715 7716 7717 7718 7719 7720 7721 7722 7723 7724 7725


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
7726
		 * the error. Verify that we are indeed in SREH error log mode. that's
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
		 * 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,
7785
				(errcode(ERRCODE_INTERNAL_ERROR),
7786 7787 7788
				 errmsg("internal error in CopySetEolType. Trying to set NEWLINE %s", 
						 cstate->eol_str)));
}
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 7844

static GpDistributionData *
InitDistributionData(CopyState cstate, Form_pg_attribute *attr,
                     AttrNumber num_phys_attrs,
                     EState *estate, bool multi_dist_policy)
{
	GpDistributionData *distData = palloc(sizeof(GpDistributionData));
	/* 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 */
	HTAB *hashmap = NULL;
	CdbHash *cdbHash = NULL;
	AttrNumber h_attnum; /* hash key attribute number */
	int p_index;
	int total_segs = getgpsegmentCount();
	int i = 0;

	if (!multi_dist_policy)
	{
		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);
	}
	else
	{
		/*
		 * 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;
		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);
P
Pengzhou Tang 已提交
7845
		policy = createHashPartitionedPolicy(NULL, cols);
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 7907 7908 7909 7910 7911 7912 7913 7914 7915 7916 7917 7918 7919 7920 7921 7922 7923 7924 7925 7926 7927 7928 7929 7930 7931 7932 7933 7934 7935 7936 7937 7938 7939 7940 7941 7942 7943 7944 7945 7946 7947 7948 7949 7950 7951 7952 7953 7954 7955 7956 7957 7958 7959 7960 7961 7962 7963 7964 7965 7966 7967 7968 7969 7970 7971 7972 7973 7974 7975 7976 7977 7978 7979 7980 7981 7982 7983 7984 7985 7986 7987 7988 7989 7990 7991 7992 7993 7994 7995 7996 7997 7998 7999 8000 8001 8002 8003 8004 8005 8006 8007 8008 8009 8010 8011 8012 8013 8014 8015 8016 8017 8018 8019 8020 8021 8022 8023 8024 8025 8026 8027 8028 8029 8030 8031 8032 8033 8034 8035 8036 8037 8038 8039 8040 8041 8042 8043 8044 8045 8046 8047 8048 8049 8050 8051 8052 8053 8054 8055 8056 8057 8058 8059 8060 8061 8062 8063 8064 8065 8066 8067 8068 8069 8070 8071 8072 8073 8074 8075 8076 8077 8078 8079 8080 8081 8082 8083 8084 8085 8086 8087 8088 8089 8090 8091 8092 8093 8094 8095 8096 8097 8098 8099 8100 8101 8102 8103 8104 8105 8106 8107 8108 8109 8110 8111 8112 8113 8114 8115 8116 8117 8118 8119 8120 8121 8122 8123 8124 8125 8126 8127 8128 8129 8130 8131 8132 8133 8134 8135 8136 8137 8138 8139 8140 8141 8142 8143 8144 8145 8146 8147 8148 8149 8150 8151 8152
	}

	/*
	 * 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;
			}
			if (estate->es_result_partitions)
			{
				if (attnum == estate->es_partition_state->max_partition_attr)
				{
					if (i > cstate->last_hash_field)
						cstate->last_hash_field = i;
				}
			}
			i++;
		}
	}

	distData->policy = policy;
	distData->p_nattrs = p_nattrs;
	distData->p_attr_types = p_attr_types;
	distData->cdbHash = cdbHash;
	distData->hashmap = hashmap;

	return distData;
}

static void
FreeDistributionData(GpDistributionData *distData)
{
	if (distData)
	{
		pfree(distData->policy);
		pfree(distData->p_attr_types);
		if (distData->cdbHash)
		{
			pfree(distData->cdbHash);
		}
		if (distData->hashmap)
		{
			pfree(distData->hashmap);
		}
		pfree(distData);

	}
}

static void
InitPartitionData(PartitionData *partitionData, EState *estate, Form_pg_attribute *attr,
				  AttrNumber num_phys_attrs, MemoryContext ctxt)
{
	Datum *part_values = NULL;
	Oid *part_typio = NULL;
	FmgrInfo *part_infuncs = NULL;
	AttrNumber *part_attnum = NULL;
	int part_attnums = 0;

	PartitionNode *n = estate->es_result_partitions;
	MemoryContext cxt_save;

	List *pattnums = get_partition_attrs(n);
	ListCell *lc;
	int ii = 0;

	cxt_save = MemoryContextSwitchTo(ctxt);

	part_values = palloc0(num_phys_attrs * sizeof(Datum));
	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;
	}
	partitionData->part_values = part_values;
	partitionData->part_typio = part_typio;
	partitionData->part_infuncs = part_infuncs;
	partitionData->part_attnum = part_attnum;
	partitionData->part_attnums = part_attnums;
}

static void
FreePartitionData(PartitionData *partitionData)
{
	if (partitionData)
	{
		if(partitionData->part_values)
		{
			pfree(partitionData->part_values);
			pfree(partitionData->part_typio);
			pfree(partitionData->part_infuncs);
			pfree(partitionData->part_attnum);
		}
		pfree(partitionData);
	}
}

/* Get distribution policy for specific part */
static GpDistributionData *
GetDistributionPolicyForPartition(CopyState cstate, EState *estate,
                                  PartitionData *partitionData, HTAB *hashmap,
                                  Oid *p_attr_types,
                                  GetAttrContext *getAttrContext,
                                  MemoryContext ctxt)
{
	ResultRelInfo *resultRelInfo;
	Datum *values_for_partition;
	GpPolicy *part_policy = NULL; /* policy for specific part */
	AttrNumber part_p_nattrs = 0; /* partition policy max attno */
	CdbHash *part_hash = NULL;
	int target_seg = 0; /* not used in attr_get_key function */

	if (!cstate->binary)
	{
		/*
		 * Text/CSV: Ensure we parse all partition attrs.
		 * Q: Wouldn't this potentially reparse values (and miss defaults)?
		 *    Why not merge with he other attr_get_key call
		 *    (replace part_values with values)?
		 */
		MemSet(partitionData->part_values, 0,
		       getAttrContext->num_phys_attrs * sizeof(Datum));
		attr_get_key(cstate, getAttrContext->cdbCopy,
		             getAttrContext->original_lineno_for_qe, target_seg,
		             partitionData->part_attnums, partitionData->part_attnum,
		             getAttrContext->attr, getAttrContext->attr_offsets,
		             getAttrContext->nulls, partitionData->part_infuncs,
		             partitionData->part_typio, partitionData->part_values);
		values_for_partition = partitionData->part_values;
	}
	else
	{
		/*
		 * Binary: We've made sure to parse partition attrs above.
		 */
		values_for_partition = getAttrContext->values;
	}

	/* values_get_partition() calls palloc() */
	MemoryContext save_cxt = MemoryContextSwitchTo(ctxt);
	GpDistributionData *distData = palloc(sizeof(GpDistributionData));
	distData->p_attr_types = p_attr_types;
	resultRelInfo = values_get_partition(values_for_partition,
	                                     getAttrContext->nulls,
	                                     getAttrContext->tupDesc, estate);
	MemoryContextSwitchTo(save_cxt);

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

			/*
			 * Make sure this all persists the current
			 * iteration.
			 */
			d->relid = relid;
			part_hash = d->cdbHash = makeCdbHash(
			        getAttrContext->cdbCopy->total_segs);
			part_policy = d->policy = GpPolicyCopy(ctxt, rel->rd_cdbpolicy);
			part_p_nattrs = part_policy->nattrs;
			heap_close(rel, NoLock);
			MemoryContextSwitchTo(save_cxt);
		}
	}
	distData->policy = part_policy;
	distData->p_nattrs = part_p_nattrs;
	distData->cdbHash = part_hash;

	return distData;
}

static unsigned int
GetTargetSeg(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;
}
A
Adam Lee 已提交
8153 8154 8155 8156 8157 8158 8159 8160 8161 8162 8163 8164 8165 8166 8167 8168 8169 8170 8171 8172 8173 8174 8175 8176 8177 8178 8179 8180 8181 8182 8183 8184 8185 8186 8187 8188 8189 8190 8191 8192 8193 8194 8195 8196

static ProgramPipes*
open_program_pipes(char *command, bool forwrite)
{
	int save_errno;
	pqsigfunc save_SIGPIPE;
	/* set up extvar */
	extvar_t extvar;
	memset(&extvar, 0, sizeof(extvar));

	external_set_env_vars(&extvar, command, false, NULL, NULL, false, 0);

	ProgramPipes *program_pipes = palloc(sizeof(ProgramPipes));
	program_pipes->pid = -1;
	program_pipes->pipes[0] = -1;
	program_pipes->pipes[1] = -1;
	program_pipes->shexec = make_command(command, &extvar);

	/*
	 * Preserve the SIGPIPE handler and set to default handling.  This
	 * allows "normal" SIGPIPE handling in the command pipeline.  Normal
	 * for PG is to *ignore* SIGPIPE.
	 */
	save_SIGPIPE = pqsignal(SIGPIPE, SIG_DFL);

	program_pipes->pid = popen_with_stderr(program_pipes->pipes, program_pipes->shexec, forwrite);

	save_errno = errno;

	/* Restore the SIGPIPE handler */
	pqsignal(SIGPIPE, save_SIGPIPE);

	if (program_pipes->pid == -1)
	{
		errno = save_errno;
		pfree(program_pipes);
		ereport(ERROR,
				(errcode(ERRCODE_INSUFFICIENT_RESOURCES),
				 errmsg("can not start command: %s", command)));
	}

	return program_pipes;
}

8197 8198
static void
close_program_pipes(CopyState cstate, bool ifThrow)
A
Adam Lee 已提交
8199 8200 8201 8202 8203 8204 8205
{
	Assert(cstate->is_program);

	int ret = 0;
	StringInfoData sinfo;
	initStringInfo(&sinfo);

8206 8207 8208 8209 8210 8211
	if (cstate->copy_file)
	{
		fclose(cstate->copy_file);
		cstate->copy_file = NULL;
	}

A
Adam Lee 已提交
8212 8213 8214 8215 8216
	/* just return if pipes not created, like when relation does not exist */
	if (!cstate->program_pipes)
	{
		return;
	}
8217 8218
	
	ret = pclose_with_stderr(cstate->program_pipes->pid, cstate->program_pipes->pipes, &sinfo);
8219 8220

	if (ret == 0 || !ifThrow)
A
Adam Lee 已提交
8221
	{
8222
		return;
A
Adam Lee 已提交
8223
	}
8224 8225

	if (ret == -1)
A
Adam Lee 已提交
8226 8227 8228 8229 8230 8231
	{
		/* pclose()/wait4() ended with an error; errno should be valid */
		ereport(ERROR,
				(errcode_for_file_access(),
				 errmsg("can not close pipe: %m")));
	}
8232
	else if (!WIFSIGNALED(ret))
A
Adam Lee 已提交
8233 8234
	{
		/*
8235
		 * pclose() returned the process termination state.
A
Adam Lee 已提交
8236 8237 8238 8239 8240 8241
		 */
		ereport(ERROR,
				(errcode(ERRCODE_SQL_ROUTINE_EXCEPTION),
				 errmsg("command error message: %s", sinfo.data)));
	}
}