PostgreSQL Source Code  git master
copy.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include "access/sysattr.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/pg_authid.h"
#include "commands/copy.h"
#include "commands/defrem.h"
#include "executor/executor.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "rewrite/rewriteHandler.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/rls.h"
Include dependency graph for copy.c:

Go to the source code of this file.

Functions

void DoCopy (ParseState *pstate, const CopyStmt *stmt, int stmt_location, int stmt_len, uint64 *processed)
 
static CopyHeaderChoice defGetCopyHeaderChoice (DefElem *def, bool is_from)
 
void ProcessCopyOptions (ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
 
ListCopyGetAttnums (TupleDesc tupDesc, Relation rel, List *attnamelist)
 

Function Documentation

◆ CopyGetAttnums()

List* CopyGetAttnums ( TupleDesc  tupDesc,
Relation  rel,
List attnamelist 
)

Definition at line 715 of file copy.c.

716 {
717  List *attnums = NIL;
718 
719  if (attnamelist == NIL)
720  {
721  /* Generate default column list */
722  int attr_count = tupDesc->natts;
723  int i;
724 
725  for (i = 0; i < attr_count; i++)
726  {
727  if (TupleDescAttr(tupDesc, i)->attisdropped)
728  continue;
729  if (TupleDescAttr(tupDesc, i)->attgenerated)
730  continue;
731  attnums = lappend_int(attnums, i + 1);
732  }
733  }
734  else
735  {
736  /* Validate the user-supplied list and extract attnums */
737  ListCell *l;
738 
739  foreach(l, attnamelist)
740  {
741  char *name = strVal(lfirst(l));
742  int attnum;
743  int i;
744 
745  /* Lookup column name */
747  for (i = 0; i < tupDesc->natts; i++)
748  {
749  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
750 
751  if (att->attisdropped)
752  continue;
753  if (namestrcmp(&(att->attname), name) == 0)
754  {
755  if (att->attgenerated)
756  ereport(ERROR,
757  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
758  errmsg("column \"%s\" is a generated column",
759  name),
760  errdetail("Generated columns cannot be used in COPY.")));
761  attnum = att->attnum;
762  break;
763  }
764  }
765  if (attnum == InvalidAttrNumber)
766  {
767  if (rel != NULL)
768  ereport(ERROR,
769  (errcode(ERRCODE_UNDEFINED_COLUMN),
770  errmsg("column \"%s\" of relation \"%s\" does not exist",
771  name, RelationGetRelationName(rel))));
772  else
773  ereport(ERROR,
774  (errcode(ERRCODE_UNDEFINED_COLUMN),
775  errmsg("column \"%s\" does not exist",
776  name)));
777  }
778  /* Check for duplicates */
779  if (list_member_int(attnums, attnum))
780  ereport(ERROR,
781  (errcode(ERRCODE_DUPLICATE_COLUMN),
782  errmsg("column \"%s\" specified more than once",
783  name)));
784  attnums = lappend_int(attnums, attnum);
785  }
786  }
787 
788  return attnums;
789 }
#define InvalidAttrNumber
Definition: attnum.h:23
int errdetail(const char *fmt,...)
Definition: elog.c:1037
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
const char * name
Definition: encode.c:561
int i
Definition: isn.c:73
List * lappend_int(List *list, int datum)
Definition: list.c:356
bool list_member_int(const List *list, int datum)
Definition: list.c:701
int namestrcmp(Name name, const char *str)
Definition: name.c:247
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:170
#define NIL
Definition: pg_list.h:66
#define RelationGetRelationName(relation)
Definition: rel.h:522
Definition: pg_list.h:52
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:72

References attnum, ereport, errcode(), errdetail(), errmsg(), ERROR, i, InvalidAttrNumber, lappend_int(), lfirst, list_member_int(), name, namestrcmp(), TupleDescData::natts, NIL, RelationGetRelationName, strVal, and TupleDescAttr.

Referenced by BeginCopyFrom(), BeginCopyTo(), and DoCopy().

◆ defGetCopyHeaderChoice()

static CopyHeaderChoice defGetCopyHeaderChoice ( DefElem def,
bool  is_from 
)
static

Definition at line 321 of file copy.c.

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  {
364  if (!is_from)
365  ereport(ERROR,
366  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
367  errmsg("cannot use \"%s\" with HEADER in COPY TO",
368  sval)));
369  return COPY_HEADER_MATCH;
370  }
371  }
372  break;
373  }
374  ereport(ERROR,
375  (errcode(ERRCODE_SYNTAX_ERROR),
376  errmsg("%s requires a Boolean value or \"match\"",
377  def->defname)));
378  return COPY_HEADER_FALSE; /* keep compiler quiet */
379 }
char * defGetString(DefElem *def)
Definition: define.c:49
@ COPY_HEADER_TRUE
Definition: copy.h:29
@ COPY_HEADER_FALSE
Definition: copy.h:28
@ COPY_HEADER_MATCH
Definition: copy.h:30
#define nodeTag(nodeptr)
Definition: nodes.h:579
@ T_Integer
Definition: nodes.h:308
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:766
Node * arg
Definition: parsenodes.h:767
#define intVal(v)
Definition: value.h:69

References DefElem::arg, COPY_HEADER_FALSE, COPY_HEADER_MATCH, COPY_HEADER_TRUE, defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, intVal, nodeTag, pg_strcasecmp(), and T_Integer.

Referenced by ProcessCopyOptions().

◆ DoCopy()

void DoCopy ( ParseState pstate,
const CopyStmt stmt,
int  stmt_location,
int  stmt_len,
uint64 *  processed 
)

Definition at line 64 of file copy.c.

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 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4925
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:715
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
struct cursor * cur
Definition: ecpg.c:28
int errhint(const char *fmt,...)
Definition: elog.c:1151
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:570
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
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
Oid GetUserId(void)
Definition: miscinit.c:491
#define makeNode(_type_)
Definition: nodes.h:622
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
@ 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
#define lfirst_int(lc)
Definition: pg_list.h:171
#define list_make1(x1)
Definition: pg_list.h:210
#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:488
#define RelationGetDescr(relation)
Definition: rel.h:514
#define RelationGetNamespace(relation)
Definition: rel.h:529
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:254
List * fields
Definition: parsenodes.h:253
bool is_program
Definition: parsenodes.h:2475
RangeVar * relation
Definition: parsenodes.h:2469
List * options
Definition: parsenodes.h:2477
bool is_from
Definition: parsenodes.h:2474
char * filename
Definition: parsenodes.h:2476
List * attlist
Definition: parsenodes.h:2472
Node * whereClause
Definition: parsenodes.h:2478
Node * query
Definition: parsenodes.h:2470
Definition: nodes.h:575
RangeTblEntry * p_rte
Definition: parse_node.h:269
List * p_rtable
Definition: parse_node.h:183
AclMode requiredPerms
Definition: parsenodes.h:1166
Bitmapset * selectedCols
Definition: parsenodes.h:1168
Bitmapset * insertedCols
Definition: parsenodes.h:1169
int stmt_len
Definition: parsenodes.h:1906
Node * stmt
Definition: parsenodes.h:1904
int stmt_location
Definition: parsenodes.h:1905
bool rd_islocaltemp
Definition: rel.h:60
int location
Definition: parsenodes.h:475
Node * val
Definition: parsenodes.h:474
List * indirection
Definition: parsenodes.h:473
char * name
Definition: parsenodes.h:472
#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
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:411
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474
bool XactReadOnly
Definition: xact.c:81

References AccessShareLock, ACL_INSERT, ACL_SELECT, addNSItemToQuery(), addRangeTableEntryForRelation(), Assert(), assign_expr_collations(), CopyStmt::attlist, BeginCopyFrom(), BeginCopyTo(), bms_add_member(), canonicalize_qual(), check_enable_rls(), coerce_to_boolean(), CopyFrom(), CopyGetAttnums(), cur, DoCopyTo(), EndCopyFrom(), EndCopyTo(), ereport, errcode(), errhint(), errmsg(), ERROR, eval_const_expressions(), ExecCheckRTPerms(), EXPR_KIND_COPY_WHERE, ColumnRef::fields, CopyStmt::filename, FirstLowInvalidHeapAttributeNumber, get_namespace_name(), GetUserId(), has_privs_of_role(), ResTarget::indirection, RangeTblEntry::insertedCols, InvalidOid, CopyStmt::is_from, CopyStmt::is_program, lappend(), lfirst, lfirst_int, list_make1, ColumnRef::location, ResTarget::location, make_ands_implicit(), makeNode, makeRangeVar(), ResTarget::name, NIL, NoLock, CopyStmt::options, ParseState::p_rtable, ParseNamespaceItem::p_rte, PreventCommandIfReadOnly(), pstrdup(), CopyStmt::query, RelationData::rd_islocaltemp, CopyStmt::relation, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::requiredPerms, RLS_ENABLED, RowExclusiveLock, select, RangeTblEntry::selectedCols, RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, table_close(), table_openrv(), transformExpr(), ResTarget::val, CopyStmt::whereClause, and XactReadOnly.

Referenced by standard_ProcessUtility().

◆ ProcessCopyOptions()

void ProcessCopyOptions ( ParseState pstate,
CopyFormatOptions opts_out,
bool  is_from,
List options 
)

Definition at line 398 of file copy.c.

402 {
403  bool format_specified = false;
404  bool freeze_specified = false;
405  bool header_specified = false;
406  ListCell *option;
407 
408  /* Support external use for option sanity checking */
409  if (opts_out == NULL)
410  opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
411 
412  opts_out->file_encoding = -1;
413 
414  /* Extract options from the statement node tree */
415  foreach(option, options)
416  {
417  DefElem *defel = lfirst_node(DefElem, option);
418 
419  if (strcmp(defel->defname, "format") == 0)
420  {
421  char *fmt = defGetString(defel);
422 
423  if (format_specified)
424  errorConflictingDefElem(defel, pstate);
425  format_specified = true;
426  if (strcmp(fmt, "text") == 0)
427  /* default format */ ;
428  else if (strcmp(fmt, "csv") == 0)
429  opts_out->csv_mode = true;
430  else if (strcmp(fmt, "binary") == 0)
431  opts_out->binary = true;
432  else
433  ereport(ERROR,
434  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
435  errmsg("COPY format \"%s\" not recognized", fmt),
436  parser_errposition(pstate, defel->location)));
437  }
438  else if (strcmp(defel->defname, "freeze") == 0)
439  {
440  if (freeze_specified)
441  errorConflictingDefElem(defel, pstate);
442  freeze_specified = true;
443  opts_out->freeze = defGetBoolean(defel);
444  }
445  else if (strcmp(defel->defname, "delimiter") == 0)
446  {
447  if (opts_out->delim)
448  errorConflictingDefElem(defel, pstate);
449  opts_out->delim = defGetString(defel);
450  }
451  else if (strcmp(defel->defname, "null") == 0)
452  {
453  if (opts_out->null_print)
454  errorConflictingDefElem(defel, pstate);
455  opts_out->null_print = defGetString(defel);
456  }
457  else if (strcmp(defel->defname, "header") == 0)
458  {
459  if (header_specified)
460  errorConflictingDefElem(defel, pstate);
461  header_specified = true;
462  opts_out->header_line = defGetCopyHeaderChoice(defel, is_from);
463  }
464  else if (strcmp(defel->defname, "quote") == 0)
465  {
466  if (opts_out->quote)
467  errorConflictingDefElem(defel, pstate);
468  opts_out->quote = defGetString(defel);
469  }
470  else if (strcmp(defel->defname, "escape") == 0)
471  {
472  if (opts_out->escape)
473  errorConflictingDefElem(defel, pstate);
474  opts_out->escape = defGetString(defel);
475  }
476  else if (strcmp(defel->defname, "force_quote") == 0)
477  {
478  if (opts_out->force_quote || opts_out->force_quote_all)
479  errorConflictingDefElem(defel, pstate);
480  if (defel->arg && IsA(defel->arg, A_Star))
481  opts_out->force_quote_all = true;
482  else if (defel->arg && IsA(defel->arg, List))
483  opts_out->force_quote = castNode(List, defel->arg);
484  else
485  ereport(ERROR,
486  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
487  errmsg("argument to option \"%s\" must be a list of column names",
488  defel->defname),
489  parser_errposition(pstate, defel->location)));
490  }
491  else if (strcmp(defel->defname, "force_not_null") == 0)
492  {
493  if (opts_out->force_notnull)
494  errorConflictingDefElem(defel, pstate);
495  if (defel->arg && IsA(defel->arg, List))
496  opts_out->force_notnull = castNode(List, defel->arg);
497  else
498  ereport(ERROR,
499  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
500  errmsg("argument to option \"%s\" must be a list of column names",
501  defel->defname),
502  parser_errposition(pstate, defel->location)));
503  }
504  else if (strcmp(defel->defname, "force_null") == 0)
505  {
506  if (opts_out->force_null)
507  errorConflictingDefElem(defel, pstate);
508  if (defel->arg && IsA(defel->arg, List))
509  opts_out->force_null = castNode(List, defel->arg);
510  else
511  ereport(ERROR,
512  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
513  errmsg("argument to option \"%s\" must be a list of column names",
514  defel->defname),
515  parser_errposition(pstate, defel->location)));
516  }
517  else if (strcmp(defel->defname, "convert_selectively") == 0)
518  {
519  /*
520  * Undocumented, not-accessible-from-SQL option: convert only the
521  * named columns to binary form, storing the rest as NULLs. It's
522  * allowed for the column list to be NIL.
523  */
524  if (opts_out->convert_selectively)
525  errorConflictingDefElem(defel, pstate);
526  opts_out->convert_selectively = true;
527  if (defel->arg == NULL || IsA(defel->arg, List))
528  opts_out->convert_select = castNode(List, defel->arg);
529  else
530  ereport(ERROR,
531  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
532  errmsg("argument to option \"%s\" must be a list of column names",
533  defel->defname),
534  parser_errposition(pstate, defel->location)));
535  }
536  else if (strcmp(defel->defname, "encoding") == 0)
537  {
538  if (opts_out->file_encoding >= 0)
539  errorConflictingDefElem(defel, pstate);
540  opts_out->file_encoding = pg_char_to_encoding(defGetString(defel));
541  if (opts_out->file_encoding < 0)
542  ereport(ERROR,
543  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
544  errmsg("argument to option \"%s\" must be a valid encoding name",
545  defel->defname),
546  parser_errposition(pstate, defel->location)));
547  }
548  else
549  ereport(ERROR,
550  (errcode(ERRCODE_SYNTAX_ERROR),
551  errmsg("option \"%s\" not recognized",
552  defel->defname),
553  parser_errposition(pstate, defel->location)));
554  }
555 
556  /*
557  * Check for incompatible options (must do these two before inserting
558  * defaults)
559  */
560  if (opts_out->binary && opts_out->delim)
561  ereport(ERROR,
562  (errcode(ERRCODE_SYNTAX_ERROR),
563  errmsg("cannot specify DELIMITER in BINARY mode")));
564 
565  if (opts_out->binary && opts_out->null_print)
566  ereport(ERROR,
567  (errcode(ERRCODE_SYNTAX_ERROR),
568  errmsg("cannot specify NULL in BINARY mode")));
569 
570  /* Set defaults for omitted options */
571  if (!opts_out->delim)
572  opts_out->delim = opts_out->csv_mode ? "," : "\t";
573 
574  if (!opts_out->null_print)
575  opts_out->null_print = opts_out->csv_mode ? "" : "\\N";
576  opts_out->null_print_len = strlen(opts_out->null_print);
577 
578  if (opts_out->csv_mode)
579  {
580  if (!opts_out->quote)
581  opts_out->quote = "\"";
582  if (!opts_out->escape)
583  opts_out->escape = opts_out->quote;
584  }
585 
586  /* Only single-byte delimiter strings are supported. */
587  if (strlen(opts_out->delim) != 1)
588  ereport(ERROR,
589  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
590  errmsg("COPY delimiter must be a single one-byte character")));
591 
592  /* Disallow end-of-line characters */
593  if (strchr(opts_out->delim, '\r') != NULL ||
594  strchr(opts_out->delim, '\n') != NULL)
595  ereport(ERROR,
596  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
597  errmsg("COPY delimiter cannot be newline or carriage return")));
598 
599  if (strchr(opts_out->null_print, '\r') != NULL ||
600  strchr(opts_out->null_print, '\n') != NULL)
601  ereport(ERROR,
602  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
603  errmsg("COPY null representation cannot use newline or carriage return")));
604 
605  /*
606  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
607  * backslash because it would be ambiguous. We can't allow the other
608  * cases because data characters matching the delimiter must be
609  * backslashed, and certain backslash combinations are interpreted
610  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
611  * more than strictly necessary, but seems best for consistency and
612  * future-proofing. Likewise we disallow all digits though only octal
613  * digits are actually dangerous.
614  */
615  if (!opts_out->csv_mode &&
616  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
617  opts_out->delim[0]) != NULL)
618  ereport(ERROR,
619  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
620  errmsg("COPY delimiter cannot be \"%s\"", opts_out->delim)));
621 
622  /* Check header */
623  if (opts_out->binary && opts_out->header_line)
624  ereport(ERROR,
625  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
626  errmsg("cannot specify HEADER in BINARY mode")));
627 
628  /* Check quote */
629  if (!opts_out->csv_mode && opts_out->quote != NULL)
630  ereport(ERROR,
631  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
632  errmsg("COPY quote available only in CSV mode")));
633 
634  if (opts_out->csv_mode && strlen(opts_out->quote) != 1)
635  ereport(ERROR,
636  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
637  errmsg("COPY quote must be a single one-byte character")));
638 
639  if (opts_out->csv_mode && opts_out->delim[0] == opts_out->quote[0])
640  ereport(ERROR,
641  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
642  errmsg("COPY delimiter and quote must be different")));
643 
644  /* Check escape */
645  if (!opts_out->csv_mode && opts_out->escape != NULL)
646  ereport(ERROR,
647  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
648  errmsg("COPY escape available only in CSV mode")));
649 
650  if (opts_out->csv_mode && strlen(opts_out->escape) != 1)
651  ereport(ERROR,
652  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
653  errmsg("COPY escape must be a single one-byte character")));
654 
655  /* Check force_quote */
656  if (!opts_out->csv_mode && (opts_out->force_quote || opts_out->force_quote_all))
657  ereport(ERROR,
658  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
659  errmsg("COPY force quote available only in CSV mode")));
660  if ((opts_out->force_quote || opts_out->force_quote_all) && is_from)
661  ereport(ERROR,
662  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
663  errmsg("COPY force quote only available using COPY TO")));
664 
665  /* Check force_notnull */
666  if (!opts_out->csv_mode && opts_out->force_notnull != NIL)
667  ereport(ERROR,
668  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
669  errmsg("COPY force not null available only in CSV mode")));
670  if (opts_out->force_notnull != NIL && !is_from)
671  ereport(ERROR,
672  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
673  errmsg("COPY force not null only available using COPY FROM")));
674 
675  /* Check force_null */
676  if (!opts_out->csv_mode && opts_out->force_null != NIL)
677  ereport(ERROR,
678  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
679  errmsg("COPY force null available only in CSV mode")));
680 
681  if (opts_out->force_null != NIL && !is_from)
682  ereport(ERROR,
683  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
684  errmsg("COPY force null only available using COPY FROM")));
685 
686  /* Don't allow the delimiter to appear in the null string. */
687  if (strchr(opts_out->null_print, opts_out->delim[0]) != NULL)
688  ereport(ERROR,
689  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
690  errmsg("COPY delimiter must not appear in the NULL specification")));
691 
692  /* Don't allow the CSV quote char to appear in the null string. */
693  if (opts_out->csv_mode &&
694  strchr(opts_out->null_print, opts_out->quote[0]) != NULL)
695  ereport(ERROR,
696  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
697  errmsg("CSV quote character must not appear in the NULL specification")));
698 }
static CopyHeaderChoice defGetCopyHeaderChoice(DefElem *def, bool is_from)
Definition: copy.c:321
bool defGetBoolean(DefElem *def)
Definition: define.c:108
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:352
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
static void const char * fmt
void * palloc0(Size size)
Definition: mcxt.c:1099
#define IsA(nodeptr, _type_)
Definition: nodes.h:625
#define castNode(_type_, nodeptr)
Definition: nodes.h:643
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:110
#define lfirst_node(type, lc)
Definition: pg_list.h:174
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
int location
Definition: parsenodes.h:770

References DefElem::arg, CopyFormatOptions::binary, castNode, CopyFormatOptions::convert_select, CopyFormatOptions::convert_selectively, CopyFormatOptions::csv_mode, defGetBoolean(), defGetCopyHeaderChoice(), defGetString(), DefElem::defname, CopyFormatOptions::delim, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), CopyFormatOptions::escape, CopyFormatOptions::file_encoding, fmt, CopyFormatOptions::force_notnull, CopyFormatOptions::force_null, CopyFormatOptions::force_quote, CopyFormatOptions::force_quote_all, CopyFormatOptions::freeze, CopyFormatOptions::header_line, IsA, lfirst_node, DefElem::location, NIL, CopyFormatOptions::null_print, CopyFormatOptions::null_print_len, palloc0(), parser_errposition(), pg_char_to_encoding(), and CopyFormatOptions::quote.

Referenced by BeginCopyFrom(), BeginCopyTo(), and file_fdw_validator().