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

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

651 {
652  List *attnums = NIL;
653 
654  if (attnamelist == NIL)
655  {
656  /* Generate default column list */
657  int attr_count = tupDesc->natts;
658  int i;
659 
660  for (i = 0; i < attr_count; i++)
661  {
662  if (TupleDescAttr(tupDesc, i)->attisdropped)
663  continue;
664  if (TupleDescAttr(tupDesc, i)->attgenerated)
665  continue;
666  attnums = lappend_int(attnums, i + 1);
667  }
668  }
669  else
670  {
671  /* Validate the user-supplied list and extract attnums */
672  ListCell *l;
673 
674  foreach(l, attnamelist)
675  {
676  char *name = strVal(lfirst(l));
677  int attnum;
678  int i;
679 
680  /* Lookup column name */
681  attnum = InvalidAttrNumber;
682  for (i = 0; i < tupDesc->natts; i++)
683  {
684  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
685 
686  if (att->attisdropped)
687  continue;
688  if (namestrcmp(&(att->attname), name) == 0)
689  {
690  if (att->attgenerated)
691  ereport(ERROR,
692  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
693  errmsg("column \"%s\" is a generated column",
694  name),
695  errdetail("Generated columns cannot be used in COPY.")));
696  attnum = att->attnum;
697  break;
698  }
699  }
700  if (attnum == InvalidAttrNumber)
701  {
702  if (rel != NULL)
703  ereport(ERROR,
704  (errcode(ERRCODE_UNDEFINED_COLUMN),
705  errmsg("column \"%s\" of relation \"%s\" does not exist",
706  name, RelationGetRelationName(rel))));
707  else
708  ereport(ERROR,
709  (errcode(ERRCODE_UNDEFINED_COLUMN),
710  errmsg("column \"%s\" does not exist",
711  name)));
712  }
713  /* Check for duplicates */
714  if (list_member_int(attnums, attnum))
715  ereport(ERROR,
716  (errcode(ERRCODE_DUPLICATE_COLUMN),
717  errmsg("column \"%s\" specified more than once",
718  name)));
719  attnums = lappend_int(attnums, attnum);
720  }
721  }
722 
723  return attnums;
724 }
#define NIL
Definition: pg_list.h:65
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:65
int errcode(int sqlerrcode)
Definition: elog.c:698
int namestrcmp(Name name, const char *str)
Definition: name.c:247
#define ERROR
Definition: elog.h:46
bool list_member_int(const List *list, int datum)
Definition: list.c:669
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define RelationGetRelationName(relation)
Definition: rel.h:511
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:207
List * lappend_int(List *list, int datum)
Definition: list.c:354
int16 attnum
Definition: pg_attribute.h:83
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:561
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
Definition: pg_list.h:50

◆ DoCopy()

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

Definition at line 64 of file copy.c.

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, SelectStmt::fromClause, get_namespace_name(), GetUserId(), ResTarget::indirection, RangeTblEntry::insertedCols, InvalidOid, CopyStmt::is_from, is_member_of_role(), 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(), SelectStmt::targetList, transformExpr(), ResTarget::val, CopyStmt::whereClause, and XactReadOnly.

Referenced by standard_ProcessUtility().

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 (!is_member_of_role(GetUserId(), ROLE_PG_EXECUTE_SERVER_PROGRAM))
84  ereport(ERROR,
85  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
86  errmsg("must be superuser or a member 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 && !is_member_of_role(GetUserId(), ROLE_PG_READ_SERVER_FILES))
93  ereport(ERROR,
94  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
95  errmsg("must be superuser or a member 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 && !is_member_of_role(GetUserId(), ROLE_PG_WRITE_SERVER_FILES))
100  ereport(ERROR,
101  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
102  errmsg("must be superuser or a member 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 */
253  select = makeNode(SelectStmt);
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 }
List * indirection
Definition: parsenodes.h:465
#define NIL
Definition: pg_list.h:65
Node * whereClause
Definition: parsenodes.h:2130
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * val
Definition: parsenodes.h:466
int errhint(const char *fmt,...)
Definition: elog.c:1156
List * attlist
Definition: parsenodes.h:2124
List * fromClause
Definition: parsenodes.h:1662
#define RelationGetDescr(relation)
Definition: rel.h:503
int LOCKMODE
Definition: lockdefs.h:26
char * name
Definition: parsenodes.h:464
Oid GetUserId(void)
Definition: miscinit.c:495
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:525
char * pstrdup(const char *in)
Definition: mcxt.c:1299
bool rd_islocaltemp
Definition: rel.h:60
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:536
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:698
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2094
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
AclMode requiredPerms
Definition: parsenodes.h:1157
unsigned int Oid
Definition: postgres_ext.h:31
bool is_program
Definition: parsenodes.h:2127
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:754
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
int location
Definition: parsenodes.h:248
int location
Definition: parsenodes.h:467
#define list_make1(x1)
Definition: pg_list.h:206
void assign_expr_collations(ParseState *pstate, Node *expr)
RangeTblEntry * p_rte
Definition: parse_node.h:268
Bitmapset * selectedCols
Definition: parsenodes.h:1159
#define ERROR
Definition: elog.h:46
#define lfirst_int(lc)
Definition: pg_list.h:170
RangeVar * relation
Definition: parsenodes.h:2121
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
Node * stmt
Definition: parsenodes.h:1572
#define NoLock
Definition: lockdefs.h:34
List * targetList
Definition: parsenodes.h:1661
#define RowExclusiveLock
Definition: lockdefs.h:38
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:294
List * options
Definition: parsenodes.h:2129
#define select(n, r, w, e, timeout)
Definition: win32_port.h:464
#define RelationGetRelationName(relation)
Definition: rel.h:511
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ACL_SELECT
Definition: parsenodes.h:83
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
int stmt_len
Definition: parsenodes.h:1574
int stmt_location
Definition: parsenodes.h:1573
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
#define InvalidOid
Definition: postgres_ext.h:36
CopyToState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
Definition: copyto.c:342
#define ereport(elevel,...)
Definition: elog.h:157
bool XactReadOnly
Definition: xact.c:78
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4869
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
#define makeNode(_type_)
Definition: nodes.h:584
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:1186
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define ACL_INSERT
Definition: parsenodes.h:82
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:650
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:408
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1564
Node * query
Definition: parsenodes.h:2122
bool is_from
Definition: parsenodes.h:2126
int errmsg(const char *fmt,...)
Definition: elog.c:909
Bitmapset * insertedCols
Definition: parsenodes.h:1160
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:568
char * filename
Definition: parsenodes.h:2128
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:773
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:477
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
List * fields
Definition: parsenodes.h:247
#define RelationGetNamespace(relation)
Definition: rel.h:518
List * p_rtable
Definition: parse_node.h:182
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ ProcessCopyOptions()

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

Definition at line 333 of file copy.c.

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

337 {
338  bool format_specified = false;
339  bool freeze_specified = false;
340  bool header_specified = false;
341  ListCell *option;
342 
343  /* Support external use for option sanity checking */
344  if (opts_out == NULL)
345  opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
346 
347  opts_out->file_encoding = -1;
348 
349  /* Extract options from the statement node tree */
350  foreach(option, options)
351  {
352  DefElem *defel = lfirst_node(DefElem, option);
353 
354  if (strcmp(defel->defname, "format") == 0)
355  {
356  char *fmt = defGetString(defel);
357 
358  if (format_specified)
359  errorConflictingDefElem(defel, pstate);
360  format_specified = true;
361  if (strcmp(fmt, "text") == 0)
362  /* default format */ ;
363  else if (strcmp(fmt, "csv") == 0)
364  opts_out->csv_mode = true;
365  else if (strcmp(fmt, "binary") == 0)
366  opts_out->binary = true;
367  else
368  ereport(ERROR,
369  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
370  errmsg("COPY format \"%s\" not recognized", fmt),
371  parser_errposition(pstate, defel->location)));
372  }
373  else if (strcmp(defel->defname, "freeze") == 0)
374  {
375  if (freeze_specified)
376  errorConflictingDefElem(defel, pstate);
377  freeze_specified = true;
378  opts_out->freeze = defGetBoolean(defel);
379  }
380  else if (strcmp(defel->defname, "delimiter") == 0)
381  {
382  if (opts_out->delim)
383  errorConflictingDefElem(defel, pstate);
384  opts_out->delim = defGetString(defel);
385  }
386  else if (strcmp(defel->defname, "null") == 0)
387  {
388  if (opts_out->null_print)
389  errorConflictingDefElem(defel, pstate);
390  opts_out->null_print = defGetString(defel);
391  }
392  else if (strcmp(defel->defname, "header") == 0)
393  {
394  if (header_specified)
395  errorConflictingDefElem(defel, pstate);
396  header_specified = true;
397  opts_out->header_line = defGetBoolean(defel);
398  }
399  else if (strcmp(defel->defname, "quote") == 0)
400  {
401  if (opts_out->quote)
402  errorConflictingDefElem(defel, pstate);
403  opts_out->quote = defGetString(defel);
404  }
405  else if (strcmp(defel->defname, "escape") == 0)
406  {
407  if (opts_out->escape)
408  errorConflictingDefElem(defel, pstate);
409  opts_out->escape = defGetString(defel);
410  }
411  else if (strcmp(defel->defname, "force_quote") == 0)
412  {
413  if (opts_out->force_quote || opts_out->force_quote_all)
414  errorConflictingDefElem(defel, pstate);
415  if (defel->arg && IsA(defel->arg, A_Star))
416  opts_out->force_quote_all = true;
417  else if (defel->arg && IsA(defel->arg, List))
418  opts_out->force_quote = castNode(List, defel->arg);
419  else
420  ereport(ERROR,
421  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
422  errmsg("argument to option \"%s\" must be a list of column names",
423  defel->defname),
424  parser_errposition(pstate, defel->location)));
425  }
426  else if (strcmp(defel->defname, "force_not_null") == 0)
427  {
428  if (opts_out->force_notnull)
429  errorConflictingDefElem(defel, pstate);
430  if (defel->arg && IsA(defel->arg, List))
431  opts_out->force_notnull = castNode(List, defel->arg);
432  else
433  ereport(ERROR,
434  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
435  errmsg("argument to option \"%s\" must be a list of column names",
436  defel->defname),
437  parser_errposition(pstate, defel->location)));
438  }
439  else if (strcmp(defel->defname, "force_null") == 0)
440  {
441  if (opts_out->force_null)
442  errorConflictingDefElem(defel, pstate);
443  if (defel->arg && IsA(defel->arg, List))
444  opts_out->force_null = castNode(List, defel->arg);
445  else
446  ereport(ERROR,
447  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
448  errmsg("argument to option \"%s\" must be a list of column names",
449  defel->defname),
450  parser_errposition(pstate, defel->location)));
451  }
452  else if (strcmp(defel->defname, "convert_selectively") == 0)
453  {
454  /*
455  * Undocumented, not-accessible-from-SQL option: convert only the
456  * named columns to binary form, storing the rest as NULLs. It's
457  * allowed for the column list to be NIL.
458  */
459  if (opts_out->convert_selectively)
460  errorConflictingDefElem(defel, pstate);
461  opts_out->convert_selectively = true;
462  if (defel->arg == NULL || IsA(defel->arg, List))
463  opts_out->convert_select = castNode(List, defel->arg);
464  else
465  ereport(ERROR,
466  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
467  errmsg("argument to option \"%s\" must be a list of column names",
468  defel->defname),
469  parser_errposition(pstate, defel->location)));
470  }
471  else if (strcmp(defel->defname, "encoding") == 0)
472  {
473  if (opts_out->file_encoding >= 0)
474  errorConflictingDefElem(defel, pstate);
475  opts_out->file_encoding = pg_char_to_encoding(defGetString(defel));
476  if (opts_out->file_encoding < 0)
477  ereport(ERROR,
478  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
479  errmsg("argument to option \"%s\" must be a valid encoding name",
480  defel->defname),
481  parser_errposition(pstate, defel->location)));
482  }
483  else
484  ereport(ERROR,
485  (errcode(ERRCODE_SYNTAX_ERROR),
486  errmsg("option \"%s\" not recognized",
487  defel->defname),
488  parser_errposition(pstate, defel->location)));
489  }
490 
491  /*
492  * Check for incompatible options (must do these two before inserting
493  * defaults)
494  */
495  if (opts_out->binary && opts_out->delim)
496  ereport(ERROR,
497  (errcode(ERRCODE_SYNTAX_ERROR),
498  errmsg("cannot specify DELIMITER in BINARY mode")));
499 
500  if (opts_out->binary && opts_out->null_print)
501  ereport(ERROR,
502  (errcode(ERRCODE_SYNTAX_ERROR),
503  errmsg("cannot specify NULL in BINARY mode")));
504 
505  /* Set defaults for omitted options */
506  if (!opts_out->delim)
507  opts_out->delim = opts_out->csv_mode ? "," : "\t";
508 
509  if (!opts_out->null_print)
510  opts_out->null_print = opts_out->csv_mode ? "" : "\\N";
511  opts_out->null_print_len = strlen(opts_out->null_print);
512 
513  if (opts_out->csv_mode)
514  {
515  if (!opts_out->quote)
516  opts_out->quote = "\"";
517  if (!opts_out->escape)
518  opts_out->escape = opts_out->quote;
519  }
520 
521  /* Only single-byte delimiter strings are supported. */
522  if (strlen(opts_out->delim) != 1)
523  ereport(ERROR,
524  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
525  errmsg("COPY delimiter must be a single one-byte character")));
526 
527  /* Disallow end-of-line characters */
528  if (strchr(opts_out->delim, '\r') != NULL ||
529  strchr(opts_out->delim, '\n') != NULL)
530  ereport(ERROR,
531  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
532  errmsg("COPY delimiter cannot be newline or carriage return")));
533 
534  if (strchr(opts_out->null_print, '\r') != NULL ||
535  strchr(opts_out->null_print, '\n') != NULL)
536  ereport(ERROR,
537  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
538  errmsg("COPY null representation cannot use newline or carriage return")));
539 
540  /*
541  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
542  * backslash because it would be ambiguous. We can't allow the other
543  * cases because data characters matching the delimiter must be
544  * backslashed, and certain backslash combinations are interpreted
545  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
546  * more than strictly necessary, but seems best for consistency and
547  * future-proofing. Likewise we disallow all digits though only octal
548  * digits are actually dangerous.
549  */
550  if (!opts_out->csv_mode &&
551  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
552  opts_out->delim[0]) != NULL)
553  ereport(ERROR,
554  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
555  errmsg("COPY delimiter cannot be \"%s\"", opts_out->delim)));
556 
557  /* Check header */
558  if (!opts_out->csv_mode && opts_out->header_line)
559  ereport(ERROR,
560  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
561  errmsg("COPY HEADER available only in CSV mode")));
562 
563  /* Check quote */
564  if (!opts_out->csv_mode && opts_out->quote != NULL)
565  ereport(ERROR,
566  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
567  errmsg("COPY quote available only in CSV mode")));
568 
569  if (opts_out->csv_mode && strlen(opts_out->quote) != 1)
570  ereport(ERROR,
571  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
572  errmsg("COPY quote must be a single one-byte character")));
573 
574  if (opts_out->csv_mode && opts_out->delim[0] == opts_out->quote[0])
575  ereport(ERROR,
576  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
577  errmsg("COPY delimiter and quote must be different")));
578 
579  /* Check escape */
580  if (!opts_out->csv_mode && opts_out->escape != NULL)
581  ereport(ERROR,
582  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
583  errmsg("COPY escape available only in CSV mode")));
584 
585  if (opts_out->csv_mode && strlen(opts_out->escape) != 1)
586  ereport(ERROR,
587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
588  errmsg("COPY escape must be a single one-byte character")));
589 
590  /* Check force_quote */
591  if (!opts_out->csv_mode && (opts_out->force_quote || opts_out->force_quote_all))
592  ereport(ERROR,
593  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
594  errmsg("COPY force quote available only in CSV mode")));
595  if ((opts_out->force_quote || opts_out->force_quote_all) && is_from)
596  ereport(ERROR,
597  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
598  errmsg("COPY force quote only available using COPY TO")));
599 
600  /* Check force_notnull */
601  if (!opts_out->csv_mode && opts_out->force_notnull != NIL)
602  ereport(ERROR,
603  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
604  errmsg("COPY force not null available only in CSV mode")));
605  if (opts_out->force_notnull != NIL && !is_from)
606  ereport(ERROR,
607  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
608  errmsg("COPY force not null only available using COPY FROM")));
609 
610  /* Check force_null */
611  if (!opts_out->csv_mode && opts_out->force_null != NIL)
612  ereport(ERROR,
613  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
614  errmsg("COPY force null available only in CSV mode")));
615 
616  if (opts_out->force_null != NIL && !is_from)
617  ereport(ERROR,
618  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
619  errmsg("COPY force null only available using COPY FROM")));
620 
621  /* Don't allow the delimiter to appear in the null string. */
622  if (strchr(opts_out->null_print, opts_out->delim[0]) != NULL)
623  ereport(ERROR,
624  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
625  errmsg("COPY delimiter must not appear in the NULL specification")));
626 
627  /* Don't allow the CSV quote char to appear in the null string. */
628  if (opts_out->csv_mode &&
629  strchr(opts_out->null_print, opts_out->quote[0]) != NULL)
630  ereport(ERROR,
631  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
632  errmsg("CSV quote character must not appear in the NULL specification")));
633 }
#define NIL
Definition: pg_list.h:65
int null_print_len
Definition: copy.h:37
#define IsA(nodeptr, _type_)
Definition: nodes.h:587
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
#define castNode(_type_, nodeptr)
Definition: nodes.h:605
int errcode(int sqlerrcode)
Definition: elog.c:698
List * force_notnull
Definition: copy.h:45
bool force_quote_all
Definition: copy.h:43
char * null_print
Definition: copy.h:36
char * quote
Definition: copy.h:40
bool defGetBoolean(DefElem *def)
Definition: define.c:106
#define ERROR
Definition: elog.h:46
char * defGetString(DefElem *def)
Definition: define.c:49
bool binary
Definition: copy.h:32
List * force_null
Definition: copy.h:47
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool csv_mode
Definition: copy.h:34
int location
Definition: parsenodes.h:761
bool header_line
Definition: copy.h:35
int file_encoding
Definition: copy.h:30
Node * arg
Definition: parsenodes.h:759
void * palloc0(Size size)
Definition: mcxt.c:1093
List * force_quote
Definition: copy.h:42
char * delim
Definition: copy.h:39
List * convert_select
Definition: copy.h:50
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:350
bool convert_selectively
Definition: copy.h:49
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
char * escape
Definition: copy.h:41
bool freeze
Definition: copy.h:33
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * defname
Definition: parsenodes.h:758
Definition: pg_list.h:50