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 721 of file copy.c.

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

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 327 of file copy.c.

328 {
329  /*
330  * If no parameter value given, assume "true" is meant.
331  */
332  if (def->arg == NULL)
333  return COPY_HEADER_TRUE;
334 
335  /*
336  * Allow 0, 1, "true", "false", "on", "off", or "match".
337  */
338  switch (nodeTag(def->arg))
339  {
340  case T_Integer:
341  switch (intVal(def->arg))
342  {
343  case 0:
344  return COPY_HEADER_FALSE;
345  case 1:
346  return COPY_HEADER_TRUE;
347  default:
348  /* otherwise, error out below */
349  break;
350  }
351  break;
352  default:
353  {
354  char *sval = defGetString(def);
355 
356  /*
357  * The set of strings accepted here should match up with the
358  * grammar's opt_boolean_or_string production.
359  */
360  if (pg_strcasecmp(sval, "true") == 0)
361  return COPY_HEADER_TRUE;
362  if (pg_strcasecmp(sval, "false") == 0)
363  return COPY_HEADER_FALSE;
364  if (pg_strcasecmp(sval, "on") == 0)
365  return COPY_HEADER_TRUE;
366  if (pg_strcasecmp(sval, "off") == 0)
367  return COPY_HEADER_FALSE;
368  if (pg_strcasecmp(sval, "match") == 0)
369  {
370  if (!is_from)
371  ereport(ERROR,
372  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
373  errmsg("cannot use \"%s\" with HEADER in COPY TO",
374  sval)));
375  return COPY_HEADER_MATCH;
376  }
377  }
378  break;
379  }
380  ereport(ERROR,
381  (errcode(ERRCODE_SYNTAX_ERROR),
382  errmsg("%s requires a Boolean value or \"match\"",
383  def->defname)));
384  return COPY_HEADER_FALSE; /* keep compiler quiet */
385 }
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:116
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:777
Node * arg
Definition: parsenodes.h:778
#define intVal(v)
Definition: value.h:79

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

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  /* MERGE is allowed by parser, but unimplemented. Reject for now */
277  if (IsA(stmt->query, MergeStmt))
278  ereport(ERROR,
279  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
280  errmsg("MERGE not supported in COPY"));
281 
282  query = makeNode(RawStmt);
283  query->stmt = stmt->query;
284  query->stmt_location = stmt_location;
285  query->stmt_len = stmt_len;
286 
287  relid = InvalidOid;
288  rel = NULL;
289  }
290 
291  if (is_from)
292  {
293  CopyFromState cstate;
294 
295  Assert(rel);
296 
297  /* check read-only transaction and parallel mode */
298  if (XactReadOnly && !rel->rd_islocaltemp)
299  PreventCommandIfReadOnly("COPY FROM");
300 
301  cstate = BeginCopyFrom(pstate, rel, whereClause,
302  stmt->filename, stmt->is_program,
303  NULL, stmt->attlist, stmt->options);
304  *processed = CopyFrom(cstate); /* copy from file to database */
305  EndCopyFrom(cstate);
306  }
307  else
308  {
309  CopyToState cstate;
310 
311  cstate = BeginCopyTo(pstate, rel, query, relid,
312  stmt->filename, stmt->is_program,
313  NULL, stmt->attlist, stmt->options);
314  *processed = DoCopyTo(cstate); /* copy from database to file */
315  EndCopyTo(cstate);
316  }
317 
318  if (rel != NULL)
319  table_close(rel, NoLock);
320 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4949
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:721
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:739
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2132
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:1333
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:632
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1707
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:749
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:357
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:728
struct cursor * cur
Definition: ecpg.c:28
int errhint(const char *fmt,...)
Definition: elog.c:1153
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:3331
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
char * pstrdup(const char *in)
Definition: mcxt.c:1483
Oid GetUserId(void)
Definition: miscinit.c:497
#define IsA(nodeptr, _type_)
Definition: nodes.h:162
#define makeNode(_type_)
Definition: nodes.h:159
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:92
@ 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:83
#define ACL_SELECT
Definition: parsenodes.h:84
#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:501
#define RelationGetDescr(relation)
Definition: rel.h:527
#define RelationGetNamespace(relation)
Definition: rel.h:542
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:260
List * fields
Definition: parsenodes.h:259
bool is_program
Definition: parsenodes.h:2203
RangeVar * relation
Definition: parsenodes.h:2197
List * options
Definition: parsenodes.h:2205
bool is_from
Definition: parsenodes.h:2202
char * filename
Definition: parsenodes.h:2204
List * attlist
Definition: parsenodes.h:2200
Node * whereClause
Definition: parsenodes.h:2206
Node * query
Definition: parsenodes.h:2198
Definition: nodes.h:112
RangeTblEntry * p_rte
Definition: parse_node.h:272
List * p_rtable
Definition: parse_node.h:183
AclMode requiredPerms
Definition: parsenodes.h:1180
Bitmapset * selectedCols
Definition: parsenodes.h:1182
Bitmapset * insertedCols
Definition: parsenodes.h:1183
int stmt_len
Definition: parsenodes.h:1633
Node * stmt
Definition: parsenodes.h:1631
int stmt_location
Definition: parsenodes.h:1632
bool rd_islocaltemp
Definition: rel.h:60
int location
Definition: parsenodes.h:485
Node * val
Definition: parsenodes.h:484
List * indirection
Definition: parsenodes.h:483
char * name
Definition: parsenodes.h:482
#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
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:411
#define select(n, r, w, e, timeout)
Definition: win32_port.h:492
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, IsA, 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 404 of file copy.c.

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

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().