PostgreSQL Source Code  git master
copy.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * copy.c
4  * Implements the COPY utility command
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  * src/backend/commands/copy.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/sysattr.h"
22 #include "access/table.h"
23 #include "access/xact.h"
24 #include "catalog/pg_authid.h"
25 #include "commands/copy.h"
26 #include "commands/defrem.h"
27 #include "executor/executor.h"
28 #include "mb/pg_wchar.h"
29 #include "miscadmin.h"
30 #include "nodes/makefuncs.h"
31 #include "optimizer/optimizer.h"
32 #include "parser/parse_coerce.h"
33 #include "parser/parse_collate.h"
34 #include "parser/parse_expr.h"
35 #include "parser/parse_relation.h"
36 #include "rewrite/rewriteHandler.h"
37 #include "utils/acl.h"
38 #include "utils/builtins.h"
39 #include "utils/lsyscache.h"
40 #include "utils/memutils.h"
41 #include "utils/rel.h"
42 #include "utils/rls.h"
43 
44 /*
45  * DoCopy executes the SQL COPY statement
46  *
47  * Either unload or reload contents of table <relation>, depending on <from>.
48  * (<from> = true means we are inserting into the table.) In the "TO" case
49  * we also support copying the output of an arbitrary SELECT, INSERT, UPDATE
50  * or DELETE query.
51  *
52  * If <pipe> is false, transfer is between the table and the file named
53  * <filename>. Otherwise, transfer is between the table and our regular
54  * input/output stream. The latter could be either stdin/stdout or a
55  * socket, depending on whether we're running under Postmaster control.
56  *
57  * Do not allow a Postgres user without the 'pg_read_server_files' or
58  * 'pg_write_server_files' role to read from or write to a file.
59  *
60  * Do not allow the copy if user doesn't have proper permission to access
61  * the table or the specifically requested columns.
62  */
63 void
64 DoCopy(ParseState *pstate, const CopyStmt *stmt,
65  int stmt_location, int stmt_len,
66  uint64 *processed)
67 {
68  bool is_from = stmt->is_from;
69  bool pipe = (stmt->filename == NULL);
70  Relation rel;
71  Oid relid;
72  RawStmt *query = NULL;
73  Node *whereClause = NULL;
74 
75  /*
76  * Disallow COPY to/from file or program except to users with the
77  * appropriate role.
78  */
79  if (!pipe)
80  {
81  if (stmt->is_program)
82  {
83  if (!has_privs_of_role(GetUserId(), ROLE_PG_EXECUTE_SERVER_PROGRAM))
84  ereport(ERROR,
85  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
86  errmsg("must be superuser or have privileges of the pg_execute_server_program role to COPY to or from an external program"),
87  errhint("Anyone can COPY to stdout or from stdin. "
88  "psql's \\copy command also works for anyone.")));
89  }
90  else
91  {
92  if (is_from && !has_privs_of_role(GetUserId(), ROLE_PG_READ_SERVER_FILES))
93  ereport(ERROR,
94  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
95  errmsg("must be superuser or have privileges of the pg_read_server_files role to COPY from a file"),
96  errhint("Anyone can COPY to stdout or from stdin. "
97  "psql's \\copy command also works for anyone.")));
98 
99  if (!is_from && !has_privs_of_role(GetUserId(), ROLE_PG_WRITE_SERVER_FILES))
100  ereport(ERROR,
101  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
102  errmsg("must be superuser or have privileges of the pg_write_server_files role to COPY to a file"),
103  errhint("Anyone can COPY to stdout or from stdin. "
104  "psql's \\copy command also works for anyone.")));
105  }
106  }
107 
108  if (stmt->relation)
109  {
110  LOCKMODE lockmode = is_from ? RowExclusiveLock : AccessShareLock;
111  ParseNamespaceItem *nsitem;
112  RangeTblEntry *rte;
113  TupleDesc tupDesc;
114  List *attnums;
115  ListCell *cur;
116 
117  Assert(!stmt->query);
118 
119  /* Open and lock the relation, using the appropriate lock type. */
120  rel = table_openrv(stmt->relation, lockmode);
121 
122  relid = RelationGetRelid(rel);
123 
124  nsitem = addRangeTableEntryForRelation(pstate, rel, lockmode,
125  NULL, false, false);
126  rte = nsitem->p_rte;
127  rte->requiredPerms = (is_from ? ACL_INSERT : ACL_SELECT);
128 
129  if (stmt->whereClause)
130  {
131  /* add nsitem to query namespace */
132  addNSItemToQuery(pstate, nsitem, false, true, true);
133 
134  /* Transform the raw expression tree */
135  whereClause = transformExpr(pstate, stmt->whereClause, EXPR_KIND_COPY_WHERE);
136 
137  /* Make sure it yields a boolean result. */
138  whereClause = coerce_to_boolean(pstate, whereClause, "WHERE");
139 
140  /* we have to fix its collations too */
141  assign_expr_collations(pstate, whereClause);
142 
143  whereClause = eval_const_expressions(NULL, whereClause);
144 
145  whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
146  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
147  }
148 
149  tupDesc = RelationGetDescr(rel);
150  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
151  foreach(cur, attnums)
152  {
153  int attno = lfirst_int(cur) -
155 
156  if (is_from)
157  rte->insertedCols = bms_add_member(rte->insertedCols, attno);
158  else
159  rte->selectedCols = bms_add_member(rte->selectedCols, attno);
160  }
161  ExecCheckRTPerms(pstate->p_rtable, true);
162 
163  /*
164  * Permission check for row security policies.
165  *
166  * check_enable_rls will ereport(ERROR) if the user has requested
167  * something invalid and will otherwise indicate if we should enable
168  * RLS (returns RLS_ENABLED) or not for this COPY statement.
169  *
170  * If the relation has a row security policy and we are to apply it
171  * then perform a "query" copy and allow the normal query processing
172  * to handle the policies.
173  *
174  * If RLS is not enabled for this, then just fall through to the
175  * normal non-filtering relation handling.
176  */
177  if (check_enable_rls(rte->relid, InvalidOid, false) == RLS_ENABLED)
178  {
180  ColumnRef *cr;
181  ResTarget *target;
182  RangeVar *from;
183  List *targetList = NIL;
184 
185  if (is_from)
186  ereport(ERROR,
187  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
188  errmsg("COPY FROM not supported with row-level security"),
189  errhint("Use INSERT statements instead.")));
190 
191  /*
192  * Build target list
193  *
194  * If no columns are specified in the attribute list of the COPY
195  * command, then the target list is 'all' columns. Therefore, '*'
196  * should be used as the target list for the resulting SELECT
197  * statement.
198  *
199  * In the case that columns are specified in the attribute list,
200  * create a ColumnRef and ResTarget for each column and add them
201  * to the target list for the resulting SELECT statement.
202  */
203  if (!stmt->attlist)
204  {
205  cr = makeNode(ColumnRef);
207  cr->location = -1;
208 
209  target = makeNode(ResTarget);
210  target->name = NULL;
211  target->indirection = NIL;
212  target->val = (Node *) cr;
213  target->location = -1;
214 
215  targetList = list_make1(target);
216  }
217  else
218  {
219  ListCell *lc;
220 
221  foreach(lc, stmt->attlist)
222  {
223  /*
224  * Build the ColumnRef for each column. The ColumnRef
225  * 'fields' property is a String node that corresponds to
226  * the column name respectively.
227  */
228  cr = makeNode(ColumnRef);
229  cr->fields = list_make1(lfirst(lc));
230  cr->location = -1;
231 
232  /* Build the ResTarget and add the ColumnRef to it. */
233  target = makeNode(ResTarget);
234  target->name = NULL;
235  target->indirection = NIL;
236  target->val = (Node *) cr;
237  target->location = -1;
238 
239  /* Add each column to the SELECT statement's target list */
240  targetList = lappend(targetList, target);
241  }
242  }
243 
244  /*
245  * Build RangeVar for from clause, fully qualified based on the
246  * relation which we have opened and locked.
247  */
250  -1);
251 
252  /* Build query */
254  select->targetList = targetList;
255  select->fromClause = list_make1(from);
256 
257  query = makeNode(RawStmt);
258  query->stmt = (Node *) select;
259  query->stmt_location = stmt_location;
260  query->stmt_len = stmt_len;
261 
262  /*
263  * Close the relation for now, but keep the lock on it to prevent
264  * changes between now and when we start the query-based COPY.
265  *
266  * We'll reopen it later as part of the query-based COPY.
267  */
268  table_close(rel, NoLock);
269  rel = NULL;
270  }
271  }
272  else
273  {
274  Assert(stmt->query);
275 
276  query = makeNode(RawStmt);
277  query->stmt = stmt->query;
278  query->stmt_location = stmt_location;
279  query->stmt_len = stmt_len;
280 
281  relid = InvalidOid;
282  rel = NULL;
283  }
284 
285  if (is_from)
286  {
287  CopyFromState cstate;
288 
289  Assert(rel);
290 
291  /* check read-only transaction and parallel mode */
292  if (XactReadOnly && !rel->rd_islocaltemp)
293  PreventCommandIfReadOnly("COPY FROM");
294 
295  cstate = BeginCopyFrom(pstate, rel, whereClause,
296  stmt->filename, stmt->is_program,
297  NULL, stmt->attlist, stmt->options);
298  *processed = CopyFrom(cstate); /* copy from file to database */
299  EndCopyFrom(cstate);
300  }
301  else
302  {
303  CopyToState cstate;
304 
305  cstate = BeginCopyTo(pstate, rel, query, relid,
306  stmt->filename, stmt->is_program,
307  stmt->attlist, stmt->options);
308  *processed = DoCopyTo(cstate); /* copy from database to file */
309  EndCopyTo(cstate);
310  }
311 
312  if (rel != NULL)
313  table_close(rel, NoLock);
314 }
315 
316 /*
317  * Extract a CopyHeaderChoice value from a DefElem. This is like
318  * defGetBoolean() but also accepts the special value "match".
319  */
320 static CopyHeaderChoice
322 {
323  /*
324  * If no parameter given, assume "true" is meant.
325  */
326  if (def->arg == NULL)
327  return COPY_HEADER_TRUE;
328 
329  /*
330  * Allow 0, 1, "true", "false", "on", "off", or "match".
331  */
332  switch (nodeTag(def->arg))
333  {
334  case T_Integer:
335  switch (intVal(def->arg))
336  {
337  case 0:
338  return COPY_HEADER_FALSE;
339  case 1:
340  return COPY_HEADER_TRUE;
341  default:
342  /* otherwise, error out below */
343  break;
344  }
345  break;
346  default:
347  {
348  char *sval = defGetString(def);
349 
350  /*
351  * The set of strings accepted here should match up with the
352  * grammar's opt_boolean_or_string production.
353  */
354  if (pg_strcasecmp(sval, "true") == 0)
355  return COPY_HEADER_TRUE;
356  if (pg_strcasecmp(sval, "false") == 0)
357  return COPY_HEADER_FALSE;
358  if (pg_strcasecmp(sval, "on") == 0)
359  return COPY_HEADER_TRUE;
360  if (pg_strcasecmp(sval, "off") == 0)
361  return COPY_HEADER_FALSE;
362  if (pg_strcasecmp(sval, "match") == 0)
363  return COPY_HEADER_MATCH;
364  }
365  break;
366  }
367  ereport(ERROR,
368  (errcode(ERRCODE_SYNTAX_ERROR),
369  errmsg("%s requires a Boolean value or \"match\"",
370  def->defname)));
371  return COPY_HEADER_FALSE; /* keep compiler quiet */
372 }
373 
374 /*
375  * Process the statement option list for COPY.
376  *
377  * Scan the options list (a list of DefElem) and transpose the information
378  * into *opts_out, applying appropriate error checking.
379  *
380  * If 'opts_out' is not NULL, it is assumed to be filled with zeroes initially.
381  *
382  * This is exported so that external users of the COPY API can sanity-check
383  * a list of options. In that usage, 'opts_out' can be passed as NULL and
384  * the collected data is just leaked until CurrentMemoryContext is reset.
385  *
386  * Note that additional checking, such as whether column names listed in FORCE
387  * QUOTE actually exist, has to be applied later. This just checks for
388  * self-consistency of the options list.
389  */
390 void
392  CopyFormatOptions *opts_out,
393  bool is_from,
394  List *options)
395 {
396  bool format_specified = false;
397  bool freeze_specified = false;
398  bool header_specified = false;
399  ListCell *option;
400 
401  /* Support external use for option sanity checking */
402  if (opts_out == NULL)
403  opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
404 
405  opts_out->file_encoding = -1;
406 
407  /* Extract options from the statement node tree */
408  foreach(option, options)
409  {
410  DefElem *defel = lfirst_node(DefElem, option);
411 
412  if (strcmp(defel->defname, "format") == 0)
413  {
414  char *fmt = defGetString(defel);
415 
416  if (format_specified)
417  errorConflictingDefElem(defel, pstate);
418  format_specified = true;
419  if (strcmp(fmt, "text") == 0)
420  /* default format */ ;
421  else if (strcmp(fmt, "csv") == 0)
422  opts_out->csv_mode = true;
423  else if (strcmp(fmt, "binary") == 0)
424  opts_out->binary = true;
425  else
426  ereport(ERROR,
427  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
428  errmsg("COPY format \"%s\" not recognized", fmt),
429  parser_errposition(pstate, defel->location)));
430  }
431  else if (strcmp(defel->defname, "freeze") == 0)
432  {
433  if (freeze_specified)
434  errorConflictingDefElem(defel, pstate);
435  freeze_specified = true;
436  opts_out->freeze = defGetBoolean(defel);
437  }
438  else if (strcmp(defel->defname, "delimiter") == 0)
439  {
440  if (opts_out->delim)
441  errorConflictingDefElem(defel, pstate);
442  opts_out->delim = defGetString(defel);
443  }
444  else if (strcmp(defel->defname, "null") == 0)
445  {
446  if (opts_out->null_print)
447  errorConflictingDefElem(defel, pstate);
448  opts_out->null_print = defGetString(defel);
449  }
450  else if (strcmp(defel->defname, "header") == 0)
451  {
452  if (header_specified)
453  errorConflictingDefElem(defel, pstate);
454  header_specified = true;
455  opts_out->header_line = defGetCopyHeaderChoice(defel);
456  }
457  else if (strcmp(defel->defname, "quote") == 0)
458  {
459  if (opts_out->quote)
460  errorConflictingDefElem(defel, pstate);
461  opts_out->quote = defGetString(defel);
462  }
463  else if (strcmp(defel->defname, "escape") == 0)
464  {
465  if (opts_out->escape)
466  errorConflictingDefElem(defel, pstate);
467  opts_out->escape = defGetString(defel);
468  }
469  else if (strcmp(defel->defname, "force_quote") == 0)
470  {
471  if (opts_out->force_quote || opts_out->force_quote_all)
472  errorConflictingDefElem(defel, pstate);
473  if (defel->arg && IsA(defel->arg, A_Star))
474  opts_out->force_quote_all = true;
475  else if (defel->arg && IsA(defel->arg, List))
476  opts_out->force_quote = castNode(List, defel->arg);
477  else
478  ereport(ERROR,
479  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
480  errmsg("argument to option \"%s\" must be a list of column names",
481  defel->defname),
482  parser_errposition(pstate, defel->location)));
483  }
484  else if (strcmp(defel->defname, "force_not_null") == 0)
485  {
486  if (opts_out->force_notnull)
487  errorConflictingDefElem(defel, pstate);
488  if (defel->arg && IsA(defel->arg, List))
489  opts_out->force_notnull = castNode(List, defel->arg);
490  else
491  ereport(ERROR,
492  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
493  errmsg("argument to option \"%s\" must be a list of column names",
494  defel->defname),
495  parser_errposition(pstate, defel->location)));
496  }
497  else if (strcmp(defel->defname, "force_null") == 0)
498  {
499  if (opts_out->force_null)
500  errorConflictingDefElem(defel, pstate);
501  if (defel->arg && IsA(defel->arg, List))
502  opts_out->force_null = castNode(List, defel->arg);
503  else
504  ereport(ERROR,
505  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
506  errmsg("argument to option \"%s\" must be a list of column names",
507  defel->defname),
508  parser_errposition(pstate, defel->location)));
509  }
510  else if (strcmp(defel->defname, "convert_selectively") == 0)
511  {
512  /*
513  * Undocumented, not-accessible-from-SQL option: convert only the
514  * named columns to binary form, storing the rest as NULLs. It's
515  * allowed for the column list to be NIL.
516  */
517  if (opts_out->convert_selectively)
518  errorConflictingDefElem(defel, pstate);
519  opts_out->convert_selectively = true;
520  if (defel->arg == NULL || IsA(defel->arg, List))
521  opts_out->convert_select = castNode(List, defel->arg);
522  else
523  ereport(ERROR,
524  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
525  errmsg("argument to option \"%s\" must be a list of column names",
526  defel->defname),
527  parser_errposition(pstate, defel->location)));
528  }
529  else if (strcmp(defel->defname, "encoding") == 0)
530  {
531  if (opts_out->file_encoding >= 0)
532  errorConflictingDefElem(defel, pstate);
533  opts_out->file_encoding = pg_char_to_encoding(defGetString(defel));
534  if (opts_out->file_encoding < 0)
535  ereport(ERROR,
536  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
537  errmsg("argument to option \"%s\" must be a valid encoding name",
538  defel->defname),
539  parser_errposition(pstate, defel->location)));
540  }
541  else
542  ereport(ERROR,
543  (errcode(ERRCODE_SYNTAX_ERROR),
544  errmsg("option \"%s\" not recognized",
545  defel->defname),
546  parser_errposition(pstate, defel->location)));
547  }
548 
549  /*
550  * Check for incompatible options (must do these two before inserting
551  * defaults)
552  */
553  if (opts_out->binary && opts_out->delim)
554  ereport(ERROR,
555  (errcode(ERRCODE_SYNTAX_ERROR),
556  errmsg("cannot specify DELIMITER in BINARY mode")));
557 
558  if (opts_out->binary && opts_out->null_print)
559  ereport(ERROR,
560  (errcode(ERRCODE_SYNTAX_ERROR),
561  errmsg("cannot specify NULL in BINARY mode")));
562 
563  /* Set defaults for omitted options */
564  if (!opts_out->delim)
565  opts_out->delim = opts_out->csv_mode ? "," : "\t";
566 
567  if (!opts_out->null_print)
568  opts_out->null_print = opts_out->csv_mode ? "" : "\\N";
569  opts_out->null_print_len = strlen(opts_out->null_print);
570 
571  if (opts_out->csv_mode)
572  {
573  if (!opts_out->quote)
574  opts_out->quote = "\"";
575  if (!opts_out->escape)
576  opts_out->escape = opts_out->quote;
577  }
578 
579  /* Only single-byte delimiter strings are supported. */
580  if (strlen(opts_out->delim) != 1)
581  ereport(ERROR,
582  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
583  errmsg("COPY delimiter must be a single one-byte character")));
584 
585  /* Disallow end-of-line characters */
586  if (strchr(opts_out->delim, '\r') != NULL ||
587  strchr(opts_out->delim, '\n') != NULL)
588  ereport(ERROR,
589  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
590  errmsg("COPY delimiter cannot be newline or carriage return")));
591 
592  if (strchr(opts_out->null_print, '\r') != NULL ||
593  strchr(opts_out->null_print, '\n') != NULL)
594  ereport(ERROR,
595  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
596  errmsg("COPY null representation cannot use newline or carriage return")));
597 
598  /*
599  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
600  * backslash because it would be ambiguous. We can't allow the other
601  * cases because data characters matching the delimiter must be
602  * backslashed, and certain backslash combinations are interpreted
603  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
604  * more than strictly necessary, but seems best for consistency and
605  * future-proofing. Likewise we disallow all digits though only octal
606  * digits are actually dangerous.
607  */
608  if (!opts_out->csv_mode &&
609  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
610  opts_out->delim[0]) != NULL)
611  ereport(ERROR,
612  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
613  errmsg("COPY delimiter cannot be \"%s\"", opts_out->delim)));
614 
615  /* Check header */
616  if (opts_out->binary && opts_out->header_line)
617  ereport(ERROR,
618  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
619  errmsg("cannot specify HEADER in BINARY mode")));
620 
621  /* Check quote */
622  if (!opts_out->csv_mode && opts_out->quote != NULL)
623  ereport(ERROR,
624  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
625  errmsg("COPY quote available only in CSV mode")));
626 
627  if (opts_out->csv_mode && strlen(opts_out->quote) != 1)
628  ereport(ERROR,
629  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
630  errmsg("COPY quote must be a single one-byte character")));
631 
632  if (opts_out->csv_mode && opts_out->delim[0] == opts_out->quote[0])
633  ereport(ERROR,
634  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
635  errmsg("COPY delimiter and quote must be different")));
636 
637  /* Check escape */
638  if (!opts_out->csv_mode && opts_out->escape != NULL)
639  ereport(ERROR,
640  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
641  errmsg("COPY escape available only in CSV mode")));
642 
643  if (opts_out->csv_mode && strlen(opts_out->escape) != 1)
644  ereport(ERROR,
645  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
646  errmsg("COPY escape must be a single one-byte character")));
647 
648  /* Check force_quote */
649  if (!opts_out->csv_mode && (opts_out->force_quote || opts_out->force_quote_all))
650  ereport(ERROR,
651  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
652  errmsg("COPY force quote available only in CSV mode")));
653  if ((opts_out->force_quote || opts_out->force_quote_all) && is_from)
654  ereport(ERROR,
655  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
656  errmsg("COPY force quote only available using COPY TO")));
657 
658  /* Check force_notnull */
659  if (!opts_out->csv_mode && opts_out->force_notnull != NIL)
660  ereport(ERROR,
661  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
662  errmsg("COPY force not null available only in CSV mode")));
663  if (opts_out->force_notnull != NIL && !is_from)
664  ereport(ERROR,
665  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
666  errmsg("COPY force not null only available using COPY FROM")));
667 
668  /* Check force_null */
669  if (!opts_out->csv_mode && opts_out->force_null != NIL)
670  ereport(ERROR,
671  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
672  errmsg("COPY force null available only in CSV mode")));
673 
674  if (opts_out->force_null != NIL && !is_from)
675  ereport(ERROR,
676  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
677  errmsg("COPY force null only available using COPY FROM")));
678 
679  /* Don't allow the delimiter to appear in the null string. */
680  if (strchr(opts_out->null_print, opts_out->delim[0]) != NULL)
681  ereport(ERROR,
682  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
683  errmsg("COPY delimiter must not appear in the NULL specification")));
684 
685  /* Don't allow the CSV quote char to appear in the null string. */
686  if (opts_out->csv_mode &&
687  strchr(opts_out->null_print, opts_out->quote[0]) != NULL)
688  ereport(ERROR,
689  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
690  errmsg("CSV quote character must not appear in the NULL specification")));
691 }
692 
693 /*
694  * CopyGetAttnums - build an integer list of attnums to be copied
695  *
696  * The input attnamelist is either the user-specified column list,
697  * or NIL if there was none (in which case we want all the non-dropped
698  * columns).
699  *
700  * We don't include generated columns in the generated full list and we don't
701  * allow them to be specified explicitly. They don't make sense for COPY
702  * FROM, but we could possibly allow them for COPY TO. But this way it's at
703  * least ensured that whatever we copy out can be copied back in.
704  *
705  * rel can be NULL ... it's only used for error reports.
706  */
707 List *
708 CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
709 {
710  List *attnums = NIL;
711 
712  if (attnamelist == NIL)
713  {
714  /* Generate default column list */
715  int attr_count = tupDesc->natts;
716  int i;
717 
718  for (i = 0; i < attr_count; i++)
719  {
720  if (TupleDescAttr(tupDesc, i)->attisdropped)
721  continue;
722  if (TupleDescAttr(tupDesc, i)->attgenerated)
723  continue;
724  attnums = lappend_int(attnums, i + 1);
725  }
726  }
727  else
728  {
729  /* Validate the user-supplied list and extract attnums */
730  ListCell *l;
731 
732  foreach(l, attnamelist)
733  {
734  char *name = strVal(lfirst(l));
735  int attnum;
736  int i;
737 
738  /* Lookup column name */
740  for (i = 0; i < tupDesc->natts; i++)
741  {
742  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
743 
744  if (att->attisdropped)
745  continue;
746  if (namestrcmp(&(att->attname), name) == 0)
747  {
748  if (att->attgenerated)
749  ereport(ERROR,
750  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
751  errmsg("column \"%s\" is a generated column",
752  name),
753  errdetail("Generated columns cannot be used in COPY.")));
754  attnum = att->attnum;
755  break;
756  }
757  }
758  if (attnum == InvalidAttrNumber)
759  {
760  if (rel != NULL)
761  ereport(ERROR,
762  (errcode(ERRCODE_UNDEFINED_COLUMN),
763  errmsg("column \"%s\" of relation \"%s\" does not exist",
764  name, RelationGetRelationName(rel))));
765  else
766  ereport(ERROR,
767  (errcode(ERRCODE_UNDEFINED_COLUMN),
768  errmsg("column \"%s\" does not exist",
769  name)));
770  }
771  /* Check for duplicates */
772  if (list_member_int(attnums, attnum))
773  ereport(ERROR,
774  (errcode(ERRCODE_DUPLICATE_COLUMN),
775  errmsg("column \"%s\" specified more than once",
776  name)));
777  attnums = lappend_int(attnums, attnum);
778  }
779  }
780 
781  return attnums;
782 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4951
#define InvalidAttrNumber
Definition: attnum.h:23
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:708
void DoCopy(ParseState *pstate, const CopyStmt *stmt, int stmt_location, int stmt_len, uint64 *processed)
Definition: copy.c:64
static CopyHeaderChoice defGetCopyHeaderChoice(DefElem *def)
Definition: copy.c:321
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:391
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:738
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2150
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1189
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:528
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1563
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:770
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:751
CopyToState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
Definition: copyto.c:341
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:352
struct cursor * cur
Definition: ecpg.c:28
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
const char * name
Definition: encode.c:561
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:570
CopyHeaderChoice
Definition: copy.h:27
@ COPY_HEADER_TRUE
Definition: copy.h:29
@ COPY_HEADER_FALSE
Definition: copy.h:28
@ COPY_HEADER_MATCH
Definition: copy.h:30
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
static void const char * fmt
List * lappend(List *list, void *datum)
Definition: list.c:336
List * lappend_int(List *list, int datum)
Definition: list.c:354
bool list_member_int(const List *list, int datum)
Definition: list.c:681
int LOCKMODE
Definition: lockdefs.h:26
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:720
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:423
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void * palloc0(Size size)
Definition: mcxt.c:1099
Oid GetUserId(void)
Definition: miscinit.c:492
int namestrcmp(Name name, const char *str)
Definition: name.c:247
#define IsA(nodeptr, _type_)
Definition: nodes.h:624
#define nodeTag(nodeptr)
Definition: nodes.h:578
@ T_Integer
Definition: nodes.h:308
#define makeNode(_type_)
Definition: nodes.h:621
#define castNode(_type_, nodeptr)
Definition: nodes.h:642
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)
void assign_expr_collations(ParseState *pstate, Node *expr)
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:112
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_INSERT
Definition: parsenodes.h:82
#define ACL_SELECT
Definition: parsenodes.h:83
int16 attnum
Definition: pg_attribute.h:83
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
#define lfirst(lc)
Definition: pg_list.h:169
#define lfirst_node(type, lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:65
#define lfirst_int(lc)
Definition: pg_list.h:170
#define list_make1(x1)
Definition: pg_list.h:206
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
#define RelationGetRelid(relation)
Definition: rel.h:489
#define RelationGetDescr(relation)
Definition: rel.h:515
#define RelationGetRelationName(relation)
Definition: rel.h:523
#define RelationGetNamespace(relation)
Definition: rel.h:530
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
int location
Definition: parsenodes.h:253
List * fields
Definition: parsenodes.h:252
bool force_quote_all
Definition: copy.h:54
bool freeze
Definition: copy.h:44
bool binary
Definition: copy.h:43
int null_print_len
Definition: copy.h:48
bool convert_selectively
Definition: copy.h:60
char * quote
Definition: copy.h:51
CopyHeaderChoice header_line
Definition: copy.h:46
List * force_quote
Definition: copy.h:53
char * escape
Definition: copy.h:52
char * null_print
Definition: copy.h:47
List * force_null
Definition: copy.h:58
char * delim
Definition: copy.h:50
List * convert_select
Definition: copy.h:61
bool csv_mode
Definition: copy.h:45
int file_encoding
Definition: copy.h:41
List * force_notnull
Definition: copy.h:56
bool is_program
Definition: parsenodes.h:2474
RangeVar * relation
Definition: parsenodes.h:2468
List * options
Definition: parsenodes.h:2476
bool is_from
Definition: parsenodes.h:2473
char * filename
Definition: parsenodes.h:2475
List * attlist
Definition: parsenodes.h:2471
Node * whereClause
Definition: parsenodes.h:2477
Node * query
Definition: parsenodes.h:2469
char * defname
Definition: parsenodes.h:765
int location
Definition: parsenodes.h:769
Node * arg
Definition: parsenodes.h:766
Definition: pg_list.h:51
Definition: nodes.h:574
RangeTblEntry * p_rte
Definition: parse_node.h:269
List * p_rtable
Definition: parse_node.h:183
AclMode requiredPerms
Definition: parsenodes.h:1165
Bitmapset * selectedCols
Definition: parsenodes.h:1167
Bitmapset * insertedCols
Definition: parsenodes.h:1168
int stmt_len
Definition: parsenodes.h:1905
Node * stmt
Definition: parsenodes.h:1903
int stmt_location
Definition: parsenodes.h:1904
bool rd_islocaltemp
Definition: rel.h:60
int location
Definition: parsenodes.h:474
Node * val
Definition: parsenodes.h:473
List * indirection
Definition: parsenodes.h:472
char * name
Definition: parsenodes.h:471
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:411
#define intVal(v)
Definition: value.h:69
#define strVal(v)
Definition: value.h:72
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474
bool XactReadOnly
Definition: xact.c:81