PostgreSQL Source Code  git master
copyto.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "commands/copy.h"
#include "commands/progress.h"
#include "executor/execdesc.h"
#include "executor/executor.h"
#include "executor/tuptable.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/optimizer.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
#include "storage/fd.h"
#include "tcop/tcopprot.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
Include dependency graph for copyto.c:

Go to the source code of this file.

Data Structures

struct  CopyToStateData
 
struct  DR_copy
 

Macros

#define DUMPSOFAR()
 

Typedefs

typedef enum CopyDest CopyDest
 
typedef struct CopyToStateData CopyToStateData
 

Enumerations

enum  CopyDest { COPY_FILE, COPY_FRONTEND }
 

Functions

static void EndCopy (CopyToState cstate)
 
static void ClosePipeToProgram (CopyToState cstate)
 
static void CopyOneRowTo (CopyToState cstate, TupleTableSlot *slot)
 
static void CopyAttributeOutText (CopyToState cstate, char *string)
 
static void CopyAttributeOutCSV (CopyToState cstate, char *string, bool use_quote, bool single_attr)
 
static void SendCopyBegin (CopyToState cstate)
 
static void SendCopyEnd (CopyToState cstate)
 
static void CopySendData (CopyToState cstate, const void *databuf, int datasize)
 
static void CopySendString (CopyToState cstate, const char *str)
 
static void CopySendChar (CopyToState cstate, char c)
 
static void CopySendEndOfRow (CopyToState cstate)
 
static void CopySendInt32 (CopyToState cstate, int32 val)
 
static void CopySendInt16 (CopyToState cstate, int16 val)
 
CopyToState BeginCopyTo (ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
 
void EndCopyTo (CopyToState cstate)
 
uint64 DoCopyTo (CopyToState cstate)
 
static void copy_dest_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
static bool copy_dest_receive (TupleTableSlot *slot, DestReceiver *self)
 
static void copy_dest_shutdown (DestReceiver *self)
 
static void copy_dest_destroy (DestReceiver *self)
 
DestReceiverCreateCopyDestReceiver (void)
 

Variables

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

Macro Definition Documentation

◆ DUMPSOFAR

#define DUMPSOFAR ( )
Value:
do { \
if (ptr > start) \
CopySendData(cstate, start, ptr - start); \
} while (0)

Definition at line 1005 of file copyto.c.

Referenced by CopyAttributeOutCSV(), and CopyAttributeOutText().

Typedef Documentation

◆ CopyDest

typedef enum CopyDest CopyDest

◆ CopyToStateData

Enumeration Type Documentation

◆ CopyDest

enum CopyDest
Enumerator
COPY_FILE 
COPY_FRONTEND 

Definition at line 50 of file copyto.c.

51 {
52  COPY_FILE, /* to file (or a piped program) */
53  COPY_FRONTEND, /* to frontend */
54 } CopyDest;
CopyDest
Definition: copyto.c:50

Function Documentation

◆ BeginCopyTo()

CopyToState BeginCopyTo ( ParseState pstate,
Relation  rel,
RawStmt raw_query,
Oid  queryRelId,
const char *  filename,
bool  is_program,
List attnamelist,
List options 
)

Definition at line 342 of file copyto.c.

References AllocateFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, attnum, CopyToStateData::attnumlist, CopyToStateData::bytes_processed, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, Query::commandType, CopyToStateData::copy_dest, COPY_FILE, CopyToStateData::copy_file, CopyToStateData::copycontext, CopyGetAttnums(), CreateDestReceiver(), CreateQueryDesc(), cur, CurrentMemoryContext, CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, DestCopyOut, DestRemote, CopyToStateData::encoding_embeds_ascii, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, ExecutorStart(), CopyFormatOptions::file_encoding, CopyToStateData::file_encoding, CopyToStateData::filename, CopyFormatOptions::force_notnull, CopyFormatOptions::force_notnull_flags, CopyFormatOptions::force_null, CopyFormatOptions::force_null_flags, CopyFormatOptions::force_quote, CopyFormatOptions::force_quote_all, CopyFormatOptions::force_quote_flags, fstat, GetActiveSnapshot(), GetDatabaseEncoding(), i, InvalidOid, InvalidSnapshot, is_absolute_path, CopyToStateData::is_program, IsA, lfirst_int, lfirst_node, linitial_node, list_length(), list_member_int(), list_member_oid(), MemoryContextSwitchTo(), NameStr, TupleDescData::natts, CopyToStateData::need_transcoding, NIL, OpenPipeStream(), CopyToStateData::opts, ParseState::p_sourcetext, palloc0(), pg_analyze_and_rewrite(), PG_BINARY_W, pg_database_encoding_max_length(), PG_ENCODING_IS_CLIENT_ONLY, PG_END_TRY, PG_FINALLY, pg_get_client_encoding(), pg_plan_query(), PG_TRY, pgstat_progress_start_command(), pgstat_progress_update_multi_param(), ProcessCopyOptions(), PROGRESS_COMMAND_COPY, PROGRESS_COPY_COMMAND, PROGRESS_COPY_COMMAND_TO, PROGRESS_COPY_TYPE, PROGRESS_COPY_TYPE_FILE, PROGRESS_COPY_TYPE_PIPE, PROGRESS_COPY_TYPE_PROGRAM, pstrdup(), PushCopiedSnapshot(), QSRC_NON_INSTEAD_RULE, QSRC_QUAL_INSTEAD_RULE, CopyToStateData::queryDesc, Query::querySource, RelationData::rd_rel, CopyToStateData::rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, PlannedStmt::relationOids, Query::returningList, S_ISDIR, S_IWGRP, S_IWOTH, stat::st_mode, generate_unaccent_rules::stdout, QueryDesc::tupDesc, TupleDescAttr, UpdateActiveSnapshotCommandId(), Query::utilityStmt, and whereToSendOutput.

Referenced by DoCopy().

350 {
351  CopyToState cstate;
352  bool pipe = (filename == NULL);
353  TupleDesc tupDesc;
354  int num_phys_attrs;
355  MemoryContext oldcontext;
356  const int progress_cols[] = {
359  };
360  int64 progress_vals[] = {
362  0
363  };
364 
365  if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
366  {
367  if (rel->rd_rel->relkind == RELKIND_VIEW)
368  ereport(ERROR,
369  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
370  errmsg("cannot copy from view \"%s\"",
372  errhint("Try the COPY (SELECT ...) TO variant.")));
373  else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
374  ereport(ERROR,
375  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
376  errmsg("cannot copy from materialized view \"%s\"",
378  errhint("Try the COPY (SELECT ...) TO variant.")));
379  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
380  ereport(ERROR,
381  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
382  errmsg("cannot copy from foreign table \"%s\"",
384  errhint("Try the COPY (SELECT ...) TO variant.")));
385  else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
386  ereport(ERROR,
387  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
388  errmsg("cannot copy from sequence \"%s\"",
389  RelationGetRelationName(rel))));
390  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
391  ereport(ERROR,
392  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
393  errmsg("cannot copy from partitioned table \"%s\"",
395  errhint("Try the COPY (SELECT ...) TO variant.")));
396  else
397  ereport(ERROR,
398  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
399  errmsg("cannot copy from non-table relation \"%s\"",
400  RelationGetRelationName(rel))));
401  }
402 
403 
404  /* Allocate workspace and zero all fields */
405  cstate = (CopyToStateData *) palloc0(sizeof(CopyToStateData));
406 
407  /*
408  * We allocate everything used by a cstate in a new memory context. This
409  * avoids memory leaks during repeated use of COPY in a query.
410  */
412  "COPY",
414 
415  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
416 
417  /* Extract options from the statement node tree */
418  ProcessCopyOptions(pstate, &cstate->opts, false /* is_from */ , options);
419 
420  /* Process the source/target relation or query */
421  if (rel)
422  {
423  Assert(!raw_query);
424 
425  cstate->rel = rel;
426 
427  tupDesc = RelationGetDescr(cstate->rel);
428  }
429  else
430  {
431  List *rewritten;
432  Query *query;
433  PlannedStmt *plan;
435 
436  cstate->rel = NULL;
437 
438  /*
439  * Run parse analysis and rewrite. Note this also acquires sufficient
440  * locks on the source table(s).
441  */
442  rewritten = pg_analyze_and_rewrite(raw_query,
443  pstate->p_sourcetext, NULL, 0,
444  NULL);
445 
446  /* check that we got back something we can work with */
447  if (rewritten == NIL)
448  {
449  ereport(ERROR,
450  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
451  errmsg("DO INSTEAD NOTHING rules are not supported for COPY")));
452  }
453  else if (list_length(rewritten) > 1)
454  {
455  ListCell *lc;
456 
457  /* examine queries to determine which error message to issue */
458  foreach(lc, rewritten)
459  {
460  Query *q = lfirst_node(Query, lc);
461 
463  ereport(ERROR,
464  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
465  errmsg("conditional DO INSTEAD rules are not supported for COPY")));
467  ereport(ERROR,
468  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
469  errmsg("DO ALSO rules are not supported for the COPY")));
470  }
471 
472  ereport(ERROR,
473  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
474  errmsg("multi-statement DO INSTEAD rules are not supported for COPY")));
475  }
476 
477  query = linitial_node(Query, rewritten);
478 
479  /* The grammar allows SELECT INTO, but we don't support that */
480  if (query->utilityStmt != NULL &&
482  ereport(ERROR,
483  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
484  errmsg("COPY (SELECT INTO) is not supported")));
485 
486  Assert(query->utilityStmt == NULL);
487 
488  /*
489  * Similarly the grammar doesn't enforce the presence of a RETURNING
490  * clause, but this is required here.
491  */
492  if (query->commandType != CMD_SELECT &&
493  query->returningList == NIL)
494  {
495  Assert(query->commandType == CMD_INSERT ||
496  query->commandType == CMD_UPDATE ||
497  query->commandType == CMD_DELETE);
498 
499  ereport(ERROR,
500  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
501  errmsg("COPY query must have a RETURNING clause")));
502  }
503 
504  /* plan the query */
505  plan = pg_plan_query(query, pstate->p_sourcetext,
506  CURSOR_OPT_PARALLEL_OK, NULL);
507 
508  /*
509  * With row-level security and a user using "COPY relation TO", we
510  * have to convert the "COPY relation TO" to a query-based COPY (eg:
511  * "COPY (SELECT * FROM relation) TO"), to allow the rewriter to add
512  * in any RLS clauses.
513  *
514  * When this happens, we are passed in the relid of the originally
515  * found relation (which we have locked). As the planner will look up
516  * the relation again, we double-check here to make sure it found the
517  * same one that we have locked.
518  */
519  if (queryRelId != InvalidOid)
520  {
521  /*
522  * Note that with RLS involved there may be multiple relations,
523  * and while the one we need is almost certainly first, we don't
524  * make any guarantees of that in the planner, so check the whole
525  * list and make sure we find the original relation.
526  */
527  if (!list_member_oid(plan->relationOids, queryRelId))
528  ereport(ERROR,
529  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
530  errmsg("relation referenced by COPY statement has changed")));
531  }
532 
533  /*
534  * Use a snapshot with an updated command ID to ensure this query sees
535  * results of any previously executed queries.
536  */
539 
540  /* Create dest receiver for COPY OUT */
542  ((DR_copy *) dest)->cstate = cstate;
543 
544  /* Create a QueryDesc requesting no output */
545  cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
548  dest, NULL, NULL, 0);
549 
550  /*
551  * Call ExecutorStart to prepare the plan for execution.
552  *
553  * ExecutorStart computes a result tupdesc for us
554  */
555  ExecutorStart(cstate->queryDesc, 0);
556 
557  tupDesc = cstate->queryDesc->tupDesc;
558  }
559 
560  /* Generate or convert list of attributes to process */
561  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
562 
563  num_phys_attrs = tupDesc->natts;
564 
565  /* Convert FORCE_QUOTE name list to per-column flags, check validity */
566  cstate->opts.force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
567  if (cstate->opts.force_quote_all)
568  {
569  int i;
570 
571  for (i = 0; i < num_phys_attrs; i++)
572  cstate->opts.force_quote_flags[i] = true;
573  }
574  else if (cstate->opts.force_quote)
575  {
576  List *attnums;
577  ListCell *cur;
578 
579  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_quote);
580 
581  foreach(cur, attnums)
582  {
583  int attnum = lfirst_int(cur);
584  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
585 
586  if (!list_member_int(cstate->attnumlist, attnum))
587  ereport(ERROR,
588  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
589  errmsg("FORCE_QUOTE column \"%s\" not referenced by COPY",
590  NameStr(attr->attname))));
591  cstate->opts.force_quote_flags[attnum - 1] = true;
592  }
593  }
594 
595  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
596  cstate->opts.force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
597  if (cstate->opts.force_notnull)
598  {
599  List *attnums;
600  ListCell *cur;
601 
602  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_notnull);
603 
604  foreach(cur, attnums)
605  {
606  int attnum = lfirst_int(cur);
607  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
608 
609  if (!list_member_int(cstate->attnumlist, attnum))
610  ereport(ERROR,
611  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
612  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
613  NameStr(attr->attname))));
614  cstate->opts.force_notnull_flags[attnum - 1] = true;
615  }
616  }
617 
618  /* Convert FORCE_NULL name list to per-column flags, check validity */
619  cstate->opts.force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
620  if (cstate->opts.force_null)
621  {
622  List *attnums;
623  ListCell *cur;
624 
625  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_null);
626 
627  foreach(cur, attnums)
628  {
629  int attnum = lfirst_int(cur);
630  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
631 
632  if (!list_member_int(cstate->attnumlist, attnum))
633  ereport(ERROR,
634  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
635  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
636  NameStr(attr->attname))));
637  cstate->opts.force_null_flags[attnum - 1] = true;
638  }
639  }
640 
641  /* Use client encoding when ENCODING option is not specified. */
642  if (cstate->opts.file_encoding < 0)
644  else
645  cstate->file_encoding = cstate->opts.file_encoding;
646 
647  /*
648  * Set up encoding conversion info. Even if the file and server encodings
649  * are the same, we must apply pg_any_to_server() to validate data in
650  * multibyte encodings.
651  */
652  cstate->need_transcoding =
653  (cstate->file_encoding != GetDatabaseEncoding() ||
655  /* See Multibyte encoding comment above */
657 
658  cstate->copy_dest = COPY_FILE; /* default */
659 
660  MemoryContextSwitchTo(oldcontext);
661 
662  if (pipe)
663  {
664  progress_vals[1] = PROGRESS_COPY_TYPE_PIPE;
665 
666  Assert(!is_program); /* the grammar does not allow this */
668  cstate->copy_file = stdout;
669  }
670  else
671  {
672  cstate->filename = pstrdup(filename);
673  cstate->is_program = is_program;
674 
675  if (is_program)
676  {
677  progress_vals[1] = PROGRESS_COPY_TYPE_PROGRAM;
678  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
679  if (cstate->copy_file == NULL)
680  ereport(ERROR,
682  errmsg("could not execute command \"%s\": %m",
683  cstate->filename)));
684  }
685  else
686  {
687  mode_t oumask; /* Pre-existing umask value */
688  struct stat st;
689 
690  progress_vals[1] = PROGRESS_COPY_TYPE_FILE;
691 
692  /*
693  * Prevent write to relative path ... too easy to shoot oneself in
694  * the foot by overwriting a database file ...
695  */
697  ereport(ERROR,
698  (errcode(ERRCODE_INVALID_NAME),
699  errmsg("relative path not allowed for COPY to file")));
700 
701  oumask = umask(S_IWGRP | S_IWOTH);
702  PG_TRY();
703  {
704  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
705  }
706  PG_FINALLY();
707  {
708  umask(oumask);
709  }
710  PG_END_TRY();
711  if (cstate->copy_file == NULL)
712  {
713  /* copy errno because ereport subfunctions might change it */
714  int save_errno = errno;
715 
716  ereport(ERROR,
718  errmsg("could not open file \"%s\" for writing: %m",
719  cstate->filename),
720  (save_errno == ENOENT || save_errno == EACCES) ?
721  errhint("COPY TO instructs the PostgreSQL server process to write a file. "
722  "You may want a client-side facility such as psql's \\copy.") : 0));
723  }
724 
725  if (fstat(fileno(cstate->copy_file), &st))
726  ereport(ERROR,
728  errmsg("could not stat file \"%s\": %m",
729  cstate->filename)));
730 
731  if (S_ISDIR(st.st_mode))
732  ereport(ERROR,
733  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
734  errmsg("\"%s\" is a directory", cstate->filename)));
735  }
736  }
737 
738  /* initialize progress */
740  cstate->rel ? RelationGetRelid(cstate->rel) : InvalidOid);
741  pgstat_progress_update_multi_param(2, progress_cols, progress_vals);
742 
743  cstate->bytes_processed = 0;
744 
745  MemoryContextSwitchTo(oldcontext);
746 
747  return cstate;
748 }
int file_encoding
Definition: copyto.c:78
#define NIL
Definition: pg_list.h:65
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
#define PROGRESS_COPY_COMMAND_TO
Definition: progress.h:146
#define AllocSetContextCreate
Definition: memutils.h:173
#define PROGRESS_COPY_TYPE_FILE
Definition: progress.h:149
int errhint(const char *fmt,...)
Definition: elog.c:1156
Relation rel
Definition: copyto.c:83
bool need_transcoding
Definition: copyto.c:79
FILE * copy_file
Definition: copyto.c:75
#define RelationGetDescr(relation)
Definition: rel.h:503
#define PROGRESS_COPY_COMMAND
Definition: progress.h:141
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * relationOids
Definition: plannodes.h:80
char * pstrdup(const char *in)
Definition: mcxt.c:1299
bool * force_quote_flags
Definition: copy.h:44
#define S_IWOTH
Definition: win32_port.h:307
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:130
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_BINARY_W
Definition: c.h:1274
uint64 bytes_processed
Definition: copyto.c:99
List * force_notnull
Definition: copy.h:45
bool force_quote_all
Definition: copy.h:43
Form_pg_class rd_rel
Definition: rel.h:109
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:642
Node * utilityStmt
Definition: parsenodes.h:128
#define linitial_node(type, l)
Definition: pg_list.h:177
#define PROGRESS_COPY_TYPE_PIPE
Definition: progress.h:151
bool is_program
Definition: copyto.c:87
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
QueryDesc * queryDesc
Definition: copyto.c:84
#define fstat
Definition: win32_port.h:274
List * attnumlist
Definition: copyto.c:85
#define ERROR
Definition: elog.h:46
#define lfirst_int(lc)
Definition: pg_list.h:170
MemoryContext copycontext
Definition: copyto.c:95
#define PROGRESS_COPY_TYPE
Definition: progress.h:142
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
List * force_null
Definition: copy.h:47
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool list_member_int(const List *list, int datum)
Definition: list.c:669
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
int errcode_for_file_access(void)
Definition: elog.c:721
#define is_absolute_path(filename)
Definition: port.h:86
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2417
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define S_IWGRP
Definition: win32_port.h:295
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
const char * p_sourcetext
Definition: parse_node.h:181
int file_encoding
Definition: copy.h:30
List * returningList
Definition: parsenodes.h:156
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2520
CopyDest copy_dest
Definition: copyto.c:74
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
#define PG_FINALLY()
Definition: elog.h:330
void * palloc0(Size size)
Definition: mcxt.c:1093
List * force_quote
Definition: copy.h:42
#define PROGRESS_COPY_TYPE_PROGRAM
Definition: progress.h:150
int GetDatabaseEncoding(void)
Definition: mbutils.c:1210
int pg_get_client_encoding(void)
Definition: mbutils.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
CmdType commandType
Definition: parsenodes.h:120
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
QuerySource querySource
Definition: parsenodes.h:122
#define Assert(condition)
Definition: c.h:804
bool * force_null_flags
Definition: copy.h:48
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:651
static int list_length(const List *l)
Definition: pg_list.h:149
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1495
CopyFormatOptions opts
Definition: copyto.c:89
#define S_ISDIR(m)
Definition: win32_port.h:316
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
static char * filename
Definition: pg_dumpall.c:92
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2816
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
#define NameStr(name)
Definition: c.h:681
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:829
bool encoding_embeds_ascii
Definition: copyto.c:80
CommandDest whereToSendOutput
Definition: postgres.c:92
char * filename
Definition: copyto.c:86
#define PG_TRY()
Definition: elog.h:313
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:477
#define PG_END_TRY()
Definition: elog.h:338
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:334
bool * force_notnull_flags
Definition: copy.h:46

◆ ClosePipeToProgram()

static void ClosePipeToProgram ( CopyToState  cstate)
static

Definition at line 292 of file copyto.c.

References Assert, ClosePipeStream(), CopyToStateData::copy_file, ereport, errcode(), errcode_for_file_access(), errdetail_internal(), errmsg(), ERROR, CopyToStateData::filename, CopyToStateData::is_program, and wait_result_to_str().

Referenced by CopySendEndOfRow(), and EndCopy().

293 {
294  int pclose_rc;
295 
296  Assert(cstate->is_program);
297 
298  pclose_rc = ClosePipeStream(cstate->copy_file);
299  if (pclose_rc == -1)
300  ereport(ERROR,
302  errmsg("could not close pipe to external command: %m")));
303  else if (pclose_rc != 0)
304  {
305  ereport(ERROR,
306  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
307  errmsg("program \"%s\" failed",
308  cstate->filename),
309  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
310  }
311 }
FILE * copy_file
Definition: copyto.c:75
int errcode(int sqlerrcode)
Definition: elog.c:698
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
bool is_program
Definition: copyto.c:87
int ClosePipeStream(FILE *file)
Definition: fd.c:2826
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:46
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * filename
Definition: copyto.c:86

◆ copy_dest_destroy()

static void copy_dest_destroy ( DestReceiver self)
static

Definition at line 1287 of file copyto.c.

References pfree().

Referenced by CreateCopyDestReceiver().

1288 {
1289  pfree(self);
1290 }
void pfree(void *pointer)
Definition: mcxt.c:1169

◆ copy_dest_receive()

static bool copy_dest_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 1259 of file copyto.c.

References CopyOneRowTo(), DR_copy::cstate, pgstat_progress_update_param(), DR_copy::processed, and PROGRESS_COPY_TUPLES_PROCESSED.

Referenced by CreateCopyDestReceiver().

1260 {
1261  DR_copy *myState = (DR_copy *) self;
1262  CopyToState cstate = myState->cstate;
1263 
1264  /* Send the data */
1265  CopyOneRowTo(cstate, slot);
1266 
1267  /* Increment the number of processed tuples, and report the progress */
1269  ++myState->processed);
1270 
1271  return true;
1272 }
static void CopyOneRowTo(CopyToState cstate, TupleTableSlot *slot)
Definition: copyto.c:931
#define PROGRESS_COPY_TUPLES_PROCESSED
Definition: progress.h:139
CopyToState cstate
Definition: copyto.c:107
void pgstat_progress_update_param(int index, int64 val)
uint64 processed
Definition: copyto.c:108

◆ copy_dest_shutdown()

static void copy_dest_shutdown ( DestReceiver self)
static

Definition at line 1278 of file copyto.c.

Referenced by CreateCopyDestReceiver().

1279 {
1280  /* no-op */
1281 }

◆ copy_dest_startup()

static void copy_dest_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)
static

Definition at line 1250 of file copyto.c.

Referenced by CreateCopyDestReceiver().

1251 {
1252  /* no-op */
1253 }

◆ CopyAttributeOutCSV()

static void CopyAttributeOutCSV ( CopyToState  cstate,
char *  string,
bool  use_quote,
bool  single_attr 
)
static

Definition at line 1165 of file copyto.c.

References CopySendChar(), CopySendString(), CopyFormatOptions::delim, DUMPSOFAR, CopyToStateData::encoding_embeds_ascii, CopyFormatOptions::escape, CopyToStateData::file_encoding, IS_HIGHBIT_SET, CopyToStateData::need_transcoding, CopyFormatOptions::null_print, CopyToStateData::opts, pg_encoding_mblen(), pg_server_to_any(), and CopyFormatOptions::quote.

Referenced by CopyOneRowTo(), and DoCopyTo().

1167 {
1168  char *ptr;
1169  char *start;
1170  char c;
1171  char delimc = cstate->opts.delim[0];
1172  char quotec = cstate->opts.quote[0];
1173  char escapec = cstate->opts.escape[0];
1174 
1175  /* force quoting if it matches null_print (before conversion!) */
1176  if (!use_quote && strcmp(string, cstate->opts.null_print) == 0)
1177  use_quote = true;
1178 
1179  if (cstate->need_transcoding)
1180  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
1181  else
1182  ptr = string;
1183 
1184  /*
1185  * Make a preliminary pass to discover if it needs quoting
1186  */
1187  if (!use_quote)
1188  {
1189  /*
1190  * Because '\.' can be a data value, quote it if it appears alone on a
1191  * line so it is not interpreted as the end-of-data marker.
1192  */
1193  if (single_attr && strcmp(ptr, "\\.") == 0)
1194  use_quote = true;
1195  else
1196  {
1197  char *tptr = ptr;
1198 
1199  while ((c = *tptr) != '\0')
1200  {
1201  if (c == delimc || c == quotec || c == '\n' || c == '\r')
1202  {
1203  use_quote = true;
1204  break;
1205  }
1206  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
1207  tptr += pg_encoding_mblen(cstate->file_encoding, tptr);
1208  else
1209  tptr++;
1210  }
1211  }
1212  }
1213 
1214  if (use_quote)
1215  {
1216  CopySendChar(cstate, quotec);
1217 
1218  /*
1219  * We adopt the same optimization strategy as in CopyAttributeOutText
1220  */
1221  start = ptr;
1222  while ((c = *ptr) != '\0')
1223  {
1224  if (c == quotec || c == escapec)
1225  {
1226  DUMPSOFAR();
1227  CopySendChar(cstate, escapec);
1228  start = ptr; /* we include char in next run */
1229  }
1230  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
1231  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
1232  else
1233  ptr++;
1234  }
1235  DUMPSOFAR();
1236 
1237  CopySendChar(cstate, quotec);
1238  }
1239  else
1240  {
1241  /* If it doesn't need quoting, we can just dump it as-is */
1242  CopySendString(cstate, ptr);
1243  }
1244 }
int file_encoding
Definition: copyto.c:78
bool need_transcoding
Definition: copyto.c:79
char * null_print
Definition: copy.h:36
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:749
char * quote
Definition: copy.h:40
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1921
char string[11]
Definition: preproc-type.c:46
static void CopySendString(CopyToState cstate, const char *str)
Definition: copyto.c:181
char * delim
Definition: copy.h:39
#define DUMPSOFAR()
Definition: copyto.c:1005
CopyFormatOptions opts
Definition: copyto.c:89
char * escape
Definition: copy.h:41
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
bool encoding_embeds_ascii
Definition: copyto.c:80

◆ CopyAttributeOutText()

static void CopyAttributeOutText ( CopyToState  cstate,
char *  string 
)
static

Definition at line 1012 of file copyto.c.

References CopySendChar(), CopyFormatOptions::delim, DUMPSOFAR, CopyToStateData::encoding_embeds_ascii, CopyToStateData::file_encoding, IS_HIGHBIT_SET, CopyToStateData::need_transcoding, CopyToStateData::opts, pg_encoding_mblen(), and pg_server_to_any().

Referenced by CopyOneRowTo().

1013 {
1014  char *ptr;
1015  char *start;
1016  char c;
1017  char delimc = cstate->opts.delim[0];
1018 
1019  if (cstate->need_transcoding)
1020  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
1021  else
1022  ptr = string;
1023 
1024  /*
1025  * We have to grovel through the string searching for control characters
1026  * and instances of the delimiter character. In most cases, though, these
1027  * are infrequent. To avoid overhead from calling CopySendData once per
1028  * character, we dump out all characters between escaped characters in a
1029  * single call. The loop invariant is that the data from "start" to "ptr"
1030  * can be sent literally, but hasn't yet been.
1031  *
1032  * We can skip pg_encoding_mblen() overhead when encoding is safe, because
1033  * in valid backend encodings, extra bytes of a multibyte character never
1034  * look like ASCII. This loop is sufficiently performance-critical that
1035  * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
1036  * of the normal safe-encoding path.
1037  */
1038  if (cstate->encoding_embeds_ascii)
1039  {
1040  start = ptr;
1041  while ((c = *ptr) != '\0')
1042  {
1043  if ((unsigned char) c < (unsigned char) 0x20)
1044  {
1045  /*
1046  * \r and \n must be escaped, the others are traditional. We
1047  * prefer to dump these using the C-like notation, rather than
1048  * a backslash and the literal character, because it makes the
1049  * dump file a bit more proof against Microsoftish data
1050  * mangling.
1051  */
1052  switch (c)
1053  {
1054  case '\b':
1055  c = 'b';
1056  break;
1057  case '\f':
1058  c = 'f';
1059  break;
1060  case '\n':
1061  c = 'n';
1062  break;
1063  case '\r':
1064  c = 'r';
1065  break;
1066  case '\t':
1067  c = 't';
1068  break;
1069  case '\v':
1070  c = 'v';
1071  break;
1072  default:
1073  /* If it's the delimiter, must backslash it */
1074  if (c == delimc)
1075  break;
1076  /* All ASCII control chars are length 1 */
1077  ptr++;
1078  continue; /* fall to end of loop */
1079  }
1080  /* if we get here, we need to convert the control char */
1081  DUMPSOFAR();
1082  CopySendChar(cstate, '\\');
1083  CopySendChar(cstate, c);
1084  start = ++ptr; /* do not include char in next run */
1085  }
1086  else if (c == '\\' || c == delimc)
1087  {
1088  DUMPSOFAR();
1089  CopySendChar(cstate, '\\');
1090  start = ptr++; /* we include char in next run */
1091  }
1092  else if (IS_HIGHBIT_SET(c))
1093  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
1094  else
1095  ptr++;
1096  }
1097  }
1098  else
1099  {
1100  start = ptr;
1101  while ((c = *ptr) != '\0')
1102  {
1103  if ((unsigned char) c < (unsigned char) 0x20)
1104  {
1105  /*
1106  * \r and \n must be escaped, the others are traditional. We
1107  * prefer to dump these using the C-like notation, rather than
1108  * a backslash and the literal character, because it makes the
1109  * dump file a bit more proof against Microsoftish data
1110  * mangling.
1111  */
1112  switch (c)
1113  {
1114  case '\b':
1115  c = 'b';
1116  break;
1117  case '\f':
1118  c = 'f';
1119  break;
1120  case '\n':
1121  c = 'n';
1122  break;
1123  case '\r':
1124  c = 'r';
1125  break;
1126  case '\t':
1127  c = 't';
1128  break;
1129  case '\v':
1130  c = 'v';
1131  break;
1132  default:
1133  /* If it's the delimiter, must backslash it */
1134  if (c == delimc)
1135  break;
1136  /* All ASCII control chars are length 1 */
1137  ptr++;
1138  continue; /* fall to end of loop */
1139  }
1140  /* if we get here, we need to convert the control char */
1141  DUMPSOFAR();
1142  CopySendChar(cstate, '\\');
1143  CopySendChar(cstate, c);
1144  start = ++ptr; /* do not include char in next run */
1145  }
1146  else if (c == '\\' || c == delimc)
1147  {
1148  DUMPSOFAR();
1149  CopySendChar(cstate, '\\');
1150  start = ptr++; /* we include char in next run */
1151  }
1152  else
1153  ptr++;
1154  }
1155  }
1156 
1157  DUMPSOFAR();
1158 }
int file_encoding
Definition: copyto.c:78
bool need_transcoding
Definition: copyto.c:79
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:749
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1921
char string[11]
Definition: preproc-type.c:46
char * delim
Definition: copy.h:39
#define DUMPSOFAR()
Definition: copyto.c:1005
CopyFormatOptions opts
Definition: copyto.c:89
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
bool encoding_embeds_ascii
Definition: copyto.c:80

◆ CopyOneRowTo()

static void CopyOneRowTo ( CopyToState  cstate,
TupleTableSlot slot 
)
static

Definition at line 931 of file copyto.c.

References attnum, CopyToStateData::attnumlist, CopyFormatOptions::binary, CopyAttributeOutCSV(), CopyAttributeOutText(), CopySendChar(), CopySendData(), CopySendEndOfRow(), CopySendInt16(), CopySendInt32(), CopySendString(), CopyFormatOptions::csv_mode, cur, CopyFormatOptions::delim, CopyFormatOptions::force_quote_flags, lfirst_int, list_length(), MemoryContextReset(), MemoryContextSwitchTo(), CopyFormatOptions::null_print_client, CopyToStateData::opts, CopyToStateData::out_functions, OutputFunctionCall(), CopyToStateData::rowcontext, SendFunctionCall(), slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, value, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by copy_dest_receive(), and DoCopyTo().

932 {
933  bool need_delim = false;
934  FmgrInfo *out_functions = cstate->out_functions;
935  MemoryContext oldcontext;
936  ListCell *cur;
937  char *string;
938 
940  oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
941 
942  if (cstate->opts.binary)
943  {
944  /* Binary per-tuple header */
945  CopySendInt16(cstate, list_length(cstate->attnumlist));
946  }
947 
948  /* Make sure the tuple is fully deconstructed */
949  slot_getallattrs(slot);
950 
951  foreach(cur, cstate->attnumlist)
952  {
953  int attnum = lfirst_int(cur);
954  Datum value = slot->tts_values[attnum - 1];
955  bool isnull = slot->tts_isnull[attnum - 1];
956 
957  if (!cstate->opts.binary)
958  {
959  if (need_delim)
960  CopySendChar(cstate, cstate->opts.delim[0]);
961  need_delim = true;
962  }
963 
964  if (isnull)
965  {
966  if (!cstate->opts.binary)
967  CopySendString(cstate, cstate->opts.null_print_client);
968  else
969  CopySendInt32(cstate, -1);
970  }
971  else
972  {
973  if (!cstate->opts.binary)
974  {
975  string = OutputFunctionCall(&out_functions[attnum - 1],
976  value);
977  if (cstate->opts.csv_mode)
978  CopyAttributeOutCSV(cstate, string,
979  cstate->opts.force_quote_flags[attnum - 1],
980  list_length(cstate->attnumlist) == 1);
981  else
982  CopyAttributeOutText(cstate, string);
983  }
984  else
985  {
986  bytea *outputbytes;
987 
988  outputbytes = SendFunctionCall(&out_functions[attnum - 1],
989  value);
990  CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
991  CopySendData(cstate, VARDATA(outputbytes),
992  VARSIZE(outputbytes) - VARHDRSZ);
993  }
994  }
995  }
996 
997  CopySendEndOfRow(cstate);
998 
999  MemoryContextSwitchTo(oldcontext);
1000 }
Definition: fmgr.h:56
#define VARDATA(PTR)
Definition: postgres.h:315
static void CopyAttributeOutCSV(CopyToState cstate, char *string, bool use_quote, bool single_attr)
Definition: copyto.c:1165
FmgrInfo * out_functions
Definition: copyto.c:97
#define VARSIZE(PTR)
Definition: postgres.h:316
#define VARHDRSZ
Definition: c.h:627
bool * force_quote_flags
Definition: copy.h:44
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static void CopySendInt16(CopyToState cstate, int16 val)
Definition: copyto.c:280
struct cursor * cur
Definition: ecpg.c:28
char * null_print_client
Definition: copy.h:38
Datum * tts_values
Definition: tuptable.h:126
MemoryContext rowcontext
Definition: copyto.c:98
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1573
List * attnumlist
Definition: copyto.c:85
#define lfirst_int(lc)
Definition: pg_list.h:170
bool binary
Definition: copy.h:32
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
bool csv_mode
Definition: copy.h:34
bool * tts_isnull
Definition: tuptable.h:128
char string[11]
Definition: preproc-type.c:46
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1634
static void CopySendString(CopyToState cstate, const char *str)
Definition: copyto.c:181
static void CopySendInt32(CopyToState cstate, int32 val)
Definition: copyto.c:268
uintptr_t Datum
Definition: postgres.h:411
char * delim
Definition: copy.h:39
static void CopySendData(CopyToState cstate, const void *databuf, int datasize)
Definition: copyto.c:175
int16 attnum
Definition: pg_attribute.h:83
static struct @143 value
static int list_length(const List *l)
Definition: pg_list.h:149
static void CopyAttributeOutText(CopyToState cstate, char *string)
Definition: copyto.c:1012
CopyFormatOptions opts
Definition: copyto.c:89
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
Definition: c.h:621
static void CopySendEndOfRow(CopyToState cstate)
Definition: copyto.c:193

◆ CopySendChar()

static void CopySendChar ( CopyToState  cstate,
char  c 
)
static

Definition at line 187 of file copyto.c.

References appendStringInfoCharMacro, and CopyToStateData::fe_msgbuf.

Referenced by CopyAttributeOutCSV(), CopyAttributeOutText(), CopyOneRowTo(), CopySendEndOfRow(), and DoCopyTo().

188 {
190 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:128
char * c
StringInfo fe_msgbuf
Definition: copyto.c:76

◆ CopySendData()

static void CopySendData ( CopyToState  cstate,
const void *  databuf,
int  datasize 
)
static

Definition at line 175 of file copyto.c.

References appendBinaryStringInfo(), and CopyToStateData::fe_msgbuf.

Referenced by CopyOneRowTo(), CopySendInt16(), CopySendInt32(), and DoCopyTo().

176 {
177  appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
178 }
StringInfo fe_msgbuf
Definition: copyto.c:76
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CopySendEndOfRow()

static void CopySendEndOfRow ( CopyToState  cstate)
static

Definition at line 193 of file copyto.c.

References CopyFormatOptions::binary, CopyToStateData::bytes_processed, ClosePipeToProgram(), CopyToStateData::copy_dest, COPY_FILE, CopyToStateData::copy_file, COPY_FRONTEND, CopySendChar(), CopySendString(), StringInfoData::data, ereport, errcode_for_file_access(), errmsg(), ERROR, CopyToStateData::fe_msgbuf, CopyToStateData::is_program, StringInfoData::len, CopyToStateData::opts, pgstat_progress_update_param(), pq_putmessage, PROGRESS_COPY_BYTES_PROCESSED, and resetStringInfo().

Referenced by CopyOneRowTo(), and DoCopyTo().

194 {
195  StringInfo fe_msgbuf = cstate->fe_msgbuf;
196 
197  switch (cstate->copy_dest)
198  {
199  case COPY_FILE:
200  if (!cstate->opts.binary)
201  {
202  /* Default line termination depends on platform */
203 #ifndef WIN32
204  CopySendChar(cstate, '\n');
205 #else
206  CopySendString(cstate, "\r\n");
207 #endif
208  }
209 
210  if (fwrite(fe_msgbuf->data, fe_msgbuf->len, 1,
211  cstate->copy_file) != 1 ||
212  ferror(cstate->copy_file))
213  {
214  if (cstate->is_program)
215  {
216  if (errno == EPIPE)
217  {
218  /*
219  * The pipe will be closed automatically on error at
220  * the end of transaction, but we might get a better
221  * error message from the subprocess' exit code than
222  * just "Broken Pipe"
223  */
224  ClosePipeToProgram(cstate);
225 
226  /*
227  * If ClosePipeToProgram() didn't throw an error, the
228  * program terminated normally, but closed the pipe
229  * first. Restore errno, and throw an error.
230  */
231  errno = EPIPE;
232  }
233  ereport(ERROR,
235  errmsg("could not write to COPY program: %m")));
236  }
237  else
238  ereport(ERROR,
240  errmsg("could not write to COPY file: %m")));
241  }
242  break;
243  case COPY_FRONTEND:
244  /* The FE/BE protocol uses \n as newline for all platforms */
245  if (!cstate->opts.binary)
246  CopySendChar(cstate, '\n');
247 
248  /* Dump the accumulated row as one CopyData message */
249  (void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
250  break;
251  }
252 
253  /* Update the progress */
254  cstate->bytes_processed += fe_msgbuf->len;
256 
257  resetStringInfo(fe_msgbuf);
258 }
FILE * copy_file
Definition: copyto.c:75
uint64 bytes_processed
Definition: copyto.c:99
bool is_program
Definition: copyto.c:87
#define ERROR
Definition: elog.h:46
bool binary
Definition: copy.h:32
static void ClosePipeToProgram(CopyToState cstate)
Definition: copyto.c:292
int errcode_for_file_access(void)
Definition: elog.c:721
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
static void CopySendString(CopyToState cstate, const char *str)
Definition: copyto.c:181
CopyDest copy_dest
Definition: copyto.c:74
StringInfo fe_msgbuf
Definition: copyto.c:76
#define ereport(elevel,...)
Definition: elog.h:157
void pgstat_progress_update_param(int index, int64 val)
CopyFormatOptions opts
Definition: copyto.c:89
int errmsg(const char *fmt,...)
Definition: elog.c:909
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
#define PROGRESS_COPY_BYTES_PROCESSED
Definition: progress.h:137
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49

◆ CopySendInt16()

static void CopySendInt16 ( CopyToState  cstate,
int16  val 
)
inlinestatic

Definition at line 280 of file copyto.c.

References buf, CopySendData(), and pg_hton16.

Referenced by CopyOneRowTo(), and DoCopyTo().

281 {
282  uint16 buf;
283 
284  buf = pg_hton16((uint16) val);
285  CopySendData(cstate, &buf, sizeof(buf));
286 }
#define pg_hton16(x)
Definition: pg_bswap.h:120
unsigned short uint16
Definition: c.h:440
static char * buf
Definition: pg_test_fsync.c:68
static void CopySendData(CopyToState cstate, const void *databuf, int datasize)
Definition: copyto.c:175
long val
Definition: informix.c:664

◆ CopySendInt32()

static void CopySendInt32 ( CopyToState  cstate,
int32  val 
)
inlinestatic

Definition at line 268 of file copyto.c.

References buf, CopySendData(), and pg_hton32.

Referenced by CopyOneRowTo(), and DoCopyTo().

269 {
270  uint32 buf;
271 
272  buf = pg_hton32((uint32) val);
273  CopySendData(cstate, &buf, sizeof(buf));
274 }
#define pg_hton32(x)
Definition: pg_bswap.h:121
static char * buf
Definition: pg_test_fsync.c:68
unsigned int uint32
Definition: c.h:441
static void CopySendData(CopyToState cstate, const void *databuf, int datasize)
Definition: copyto.c:175
long val
Definition: informix.c:664

◆ CopySendString()

static void CopySendString ( CopyToState  cstate,
const char *  str 
)
static

Definition at line 181 of file copyto.c.

References appendBinaryStringInfo(), and CopyToStateData::fe_msgbuf.

Referenced by CopyAttributeOutCSV(), CopyOneRowTo(), and CopySendEndOfRow().

182 {
183  appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
184 }
StringInfo fe_msgbuf
Definition: copyto.c:76
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CreateCopyDestReceiver()

DestReceiver* CreateCopyDestReceiver ( void  )

Definition at line 1296 of file copyto.c.

References copy_dest_destroy(), copy_dest_receive(), copy_dest_shutdown(), copy_dest_startup(), DestCopyOut, and palloc().

Referenced by CreateDestReceiver().

1297 {
1298  DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
1299 
1300  self->pub.receiveSlot = copy_dest_receive;
1301  self->pub.rStartup = copy_dest_startup;
1302  self->pub.rShutdown = copy_dest_shutdown;
1303  self->pub.rDestroy = copy_dest_destroy;
1304  self->pub.mydest = DestCopyOut;
1305 
1306  self->cstate = NULL; /* will be set later */
1307  self->processed = 0;
1308 
1309  return (DestReceiver *) self;
1310 }
static void copy_dest_destroy(DestReceiver *self)
Definition: copyto.c:1287
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copyto.c:1259
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copyto.c:1250
void * palloc(Size size)
Definition: mcxt.c:1062
static void copy_dest_shutdown(DestReceiver *self)
Definition: copyto.c:1278

◆ DoCopyTo()

uint64 DoCopyTo ( CopyToState  cstate)

Definition at line 773 of file copyto.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, attname, attnum, CopyToStateData::attnumlist, CopyFormatOptions::binary, BinarySignature, CHECK_FOR_INTERRUPTS, CopyAttributeOutCSV(), CopyOneRowTo(), CopySendChar(), CopySendData(), CopySendEndOfRow(), CopySendInt16(), CopySendInt32(), cur, CurrentMemoryContext, CopyFormatOptions::delim, QueryDesc::dest, DestRemote, ExecDropSingleTupleTableSlot(), ExecutorRun(), CopyToStateData::fe_msgbuf, CopyToStateData::file_encoding, CopyToStateData::filename, fmgr_info(), ForwardScanDirection, GetActiveSnapshot(), getTypeBinaryOutputInfo(), getTypeOutputInfo(), CopyFormatOptions::header_line, lfirst_int, list_length(), makeStringInfo(), MemoryContextDelete(), NameStr, TupleDescData::natts, CopyToStateData::need_transcoding, CopyFormatOptions::null_print, CopyFormatOptions::null_print_client, CopyFormatOptions::null_print_len, CopyToStateData::opts, CopyToStateData::out_functions, palloc(), pg_server_to_any(), pgstat_progress_update_param(), PROGRESS_COPY_TUPLES_PROCESSED, CopyToStateData::queryDesc, CopyToStateData::rel, RelationGetDescr, CopyToStateData::rowcontext, SendCopyBegin(), SendCopyEnd(), slot_getallattrs(), table_beginscan(), table_endscan(), table_scan_getnextslot(), table_slot_create(), QueryDesc::tupDesc, TupleDescAttr, and whereToSendOutput.

Referenced by DoCopy().

774 {
775  bool pipe = (cstate->filename == NULL);
776  bool fe_copy = (pipe && whereToSendOutput == DestRemote);
777  TupleDesc tupDesc;
778  int num_phys_attrs;
779  ListCell *cur;
780  uint64 processed;
781 
782  if (fe_copy)
783  SendCopyBegin(cstate);
784 
785  if (cstate->rel)
786  tupDesc = RelationGetDescr(cstate->rel);
787  else
788  tupDesc = cstate->queryDesc->tupDesc;
789  num_phys_attrs = tupDesc->natts;
790  cstate->opts.null_print_client = cstate->opts.null_print; /* default */
791 
792  /* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
793  cstate->fe_msgbuf = makeStringInfo();
794 
795  /* Get info about the columns we need to process. */
796  cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
797  foreach(cur, cstate->attnumlist)
798  {
799  int attnum = lfirst_int(cur);
800  Oid out_func_oid;
801  bool isvarlena;
802  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
803 
804  if (cstate->opts.binary)
805  getTypeBinaryOutputInfo(attr->atttypid,
806  &out_func_oid,
807  &isvarlena);
808  else
809  getTypeOutputInfo(attr->atttypid,
810  &out_func_oid,
811  &isvarlena);
812  fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
813  }
814 
815  /*
816  * Create a temporary memory context that we can reset once per row to
817  * recover palloc'd memory. This avoids any problems with leaks inside
818  * datatype output routines, and should be faster than retail pfree's
819  * anyway. (We don't need a whole econtext as CopyFrom does.)
820  */
822  "COPY TO",
824 
825  if (cstate->opts.binary)
826  {
827  /* Generate header for a binary copy */
828  int32 tmp;
829 
830  /* Signature */
831  CopySendData(cstate, BinarySignature, 11);
832  /* Flags field */
833  tmp = 0;
834  CopySendInt32(cstate, tmp);
835  /* No header extension */
836  tmp = 0;
837  CopySendInt32(cstate, tmp);
838  }
839  else
840  {
841  /*
842  * For non-binary copy, we need to convert null_print to file
843  * encoding, because it will be sent directly with CopySendString.
844  */
845  if (cstate->need_transcoding)
847  cstate->opts.null_print_len,
848  cstate->file_encoding);
849 
850  /* if a header has been requested send the line */
851  if (cstate->opts.header_line)
852  {
853  bool hdr_delim = false;
854 
855  foreach(cur, cstate->attnumlist)
856  {
857  int attnum = lfirst_int(cur);
858  char *colname;
859 
860  if (hdr_delim)
861  CopySendChar(cstate, cstate->opts.delim[0]);
862  hdr_delim = true;
863 
864  colname = NameStr(TupleDescAttr(tupDesc, attnum - 1)->attname);
865 
866  CopyAttributeOutCSV(cstate, colname, false,
867  list_length(cstate->attnumlist) == 1);
868  }
869 
870  CopySendEndOfRow(cstate);
871  }
872  }
873 
874  if (cstate->rel)
875  {
876  TupleTableSlot *slot;
877  TableScanDesc scandesc;
878 
879  scandesc = table_beginscan(cstate->rel, GetActiveSnapshot(), 0, NULL);
880  slot = table_slot_create(cstate->rel, NULL);
881 
882  processed = 0;
883  while (table_scan_getnextslot(scandesc, ForwardScanDirection, slot))
884  {
886 
887  /* Deconstruct the tuple ... */
888  slot_getallattrs(slot);
889 
890  /* Format and send the data */
891  CopyOneRowTo(cstate, slot);
892 
893  /*
894  * Increment the number of processed tuples, and report the
895  * progress.
896  */
898  ++processed);
899  }
900 
902  table_endscan(scandesc);
903  }
904  else
905  {
906  /* run the plan --- the dest receiver will send tuples */
907  ExecutorRun(cstate->queryDesc, ForwardScanDirection, 0L, true);
908  processed = ((DR_copy *) cstate->queryDesc->dest)->processed;
909  }
910 
911  if (cstate->opts.binary)
912  {
913  /* Generate trailer for a binary copy */
914  CopySendInt16(cstate, -1);
915  /* Need to flush out the trailer */
916  CopySendEndOfRow(cstate);
917  }
918 
920 
921  if (fe_copy)
922  SendCopyEnd(cstate);
923 
924  return processed;
925 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
int file_encoding
Definition: copyto.c:78
Definition: fmgr.h:56
int null_print_len
Definition: copy.h:37
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
Relation rel
Definition: copyto.c:83
static void CopyAttributeOutCSV(CopyToState cstate, char *string, bool use_quote, bool single_attr)
Definition: copyto.c:1165
bool need_transcoding
Definition: copyto.c:79
FmgrInfo * out_functions
Definition: copyto.c:97
#define RelationGetDescr(relation)
Definition: rel.h:503
static void SendCopyEnd(CopyToState cstate)
Definition: copyto.c:156
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
static void CopySendInt16(CopyToState cstate, int16 val)
Definition: copyto.c:280
struct cursor * cur
Definition: ecpg.c:28
char * null_print_client
Definition: copy.h:38
MemoryContext rowcontext
Definition: copyto.c:98
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1032
unsigned int Oid
Definition: postgres_ext.h:31
char * null_print
Definition: copy.h:36
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:749
signed int int32
Definition: c.h:429
static void CopyOneRowTo(CopyToState cstate, TupleTableSlot *slot)
Definition: copyto.c:931
QueryDesc * queryDesc
Definition: copyto.c:84
static void SendCopyBegin(CopyToState cstate)
Definition: copyto.c:139
List * attnumlist
Definition: copyto.c:85
NameData attname
Definition: pg_attribute.h:41
static TableScanDesc table_beginscan(Relation rel, Snapshot snapshot, int nkeys, struct ScanKeyData *key)
Definition: tableam.h:883
#define lfirst_int(lc)
Definition: pg_list.h:170
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count, bool execute_once)
Definition: execMain.c:298
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
bool binary
Definition: copy.h:32
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
bool header_line
Definition: copy.h:35
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void CopySendInt32(CopyToState cstate, int32 val)
Definition: copyto.c:268
TupleDesc tupDesc
Definition: execdesc.h:47
StringInfo fe_msgbuf
Definition: copyto.c:76
void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
Definition: lsyscache.c:2920
char * delim
Definition: copy.h:39
static void CopySendData(CopyToState cstate, const void *databuf, int datasize)
Definition: copyto.c:175
#define PROGRESS_COPY_TUPLES_PROCESSED
Definition: progress.h:139
int16 attnum
Definition: pg_attribute.h:83
void pgstat_progress_update_param(int index, int64 val)
static const char BinarySignature[11]
Definition: copyto.c:112
static int list_length(const List *l)
Definition: pg_list.h:149
CopyFormatOptions opts
Definition: copyto.c:89
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
DestReceiver * dest
Definition: execdesc.h:41
void * palloc(Size size)
Definition: mcxt.c:1062
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
#define NameStr(name)
Definition: c.h:681
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
CommandDest whereToSendOutput
Definition: postgres.c:92
char * filename
Definition: copyto.c:86
static void CopySendEndOfRow(CopyToState cstate)
Definition: copyto.c:193

◆ EndCopy()

static void EndCopy ( CopyToState  cstate)
static

Definition at line 317 of file copyto.c.

References ClosePipeToProgram(), CopyToStateData::copy_file, CopyToStateData::copycontext, ereport, errcode_for_file_access(), errmsg(), ERROR, CopyToStateData::filename, FreeFile(), CopyToStateData::is_program, MemoryContextDelete(), pfree(), and pgstat_progress_end_command().

Referenced by EndCopyTo().

318 {
319  if (cstate->is_program)
320  {
321  ClosePipeToProgram(cstate);
322  }
323  else
324  {
325  if (cstate->filename != NULL && FreeFile(cstate->copy_file))
326  ereport(ERROR,
328  errmsg("could not close file \"%s\": %m",
329  cstate->filename)));
330  }
331 
333 
335  pfree(cstate);
336 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
FILE * copy_file
Definition: copyto.c:75
void pgstat_progress_end_command(void)
bool is_program
Definition: copyto.c:87
void pfree(void *pointer)
Definition: mcxt.c:1169
#define ERROR
Definition: elog.h:46
MemoryContext copycontext
Definition: copyto.c:95
static void ClosePipeToProgram(CopyToState cstate)
Definition: copyto.c:292
int errcode_for_file_access(void)
Definition: elog.c:721
#define ereport(elevel,...)
Definition: elog.h:157
int FreeFile(FILE *file)
Definition: fd.c:2616
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * filename
Definition: copyto.c:86

◆ EndCopyTo()

void EndCopyTo ( CopyToState  cstate)

Definition at line 754 of file copyto.c.

References EndCopy(), ExecutorEnd(), ExecutorFinish(), FreeQueryDesc(), PopActiveSnapshot(), and CopyToStateData::queryDesc.

Referenced by DoCopy().

755 {
756  if (cstate->queryDesc != NULL)
757  {
758  /* Close down the query and free resources. */
759  ExecutorFinish(cstate->queryDesc);
760  ExecutorEnd(cstate->queryDesc);
761  FreeQueryDesc(cstate->queryDesc);
763  }
764 
765  /* Clean up storage */
766  EndCopy(cstate);
767 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
static void EndCopy(CopyToState cstate)
Definition: copyto.c:317
QueryDesc * queryDesc
Definition: copyto.c:84
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:459
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:399

◆ SendCopyBegin()

static void SendCopyBegin ( CopyToState  cstate)
static

Definition at line 139 of file copyto.c.

References CopyToStateData::attnumlist, CopyFormatOptions::binary, buf, CopyToStateData::copy_dest, COPY_FRONTEND, format, i, list_length(), CopyToStateData::opts, pq_beginmessage(), pq_endmessage(), pq_sendbyte(), and pq_sendint16().

Referenced by DoCopyTo().

140 {
142  int natts = list_length(cstate->attnumlist);
143  int16 format = (cstate->opts.binary ? 1 : 0);
144  int i;
145 
146  pq_beginmessage(&buf, 'H');
147  pq_sendbyte(&buf, format); /* overall format */
148  pq_sendint16(&buf, natts);
149  for (i = 0; i < natts; i++)
150  pq_sendint16(&buf, format); /* per-column formats */
151  pq_endmessage(&buf);
152  cstate->copy_dest = COPY_FRONTEND;
153 }
signed short int16
Definition: c.h:428
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
List * attnumlist
Definition: copyto.c:85
bool binary
Definition: copy.h:32
static char * buf
Definition: pg_test_fsync.c:68
CopyDest copy_dest
Definition: copyto.c:74
static int list_length(const List *l)
Definition: pg_list.h:149
CopyFormatOptions opts
Definition: copyto.c:89
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
int i
static char format

◆ SendCopyEnd()

static void SendCopyEnd ( CopyToState  cstate)
static

Definition at line 156 of file copyto.c.

References Assert, CopyToStateData::fe_msgbuf, StringInfoData::len, and pq_putemptymessage().

Referenced by DoCopyTo().

157 {
158  /* Shouldn't have any unsent data */
159  Assert(cstate->fe_msgbuf->len == 0);
160  /* Send Copy Done message */
161  pq_putemptymessage('c');
162 }
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
StringInfo fe_msgbuf
Definition: copyto.c:76
#define Assert(condition)
Definition: c.h:804

Variable Documentation

◆ BinarySignature

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

Definition at line 112 of file copyto.c.

Referenced by DoCopyTo().