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-2024, 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 "utils/acl.h"
37 #include "utils/builtins.h"
38 #include "utils/lsyscache.h"
39 #include "utils/rel.h"
40 #include "utils/rls.h"
41 
42 /*
43  * DoCopy executes the SQL COPY statement
44  *
45  * Either unload or reload contents of table <relation>, depending on <from>.
46  * (<from> = true means we are inserting into the table.) In the "TO" case
47  * we also support copying the output of an arbitrary SELECT, INSERT, UPDATE
48  * or DELETE query.
49  *
50  * If <pipe> is false, transfer is between the table and the file named
51  * <filename>. Otherwise, transfer is between the table and our regular
52  * input/output stream. The latter could be either stdin/stdout or a
53  * socket, depending on whether we're running under Postmaster control.
54  *
55  * Do not allow a Postgres user without the 'pg_read_server_files' or
56  * 'pg_write_server_files' role to read from or write to a file.
57  *
58  * Do not allow the copy if user doesn't have proper permission to access
59  * the table or the specifically requested columns.
60  */
61 void
62 DoCopy(ParseState *pstate, const CopyStmt *stmt,
63  int stmt_location, int stmt_len,
64  uint64 *processed)
65 {
66  bool is_from = stmt->is_from;
67  bool pipe = (stmt->filename == NULL);
68  Relation rel;
69  Oid relid;
70  RawStmt *query = NULL;
71  Node *whereClause = NULL;
72 
73  /*
74  * Disallow COPY to/from file or program except to users with the
75  * appropriate role.
76  */
77  if (!pipe)
78  {
79  if (stmt->is_program)
80  {
81  if (!has_privs_of_role(GetUserId(), ROLE_PG_EXECUTE_SERVER_PROGRAM))
82  ereport(ERROR,
83  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
84  errmsg("permission denied to COPY to or from an external program"),
85  errdetail("Only roles with privileges of the \"%s\" role may COPY to or from an external program.",
86  "pg_execute_server_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("permission denied to COPY from a file"),
96  errdetail("Only roles with privileges of the \"%s\" role may COPY from a file.",
97  "pg_read_server_files"),
98  errhint("Anyone can COPY to stdout or from stdin. "
99  "psql's \\copy command also works for anyone.")));
100 
101  if (!is_from && !has_privs_of_role(GetUserId(), ROLE_PG_WRITE_SERVER_FILES))
102  ereport(ERROR,
103  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
104  errmsg("permission denied to COPY to a file"),
105  errdetail("Only roles with privileges of the \"%s\" role may COPY to a file.",
106  "pg_write_server_files"),
107  errhint("Anyone can COPY to stdout or from stdin. "
108  "psql's \\copy command also works for anyone.")));
109  }
110  }
111 
112  if (stmt->relation)
113  {
114  LOCKMODE lockmode = is_from ? RowExclusiveLock : AccessShareLock;
115  ParseNamespaceItem *nsitem;
116  RTEPermissionInfo *perminfo;
117  TupleDesc tupDesc;
118  List *attnums;
119  ListCell *cur;
120 
121  Assert(!stmt->query);
122 
123  /* Open and lock the relation, using the appropriate lock type. */
124  rel = table_openrv(stmt->relation, lockmode);
125 
126  relid = RelationGetRelid(rel);
127 
128  nsitem = addRangeTableEntryForRelation(pstate, rel, lockmode,
129  NULL, false, false);
130 
131  perminfo = nsitem->p_perminfo;
132  perminfo->requiredPerms = (is_from ? ACL_INSERT : ACL_SELECT);
133 
134  if (stmt->whereClause)
135  {
136  /* add nsitem to query namespace */
137  addNSItemToQuery(pstate, nsitem, false, true, true);
138 
139  /* Transform the raw expression tree */
140  whereClause = transformExpr(pstate, stmt->whereClause, EXPR_KIND_COPY_WHERE);
141 
142  /* Make sure it yields a boolean result. */
143  whereClause = coerce_to_boolean(pstate, whereClause, "WHERE");
144 
145  /* we have to fix its collations too */
146  assign_expr_collations(pstate, whereClause);
147 
148  whereClause = eval_const_expressions(NULL, whereClause);
149 
150  whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
151  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
152  }
153 
154  tupDesc = RelationGetDescr(rel);
155  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
156  foreach(cur, attnums)
157  {
158  int attno;
159  Bitmapset **bms;
160 
162  bms = is_from ? &perminfo->insertedCols : &perminfo->selectedCols;
163 
164  *bms = bms_add_member(*bms, attno);
165  }
166  ExecCheckPermissions(pstate->p_rtable, list_make1(perminfo), true);
167 
168  /*
169  * Permission check for row security policies.
170  *
171  * check_enable_rls will ereport(ERROR) if the user has requested
172  * something invalid and will otherwise indicate if we should enable
173  * RLS (returns RLS_ENABLED) or not for this COPY statement.
174  *
175  * If the relation has a row security policy and we are to apply it
176  * then perform a "query" copy and allow the normal query processing
177  * to handle the policies.
178  *
179  * If RLS is not enabled for this, then just fall through to the
180  * normal non-filtering relation handling.
181  */
182  if (check_enable_rls(relid, InvalidOid, false) == RLS_ENABLED)
183  {
185  ColumnRef *cr;
186  ResTarget *target;
187  RangeVar *from;
188  List *targetList = NIL;
189 
190  if (is_from)
191  ereport(ERROR,
192  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
193  errmsg("COPY FROM not supported with row-level security"),
194  errhint("Use INSERT statements instead.")));
195 
196  /*
197  * Build target list
198  *
199  * If no columns are specified in the attribute list of the COPY
200  * command, then the target list is 'all' columns. Therefore, '*'
201  * should be used as the target list for the resulting SELECT
202  * statement.
203  *
204  * In the case that columns are specified in the attribute list,
205  * create a ColumnRef and ResTarget for each column and add them
206  * to the target list for the resulting SELECT statement.
207  */
208  if (!stmt->attlist)
209  {
210  cr = makeNode(ColumnRef);
212  cr->location = -1;
213 
214  target = makeNode(ResTarget);
215  target->name = NULL;
216  target->indirection = NIL;
217  target->val = (Node *) cr;
218  target->location = -1;
219 
220  targetList = list_make1(target);
221  }
222  else
223  {
224  ListCell *lc;
225 
226  foreach(lc, stmt->attlist)
227  {
228  /*
229  * Build the ColumnRef for each column. The ColumnRef
230  * 'fields' property is a String node that corresponds to
231  * the column name respectively.
232  */
233  cr = makeNode(ColumnRef);
234  cr->fields = list_make1(lfirst(lc));
235  cr->location = -1;
236 
237  /* Build the ResTarget and add the ColumnRef to it. */
238  target = makeNode(ResTarget);
239  target->name = NULL;
240  target->indirection = NIL;
241  target->val = (Node *) cr;
242  target->location = -1;
243 
244  /* Add each column to the SELECT statement's target list */
245  targetList = lappend(targetList, target);
246  }
247  }
248 
249  /*
250  * Build RangeVar for from clause, fully qualified based on the
251  * relation which we have opened and locked. Use "ONLY" so that
252  * COPY retrieves rows from only the target table not any
253  * inheritance children, the same as when RLS doesn't apply.
254  */
257  -1);
258  from->inh = false; /* apply ONLY */
259 
260  /* Build query */
262  select->targetList = targetList;
263  select->fromClause = list_make1(from);
264 
265  query = makeNode(RawStmt);
266  query->stmt = (Node *) select;
267  query->stmt_location = stmt_location;
268  query->stmt_len = stmt_len;
269 
270  /*
271  * Close the relation for now, but keep the lock on it to prevent
272  * changes between now and when we start the query-based COPY.
273  *
274  * We'll reopen it later as part of the query-based COPY.
275  */
276  table_close(rel, NoLock);
277  rel = NULL;
278  }
279  }
280  else
281  {
282  Assert(stmt->query);
283 
284  query = makeNode(RawStmt);
285  query->stmt = stmt->query;
286  query->stmt_location = stmt_location;
287  query->stmt_len = stmt_len;
288 
289  relid = InvalidOid;
290  rel = NULL;
291  }
292 
293  if (is_from)
294  {
295  CopyFromState cstate;
296 
297  Assert(rel);
298 
299  /* check read-only transaction and parallel mode */
300  if (XactReadOnly && !rel->rd_islocaltemp)
301  PreventCommandIfReadOnly("COPY FROM");
302 
303  cstate = BeginCopyFrom(pstate, rel, whereClause,
304  stmt->filename, stmt->is_program,
305  NULL, stmt->attlist, stmt->options);
306  *processed = CopyFrom(cstate); /* copy from file to database */
307  EndCopyFrom(cstate);
308  }
309  else
310  {
311  CopyToState cstate;
312 
313  cstate = BeginCopyTo(pstate, rel, query, relid,
314  stmt->filename, stmt->is_program,
315  NULL, stmt->attlist, stmt->options);
316  *processed = DoCopyTo(cstate); /* copy from database to file */
317  EndCopyTo(cstate);
318  }
319 
320  if (rel != NULL)
321  table_close(rel, NoLock);
322 }
323 
324 /*
325  * Extract a CopyHeaderChoice value from a DefElem. This is like
326  * defGetBoolean() but also accepts the special value "match".
327  */
328 static CopyHeaderChoice
329 defGetCopyHeaderChoice(DefElem *def, bool is_from)
330 {
331  /*
332  * If no parameter value given, assume "true" is meant.
333  */
334  if (def->arg == NULL)
335  return COPY_HEADER_TRUE;
336 
337  /*
338  * Allow 0, 1, "true", "false", "on", "off", or "match".
339  */
340  switch (nodeTag(def->arg))
341  {
342  case T_Integer:
343  switch (intVal(def->arg))
344  {
345  case 0:
346  return COPY_HEADER_FALSE;
347  case 1:
348  return COPY_HEADER_TRUE;
349  default:
350  /* otherwise, error out below */
351  break;
352  }
353  break;
354  default:
355  {
356  char *sval = defGetString(def);
357 
358  /*
359  * The set of strings accepted here should match up with the
360  * grammar's opt_boolean_or_string production.
361  */
362  if (pg_strcasecmp(sval, "true") == 0)
363  return COPY_HEADER_TRUE;
364  if (pg_strcasecmp(sval, "false") == 0)
365  return COPY_HEADER_FALSE;
366  if (pg_strcasecmp(sval, "on") == 0)
367  return COPY_HEADER_TRUE;
368  if (pg_strcasecmp(sval, "off") == 0)
369  return COPY_HEADER_FALSE;
370  if (pg_strcasecmp(sval, "match") == 0)
371  {
372  if (!is_from)
373  ereport(ERROR,
374  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
375  errmsg("cannot use \"%s\" with HEADER in COPY TO",
376  sval)));
377  return COPY_HEADER_MATCH;
378  }
379  }
380  break;
381  }
382  ereport(ERROR,
383  (errcode(ERRCODE_SYNTAX_ERROR),
384  errmsg("%s requires a Boolean value or \"match\"",
385  def->defname)));
386  return COPY_HEADER_FALSE; /* keep compiler quiet */
387 }
388 
389 /*
390  * Extract a CopyOnErrorChoice value from a DefElem.
391  */
392 static CopyOnErrorChoice
393 defGetCopyOnErrorChoice(DefElem *def, ParseState *pstate, bool is_from)
394 {
395  char *sval = defGetString(def);
396 
397  if (!is_from)
398  ereport(ERROR,
399  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
400  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
401  second %s is a COPY with direction, e.g. COPY TO */
402  errmsg("COPY %s cannot be used with %s", "ON_ERROR", "COPY TO"),
403  parser_errposition(pstate, def->location)));
404 
405  /*
406  * Allow "stop", or "ignore" values.
407  */
408  if (pg_strcasecmp(sval, "stop") == 0)
409  return COPY_ON_ERROR_STOP;
410  if (pg_strcasecmp(sval, "ignore") == 0)
411  return COPY_ON_ERROR_IGNORE;
412 
413  ereport(ERROR,
414  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
415  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR */
416  errmsg("COPY %s \"%s\" not recognized", "ON_ERROR", sval),
417  parser_errposition(pstate, def->location)));
418  return COPY_ON_ERROR_STOP; /* keep compiler quiet */
419 }
420 
421 /*
422  * Extract a CopyLogVerbosityChoice value from a DefElem.
423  */
426 {
427  char *sval;
428 
429  /*
430  * Allow "default", or "verbose" values.
431  */
432  sval = defGetString(def);
433  if (pg_strcasecmp(sval, "default") == 0)
435  if (pg_strcasecmp(sval, "verbose") == 0)
437 
438  ereport(ERROR,
439  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
440  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR */
441  errmsg("COPY %s \"%s\" not recognized", "LOG_VERBOSITY", sval),
442  parser_errposition(pstate, def->location)));
443  return COPY_LOG_VERBOSITY_DEFAULT; /* keep compiler quiet */
444 }
445 
446 /*
447  * Process the statement option list for COPY.
448  *
449  * Scan the options list (a list of DefElem) and transpose the information
450  * into *opts_out, applying appropriate error checking.
451  *
452  * If 'opts_out' is not NULL, it is assumed to be filled with zeroes initially.
453  *
454  * This is exported so that external users of the COPY API can sanity-check
455  * a list of options. In that usage, 'opts_out' can be passed as NULL and
456  * the collected data is just leaked until CurrentMemoryContext is reset.
457  *
458  * Note that additional checking, such as whether column names listed in FORCE
459  * QUOTE actually exist, has to be applied later. This just checks for
460  * self-consistency of the options list.
461  */
462 void
464  CopyFormatOptions *opts_out,
465  bool is_from,
466  List *options)
467 {
468  bool format_specified = false;
469  bool freeze_specified = false;
470  bool header_specified = false;
471  bool on_error_specified = false;
472  bool log_verbosity_specified = false;
473  ListCell *option;
474 
475  /* Support external use for option sanity checking */
476  if (opts_out == NULL)
477  opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
478 
479  opts_out->file_encoding = -1;
480 
481  /* Extract options from the statement node tree */
482  foreach(option, options)
483  {
484  DefElem *defel = lfirst_node(DefElem, option);
485 
486  if (strcmp(defel->defname, "format") == 0)
487  {
488  char *fmt = defGetString(defel);
489 
490  if (format_specified)
491  errorConflictingDefElem(defel, pstate);
492  format_specified = true;
493  if (strcmp(fmt, "text") == 0)
494  /* default format */ ;
495  else if (strcmp(fmt, "csv") == 0)
496  opts_out->csv_mode = true;
497  else if (strcmp(fmt, "binary") == 0)
498  opts_out->binary = true;
499  else
500  ereport(ERROR,
501  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
502  errmsg("COPY format \"%s\" not recognized", fmt),
503  parser_errposition(pstate, defel->location)));
504  }
505  else if (strcmp(defel->defname, "freeze") == 0)
506  {
507  if (freeze_specified)
508  errorConflictingDefElem(defel, pstate);
509  freeze_specified = true;
510  opts_out->freeze = defGetBoolean(defel);
511  }
512  else if (strcmp(defel->defname, "delimiter") == 0)
513  {
514  if (opts_out->delim)
515  errorConflictingDefElem(defel, pstate);
516  opts_out->delim = defGetString(defel);
517  }
518  else if (strcmp(defel->defname, "null") == 0)
519  {
520  if (opts_out->null_print)
521  errorConflictingDefElem(defel, pstate);
522  opts_out->null_print = defGetString(defel);
523  }
524  else if (strcmp(defel->defname, "default") == 0)
525  {
526  if (opts_out->default_print)
527  errorConflictingDefElem(defel, pstate);
528  opts_out->default_print = defGetString(defel);
529  }
530  else if (strcmp(defel->defname, "header") == 0)
531  {
532  if (header_specified)
533  errorConflictingDefElem(defel, pstate);
534  header_specified = true;
535  opts_out->header_line = defGetCopyHeaderChoice(defel, is_from);
536  }
537  else if (strcmp(defel->defname, "quote") == 0)
538  {
539  if (opts_out->quote)
540  errorConflictingDefElem(defel, pstate);
541  opts_out->quote = defGetString(defel);
542  }
543  else if (strcmp(defel->defname, "escape") == 0)
544  {
545  if (opts_out->escape)
546  errorConflictingDefElem(defel, pstate);
547  opts_out->escape = defGetString(defel);
548  }
549  else if (strcmp(defel->defname, "force_quote") == 0)
550  {
551  if (opts_out->force_quote || opts_out->force_quote_all)
552  errorConflictingDefElem(defel, pstate);
553  if (defel->arg && IsA(defel->arg, A_Star))
554  opts_out->force_quote_all = true;
555  else if (defel->arg && IsA(defel->arg, List))
556  opts_out->force_quote = castNode(List, defel->arg);
557  else
558  ereport(ERROR,
559  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
560  errmsg("argument to option \"%s\" must be a list of column names",
561  defel->defname),
562  parser_errposition(pstate, defel->location)));
563  }
564  else if (strcmp(defel->defname, "force_not_null") == 0)
565  {
566  if (opts_out->force_notnull || opts_out->force_notnull_all)
567  errorConflictingDefElem(defel, pstate);
568  if (defel->arg && IsA(defel->arg, A_Star))
569  opts_out->force_notnull_all = true;
570  else if (defel->arg && IsA(defel->arg, List))
571  opts_out->force_notnull = castNode(List, defel->arg);
572  else
573  ereport(ERROR,
574  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
575  errmsg("argument to option \"%s\" must be a list of column names",
576  defel->defname),
577  parser_errposition(pstate, defel->location)));
578  }
579  else if (strcmp(defel->defname, "force_null") == 0)
580  {
581  if (opts_out->force_null || opts_out->force_null_all)
582  errorConflictingDefElem(defel, pstate);
583  if (defel->arg && IsA(defel->arg, A_Star))
584  opts_out->force_null_all = true;
585  else if (defel->arg && IsA(defel->arg, List))
586  opts_out->force_null = castNode(List, defel->arg);
587  else
588  ereport(ERROR,
589  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
590  errmsg("argument to option \"%s\" must be a list of column names",
591  defel->defname),
592  parser_errposition(pstate, defel->location)));
593  }
594  else if (strcmp(defel->defname, "convert_selectively") == 0)
595  {
596  /*
597  * Undocumented, not-accessible-from-SQL option: convert only the
598  * named columns to binary form, storing the rest as NULLs. It's
599  * allowed for the column list to be NIL.
600  */
601  if (opts_out->convert_selectively)
602  errorConflictingDefElem(defel, pstate);
603  opts_out->convert_selectively = true;
604  if (defel->arg == NULL || IsA(defel->arg, List))
605  opts_out->convert_select = castNode(List, defel->arg);
606  else
607  ereport(ERROR,
608  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
609  errmsg("argument to option \"%s\" must be a list of column names",
610  defel->defname),
611  parser_errposition(pstate, defel->location)));
612  }
613  else if (strcmp(defel->defname, "encoding") == 0)
614  {
615  if (opts_out->file_encoding >= 0)
616  errorConflictingDefElem(defel, pstate);
617  opts_out->file_encoding = pg_char_to_encoding(defGetString(defel));
618  if (opts_out->file_encoding < 0)
619  ereport(ERROR,
620  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
621  errmsg("argument to option \"%s\" must be a valid encoding name",
622  defel->defname),
623  parser_errposition(pstate, defel->location)));
624  }
625  else if (strcmp(defel->defname, "on_error") == 0)
626  {
627  if (on_error_specified)
628  errorConflictingDefElem(defel, pstate);
629  on_error_specified = true;
630  opts_out->on_error = defGetCopyOnErrorChoice(defel, pstate, is_from);
631  }
632  else if (strcmp(defel->defname, "log_verbosity") == 0)
633  {
634  if (log_verbosity_specified)
635  errorConflictingDefElem(defel, pstate);
636  log_verbosity_specified = true;
637  opts_out->log_verbosity = defGetCopyLogVerbosityChoice(defel, pstate);
638  }
639  else
640  ereport(ERROR,
641  (errcode(ERRCODE_SYNTAX_ERROR),
642  errmsg("option \"%s\" not recognized",
643  defel->defname),
644  parser_errposition(pstate, defel->location)));
645  }
646 
647  /*
648  * Check for incompatible options (must do these two before inserting
649  * defaults)
650  */
651  if (opts_out->binary && opts_out->delim)
652  ereport(ERROR,
653  (errcode(ERRCODE_SYNTAX_ERROR),
654  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
655  errmsg("cannot specify %s in BINARY mode", "DELIMITER")));
656 
657  if (opts_out->binary && opts_out->null_print)
658  ereport(ERROR,
659  (errcode(ERRCODE_SYNTAX_ERROR),
660  errmsg("cannot specify %s in BINARY mode", "NULL")));
661 
662  if (opts_out->binary && opts_out->default_print)
663  ereport(ERROR,
664  (errcode(ERRCODE_SYNTAX_ERROR),
665  errmsg("cannot specify %s in BINARY mode", "DEFAULT")));
666 
667  if (opts_out->binary && opts_out->on_error != COPY_ON_ERROR_STOP)
668  ereport(ERROR,
669  (errcode(ERRCODE_SYNTAX_ERROR),
670  errmsg("only ON_ERROR STOP is allowed in BINARY mode")));
671 
672  /* Set defaults for omitted options */
673  if (!opts_out->delim)
674  opts_out->delim = opts_out->csv_mode ? "," : "\t";
675 
676  if (!opts_out->null_print)
677  opts_out->null_print = opts_out->csv_mode ? "" : "\\N";
678  opts_out->null_print_len = strlen(opts_out->null_print);
679 
680  if (opts_out->csv_mode)
681  {
682  if (!opts_out->quote)
683  opts_out->quote = "\"";
684  if (!opts_out->escape)
685  opts_out->escape = opts_out->quote;
686  }
687 
688  /* Only single-byte delimiter strings are supported. */
689  if (strlen(opts_out->delim) != 1)
690  ereport(ERROR,
691  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
692  errmsg("COPY delimiter must be a single one-byte character")));
693 
694  /* Disallow end-of-line characters */
695  if (strchr(opts_out->delim, '\r') != NULL ||
696  strchr(opts_out->delim, '\n') != NULL)
697  ereport(ERROR,
698  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
699  errmsg("COPY delimiter cannot be newline or carriage return")));
700 
701  if (strchr(opts_out->null_print, '\r') != NULL ||
702  strchr(opts_out->null_print, '\n') != NULL)
703  ereport(ERROR,
704  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
705  errmsg("COPY null representation cannot use newline or carriage return")));
706 
707  if (opts_out->default_print)
708  {
709  opts_out->default_print_len = strlen(opts_out->default_print);
710 
711  if (strchr(opts_out->default_print, '\r') != NULL ||
712  strchr(opts_out->default_print, '\n') != NULL)
713  ereport(ERROR,
714  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
715  errmsg("COPY default representation cannot use newline or carriage return")));
716  }
717 
718  /*
719  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
720  * backslash because it would be ambiguous. We can't allow the other
721  * cases because data characters matching the delimiter must be
722  * backslashed, and certain backslash combinations are interpreted
723  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
724  * more than strictly necessary, but seems best for consistency and
725  * future-proofing. Likewise we disallow all digits though only octal
726  * digits are actually dangerous.
727  */
728  if (!opts_out->csv_mode &&
729  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
730  opts_out->delim[0]) != NULL)
731  ereport(ERROR,
732  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
733  errmsg("COPY delimiter cannot be \"%s\"", opts_out->delim)));
734 
735  /* Check header */
736  if (opts_out->binary && opts_out->header_line)
737  ereport(ERROR,
738  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
739  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
740  errmsg("cannot specify %s in BINARY mode", "HEADER")));
741 
742  /* Check quote */
743  if (!opts_out->csv_mode && opts_out->quote != NULL)
744  ereport(ERROR,
745  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
746  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
747  errmsg("COPY %s requires CSV mode", "QUOTE")));
748 
749  if (opts_out->csv_mode && strlen(opts_out->quote) != 1)
750  ereport(ERROR,
751  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
752  errmsg("COPY quote must be a single one-byte character")));
753 
754  if (opts_out->csv_mode && opts_out->delim[0] == opts_out->quote[0])
755  ereport(ERROR,
756  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
757  errmsg("COPY delimiter and quote must be different")));
758 
759  /* Check escape */
760  if (!opts_out->csv_mode && opts_out->escape != NULL)
761  ereport(ERROR,
762  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
763  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
764  errmsg("COPY %s requires CSV mode", "ESCAPE")));
765 
766  if (opts_out->csv_mode && strlen(opts_out->escape) != 1)
767  ereport(ERROR,
768  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
769  errmsg("COPY escape must be a single one-byte character")));
770 
771  /* Check force_quote */
772  if (!opts_out->csv_mode && (opts_out->force_quote || opts_out->force_quote_all))
773  ereport(ERROR,
774  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
775  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
776  errmsg("COPY %s requires CSV mode", "FORCE_QUOTE")));
777  if ((opts_out->force_quote || opts_out->force_quote_all) && is_from)
778  ereport(ERROR,
779  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
780  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
781  second %s is a COPY with direction, e.g. COPY TO */
782  errmsg("COPY %s cannot be used with %s", "FORCE_QUOTE",
783  "COPY FROM")));
784 
785  /* Check force_notnull */
786  if (!opts_out->csv_mode && opts_out->force_notnull != NIL)
787  ereport(ERROR,
788  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
789  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
790  errmsg("COPY %s requires CSV mode", "FORCE_NOT_NULL")));
791  if (opts_out->force_notnull != NIL && !is_from)
792  ereport(ERROR,
793  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
794  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
795  second %s is a COPY with direction, e.g. COPY TO */
796  errmsg("COPY %s cannot be used with %s", "FORCE_NOT_NULL",
797  "COPY TO")));
798 
799  /* Check force_null */
800  if (!opts_out->csv_mode && opts_out->force_null != NIL)
801  ereport(ERROR,
802  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
803  /*- translator: %s is the name of a COPY option, e.g. ON_ERROR */
804  errmsg("COPY %s requires CSV mode", "FORCE_NULL")));
805 
806  if (opts_out->force_null != NIL && !is_from)
807  ereport(ERROR,
808  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
809  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
810  second %s is a COPY with direction, e.g. COPY TO */
811  errmsg("COPY %s cannot be used with %s", "FORCE_NULL",
812  "COPY TO")));
813 
814  /* Don't allow the delimiter to appear in the null string. */
815  if (strchr(opts_out->null_print, opts_out->delim[0]) != NULL)
816  ereport(ERROR,
817  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
818  /*- translator: %s is the name of a COPY option, e.g. NULL */
819  errmsg("COPY delimiter character must not appear in the %s specification",
820  "NULL")));
821 
822  /* Don't allow the CSV quote char to appear in the null string. */
823  if (opts_out->csv_mode &&
824  strchr(opts_out->null_print, opts_out->quote[0]) != NULL)
825  ereport(ERROR,
826  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
827  /*- translator: %s is the name of a COPY option, e.g. NULL */
828  errmsg("CSV quote character must not appear in the %s specification",
829  "NULL")));
830 
831  /* Check freeze */
832  if (opts_out->freeze && !is_from)
833  ereport(ERROR,
834  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
835  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
836  second %s is a COPY with direction, e.g. COPY TO */
837  errmsg("COPY %s cannot be used with %s", "FREEZE",
838  "COPY TO")));
839 
840  if (opts_out->default_print)
841  {
842  if (!is_from)
843  ereport(ERROR,
844  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
845  /*- translator: first %s is the name of a COPY option, e.g. ON_ERROR,
846  second %s is a COPY with direction, e.g. COPY TO */
847  errmsg("COPY %s cannot be used with %s", "DEFAULT",
848  "COPY TO")));
849 
850  /* Don't allow the delimiter to appear in the default string. */
851  if (strchr(opts_out->default_print, opts_out->delim[0]) != NULL)
852  ereport(ERROR,
853  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
854  /*- translator: %s is the name of a COPY option, e.g. NULL */
855  errmsg("COPY delimiter character must not appear in the %s specification",
856  "DEFAULT")));
857 
858  /* Don't allow the CSV quote char to appear in the default string. */
859  if (opts_out->csv_mode &&
860  strchr(opts_out->default_print, opts_out->quote[0]) != NULL)
861  ereport(ERROR,
862  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
863  /*- translator: %s is the name of a COPY option, e.g. NULL */
864  errmsg("CSV quote character must not appear in the %s specification",
865  "DEFAULT")));
866 
867  /* Don't allow the NULL and DEFAULT string to be the same */
868  if (opts_out->null_print_len == opts_out->default_print_len &&
869  strncmp(opts_out->null_print, opts_out->default_print,
870  opts_out->null_print_len) == 0)
871  ereport(ERROR,
872  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
873  errmsg("NULL specification and DEFAULT specification cannot be the same")));
874  }
875 }
876 
877 /*
878  * CopyGetAttnums - build an integer list of attnums to be copied
879  *
880  * The input attnamelist is either the user-specified column list,
881  * or NIL if there was none (in which case we want all the non-dropped
882  * columns).
883  *
884  * We don't include generated columns in the generated full list and we don't
885  * allow them to be specified explicitly. They don't make sense for COPY
886  * FROM, but we could possibly allow them for COPY TO. But this way it's at
887  * least ensured that whatever we copy out can be copied back in.
888  *
889  * rel can be NULL ... it's only used for error reports.
890  */
891 List *
892 CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
893 {
894  List *attnums = NIL;
895 
896  if (attnamelist == NIL)
897  {
898  /* Generate default column list */
899  int attr_count = tupDesc->natts;
900  int i;
901 
902  for (i = 0; i < attr_count; i++)
903  {
904  if (TupleDescAttr(tupDesc, i)->attisdropped)
905  continue;
906  if (TupleDescAttr(tupDesc, i)->attgenerated)
907  continue;
908  attnums = lappend_int(attnums, i + 1);
909  }
910  }
911  else
912  {
913  /* Validate the user-supplied list and extract attnums */
914  ListCell *l;
915 
916  foreach(l, attnamelist)
917  {
918  char *name = strVal(lfirst(l));
919  int attnum;
920  int i;
921 
922  /* Lookup column name */
924  for (i = 0; i < tupDesc->natts; i++)
925  {
926  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
927 
928  if (att->attisdropped)
929  continue;
930  if (namestrcmp(&(att->attname), name) == 0)
931  {
932  if (att->attgenerated)
933  ereport(ERROR,
934  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
935  errmsg("column \"%s\" is a generated column",
936  name),
937  errdetail("Generated columns cannot be used in COPY.")));
938  attnum = att->attnum;
939  break;
940  }
941  }
942  if (attnum == InvalidAttrNumber)
943  {
944  if (rel != NULL)
945  ereport(ERROR,
946  (errcode(ERRCODE_UNDEFINED_COLUMN),
947  errmsg("column \"%s\" of relation \"%s\" does not exist",
948  name, RelationGetRelationName(rel))));
949  else
950  ereport(ERROR,
951  (errcode(ERRCODE_UNDEFINED_COLUMN),
952  errmsg("column \"%s\" does not exist",
953  name)));
954  }
955  /* Check for duplicates */
956  if (list_member_int(attnums, attnum))
957  ereport(ERROR,
958  (errcode(ERRCODE_DUPLICATE_COLUMN),
959  errmsg("column \"%s\" specified more than once",
960  name)));
961  attnums = lappend_int(attnums, attnum);
962  }
963  }
964 
965  return attnums;
966 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:5134
#define InvalidAttrNumber
Definition: attnum.h:23
static CopyHeaderChoice defGetCopyHeaderChoice(DefElem *def, bool is_from)
Definition: copy.c:329
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:892
void DoCopy(ParseState *pstate, const CopyStmt *stmt, int stmt_location, int stmt_len, uint64 *processed)
Definition: copy.c:62
static CopyOnErrorChoice defGetCopyOnErrorChoice(DefElem *def, ParseState *pstate, bool is_from)
Definition: copy.c:393
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:463
static CopyLogVerbosityChoice defGetCopyLogVerbosityChoice(DefElem *def, ParseState *pstate)
Definition: copy.c:425
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:815
#define Assert(condition)
Definition: c.h:858
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2254
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:1380
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:640
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1799
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:743
CopyToState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, copy_data_dest_cb data_dest_cb, List *attnamelist, List *options)
Definition: copyto.c:350
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:722
bool defGetBoolean(DefElem *def)
Definition: define.c:107
char * defGetString(DefElem *def)
Definition: define.c:48
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:384
struct cursor * cur
Definition: ecpg.c:28
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:574
CopyOnErrorChoice
Definition: copy.h:38
@ COPY_ON_ERROR_IGNORE
Definition: copy.h:40
@ COPY_ON_ERROR_STOP
Definition: copy.h:39
CopyLogVerbosityChoice
Definition: copy.h:47
@ COPY_LOG_VERBOSITY_VERBOSE
Definition: copy.h:49
@ COPY_LOG_VERBOSITY_DEFAULT
Definition: copy.h:48
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
#define stmt
Definition: indent_codes.h:59
int i
Definition: isn.c:73
static void const char * fmt
List * lappend(List *list, void *datum)
Definition: list.c:339
List * lappend_int(List *list, int datum)
Definition: list.c:357
bool list_member_int(const List *list, int datum)
Definition: list.c:702
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:3366
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:737
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
char * pstrdup(const char *in)
Definition: mcxt.c:1696
void * palloc0(Size size)
Definition: mcxt.c:1347
Oid GetUserId(void)
Definition: miscinit.c:514
int namestrcmp(Name name, const char *str)
Definition: name.c:247
#define IsA(nodeptr, _type_)
Definition: nodes.h:158
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define makeNode(_type_)
Definition: nodes.h:155
#define castNode(_type_, nodeptr)
Definition: nodes.h:176
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:120
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:106
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:82
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:76
#define ACL_SELECT
Definition: parsenodes.h:77
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define lfirst(lc)
Definition: pg_list.h:172
#define lfirst_node(type, lc)
Definition: pg_list.h:176
#define NIL
Definition: pg_list.h:68
#define lfirst_int(lc)
Definition: pg_list.h:173
#define list_make1(x1)
Definition: pg_list.h:212
#define pg_char_to_encoding
Definition: pg_wchar.h:629
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:293
#define RelationGetRelid(relation)
Definition: rel.h:505
#define RelationGetDescr(relation)
Definition: rel.h:531
#define RelationGetRelationName(relation)
Definition: rel.h:539
#define RelationGetNamespace(relation)
Definition: rel.h:546
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
ParseLoc location
Definition: parsenodes.h:295
List * fields
Definition: parsenodes.h:294
int default_print_len
Definition: copy.h:70
bool force_notnull_all
Definition: copy.h:78
bool force_quote_all
Definition: copy.h:75
bool freeze
Definition: copy.h:63
bool binary
Definition: copy.h:62
int null_print_len
Definition: copy.h:67
bool convert_selectively
Definition: copy.h:83
CopyLogVerbosityChoice log_verbosity
Definition: copy.h:85
char * quote
Definition: copy.h:72
CopyOnErrorChoice on_error
Definition: copy.h:84
CopyHeaderChoice header_line
Definition: copy.h:65
List * force_quote
Definition: copy.h:74
char * escape
Definition: copy.h:73
char * null_print
Definition: copy.h:66
List * force_null
Definition: copy.h:80
char * delim
Definition: copy.h:71
List * convert_select
Definition: copy.h:86
bool force_null_all
Definition: copy.h:81
bool csv_mode
Definition: copy.h:64
int file_encoding
Definition: copy.h:60
char * default_print
Definition: copy.h:69
List * force_notnull
Definition: copy.h:77
char * defname
Definition: parsenodes.h:815
ParseLoc location
Definition: parsenodes.h:819
Node * arg
Definition: parsenodes.h:816
Definition: pg_list.h:54
Definition: nodes.h:129
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:289
List * p_rtable
Definition: parse_node.h:194
Bitmapset * selectedCols
Definition: parsenodes.h:1284
AclMode requiredPerms
Definition: parsenodes.h:1282
Bitmapset * insertedCols
Definition: parsenodes.h:1285
bool inh
Definition: primnodes.h:85
ParseLoc stmt_location
Definition: parsenodes.h:2013
ParseLoc stmt_len
Definition: parsenodes.h:2014
Node * stmt
Definition: parsenodes.h:2012
bool rd_islocaltemp
Definition: rel.h:61
Node * val
Definition: parsenodes.h:519
ParseLoc location
Definition: parsenodes.h:520
List * indirection
Definition: parsenodes.h:518
char * name
Definition: parsenodes.h:517
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:83
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:404
#define intVal(v)
Definition: value.h:79
#define strVal(v)
Definition: value.h:82
const char * name
#define select(n, r, w, e, timeout)
Definition: win32_port.h:513
bool XactReadOnly
Definition: xact.c:81