PostgreSQL Source Code  git master
copyto.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * copyto.c
4  * COPY <table> TO file/program/client
5  *
6  * Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/commands/copyto.c
12  *
13  *-------------------------------------------------------------------------
14  */
15 #include "postgres.h"
16 
17 #include <ctype.h>
18 #include <unistd.h>
19 #include <sys/stat.h>
20 
21 #include "access/heapam.h"
22 #include "access/htup_details.h"
23 #include "access/tableam.h"
24 #include "access/xact.h"
25 #include "access/xlog.h"
26 #include "commands/copy.h"
27 #include "commands/progress.h"
28 #include "executor/execdesc.h"
29 #include "executor/executor.h"
30 #include "executor/tuptable.h"
31 #include "libpq/libpq.h"
32 #include "libpq/pqformat.h"
33 #include "mb/pg_wchar.h"
34 #include "miscadmin.h"
35 #include "optimizer/optimizer.h"
36 #include "pgstat.h"
37 #include "rewrite/rewriteHandler.h"
38 #include "storage/fd.h"
39 #include "tcop/tcopprot.h"
40 #include "utils/lsyscache.h"
41 #include "utils/memutils.h"
42 #include "utils/partcache.h"
43 #include "utils/rel.h"
44 #include "utils/snapmgr.h"
45 
46 /*
47  * Represents the different dest cases we need to worry about at
48  * the bottom level
49  */
50 typedef enum CopyDest
51 {
52  COPY_FILE, /* to file (or a piped program) */
53  COPY_FRONTEND, /* to frontend */
54 } CopyDest;
55 
56 /*
57  * This struct contains all the state variables used throughout a COPY TO
58  * operation.
59  *
60  * Multi-byte encodings: all supported client-side encodings encode multi-byte
61  * characters by having the first byte's high bit set. Subsequent bytes of the
62  * character can have the high bit not set. When scanning data in such an
63  * encoding to look for a match to a single-byte (ie ASCII) character, we must
64  * use the full pg_encoding_mblen() machinery to skip over multibyte
65  * characters, else we might find a false match to a trailing byte. In
66  * supported server encodings, there is no possibility of a false match, and
67  * it's faster to make useless comparisons to trailing bytes than it is to
68  * invoke pg_encoding_mblen() to skip over them. encoding_embeds_ascii is true
69  * when we have to do it the hard way.
70  */
71 typedef struct CopyToStateData
72 {
73  /* low-level state data */
74  CopyDest copy_dest; /* type of copy source/destination */
75  FILE *copy_file; /* used if copy_dest == COPY_FILE */
76  StringInfo fe_msgbuf; /* used for all dests during COPY TO */
77 
78  int file_encoding; /* file or remote side's character encoding */
79  bool need_transcoding; /* file encoding diff from server? */
80  bool encoding_embeds_ascii; /* ASCII can be non-first byte? */
81 
82  /* parameters from the COPY command */
83  Relation rel; /* relation to copy to */
84  QueryDesc *queryDesc; /* executable query to copy from */
85  List *attnumlist; /* integer list of attnums to copy */
86  char *filename; /* filename, or NULL for STDOUT */
87  bool is_program; /* is 'filename' a program to popen? */
88 
90  Node *whereClause; /* WHERE condition (or NULL) */
91 
92  /*
93  * Working state
94  */
95  MemoryContext copycontext; /* per-copy execution context */
96 
97  FmgrInfo *out_functions; /* lookup info for output functions */
98  MemoryContext rowcontext; /* per-row evaluation context */
99  uint64 bytes_processed; /* number of bytes processed so far */
100 
102 
103 /* DestReceiver for COPY (query) TO */
104 typedef struct
105 {
106  DestReceiver pub; /* publicly-known function pointers */
107  CopyToState cstate; /* CopyToStateData for the command */
108  uint64 processed; /* # of tuples processed */
109 } DR_copy;
110 
111 /* NOTE: there's a copy of this in copyfromparse.c */
112 static const char BinarySignature[11] = "PGCOPY\n\377\r\n\0";
113 
114 
115 /* non-export function prototypes */
116 static void EndCopy(CopyToState cstate);
117 static void ClosePipeToProgram(CopyToState cstate);
118 static void CopyOneRowTo(CopyToState cstate, TupleTableSlot *slot);
119 static void CopyAttributeOutText(CopyToState cstate, char *string);
120 static void CopyAttributeOutCSV(CopyToState cstate, char *string,
121  bool use_quote, bool single_attr);
122 
123 /* Low-level communications functions */
124 static void SendCopyBegin(CopyToState cstate);
125 static void SendCopyEnd(CopyToState cstate);
126 static void CopySendData(CopyToState cstate, const void *databuf, int datasize);
127 static void CopySendString(CopyToState cstate, const char *str);
128 static void CopySendChar(CopyToState cstate, char c);
129 static void CopySendEndOfRow(CopyToState cstate);
130 static void CopySendInt32(CopyToState cstate, int32 val);
131 static void CopySendInt16(CopyToState cstate, int16 val);
132 
133 
134 /*
135  * Send copy start/stop messages for frontend copies. These have changed
136  * in past protocol redesigns.
137  */
138 static void
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 }
154 
155 static void
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 }
163 
164 /*----------
165  * CopySendData sends output data to the destination (file or frontend)
166  * CopySendString does the same for null-terminated strings
167  * CopySendChar does the same for single characters
168  * CopySendEndOfRow does the appropriate thing at end of each data row
169  * (data is not actually flushed except by CopySendEndOfRow)
170  *
171  * NB: no data conversion is applied by these functions
172  *----------
173  */
174 static void
175 CopySendData(CopyToState cstate, const void *databuf, int datasize)
176 {
177  appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
178 }
179 
180 static void
181 CopySendString(CopyToState cstate, const char *str)
182 {
183  appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
184 }
185 
186 static void
188 {
190 }
191 
192 static void
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 }
259 
260 /*
261  * These functions do apply some data conversion
262  */
263 
264 /*
265  * CopySendInt32 sends an int32 in network byte order
266  */
267 static inline void
269 {
270  uint32 buf;
271 
272  buf = pg_hton32((uint32) val);
273  CopySendData(cstate, &buf, sizeof(buf));
274 }
275 
276 /*
277  * CopySendInt16 sends an int16 in network byte order
278  */
279 static inline void
281 {
282  uint16 buf;
283 
284  buf = pg_hton16((uint16) val);
285  CopySendData(cstate, &buf, sizeof(buf));
286 }
287 
288 /*
289  * Closes the pipe to an external program, checking the pclose() return code.
290  */
291 static void
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 }
312 
313 /*
314  * Release resources allocated in a cstate for COPY TO/FROM.
315  */
316 static void
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 }
337 
338 /*
339  * Setup CopyToState to read tuples from a table or a query for COPY TO.
340  */
343  Relation rel,
344  RawStmt *raw_query,
345  Oid queryRelId,
346  const char *filename,
347  bool is_program,
348  List *attnamelist,
349  List *options)
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  */
696  if (!is_absolute_path(filename))
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 }
749 
750 /*
751  * Clean up storage and release resources for COPY TO.
752  */
753 void
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 }
768 
769 /*
770  * Copy from relation or query TO file.
771  */
772 uint64
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 }
926 
927 /*
928  * Emit one row during DoCopyTo().
929  */
930 static void
932 {
933  bool need_delim = false;
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 }
1001 
1002 /*
1003  * Send text representation of one attribute, with conversion and escaping
1004  */
1005 #define DUMPSOFAR() \
1006  do { \
1007  if (ptr > start) \
1008  CopySendData(cstate, start, ptr - start); \
1009  } while (0)
1010 
1011 static void
1012 CopyAttributeOutText(CopyToState cstate, char *string)
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 }
1159 
1160 /*
1161  * Send text representation of one attribute, with conversion and
1162  * CSV-style escaping
1163  */
1164 static void
1165 CopyAttributeOutCSV(CopyToState cstate, char *string,
1166  bool use_quote, bool single_attr)
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 }
1245 
1246 /*
1247  * copy_dest_startup --- executor startup
1248  */
1249 static void
1250 copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
1251 {
1252  /* no-op */
1253 }
1254 
1255 /*
1256  * copy_dest_receive --- receive one tuple
1257  */
1258 static bool
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 }
1273 
1274 /*
1275  * copy_dest_shutdown --- executor end
1276  */
1277 static void
1279 {
1280  /* no-op */
1281 }
1282 
1283 /*
1284  * copy_dest_destroy --- release DestReceiver object
1285  */
1286 static void
1288 {
1289  pfree(self);
1290 }
1291 
1292 /*
1293  * CreateCopyDestReceiver -- create a suitable DestReceiver object
1294  */
1295 DestReceiver *
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 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
int file_encoding
Definition: copyto.c:78
signed short int16
Definition: c.h:428
#define NIL
Definition: pg_list.h:65
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
Definition: fmgr.h:56
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:743
int null_print_len
Definition: copy.h:37
#define IsA(nodeptr, _type_)
Definition: nodes.h:589
#define PROGRESS_COPY_COMMAND_TO
Definition: progress.h:146
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define PROGRESS_COPY_TYPE_FILE
Definition: progress.h:149
int errhint(const char *fmt,...)
Definition: elog.c:1156
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2854
#define VARDATA(PTR)
Definition: postgres.h:315
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
FILE * copy_file
Definition: copyto.c:75
FmgrInfo * out_functions
Definition: copyto.c:97
#define RelationGetDescr(relation)
Definition: rel.h:503
static void SendCopyEnd(CopyToState cstate)
Definition: copyto.c:156
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
#define PROGRESS_COPY_COMMAND
Definition: progress.h:141
#define VARSIZE(PTR)
Definition: postgres.h:316
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define VARHDRSZ
Definition: c.h:627
List * relationOids
Definition: plannodes.h:80
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define pg_hton16(x)
Definition: pg_bswap.h:120
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
bool * force_quote_flags
Definition: copy.h:44
#define S_IWOTH
Definition: win32_port.h:315
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:130
DestReceiver pub
Definition: copyto.c:106
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:801
static void CopySendInt16(CopyToState cstate, int16 val)
Definition: copyto.c:280
Definition: nodes.h:538
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:698
#define PG_BINARY_W
Definition: c.h:1274
char * null_print_client
Definition: copy.h:38
uint64 bytes_processed
Definition: copyto.c:99
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
List * force_notnull
Definition: copy.h:45
Datum * tts_values
Definition: tuptable.h:126
MemoryContext rowcontext
Definition: copyto.c:98
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:143
void PopActiveSnapshot(void)
Definition: snapmgr.c:774
static void copy_dest_destroy(DestReceiver *self)
Definition: copyto.c:1287
bool force_quote_all
Definition: copy.h:43
static bool table_scan_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
Definition: tableam.h:1032
Form_pg_class rd_rel
Definition: rel.h:109
unsigned int Oid
Definition: postgres_ext.h:31
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
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:754
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
void pgstat_progress_end_command(void)
bool is_program
Definition: copyto.c:87
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
static void EndCopy(CopyToState cstate)
Definition: copyto.c:317
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
int ClosePipeStream(FILE *file)
Definition: fd.c:2869
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1573
static void CopyOneRowTo(CopyToState cstate, TupleTableSlot *slot)
Definition: copyto.c:931
QueryDesc * queryDesc
Definition: copyto.c:84
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
static void SendCopyBegin(CopyToState cstate)
Definition: copyto.c:139
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:459
char * quote
Definition: copy.h:40
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:128
#define fstat
Definition: win32_port.h:282
List * attnumlist
Definition: copyto.c:85
unsigned short uint16
Definition: c.h:440
void pfree(void *pointer)
Definition: mcxt.c:1169
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1156
#define ERROR
Definition: elog.h:46
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
#define pg_hton32(x)
Definition: pg_bswap.h:121
MemoryContext copycontext
Definition: copyto.c:95
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
#define PROGRESS_COPY_TYPE
Definition: progress.h:142
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:731
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
bool binary
Definition: copy.h:32
List * force_null
Definition: copy.h:47
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
#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
bool csv_mode
Definition: copy.h:34
char * c
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
static void ClosePipeToProgram(CopyToState cstate)
Definition: copyto.c:292
static char * buf
Definition: pg_test_fsync.c:68
bool * tts_isnull
Definition: tuptable.h:128
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
int errcode_for_file_access(void)
Definition: elog.c:721
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1914
bool header_line
Definition: copy.h:35
#define is_absolute_path(filename)
Definition: port.h:86
char string[11]
Definition: preproc-type.c:46
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2460
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copyto.c:1259
#define RelationGetRelationName(relation)
Definition: rel.h:511
#define S_IWGRP
Definition: win32_port.h:303
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
unsigned int uint32
Definition: c.h:441
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1634
static void CopySendString(CopyToState cstate, const char *str)
Definition: copyto.c:181
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:2563
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copyto.c:1250
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:399
CopyDest copy_dest
Definition: copyto.c:74
static void CopySendInt32(CopyToState cstate, int32 val)
Definition: copyto.c:268
struct CopyToStateData CopyToStateData
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
StringInfo fe_msgbuf
Definition: copyto.c:76
#define PG_FINALLY()
Definition: elog.h:330
void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
Definition: lsyscache.c:2920
void * palloc0(Size size)
Definition: mcxt.c:1093
List * force_quote
Definition: copy.h:42
uintptr_t Datum
Definition: postgres.h:411
char * delim
Definition: copy.h:39
#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 DUMPSOFAR()
Definition: copyto.c:1005
unsigned short st_mode
Definition: win32_port.h:268
static void CopySendData(CopyToState cstate, const void *databuf, int datasize)
Definition: copyto.c:175
#define PROGRESS_COPY_TUPLES_PROCESSED
Definition: progress.h:139
#define InvalidOid
Definition: postgres_ext.h:36
CopyToState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
Definition: copyto.c:342
int16 attnum
Definition: pg_attribute.h:83
static struct @143 value
#define ereport(elevel,...)
Definition: elog.h:157
CopyDest
Definition: copyto.c:50
CmdType commandType
Definition: parsenodes.h:120
CopyToState cstate
Definition: copyto.c:107
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
void pgstat_progress_update_param(int index, int64 val)
bool * force_null_flags
Definition: copy.h:48
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:650
static const char BinarySignature[11]
Definition: copyto.c:112
static int list_length(const List *l)
Definition: pg_list.h:149
static void CopyAttributeOutText(CopyToState cstate, char *string)
Definition: copyto.c:1012
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:324
int FreeFile(FILE *file)
Definition: fd.c:2659
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
char * escape
Definition: copy.h:41
DestReceiver * dest
Definition: execdesc.h:41
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2829
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
static void CopySendChar(CopyToState cstate, char c)
Definition: copyto.c:187
#define PROGRESS_COPY_BYTES_PROCESSED
Definition: progress.h:137
int i
DestReceiver * CreateCopyDestReceiver(void)
Definition: copyto.c:1296
Node * whereClause
Definition: copyto.c:90
#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
Definition: c.h:621
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static char format
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:49
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:773
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
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227
long val
Definition: informix.c:664
#define PG_END_TRY()
Definition: elog.h:338
static void CopySendEndOfRow(CopyToState cstate)
Definition: copyto.c:193
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:333
static void copy_dest_shutdown(DestReceiver *self)
Definition: copyto.c:1278
uint64 processed
Definition: copyto.c:108
bool * force_notnull_flags
Definition: copy.h:46