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