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

787 {
788  List *attnums = NIL;
789 
790  if (attnamelist == NIL)
791  {
792  /* Generate default column list */
793  int attr_count = tupDesc->natts;
794  int i;
795 
796  for (i = 0; i < attr_count; i++)
797  {
798  if (TupleDescAttr(tupDesc, i)->attisdropped)
799  continue;
800  if (TupleDescAttr(tupDesc, i)->attgenerated)
801  continue;
802  attnums = lappend_int(attnums, i + 1);
803  }
804  }
805  else
806  {
807  /* Validate the user-supplied list and extract attnums */
808  ListCell *l;
809 
810  foreach(l, attnamelist)
811  {
812  char *name = strVal(lfirst(l));
813  int attnum;
814  int i;
815 
816  /* Lookup column name */
818  for (i = 0; i < tupDesc->natts; i++)
819  {
820  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
821 
822  if (att->attisdropped)
823  continue;
824  if (namestrcmp(&(att->attname), name) == 0)
825  {
826  if (att->attgenerated)
827  ereport(ERROR,
828  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
829  errmsg("column \"%s\" is a generated column",
830  name),
831  errdetail("Generated columns cannot be used in COPY.")));
832  attnum = att->attnum;
833  break;
834  }
835  }
836  if (attnum == InvalidAttrNumber)
837  {
838  if (rel != NULL)
839  ereport(ERROR,
840  (errcode(ERRCODE_UNDEFINED_COLUMN),
841  errmsg("column \"%s\" of relation \"%s\" does not exist",
842  name, RelationGetRelationName(rel))));
843  else
844  ereport(ERROR,
845  (errcode(ERRCODE_UNDEFINED_COLUMN),
846  errmsg("column \"%s\" does not exist",
847  name)));
848  }
849  /* Check for duplicates */
850  if (list_member_int(attnums, attnum))
851  ereport(ERROR,
852  (errcode(ERRCODE_DUPLICATE_COLUMN),
853  errmsg("column \"%s\" specified more than once",
854  name)));
855  attnums = lappend_int(attnums, attnum);
856  }
857  }
858 
859  return attnums;
860 }
#define InvalidAttrNumber
Definition: attnum.h:23
int errdetail(const char *fmt,...)
Definition: elog.c:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
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:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define RelationGetRelationName(relation)
Definition: rel.h:538
Definition: pg_list.h:54
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:82
const char * name

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

338 {
339  /*
340  * If no parameter value given, assume "true" is meant.
341  */
342  if (def->arg == NULL)
343  return COPY_HEADER_TRUE;
344 
345  /*
346  * Allow 0, 1, "true", "false", "on", "off", or "match".
347  */
348  switch (nodeTag(def->arg))
349  {
350  case T_Integer:
351  switch (intVal(def->arg))
352  {
353  case 0:
354  return COPY_HEADER_FALSE;
355  case 1:
356  return COPY_HEADER_TRUE;
357  default:
358  /* otherwise, error out below */
359  break;
360  }
361  break;
362  default:
363  {
364  char *sval = defGetString(def);
365 
366  /*
367  * The set of strings accepted here should match up with the
368  * grammar's opt_boolean_or_string production.
369  */
370  if (pg_strcasecmp(sval, "true") == 0)
371  return COPY_HEADER_TRUE;
372  if (pg_strcasecmp(sval, "false") == 0)
373  return COPY_HEADER_FALSE;
374  if (pg_strcasecmp(sval, "on") == 0)
375  return COPY_HEADER_TRUE;
376  if (pg_strcasecmp(sval, "off") == 0)
377  return COPY_HEADER_FALSE;
378  if (pg_strcasecmp(sval, "match") == 0)
379  {
380  if (!is_from)
381  ereport(ERROR,
382  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
383  errmsg("cannot use \"%s\" with HEADER in COPY TO",
384  sval)));
385  return COPY_HEADER_MATCH;
386  }
387  }
388  break;
389  }
390  ereport(ERROR,
391  (errcode(ERRCODE_SYNTAX_ERROR),
392  errmsg("%s requires a Boolean value or \"match\"",
393  def->defname)));
394  return COPY_HEADER_FALSE; /* keep compiler quiet */
395 }
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:133
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
char * defname
Definition: parsenodes.h:809
Node * arg
Definition: parsenodes.h:810
#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("permission denied to COPY to or from an external program"),
87  errdetail("Only roles with privileges of the \"%s\" role may COPY to or from an external program.",
88  "pg_execute_server_program"),
89  errhint("Anyone can COPY to stdout or from stdin. "
90  "psql's \\copy command also works for anyone.")));
91  }
92  else
93  {
94  if (is_from && !has_privs_of_role(GetUserId(), ROLE_PG_READ_SERVER_FILES))
95  ereport(ERROR,
96  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
97  errmsg("permission denied to COPY from a file"),
98  errdetail("Only roles with privileges of the \"%s\" role may COPY from a file.",
99  "pg_read_server_files"),
100  errhint("Anyone can COPY to stdout or from stdin. "
101  "psql's \\copy command also works for anyone.")));
102 
103  if (!is_from && !has_privs_of_role(GetUserId(), ROLE_PG_WRITE_SERVER_FILES))
104  ereport(ERROR,
105  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
106  errmsg("permission denied to COPY to a file"),
107  errdetail("Only roles with privileges of the \"%s\" role may COPY to a file.",
108  "pg_write_server_files"),
109  errhint("Anyone can COPY to stdout or from stdin. "
110  "psql's \\copy command also works for anyone.")));
111  }
112  }
113 
114  if (stmt->relation)
115  {
116  LOCKMODE lockmode = is_from ? RowExclusiveLock : AccessShareLock;
117  ParseNamespaceItem *nsitem;
118  RTEPermissionInfo *perminfo;
119  TupleDesc tupDesc;
120  List *attnums;
121  ListCell *cur;
122 
123  Assert(!stmt->query);
124 
125  /* Open and lock the relation, using the appropriate lock type. */
126  rel = table_openrv(stmt->relation, lockmode);
127 
128  relid = RelationGetRelid(rel);
129 
130  nsitem = addRangeTableEntryForRelation(pstate, rel, lockmode,
131  NULL, false, false);
132 
133  perminfo = nsitem->p_perminfo;
134  perminfo->requiredPerms = (is_from ? ACL_INSERT : ACL_SELECT);
135 
136  if (stmt->whereClause)
137  {
138  /* add nsitem to query namespace */
139  addNSItemToQuery(pstate, nsitem, false, true, true);
140 
141  /* Transform the raw expression tree */
142  whereClause = transformExpr(pstate, stmt->whereClause, EXPR_KIND_COPY_WHERE);
143 
144  /* Make sure it yields a boolean result. */
145  whereClause = coerce_to_boolean(pstate, whereClause, "WHERE");
146 
147  /* we have to fix its collations too */
148  assign_expr_collations(pstate, whereClause);
149 
150  whereClause = eval_const_expressions(NULL, whereClause);
151 
152  whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
153  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
154  }
155 
156  tupDesc = RelationGetDescr(rel);
157  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
158  foreach(cur, attnums)
159  {
160  int attno;
161  Bitmapset **bms;
162 
164  bms = is_from ? &perminfo->insertedCols : &perminfo->selectedCols;
165 
166  *bms = bms_add_member(*bms, attno);
167  }
168  ExecCheckPermissions(pstate->p_rtable, list_make1(perminfo), true);
169 
170  /*
171  * Permission check for row security policies.
172  *
173  * check_enable_rls will ereport(ERROR) if the user has requested
174  * something invalid and will otherwise indicate if we should enable
175  * RLS (returns RLS_ENABLED) or not for this COPY statement.
176  *
177  * If the relation has a row security policy and we are to apply it
178  * then perform a "query" copy and allow the normal query processing
179  * to handle the policies.
180  *
181  * If RLS is not enabled for this, then just fall through to the
182  * normal non-filtering relation handling.
183  */
184  if (check_enable_rls(relid, InvalidOid, false) == RLS_ENABLED)
185  {
187  ColumnRef *cr;
188  ResTarget *target;
189  RangeVar *from;
190  List *targetList = NIL;
191 
192  if (is_from)
193  ereport(ERROR,
194  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
195  errmsg("COPY FROM not supported with row-level security"),
196  errhint("Use INSERT statements instead.")));
197 
198  /*
199  * Build target list
200  *
201  * If no columns are specified in the attribute list of the COPY
202  * command, then the target list is 'all' columns. Therefore, '*'
203  * should be used as the target list for the resulting SELECT
204  * statement.
205  *
206  * In the case that columns are specified in the attribute list,
207  * create a ColumnRef and ResTarget for each column and add them
208  * to the target list for the resulting SELECT statement.
209  */
210  if (!stmt->attlist)
211  {
212  cr = makeNode(ColumnRef);
214  cr->location = -1;
215 
216  target = makeNode(ResTarget);
217  target->name = NULL;
218  target->indirection = NIL;
219  target->val = (Node *) cr;
220  target->location = -1;
221 
222  targetList = list_make1(target);
223  }
224  else
225  {
226  ListCell *lc;
227 
228  foreach(lc, stmt->attlist)
229  {
230  /*
231  * Build the ColumnRef for each column. The ColumnRef
232  * 'fields' property is a String node that corresponds to
233  * the column name respectively.
234  */
235  cr = makeNode(ColumnRef);
236  cr->fields = list_make1(lfirst(lc));
237  cr->location = -1;
238 
239  /* Build the ResTarget and add the ColumnRef to it. */
240  target = makeNode(ResTarget);
241  target->name = NULL;
242  target->indirection = NIL;
243  target->val = (Node *) cr;
244  target->location = -1;
245 
246  /* Add each column to the SELECT statement's target list */
247  targetList = lappend(targetList, target);
248  }
249  }
250 
251  /*
252  * Build RangeVar for from clause, fully qualified based on the
253  * relation which we have opened and locked. Use "ONLY" so that
254  * COPY retrieves rows from only the target table not any
255  * inheritance children, the same as when RLS doesn't apply.
256  */
259  -1);
260  from->inh = false; /* apply ONLY */
261 
262  /* Build query */
264  select->targetList = targetList;
265  select->fromClause = list_make1(from);
266 
267  query = makeNode(RawStmt);
268  query->stmt = (Node *) select;
269  query->stmt_location = stmt_location;
270  query->stmt_len = stmt_len;
271 
272  /*
273  * Close the relation for now, but keep the lock on it to prevent
274  * changes between now and when we start the query-based COPY.
275  *
276  * We'll reopen it later as part of the query-based COPY.
277  */
278  table_close(rel, NoLock);
279  rel = NULL;
280  }
281  }
282  else
283  {
284  Assert(stmt->query);
285 
286  /* MERGE is allowed by parser, but unimplemented. Reject for now */
287  if (IsA(stmt->query, MergeStmt))
288  ereport(ERROR,
289  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
290  errmsg("MERGE not supported in COPY"));
291 
292  query = makeNode(RawStmt);
293  query->stmt = stmt->query;
294  query->stmt_location = stmt_location;
295  query->stmt_len = stmt_len;
296 
297  relid = InvalidOid;
298  rel = NULL;
299  }
300 
301  if (is_from)
302  {
303  CopyFromState cstate;
304 
305  Assert(rel);
306 
307  /* check read-only transaction and parallel mode */
308  if (XactReadOnly && !rel->rd_islocaltemp)
309  PreventCommandIfReadOnly("COPY FROM");
310 
311  cstate = BeginCopyFrom(pstate, rel, whereClause,
312  stmt->filename, stmt->is_program,
313  NULL, stmt->attlist, stmt->options);
314  *processed = CopyFrom(cstate); /* copy from file to database */
315  EndCopyFrom(cstate);
316  }
317  else
318  {
319  CopyToState cstate;
320 
321  cstate = BeginCopyTo(pstate, rel, query, relid,
322  stmt->filename, stmt->is_program,
323  NULL, stmt->attlist, stmt->options);
324  *processed = DoCopyTo(cstate); /* copy from database to file */
325  EndCopyTo(cstate);
326  }
327 
328  if (rel != NULL)
329  table_close(rel, NoLock);
330 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4961
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:786
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2171
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:1334
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:632
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1733
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:746
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:725
struct cursor * cur
Definition: ecpg.c:28
int errhint(const char *fmt,...)
Definition: elog.c:1316
bool ExecCheckPermissions(List *rangeTable, List *rteperminfos, bool ereport_on_violation)
Definition: execMain.c:581
#define stmt
Definition: indent_codes.h:59
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:3348
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:722
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
char * pstrdup(const char *in)
Definition: mcxt.c:1644
Oid GetUserId(void)
Definition: miscinit.c:509
#define IsA(nodeptr, _type_)
Definition: nodes.h:179
#define makeNode(_type_)
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:110
@ EXPR_KIND_COPY_WHERE
Definition: parse_node.h:81
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
#define ACL_INSERT
Definition: parsenodes.h:83
#define ACL_SELECT
Definition: parsenodes.h:84
#define lfirst_int(lc)
Definition: pg_list.h:173
#define list_make1(x1)
Definition: pg_list.h:212
#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:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetNamespace(relation)
Definition: rel.h:545
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:292
List * fields
Definition: parsenodes.h:291
Definition: nodes.h:129
RTEPermissionInfo * p_perminfo
Definition: parse_node.h:288
List * p_rtable
Definition: parse_node.h:193
Bitmapset * selectedCols
Definition: parsenodes.h:1247
AclMode requiredPerms
Definition: parsenodes.h:1245
Bitmapset * insertedCols
Definition: parsenodes.h:1248
bool inh
Definition: primnodes.h:77
int stmt_len
Definition: parsenodes.h:1887
Node * stmt
Definition: parsenodes.h:1885
int stmt_location
Definition: parsenodes.h:1886
bool rd_islocaltemp
Definition: rel.h:61
int location
Definition: parsenodes.h:517
Node * val
Definition: parsenodes.h:516
List * indirection
Definition: parsenodes.h:515
char * name
Definition: parsenodes.h:514
#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:495
bool XactReadOnly
Definition: xact.c:82

References AccessShareLock, ACL_INSERT, ACL_SELECT, addNSItemToQuery(), addRangeTableEntryForRelation(), Assert(), assign_expr_collations(), BeginCopyFrom(), BeginCopyTo(), bms_add_member(), canonicalize_qual(), check_enable_rls(), coerce_to_boolean(), CopyFrom(), CopyGetAttnums(), cur, DoCopyTo(), EndCopyFrom(), EndCopyTo(), ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, eval_const_expressions(), ExecCheckPermissions(), EXPR_KIND_COPY_WHERE, ColumnRef::fields, FirstLowInvalidHeapAttributeNumber, get_namespace_name(), GetUserId(), has_privs_of_role(), ResTarget::indirection, RangeVar::inh, RTEPermissionInfo::insertedCols, InvalidOid, IsA, lappend(), lfirst, lfirst_int, list_make1, ColumnRef::location, ResTarget::location, make_ands_implicit(), makeNode, makeRangeVar(), ResTarget::name, NIL, NoLock, ParseNamespaceItem::p_perminfo, ParseState::p_rtable, PreventCommandIfReadOnly(), pstrdup(), RelationData::rd_islocaltemp, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RTEPermissionInfo::requiredPerms, RLS_ENABLED, RowExclusiveLock, select, RTEPermissionInfo::selectedCols, RawStmt::stmt, stmt, RawStmt::stmt_len, RawStmt::stmt_location, table_close(), table_openrv(), transformExpr(), ResTarget::val, and XactReadOnly.

Referenced by standard_ProcessUtility().

◆ ProcessCopyOptions()

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

Definition at line 414 of file copy.c.

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

References DefElem::arg, CopyFormatOptions::binary, castNode, CopyFormatOptions::convert_select, CopyFormatOptions::convert_selectively, CopyFormatOptions::csv_mode, CopyFormatOptions::default_print, CopyFormatOptions::default_print_len, defGetBoolean(), defGetCopyHeaderChoice(), defGetString(), DefElem::defname, CopyFormatOptions::delim, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), CopyFormatOptions::escape, CopyFormatOptions::file_encoding, fmt, CopyFormatOptions::force_notnull, CopyFormatOptions::force_notnull_all, CopyFormatOptions::force_null, CopyFormatOptions::force_null_all, 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().