copy.c 30.6 KB
Newer Older
1 2
/*-------------------------------------------------------------------------
 *
3
 * copy.c
4 5 6 7 8
 *
 * Copyright (c) 1994, Regents of the University of California
 *
 *
 * IDENTIFICATION
9
 *	  $Header: /cvsroot/pgsql/src/backend/commands/copy.c,v 1.74 1999/04/25 03:19:09 tgl Exp $
10 11 12
 *
 *-------------------------------------------------------------------------
 */
13

M
Marc G. Fournier 已提交
14 15 16
#include <string.h>
#include <unistd.h>

17 18 19 20 21 22 23
#include <postgres.h>

#include <access/heapam.h>
#include <tcop/dest.h>
#include <fmgr.h>
#include <miscadmin.h>
#include <utils/builtins.h>
24
#include <utils/acl.h>
M
-Wall'd  
Marc G. Fournier 已提交
25
#include <sys/stat.h>
26 27 28 29 30 31 32 33 34
#include <catalog/pg_index.h>
#include <utils/syscache.h>
#include <utils/memutils.h>
#include <executor/executor.h>
#include <access/transam.h>
#include <catalog/index.h>
#include <access/genam.h>
#include <catalog/pg_type.h>
#include <catalog/catname.h>
35
#include <catalog/pg_shadow.h>
36
#include <commands/copy.h>
37
#include "commands/trigger.h"
38
#include <storage/fd.h>
M
 
Marc G. Fournier 已提交
39
#include <libpq/libpq.h>
40

41 42 43 44
#ifdef MULTIBYTE
#include "mb/pg_wchar.h"
#endif

45 46
#define ISOCTAL(c) (((c) >= '0') && ((c) <= '7'))
#define VALUE(c) ((c) - '0')
47 48 49


/* non-export function prototypes */
50 51
static void CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim);
static void CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim);
52 53 54 55
static Oid	GetOutputFunction(Oid type);
static Oid	GetTypeElement(Oid type);
static Oid	GetInputFunction(Oid type);
static Oid	IsTypeByVal(Oid type);
56
static void GetIndexRelations(Oid main_relation_oid,
57
				  int *n_indices,
58
				  Relation **index_rels);
59

M
Marc G. Fournier 已提交
60
#ifdef COPY_PATCH
61 62
static void CopyReadNewline(FILE *fp, int *newline);
static char *CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline);
63

M
Marc G. Fournier 已提交
64
#else
65
static char *CopyReadAttribute(FILE *fp, bool *isnull, char *delim);
66

M
Marc G. Fournier 已提交
67
#endif
68
static void CopyAttributeOut(FILE *fp, char *string, char *delim, int is_array);
69
static int	CountTuples(Relation relation);
70

71
static int	lineno;
72

M
 
Marc G. Fournier 已提交
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
/* 
 * Internal communications functions
 */
inline void CopySendData(void *databuf, int datasize, FILE *fp);
inline void CopySendString(char *str, FILE *fp);
inline void CopySendChar(char c, FILE *fp);
inline void CopyGetData(void *databuf, int datasize, FILE *fp);
inline int CopyGetChar(FILE *fp);
inline int CopyGetEof(FILE *fp);
inline int CopyPeekChar(FILE *fp);
inline void CopyDonePeek(FILE *fp, int c, int pickup);

/*
 * CopySendData sends output data either to the file
 *  specified by fp or, if fp is NULL, using the standard
 *  backend->frontend functions
 *
 * CopySendString does the same for null-terminated strings
 * CopySendChar does the same for single characters
92 93
 *
 * NB: no data conversion is applied by these functions
M
 
Marc G. Fournier 已提交
94 95 96
 */
inline void CopySendData(void *databuf, int datasize, FILE *fp) {
  if (!fp)
97
	  pq_putbytes((char*) databuf, datasize);
M
 
Marc G. Fournier 已提交
98
  else
99
	  fwrite(databuf, datasize, 1, fp);
M
 
Marc G. Fournier 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
}
    
inline void CopySendString(char *str, FILE *fp) {
  CopySendData(str,strlen(str),fp);
}

inline void CopySendChar(char c, FILE *fp) {
  CopySendData(&c,1,fp);
}

/*
 * CopyGetData reads output data either from the file
 *  specified by fp or, if fp is NULL, using the standard
 *  backend->frontend functions
 *
 * CopyGetChar does the same for single characters
 * CopyGetEof checks if it's EOF on the input
117 118
 *
 * NB: no data conversion is applied by these functions
M
 
Marc G. Fournier 已提交
119 120 121
 */
inline void CopyGetData(void *databuf, int datasize, FILE *fp) {
  if (!fp)
122
    pq_getbytes((char*) databuf, datasize); 
M
 
Marc G. Fournier 已提交
123 124 125 126 127 128
  else 
    fread(databuf, datasize, 1, fp);
}

inline int CopyGetChar(FILE *fp) {
  if (!fp) 
129 130 131 132 133 134
  {
	  unsigned char ch;
	  if (pq_getbytes((char*) &ch, 1))
		  return EOF;
	  return ch;
  }
M
 
Marc G. Fournier 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
  else
    return getc(fp);
}

inline int CopyGetEof(FILE *fp) {
  if (!fp)
    return 0; /* Never return EOF when talking to frontend ? */
  else
    return feof(fp);
}

/*
 * CopyPeekChar reads a byte in "peekable" mode.
 * after each call to CopyPeekChar, a call to CopyDonePeek _must_
 * follow.
 * CopyDonePeek will either take the peeked char off the steam 
 * (if pickup is != 0) or leave it on the stream (if pickup == 0)
 */
inline int CopyPeekChar(FILE *fp) {
  if (!fp) 
155
    return pq_peekbyte();
M
 
Marc G. Fournier 已提交
156 157 158 159 160 161 162 163 164
  else
    return getc(fp);
}

inline void CopyDonePeek(FILE *fp, int c, int pickup) {
  if (!fp) {
    if (pickup) {
      /* We want to pick it up - just receive again into dummy buffer */
      char c;
165
      pq_getbytes(&c, 1);
M
 
Marc G. Fournier 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179
    }
    /* If we didn't want to pick it up, just leave it where it sits */
  }
  else {
    if (!pickup) {
      /* We don't want to pick it up - so put it back in there */
      ungetc(c,fp);
    }
    /* If we wanted to pick it up, it's already there */
  }
}
    


180
/*
181
 *	 DoCopy executes a the SQL COPY statement.
182 183
 */

184
void
185 186 187
DoCopy(char *relname, bool binary, bool oids, bool from, bool pipe,
	   char *filename, char *delim)
{
188 189 190 191 192
/*----------------------------------------------------------------------------
  Either unload or reload contents of class <relname>, depending on <from>.

  If <pipe> is false, transfer is between the class and the file named
  <filename>.  Otherwise, transfer is between the class and our regular
193
  input/output stream.	The latter could be either stdin/stdout or a
194 195 196
  socket, depending on whether we're running under Postmaster control.

  Iff <binary>, unload or reload in the binary format, as opposed to the
197
  more wasteful but more robust and portable text format.
198

199
  If in the text format, delimit columns with delimiter <delim>.
200 201

  When loading in the text format from an input stream (as opposed to
202
  a file), recognize a "." on a line by itself as EOF.	Also recognize
203 204 205 206 207 208
  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.

  Iff <oids>, unload or reload the format that includes OID information.

  Do not allow a Postgres user without superuser privilege to read from
209
  or write to a file.
210 211 212 213 214

  Do not allow the copy if user doesn't have proper permission to access
  the class.
----------------------------------------------------------------------------*/

215 216
	static FILE *fp;			/* static for cleanup */
	static bool file_opened = false;	/* static for cleanup */
217 218 219 220
	Relation	rel;
	extern char *UserName;		/* defined in global.c */
	const AclMode required_access = from ? ACL_WR : ACL_RD;
	int			result;
221

222
	/*
223 224 225
	 * Close previous file opened for COPY but failed with elog(). There
	 * should be a better way, but would not be modular. Prevents file
	 * descriptor leak.  bjm 1998/08/29
226 227
	 */
	if (file_opened)
228
	{
229
		FreeFile(fp);
230 231
		file_opened = false;
	}
232

233 234
	rel = heap_openr(relname);
	if (rel == NULL)
235
		elog(ERROR, "COPY command failed.  Class %s "
236 237 238 239
			 "does not exist.", relname);

	result = pg_aclcheck(relname, UserName, required_access);
	if (result != ACLCHECK_OK)
240
		elog(ERROR, "%s: %s", relname, aclcheck_error_strings[result]);
241 242
	/* Above should not return */
	else if (!superuser() && !pipe)
243
		elog(ERROR, "You must have Postgres superuser privilege to do a COPY "
244 245 246 247 248 249 250 251
			 "directly to or from a file.  Anyone can COPY to stdout or "
			 "from stdin.  Psql's \\copy command also works for anyone.");
	/* Above should not return. */
	else
	{
		if (from)
		{						/* copy from file to database */
			if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
252
				elog(ERROR, "You can't change sequence relation %s", relname);
253 254 255 256 257
			if (pipe)
			{
				if (IsUnderPostmaster)
				{
					ReceiveCopyBegin();
M
 
Marc G. Fournier 已提交
258
					fp = NULL;
259 260 261 262 263 264
				}
				else
					fp = stdin;
			}
			else
			{
265
#ifndef __CYGWIN32__
266
				fp = AllocateFile(filename, "r");
267 268 269
#else
				fp = AllocateFile(filename, "rb");
#endif
270
				if (fp == NULL)
271
					elog(ERROR, "COPY command, running in backend with "
272 273 274
						 "effective uid %d, could not open file '%s' for "
						 "reading.  Errno = %s (%d).",
						 geteuid(), filename, strerror(errno), errno);
275
				file_opened = true;
276 277 278 279 280 281 282 283 284 285
			}
			CopyFrom(rel, binary, oids, fp, delim);
		}
		else
		{						/* copy from database to file */
			if (pipe)
			{
				if (IsUnderPostmaster)
				{
					SendCopyBegin();
286
					pq_startcopyout();
M
 
Marc G. Fournier 已提交
287
					fp = NULL;
288 289 290 291 292 293
				}
				else
					fp = stdout;
			}
			else
			{
294
				mode_t		oumask;		/* Pre-existing umask value */
295 296

				oumask = umask((mode_t) 0);
297
#ifndef __CYGWIN32__
298
				fp = AllocateFile(filename, "w");
299 300 301
#else
				fp = AllocateFile(filename, "wb");
#endif
302 303
				umask(oumask);
				if (fp == NULL)
304
					elog(ERROR, "COPY command, running in backend with "
305 306 307
						 "effective uid %d, could not open file '%s' for "
						 "writing.  Errno = %s (%d).",
						 geteuid(), filename, strerror(errno), errno);
308
				file_opened = true;
309 310 311 312
			}
			CopyTo(rel, binary, oids, fp, delim);
		}
		if (!pipe)
313
		{
314
			FreeFile(fp);
315 316
			file_opened = false;
		}
317
		else if (!from)
318
		{
319 320 321 322
			if (!binary)
				CopySendData("\\.\n",3,fp);
			if (IsUnderPostmaster)
				pq_endcopyout(false);
323 324
		}
	}
325 326
}

327 328


329
static void
330
CopyTo(Relation rel, bool binary, bool oids, FILE *fp, char *delim)
331
{
332 333
	HeapTuple	tuple;
	HeapScanDesc scandesc;
334

335 336
	int32		attr_count,
				i;
337
	Form_pg_attribute *attr;
338
	FmgrInfo   *out_functions;
339 340
	Oid			out_func_oid;
	Oid		   *elements;
341
	int32	   *typmod;
342 343 344
	Datum		value;
	bool		isnull;			/* The attribute we are copying is null */
	char	   *nulls;
345 346 347 348 349 350 351 352

	/*
	 * <nulls> is a (dynamically allocated) array with one character per
	 * attribute in the instance being copied.	nulls[I-1] is 'n' if
	 * Attribute Number I is null, and ' ' otherwise.
	 *
	 * <nulls> is meaningful only if we are doing a binary copy.
	 */
353 354 355
	char	   *string;
	int32		ntuples;
	TupleDesc	tupDesc;
356

357
	scandesc = heap_beginscan(rel, 0, SnapshotNow, 0, NULL);
358 359 360 361 362 363 364

	attr_count = rel->rd_att->natts;
	attr = rel->rd_att->attrs;
	tupDesc = rel->rd_att;

	if (!binary)
	{
365
		out_functions = (FmgrInfo *) palloc(attr_count * sizeof(FmgrInfo));
366
		elements = (Oid *) palloc(attr_count * sizeof(Oid));
367
		typmod = (int32 *) palloc(attr_count * sizeof(int32));
368 369 370
		for (i = 0; i < attr_count; i++)
		{
			out_func_oid = (Oid) GetOutputFunction(attr[i]->atttypid);
371
			fmgr_info(out_func_oid, &out_functions[i]);
372
			elements[i] = GetTypeElement(attr[i]->atttypid);
B
Bruce Momjian 已提交
373
			typmod[i] = attr[i]->atttypmod;
374 375 376 377 378 379 380
		}
		nulls = NULL;			/* meaningless, but compiler doesn't know
								 * that */
	}
	else
	{
		elements = NULL;
B
Bruce Momjian 已提交
381
		typmod = NULL;
382 383 384 385 386 387 388 389
		out_functions = NULL;
		nulls = (char *) palloc(attr_count);
		for (i = 0; i < attr_count; i++)
			nulls[i] = ' ';

		/* XXX expensive */

		ntuples = CountTuples(rel);
M
 
Marc G. Fournier 已提交
390
		CopySendData(&ntuples, sizeof(int32), fp);
391 392
	}

393
	while (HeapTupleIsValid(tuple = heap_getnext(scandesc, 0)))
394 395 396 397
	{

		if (oids && !binary)
		{
M
 
Marc G. Fournier 已提交
398 399
		        CopySendString(oidout(tuple->t_data->t_oid),fp);
			CopySendChar(delim[0],fp);
400 401 402 403
		}

		for (i = 0; i < attr_count; i++)
		{
404
			value = heap_getattr(tuple, i + 1, tupDesc, &isnull);
405 406 407 408
			if (!binary)
			{
				if (!isnull)
				{
B
Bruce Momjian 已提交
409
					string = (char *) (*fmgr_faddr(&out_functions[i]))
410
						(value, elements[i], typmod[i]);
411
					CopyAttributeOut(fp, string, delim, attr[i]->attnelems);
412 413 414
					pfree(string);
				}
				else
M
 
Marc G. Fournier 已提交
415
					CopySendString("\\N", fp);	/* null indicator */
416 417

				if (i == attr_count - 1)
M
 
Marc G. Fournier 已提交
418
					CopySendChar('\n', fp);
419 420 421 422 423 424 425
				else
				{

					/*
					 * when copying out, only use the first char of the
					 * delim string
					 */
M
 
Marc G. Fournier 已提交
426
					CopySendChar(delim[0], fp);
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
				}
			}
			else
			{

				/*
				 * only interesting thing heap_getattr tells us in this
				 * case is if we have a null attribute or not.
				 */
				if (isnull)
					nulls[i] = 'n';
			}
		}

		if (binary)
		{
443 444
			int32		null_ct = 0,
						length;
445 446 447 448 449 450 451

			for (i = 0; i < attr_count; i++)
			{
				if (nulls[i] == 'n')
					null_ct++;
			}

452
			length = tuple->t_len - tuple->t_data->t_hoff;
M
 
Marc G. Fournier 已提交
453
			CopySendData(&length, sizeof(int32), fp);
454
			if (oids)
M
 
Marc G. Fournier 已提交
455
				CopySendData((char *) &tuple->t_data->t_oid, sizeof(int32), fp);
456

M
 
Marc G. Fournier 已提交
457
			CopySendData(&null_ct, sizeof(int32), fp);
458 459 460 461 462 463
			if (null_ct > 0)
			{
				for (i = 0; i < attr_count; i++)
				{
					if (nulls[i] == 'n')
					{
M
 
Marc G. Fournier 已提交
464
						CopySendData(&i, sizeof(int32), fp);
465 466 467 468
						nulls[i] = ' ';
					}
				}
			}
M
 
Marc G. Fournier 已提交
469 470
			CopySendData((char *) tuple->t_data + tuple->t_data->t_hoff, 
					length, fp);
471 472 473 474 475 476 477 478 479 480
		}
	}

	heap_endscan(scandesc);
	if (binary)
		pfree(nulls);
	else
	{
		pfree(out_functions);
		pfree(elements);
B
Bruce Momjian 已提交
481
		pfree(typmod);
482 483 484
	}

	heap_close(rel);
485 486 487
}

static void
488
CopyFrom(Relation rel, bool binary, bool oids, FILE *fp, char *delim)
489
{
490 491
	HeapTuple	tuple;
	AttrNumber	attr_count;
492
	Form_pg_attribute *attr;
493 494
	FmgrInfo   *in_functions;
	int			i;
495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
	Oid			in_func_oid;
	Datum	   *values;
	char	   *nulls,
			   *index_nulls;
	bool	   *byval;
	bool		isnull;
	bool		has_index;
	int			done = 0;
	char	   *string = NULL,
			   *ptr;
	Relation   *index_rels;
	int32		len,
				null_ct,
				null_id;
	int32		ntuples,
				tuples_read = 0;
	bool		reading_to_eof = true;
	Oid		   *elements;
513
	int32	   *typmod;
514 515 516 517
	FuncIndexInfo *finfo,
			  **finfoP = NULL;
	TupleDesc  *itupdescArr;
	HeapTuple	pgIndexTup;
518
	Form_pg_index *pgIndexP = NULL;
519 520 521 522 523
	int		   *indexNatts = NULL;
	char	   *predString;
	Node	  **indexPred = NULL;
	TupleDesc	rtupdesc;
	ExprContext *econtext = NULL;
524
	EState		*estate = makeNode(EState);	/* for ExecConstraints() */
525

526
#ifndef OMIT_PARTIAL_INDEX
527
	TupleTable	tupleTable;
528 529
	TupleTableSlot *slot = NULL;

530
#endif
531 532 533 534
	int			natts;
	AttrNumber *attnumP;
	Datum	   *idatum;
	int			n_indices;
535
	InsertIndexResult indexRes;
536 537 538
	TupleDesc	tupDesc;
	Oid			loaded_oid;
	bool		skip_tuple = false;
539

540
	tupDesc = RelationGetDescr(rel);
541 542 543 544 545 546 547 548 549 550 551 552
	attr = tupDesc->attrs;
	attr_count = tupDesc->natts;

	has_index = false;

	/*
	 * This may be a scalar or a functional index.	We initialize all
	 * kinds of arrays here to avoid doing extra work at every tuple copy.
	 */

	if (rel->rd_rel->relhasindex)
	{
553
		GetIndexRelations(RelationGetRelid(rel), &n_indices, &index_rels);
554 555 556
		if (n_indices > 0)
		{
			has_index = true;
557 558
			itupdescArr = (TupleDesc *) palloc(n_indices * sizeof(TupleDesc));
			pgIndexP = (Form_pg_index *) palloc(n_indices * sizeof(Form_pg_index));
559 560 561 562 563 564 565
			indexNatts = (int *) palloc(n_indices * sizeof(int));
			finfo = (FuncIndexInfo *) palloc(n_indices * sizeof(FuncIndexInfo));
			finfoP = (FuncIndexInfo **) palloc(n_indices * sizeof(FuncIndexInfo *));
			indexPred = (Node **) palloc(n_indices * sizeof(Node *));
			econtext = NULL;
			for (i = 0; i < n_indices; i++)
			{
566
				itupdescArr[i] = RelationGetDescr(index_rels[i]);
567
				pgIndexTup = SearchSysCacheTuple(INDEXRELID,
568
					   ObjectIdGetDatum(RelationGetRelid(index_rels[i])),
569 570
										0, 0, 0);
				Assert(pgIndexTup);
571
				pgIndexP[i] = (Form_pg_index) GETSTRUCT(pgIndexTup);
572
				for (attnumP = &(pgIndexP[i]->indkey[0]), natts = 0;
B
Bruce Momjian 已提交
573
					 natts < INDEX_MAX_KEYS && *attnumP != InvalidAttrNumber;
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593
					 attnumP++, natts++);
				if (pgIndexP[i]->indproc != InvalidOid)
				{
					FIgetnArgs(&finfo[i]) = natts;
					natts = 1;
					FIgetProcOid(&finfo[i]) = pgIndexP[i]->indproc;
					*(FIgetname(&finfo[i])) = '\0';
					finfoP[i] = &finfo[i];
				}
				else
					finfoP[i] = (FuncIndexInfo *) NULL;
				indexNatts[i] = natts;
				if (VARSIZE(&pgIndexP[i]->indpred) != 0)
				{
					predString = fmgr(F_TEXTOUT, &pgIndexP[i]->indpred);
					indexPred[i] = stringToNode(predString);
					pfree(predString);
					/* make dummy ExprContext for use by ExecQual */
					if (econtext == NULL)
					{
594
#ifndef OMIT_PARTIAL_INDEX
595 596 597 598
						tupleTable = ExecCreateTupleTable(1);
						slot = ExecAllocTableSlot(tupleTable);
						econtext = makeNode(ExprContext);
						econtext->ecxt_scantuple = slot;
599
						rtupdesc = RelationGetDescr(rel);
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
						slot->ttc_tupleDescriptor = rtupdesc;

						/*
						 * There's no buffer associated with heap tuples
						 * here, so I set the slot's buffer to NULL.
						 * Currently, it appears that the only way a
						 * buffer could be needed would be if the partial
						 * index predicate referred to the "lock" system
						 * attribute.  If it did, then heap_getattr would
						 * call HeapTupleGetRuleLock, which uses the
						 * buffer's descriptor to get the relation id.
						 * Rather than try to fix this, I'll just disallow
						 * partial indexes on "lock", which wouldn't be
						 * useful anyway. --Nels, Nov '92
						 */
						/* SetSlotBuffer(slot, (Buffer) NULL); */
						/* SetSlotShouldFree(slot, false); */
						slot->ttc_buffer = (Buffer) NULL;
						slot->ttc_shouldFree = false;
619
#endif	 /* OMIT_PARTIAL_INDEX */
620 621 622 623 624 625 626 627 628 629
					}
				}
				else
					indexPred[i] = NULL;
			}
		}
	}

	if (!binary)
	{
630
		in_functions = (FmgrInfo *) palloc(attr_count * sizeof(FmgrInfo));
631
		elements = (Oid *) palloc(attr_count * sizeof(Oid));
632
		typmod = (int32 *) palloc(attr_count * sizeof(int32));
633 634 635
		for (i = 0; i < attr_count; i++)
		{
			in_func_oid = (Oid) GetInputFunction(attr[i]->atttypid);
636
			fmgr_info(in_func_oid, &in_functions[i]);
637
			elements[i] = GetTypeElement(attr[i]->atttypid);
B
Bruce Momjian 已提交
638
			typmod[i] = attr[i]->atttypmod;
639 640 641 642 643 644
		}
	}
	else
	{
		in_functions = NULL;
		elements = NULL;
B
Bruce Momjian 已提交
645
		typmod = NULL;
M
 
Marc G. Fournier 已提交
646
		CopyGetData(&ntuples, sizeof(int32), fp);
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668
		if (ntuples != 0)
			reading_to_eof = false;
	}

	values = (Datum *) palloc(sizeof(Datum) * attr_count);
	nulls = (char *) palloc(attr_count);
	index_nulls = (char *) palloc(attr_count);
	idatum = (Datum *) palloc(sizeof(Datum) * attr_count);
	byval = (bool *) palloc(attr_count * sizeof(bool));

	for (i = 0; i < attr_count; i++)
	{
		nulls[i] = ' ';
		index_nulls[i] = ' ';
		byval[i] = (bool) IsTypeByVal(attr[i]->atttypid);
	}

	lineno = 0;
	while (!done)
	{
		if (!binary)
		{
M
Marc G. Fournier 已提交
669
#ifdef COPY_PATCH
670
			int			newline = 0;
671

M
Marc G. Fournier 已提交
672
#endif
673 674 675
			lineno++;
			if (oids)
			{
M
Marc G. Fournier 已提交
676
#ifdef COPY_PATCH
677
				string = CopyReadAttribute(fp, &isnull, delim, &newline);
M
Marc G. Fournier 已提交
678
#else
679
				string = CopyReadAttribute(fp, &isnull, delim);
M
Marc G. Fournier 已提交
680
#endif
681 682 683 684 685 686
				if (string == NULL)
					done = 1;
				else
				{
					loaded_oid = oidin(string);
					if (loaded_oid < BootstrapObjectIdData)
M
 
Marc G. Fournier 已提交
687
						elog(ERROR, "COPY TEXT: Invalid Oid. line: %d", lineno);
688 689 690 691
				}
			}
			for (i = 0; i < attr_count && !done; i++)
			{
M
Marc G. Fournier 已提交
692
#ifdef COPY_PATCH
693
				string = CopyReadAttribute(fp, &isnull, delim, &newline);
M
Marc G. Fournier 已提交
694
#else
695
				string = CopyReadAttribute(fp, &isnull, delim);
M
Marc G. Fournier 已提交
696
#endif
697 698 699 700 701 702 703 704 705
				if (isnull)
				{
					values[i] = PointerGetDatum(NULL);
					nulls[i] = 'n';
				}
				else if (string == NULL)
					done = 1;
				else
				{
706
					values[i] = (Datum) (*fmgr_faddr(&in_functions[i])) (string,
707 708
															 elements[i],
															  typmod[i]);
709 710 711 712 713 714 715

					/*
					 * Sanity check - by reference attributes cannot
					 * return NULL
					 */
					if (!PointerIsValid(values[i]) &&
						!(rel->rd_att->attrs[i]->attbyval))
716
						elog(ERROR, "copy from line %d: Bad file format", lineno);
717 718
				}
			}
M
Marc G. Fournier 已提交
719
#ifdef COPY_PATCH
720 721
			if (!done)
				CopyReadNewline(fp, &newline);
M
Marc G. Fournier 已提交
722
#endif
723 724 725
		}
		else
		{						/* binary */
M
 
Marc G. Fournier 已提交
726 727
			CopyGetData(&len, sizeof(int32), fp);
			if (CopyGetEof(fp))
728 729 730 731 732
				done = 1;
			else
			{
				if (oids)
				{
M
 
Marc G. Fournier 已提交
733
					CopyGetData(&loaded_oid, sizeof(int32), fp);
734
					if (loaded_oid < BootstrapObjectIdData)
M
 
Marc G. Fournier 已提交
735
						elog(ERROR, "COPY BINARY: Invalid Oid line: %d", lineno);
736
				}
M
 
Marc G. Fournier 已提交
737
				CopyGetData(&null_ct, sizeof(int32), fp);
738 739 740 741
				if (null_ct > 0)
				{
					for (i = 0; i < null_ct; i++)
					{
M
 
Marc G. Fournier 已提交
742
						CopyGetData(&null_id, sizeof(int32), fp);
743 744 745
						nulls[null_id] = 'n';
					}
				}
746

747
				string = (char *) palloc(len);
M
 
Marc G. Fournier 已提交
748
				CopyGetData(string, len, fp);
749 750 751 752 753 754 755 756 757 758

				ptr = string;

				for (i = 0; i < attr_count; i++)
				{
					if (byval[i] && nulls[i] != 'n')
					{

						switch (attr[i]->attlen)
						{
759
							case sizeof(char):
760
								values[i] = (Datum) *(unsigned char *) ptr;
761 762 763 764
								ptr += sizeof(char);
								break;
							case sizeof(short):
								ptr = (char *) SHORTALIGN(ptr);
765
								values[i] = (Datum) *(unsigned short *) ptr;
766 767 768 769
								ptr += sizeof(short);
								break;
							case sizeof(int32):
								ptr = (char *) INTALIGN(ptr);
770
								values[i] = (Datum) *(uint32 *) ptr;
771 772 773
								ptr += sizeof(int32);
								break;
							default:
M
 
Marc G. Fournier 已提交
774
								elog(ERROR, "COPY BINARY: impossible size! line: %d", lineno);
775
								break;
776 777 778 779
						}
					}
					else if (nulls[i] != 'n')
					{
B
Bruce Momjian 已提交
780
						ptr = (char *)att_align(ptr, attr[i]->attlen, attr[i]->attalign);
781 782
						values[i] = (Datum) ptr;
						ptr = att_addlength(ptr, attr[i]->attlen, ptr);
783 784 785 786 787 788 789 790 791 792 793 794 795 796
					}
				}
			}
		}
		if (done)
			continue;

		/*
		 * Does it have any sence ? - vadim 12/14/96
		 *
		 * tupDesc = CreateTupleDesc(attr_count, attr);
		 */
		tuple = heap_formtuple(tupDesc, values, nulls);
		if (oids)
797
			tuple->t_data->t_oid = loaded_oid;
798 799 800 801 802 803

		skip_tuple = false;
		/* BEFORE ROW INSERT Triggers */
		if (rel->trigdesc &&
			rel->trigdesc->n_before_row[TRIGGER_EVENT_INSERT] > 0)
		{
804
			HeapTuple	newtuple;
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824

			newtuple = ExecBRInsertTriggers(rel, tuple);

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

		if (!skip_tuple)
		{
			/* ----------------
			 * Check the constraints of a tuple
			 * ----------------
			 */

			if (rel->rd_att->constr)
825
				ExecConstraints("CopyFrom", rel, tuple, estate);
826 827 828 829 830 831 832 833 834

			heap_insert(rel, tuple);

			if (has_index)
			{
				for (i = 0; i < n_indices; i++)
				{
					if (indexPred[i] != NULL)
					{
835
#ifndef OMIT_PARTIAL_INDEX
836 837 838 839 840 841 842 843 844

						/*
						 * if tuple doesn't satisfy predicate, don't
						 * update index
						 */
						slot->val = tuple;
						/* SetSlotContents(slot, tuple); */
						if (ExecQual((List *) indexPred[i], econtext) == false)
							continue;
845
#endif	 /* OMIT_PARTIAL_INDEX */
846 847
					}
					FormIndexDatum(indexNatts[i],
B
Bruce Momjian 已提交
848
								(AttrNumber *) &(pgIndexP[i]->indkey[0]),
849 850 851 852 853 854
								   tuple,
								   tupDesc,
								   idatum,
								   index_nulls,
								   finfoP[i]);
					indexRes = index_insert(index_rels[i], idatum, index_nulls,
855
											&(tuple->t_self), rel);
856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
					if (indexRes)
						pfree(indexRes);
				}
			}
			/* AFTER ROW INSERT Triggers */
			if (rel->trigdesc &&
				rel->trigdesc->n_after_row[TRIGGER_EVENT_INSERT] > 0)
				ExecARInsertTriggers(rel, tuple);
		}

		if (binary)
			pfree(string);

		for (i = 0; i < attr_count; i++)
		{
			if (!byval[i] && nulls[i] != 'n')
			{
				if (!binary)
					pfree((void *) values[i]);
			}
			else if (nulls[i] == 'n')
				nulls[i] = ' ';
		}

		pfree(tuple);
		tuples_read++;

		if (!reading_to_eof && ntuples == tuples_read)
			done = true;
	}
	pfree(values);
B
Bruce Momjian 已提交
887
	pfree(nulls);
888 889 890 891
	pfree(index_nulls);
	pfree(idatum);
	pfree(byval);
	
892
	if (!binary)
B
Bruce Momjian 已提交
893
	{
894
		pfree(in_functions);
B
Bruce Momjian 已提交
895 896 897
		pfree(elements);
		pfree(typmod);
	}
V
Vadim B. Mikheev 已提交
898 899 900 901 902 903 904 905 906 907 908 909 910 911

	/* comments in execUtils.c */
	if (has_index)
	{
		for (i = 0; i < n_indices; i++)
		{
			if (index_rels[i] == NULL)
				continue;
			if ((index_rels[i])->rd_rel->relam != BTREE_AM_OID && 
				(index_rels[i])->rd_rel->relam != HASH_AM_OID)
				UnlockRelation(index_rels[i], AccessExclusiveLock);
			index_close(index_rels[i]);
		}
	}
912
	heap_close(rel);
913 914
}

915 916


917
static Oid
918 919
GetOutputFunction(Oid type)
{
920
	HeapTuple	typeTuple;
921 922 923 924 925 926

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type),
									0, 0, 0);

	if (HeapTupleIsValid(typeTuple))
927
		return (int) ((Form_pg_type) GETSTRUCT(typeTuple))->typoutput;
928

929
	elog(ERROR, "GetOutputFunction: Cache lookup of type %d failed", type);
930
	return InvalidOid;
931 932
}

933
static Oid
934 935
GetTypeElement(Oid type)
{
936
	HeapTuple	typeTuple;
937 938 939 940 941 942

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type),
									0, 0, 0);

	if (HeapTupleIsValid(typeTuple))
943
		return (int) ((Form_pg_type) GETSTRUCT(typeTuple))->typelem;
944

945
	elog(ERROR, "GetOutputFunction: Cache lookup of type %d failed", type);
946
	return InvalidOid;
947 948
}

949
static Oid
950 951
GetInputFunction(Oid type)
{
952
	HeapTuple	typeTuple;
953 954 955 956 957 958

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type),
									0, 0, 0);

	if (HeapTupleIsValid(typeTuple))
959
		return (int) ((Form_pg_type) GETSTRUCT(typeTuple))->typinput;
960

961
	elog(ERROR, "GetInputFunction: Cache lookup of type %d failed", type);
962
	return InvalidOid;
963 964
}

965
static Oid
966 967
IsTypeByVal(Oid type)
{
968
	HeapTuple	typeTuple;
969 970 971 972 973 974

	typeTuple = SearchSysCacheTuple(TYPOID,
									ObjectIdGetDatum(type),
									0, 0, 0);

	if (HeapTupleIsValid(typeTuple))
975
		return (int) ((Form_pg_type) GETSTRUCT(typeTuple))->typbyval;
976

977
	elog(ERROR, "GetInputFunction: Cache lookup of type %d failed", type);
978

979
	return InvalidOid;
980 981
}

982
/*
983 984 985 986 987 988 989
 * Given the OID of a relation, return an array of index relation descriptors
 * and the number of index relations.  These relation descriptors are open
 * using heap_open().
 *
 * Space for the array itself is palloc'ed.
 */

990 991
typedef struct rel_list
{
992
	Oid			index_rel_oid;
993
	struct rel_list *next;
994
} RelationList;
995 996 997

static void
GetIndexRelations(Oid main_relation_oid,
998
				  int *n_indices,
999
				  Relation **index_rels)
1000
{
1001 1002 1003 1004 1005 1006 1007 1008 1009
	RelationList *head,
			   *scan;
	Relation	pg_index_rel;
	HeapScanDesc scandesc;
	Oid			index_relation_oid;
	HeapTuple	tuple;
	TupleDesc	tupDesc;
	int			i;
	bool		isnull;
1010 1011

	pg_index_rel = heap_openr(IndexRelationName);
1012
	scandesc = heap_beginscan(pg_index_rel, 0, SnapshotNow, 0, NULL);
1013
	tupDesc = RelationGetDescr(pg_index_rel);
1014 1015 1016 1017 1018 1019 1020

	*n_indices = 0;

	head = (RelationList *) palloc(sizeof(RelationList));
	scan = head;
	head->next = NULL;

1021
	while (HeapTupleIsValid(tuple = heap_getnext(scandesc, 0)))
1022 1023
	{

1024
		index_relation_oid = (Oid) DatumGetInt32(heap_getattr(tuple, 2,
1025 1026 1027
											 tupDesc, &isnull));
		if (index_relation_oid == main_relation_oid)
		{
1028
			scan->index_rel_oid = (Oid) DatumGetInt32(heap_getattr(tuple,
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
												 Anum_pg_index_indexrelid,
												 tupDesc, &isnull));
			(*n_indices)++;
			scan->next = (RelationList *) palloc(sizeof(RelationList));
			scan = scan->next;
		}
	}

	heap_endscan(scandesc);
	heap_close(pg_index_rel);

	/* We cannot trust to relhasindex of the main_relation now, so... */
	if (*n_indices == 0)
		return;

	*index_rels = (Relation *) palloc(*n_indices * sizeof(Relation));

	for (i = 0, scan = head; i < *n_indices; i++, scan = scan->next)
V
Vadim B. Mikheev 已提交
1047
	{
1048
		(*index_rels)[i] = index_open(scan->index_rel_oid);
V
Vadim B. Mikheev 已提交
1049 1050 1051 1052 1053 1054
		/* comments in execUtils.c */
		if ((*index_rels)[i] != NULL && 
			((*index_rels)[i])->rd_rel->relam != BTREE_AM_OID &&
			((*index_rels)[i])->rd_rel->relam != HASH_AM_OID)
			LockRelation((*index_rels)[i], AccessExclusiveLock);
	}
1055 1056 1057 1058 1059 1060 1061

	for (i = 0, scan = head; i < *n_indices + 1; i++)
	{
		scan = head->next;
		pfree(head);
		head = scan;
	}
1062 1063 1064 1065 1066 1067 1068
}

#define EXT_ATTLEN 5*8192

/*
   returns 1 is c is in s
*/
1069
static bool
1070
inString(char c, char *s)
1071
{
1072
	int			i;
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084

	if (s)
	{
		i = 0;
		while (s[i] != '\0')
		{
			if (s[i] == c)
				return 1;
			i++;
		}
	}
	return 0;
1085 1086
}

M
Marc G. Fournier 已提交
1087 1088 1089 1090 1091
#ifdef COPY_PATCH
/*
 * Reads input from fp until an end of line is seen.
 */

1092
static void
1093
CopyReadNewline(FILE *fp, int *newline)
M
Marc G. Fournier 已提交
1094
{
1095 1096
	if (!*newline)
	{
1097
		elog(NOTICE, "CopyReadNewline: line %d - extra fields ignored", lineno);
M
 
Marc G. Fournier 已提交
1098
		while (!CopyGetEof(fp) && (CopyGetChar(fp) != '\n'));
1099 1100
	}
	*newline = 0;
M
Marc G. Fournier 已提交
1101
}
1102

M
Marc G. Fournier 已提交
1103 1104
#endif

1105 1106 1107 1108 1109 1110 1111
/*
 * Reads input from fp until eof is seen.  If we are reading from standard
 * input, AND we see a dot on a line by itself (a dot followed immediately
 * by a newline), we exit as if we saw eof.  This is so that copy pipelines
 * can be used as standard input.
 */

1112
static char *
M
Marc G. Fournier 已提交
1113
#ifdef COPY_PATCH
1114
CopyReadAttribute(FILE *fp, bool *isnull, char *delim, int *newline)
M
Marc G. Fournier 已提交
1115
#else
1116
CopyReadAttribute(FILE *fp, bool *isnull, char *delim)
M
Marc G. Fournier 已提交
1117
#endif
1118
{
1119 1120 1121 1122
	static char attribute[EXT_ATTLEN];
	char		c;
	int			done = 0;
	int			i = 0;
1123

1124
#ifdef MULTIBYTE
1125 1126 1127 1128 1129
	int			mblen;
	int			encoding;
	unsigned char s[2];
	int			j;

1130 1131 1132 1133 1134 1135
#endif

#ifdef MULTIBYTE
	encoding = pg_get_client_encoding();
	s[1] = 0;
#endif
1136

M
Marc G. Fournier 已提交
1137
#ifdef COPY_PATCH
1138 1139 1140 1141
	/* if last delimiter was a newline return a NULL attribute */
	if (*newline)
	{
		*isnull = (bool) true;
1142
		return NULL;
1143
	}
M
Marc G. Fournier 已提交
1144 1145
#endif

1146
	*isnull = (bool) false;		/* set default */
M
 
Marc G. Fournier 已提交
1147
	if (CopyGetEof(fp))
1148
		return NULL;
1149 1150 1151

	while (!done)
	{
M
 
Marc G. Fournier 已提交
1152
		c = CopyGetChar(fp);
1153

M
 
Marc G. Fournier 已提交
1154
		if (CopyGetEof(fp))
1155
			return NULL;
1156 1157
		else if (c == '\\')
		{
M
 
Marc G. Fournier 已提交
1158 1159
			c = CopyGetChar(fp);
			if (CopyGetEof(fp))
1160
				return NULL;
1161 1162
			switch (c)
			{
1163 1164 1165 1166 1167 1168 1169 1170
				case '0':
				case '1':
				case '2':
				case '3':
				case '4':
				case '5':
				case '6':
				case '7':
1171
					{
1172 1173 1174
						int			val;

						val = VALUE(c);
M
 
Marc G. Fournier 已提交
1175
						c = CopyPeekChar(fp);
1176 1177 1178
						if (ISOCTAL(c))
						{
							val = (val << 3) + VALUE(c);
M
 
Marc G. Fournier 已提交
1179 1180 1181 1182
							CopyDonePeek(fp, c, 1); /* Pick up the character! */
							c = CopyPeekChar(fp);
							if (ISOCTAL(c)) {
							        CopyDonePeek(fp,c,1); /* pick up! */
1183
								val = (val << 3) + VALUE(c);
M
 
Marc G. Fournier 已提交
1184
							}
1185 1186
							else
							{
M
 
Marc G. Fournier 已提交
1187 1188
							        if (CopyGetEof(fp)) {
								        CopyDonePeek(fp,c,1); /* pick up */
1189
									return NULL;
M
 
Marc G. Fournier 已提交
1190 1191
								}
								CopyDonePeek(fp,c,0); /* Return to stream! */
1192
							}
1193 1194 1195
						}
						else
						{
M
 
Marc G. Fournier 已提交
1196
							if (CopyGetEof(fp))
1197
								return NULL;
M
 
Marc G. Fournier 已提交
1198
							CopyDonePeek(fp,c,0); /* Return to stream! */
1199
						}
1200
						c = val & 0377;
1201
					}
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
					break;
				case 'b':
					c = '\b';
					break;
				case 'f':
					c = '\f';
					break;
				case 'n':
					c = '\n';
					break;
				case 'r':
					c = '\r';
					break;
				case 't':
					c = '\t';
					break;
				case 'v':
					c = '\v';
					break;
				case 'N':
					attribute[0] = '\0';		/* just to be safe */
					*isnull = (bool) true;
					break;
				case '.':
M
 
Marc G. Fournier 已提交
1226
					c = CopyGetChar(fp);
1227
					if (c != '\n')
M
 
Marc G. Fournier 已提交
1228
						elog(ERROR, "CopyReadAttribute - end of record marker corrupted. line: %d", lineno);
1229
					return NULL;
1230
					break;
1231 1232 1233 1234
			}
		}
		else if (inString(c, delim) || c == '\n')
		{
M
Marc G. Fournier 已提交
1235
#ifdef COPY_PATCH
1236 1237
			if (c == '\n')
				*newline = 1;
M
Marc G. Fournier 已提交
1238
#endif
1239 1240
			done = 1;
		}
1241
		if (!done)
1242
			attribute[i++] = c;
1243
#ifdef MULTIBYTE
1244 1245 1246 1247 1248
		s[0] = c;
		mblen = pg_encoding_mblen(encoding, s);
		mblen--;
		for (j = 0; j < mblen; j++)
		{
M
 
Marc G. Fournier 已提交
1249 1250
			c = CopyGetChar(fp);
			if (CopyGetEof(fp))
1251 1252 1253
				return NULL;
			attribute[i++] = c;
		}
1254
#endif
1255
		if (i == EXT_ATTLEN - 1)
M
 
Marc G. Fournier 已提交
1256
			elog(ERROR, "CopyReadAttribute - attribute length too long. line: %d", lineno);
1257 1258
	}
	attribute[i] = '\0';
1259
#ifdef MULTIBYTE
1260
	return (pg_client_to_server((unsigned char *) attribute, strlen(attribute)));
1261
#else
1262
	return &attribute[0];
1263
#endif
1264 1265
}

1266
static void
1267
CopyAttributeOut(FILE *fp, char *server_string, char *delim, int is_array)
1268
{
1269
	char	   *string;
1270
	char		c;
1271

1272
#ifdef MULTIBYTE
1273 1274 1275 1276
	int			mblen;
	int			encoding;
	int			i;

1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
#endif

#ifdef MULTIBYTE
	string = pg_server_to_client(server_string, strlen(server_string));
	encoding = pg_get_client_encoding();
#else
	string = server_string;
#endif

#ifdef MULTIBYTE
	for (; (mblen = pg_encoding_mblen(encoding, string)) &&
1288
		 ((c = *string) != '\0'); string += mblen)
1289
#else
1290
	for (; (c = *string) != '\0'; string++)
1291
#endif
1292 1293 1294
	{
		if (c == delim[0] || c == '\n' ||
			(c == '\\' && !is_array))
M
 
Marc G. Fournier 已提交
1295
			CopySendChar('\\', fp);
1296
		else if (c == '\\' && is_array)
1297
		{
1298 1299 1300
			if (*(string + 1) == '\\')
			{
				/* translate \\ to \\\\ */
M
 
Marc G. Fournier 已提交
1301 1302 1303
				CopySendChar('\\', fp);
				CopySendChar('\\', fp);
				CopySendChar('\\', fp);
1304 1305 1306 1307 1308
				string++;
			}
			else if (*(string + 1) == '"')
			{
				/* translate \" to \\\" */
M
 
Marc G. Fournier 已提交
1309 1310
				CopySendChar('\\', fp);
				CopySendChar('\\', fp);
1311
			}
1312
		}
1313
#ifdef MULTIBYTE
1314
		for (i = 0; i < mblen; i++)
M
 
Marc G. Fournier 已提交
1315
			CopySendChar(*(string + i), fp);
1316
#else
M
 
Marc G. Fournier 已提交
1317
		CopySendChar(*string, fp);
1318
#endif
1319
	}
1320
}
1321 1322

/*
1323
 * Returns the number of tuples in a relation.	Unfortunately, currently
1324 1325 1326 1327 1328 1329 1330
 * must do a scan of the entire relation to determine this.
 *
 * relation is expected to be an open relation descriptor.
 */
static int
CountTuples(Relation relation)
{
1331 1332
	HeapScanDesc scandesc;
	HeapTuple	tuple;
1333

1334
	int			i;
1335

1336
	scandesc = heap_beginscan(relation, 0, SnapshotNow, 0, NULL);
1337

1338 1339 1340
	i = 0;
	while (HeapTupleIsValid(tuple = heap_getnext(scandesc, 0)))
		i++;
1341
	heap_endscan(scandesc);
1342
	return i;
1343
}