Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * copyfrom.c
4 : : * COPY <table> FROM file/program/client
5 : : *
6 : : * This file contains routines needed to efficiently load tuples into a
7 : : * table. That includes looking up the correct partition, firing triggers,
8 : : * calling the table AM function to insert the data, and updating indexes.
9 : : * Reading data from the input file or client and parsing it into Datums
10 : : * is handled in copyfromparse.c.
11 : : *
12 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
13 : : * Portions Copyright (c) 1994, Regents of the University of California
14 : : *
15 : : *
16 : : * IDENTIFICATION
17 : : * src/backend/commands/copyfrom.c
18 : : *
19 : : *-------------------------------------------------------------------------
20 : : */
21 : : #include "postgres.h"
22 : :
23 : : #include <ctype.h>
24 : : #include <unistd.h>
25 : : #include <sys/stat.h>
26 : :
27 : : #include "access/heapam.h"
28 : : #include "access/tableam.h"
29 : : #include "access/tupconvert.h"
30 : : #include "access/xact.h"
31 : : #include "catalog/namespace.h"
32 : : #include "commands/copyapi.h"
33 : : #include "commands/copyfrom_internal.h"
34 : : #include "commands/progress.h"
35 : : #include "commands/trigger.h"
36 : : #include "executor/execPartition.h"
37 : : #include "executor/executor.h"
38 : : #include "executor/nodeModifyTable.h"
39 : : #include "executor/tuptable.h"
40 : : #include "foreign/fdwapi.h"
41 : : #include "mb/pg_wchar.h"
42 : : #include "miscadmin.h"
43 : : #include "nodes/miscnodes.h"
44 : : #include "optimizer/optimizer.h"
45 : : #include "pgstat.h"
46 : : #include "rewrite/rewriteHandler.h"
47 : : #include "storage/fd.h"
48 : : #include "tcop/tcopprot.h"
49 : : #include "utils/lsyscache.h"
50 : : #include "utils/memutils.h"
51 : : #include "utils/portal.h"
52 : : #include "utils/rel.h"
53 : : #include "utils/snapmgr.h"
54 : : #include "utils/typcache.h"
55 : :
56 : : /*
57 : : * No more than this many tuples per CopyMultiInsertBuffer
58 : : *
59 : : * Caution: Don't make this too big, as we could end up with this many
60 : : * CopyMultiInsertBuffer items stored in CopyMultiInsertInfo's
61 : : * multiInsertBuffers list. Increasing this can cause quadratic growth in
62 : : * memory requirements during copies into partitioned tables with a large
63 : : * number of partitions.
64 : : */
65 : : #define MAX_BUFFERED_TUPLES 1000
66 : :
67 : : /*
68 : : * Flush buffers if there are >= this many bytes, as counted by the input
69 : : * size, of tuples stored.
70 : : */
71 : : #define MAX_BUFFERED_BYTES 65535
72 : :
73 : : /*
74 : : * Trim the list of buffers back down to this number after flushing. This
75 : : * must be >= 2.
76 : : */
77 : : #define MAX_PARTITION_BUFFERS 32
78 : :
79 : : /* Stores multi-insert data related to a single relation in CopyFrom. */
80 : : typedef struct CopyMultiInsertBuffer
81 : : {
82 : : TupleTableSlot *slots[MAX_BUFFERED_TUPLES]; /* Array to store tuples */
83 : : ResultRelInfo *resultRelInfo; /* ResultRelInfo for 'relid' */
84 : : BulkInsertState bistate; /* BulkInsertState for this rel if plain
85 : : * table; NULL if foreign table */
86 : : int nused; /* number of 'slots' containing tuples */
87 : : uint64 linenos[MAX_BUFFERED_TUPLES]; /* Line # of tuple in copy
88 : : * stream */
89 : : } CopyMultiInsertBuffer;
90 : :
91 : : /*
92 : : * Stores one or many CopyMultiInsertBuffers and details about the size and
93 : : * number of tuples which are stored in them. This allows multiple buffers to
94 : : * exist at once when COPYing into a partitioned table.
95 : : */
96 : : typedef struct CopyMultiInsertInfo
97 : : {
98 : : List *multiInsertBuffers; /* List of tracked CopyMultiInsertBuffers */
99 : : int bufferedTuples; /* number of tuples buffered over all buffers */
100 : : int bufferedBytes; /* number of bytes from all buffered tuples */
101 : : CopyFromState cstate; /* Copy state for this CopyMultiInsertInfo */
102 : : EState *estate; /* Executor state used for COPY */
103 : : CommandId mycid; /* Command Id used for COPY */
104 : : uint32 ti_options; /* table insert options */
105 : : } CopyMultiInsertInfo;
106 : :
107 : :
108 : : /* non-export function prototypes */
109 : : static void ClosePipeFromProgram(CopyFromState cstate);
110 : :
111 : : /*
112 : : * Built-in format-specific routines. One-row callbacks are defined in
113 : : * copyfromparse.c.
114 : : */
115 : : static void CopyFromTextLikeInFunc(CopyFromState cstate, Oid atttypid, FmgrInfo *finfo,
116 : : Oid *typioparam);
117 : : static void CopyFromTextLikeStart(CopyFromState cstate, TupleDesc tupDesc);
118 : : static void CopyFromTextLikeEnd(CopyFromState cstate);
119 : : static void CopyFromBinaryInFunc(CopyFromState cstate, Oid atttypid,
120 : : FmgrInfo *finfo, Oid *typioparam);
121 : : static void CopyFromBinaryStart(CopyFromState cstate, TupleDesc tupDesc);
122 : : static void CopyFromBinaryEnd(CopyFromState cstate);
123 : :
124 : :
125 : : /*
126 : : * COPY FROM routines for built-in formats.
127 : : *
128 : : * CSV and text formats share the same TextLike routines except for the
129 : : * one-row callback.
130 : : */
131 : :
132 : : /* text format */
133 : : static const CopyFromRoutine CopyFromRoutineText = {
134 : : .CopyFromInFunc = CopyFromTextLikeInFunc,
135 : : .CopyFromStart = CopyFromTextLikeStart,
136 : : .CopyFromOneRow = CopyFromTextOneRow,
137 : : .CopyFromEnd = CopyFromTextLikeEnd,
138 : : };
139 : :
140 : : /* CSV format */
141 : : static const CopyFromRoutine CopyFromRoutineCSV = {
142 : : .CopyFromInFunc = CopyFromTextLikeInFunc,
143 : : .CopyFromStart = CopyFromTextLikeStart,
144 : : .CopyFromOneRow = CopyFromCSVOneRow,
145 : : .CopyFromEnd = CopyFromTextLikeEnd,
146 : : };
147 : :
148 : : /* binary format */
149 : : static const CopyFromRoutine CopyFromRoutineBinary = {
150 : : .CopyFromInFunc = CopyFromBinaryInFunc,
151 : : .CopyFromStart = CopyFromBinaryStart,
152 : : .CopyFromOneRow = CopyFromBinaryOneRow,
153 : : .CopyFromEnd = CopyFromBinaryEnd,
154 : : };
155 : :
156 : : /* Return a COPY FROM routine for the given options */
157 : : static const CopyFromRoutine *
158 : 1274 : CopyFromGetRoutine(const CopyFormatOptions *opts)
159 : : {
160 [ + + ]: 1274 : if (opts->format == COPY_FORMAT_CSV)
161 : 194 : return &CopyFromRoutineCSV;
162 [ + + ]: 1080 : else if (opts->format == COPY_FORMAT_BINARY)
163 : 9 : return &CopyFromRoutineBinary;
164 : :
165 : : /* default is text */
166 : 1071 : return &CopyFromRoutineText;
167 : : }
168 : :
169 : : /* Implementation of the start callback for text and CSV formats */
170 : : static void
171 : 1249 : CopyFromTextLikeStart(CopyFromState cstate, TupleDesc tupDesc)
172 : : {
173 : : AttrNumber attr_count;
174 : :
175 : : /*
176 : : * If encoding conversion is needed, we need another buffer to hold the
177 : : * converted input data. Otherwise, we can just point input_buf to the
178 : : * same buffer as raw_buf.
179 : : */
180 [ + + ]: 1249 : if (cstate->need_transcoding)
181 : : {
182 : 24 : cstate->input_buf = (char *) palloc(INPUT_BUF_SIZE + 1);
183 : 24 : cstate->input_buf_index = cstate->input_buf_len = 0;
184 : : }
185 : : else
186 : 1225 : cstate->input_buf = cstate->raw_buf;
187 : 1249 : cstate->input_reached_eof = false;
188 : :
189 : 1249 : initStringInfo(&cstate->line_buf);
190 : :
191 : : /*
192 : : * Create workspace for CopyReadAttributes results; used by CSV and text
193 : : * format.
194 : : */
195 : 1249 : attr_count = list_length(cstate->attnumlist);
196 : 1249 : cstate->max_fields = attr_count;
197 : 1249 : cstate->raw_fields = palloc_array(char *, attr_count);
198 : 1249 : }
199 : :
200 : : /*
201 : : * Implementation of the infunc callback for text and CSV formats. Assign
202 : : * the input function data to the given *finfo.
203 : : */
204 : : static void
205 : 3669 : CopyFromTextLikeInFunc(CopyFromState cstate, Oid atttypid, FmgrInfo *finfo,
206 : : Oid *typioparam)
207 : : {
208 : : Oid func_oid;
209 : :
210 : 3669 : getTypeInputInfo(atttypid, &func_oid, typioparam);
211 : 3669 : fmgr_info(func_oid, finfo);
212 : 3669 : }
213 : :
214 : : /* Implementation of the end callback for text and CSV formats */
215 : : static void
216 : 1046 : CopyFromTextLikeEnd(CopyFromState cstate)
217 : : {
218 : : /* nothing to do */
219 : 1046 : }
220 : :
221 : : /* Implementation of the start callback for binary format */
222 : : static void
223 : 8 : CopyFromBinaryStart(CopyFromState cstate, TupleDesc tupDesc)
224 : : {
225 : : /* Read and verify binary header */
226 : 8 : ReceiveCopyBinaryHeader(cstate);
227 : 8 : }
228 : :
229 : : /*
230 : : * Implementation of the infunc callback for binary format. Assign
231 : : * the binary input function to the given *finfo.
232 : : */
233 : : static void
234 : 38 : CopyFromBinaryInFunc(CopyFromState cstate, Oid atttypid,
235 : : FmgrInfo *finfo, Oid *typioparam)
236 : : {
237 : : Oid func_oid;
238 : :
239 : 38 : getTypeBinaryInputInfo(atttypid, &func_oid, typioparam);
240 : 37 : fmgr_info(func_oid, finfo);
241 : 37 : }
242 : :
243 : : /* Implementation of the end callback for binary format */
244 : : static void
245 : 7 : CopyFromBinaryEnd(CopyFromState cstate)
246 : : {
247 : : /* nothing to do */
248 : 7 : }
249 : :
250 : : /*
251 : : * error context callback for COPY FROM
252 : : *
253 : : * The argument for the error context must be CopyFromState.
254 : : */
255 : : void
256 : 259 : CopyFromErrorCallback(void *arg)
257 : : {
258 : 259 : CopyFromState cstate = (CopyFromState) arg;
259 : :
260 [ + + ]: 259 : if (cstate->relname_only)
261 : : {
262 : 45 : errcontext("COPY %s",
263 : : cstate->cur_relname);
264 : 45 : return;
265 : : }
266 [ + + ]: 214 : if (cstate->opts.format == COPY_FORMAT_BINARY)
267 : : {
268 : : /* can't usefully display the data */
269 [ + - ]: 1 : if (cstate->cur_attname)
270 : 1 : errcontext("COPY %s, line %" PRIu64 ", column %s",
271 : : cstate->cur_relname,
272 : : cstate->cur_lineno,
273 : : cstate->cur_attname);
274 : : else
275 : 0 : errcontext("COPY %s, line %" PRIu64,
276 : : cstate->cur_relname,
277 : : cstate->cur_lineno);
278 : : }
279 : : else
280 : : {
281 [ + + + + ]: 213 : if (cstate->cur_attname && cstate->cur_attval)
282 : 29 : {
283 : : /* error is relevant to a particular column */
284 : : char *attval;
285 : :
286 : 29 : attval = CopyLimitPrintoutLength(cstate->cur_attval);
287 : 29 : errcontext("COPY %s, line %" PRIu64 ", column %s: \"%s\"",
288 : : cstate->cur_relname,
289 : : cstate->cur_lineno,
290 : : cstate->cur_attname,
291 : : attval);
292 : 29 : pfree(attval);
293 : : }
294 [ + + ]: 184 : else if (cstate->cur_attname)
295 : : {
296 : : /* error is relevant to a particular column, value is NULL */
297 : 12 : errcontext("COPY %s, line %" PRIu64 ", column %s: null input",
298 : : cstate->cur_relname,
299 : : cstate->cur_lineno,
300 : : cstate->cur_attname);
301 : : }
302 : : else
303 : : {
304 : : /*
305 : : * Error is relevant to a particular line.
306 : : *
307 : : * If line_buf still contains the correct line, print it.
308 : : */
309 [ + + ]: 172 : if (cstate->line_buf_valid)
310 : : {
311 : : char *lineval;
312 : :
313 : 146 : lineval = CopyLimitPrintoutLength(cstate->line_buf.data);
314 : 146 : errcontext("COPY %s, line %" PRIu64 ": \"%s\"",
315 : : cstate->cur_relname,
316 : : cstate->cur_lineno, lineval);
317 : 146 : pfree(lineval);
318 : : }
319 : : else
320 : : {
321 : 26 : errcontext("COPY %s, line %" PRIu64,
322 : : cstate->cur_relname,
323 : : cstate->cur_lineno);
324 : : }
325 : : }
326 : : }
327 : : }
328 : :
329 : : /*
330 : : * Make sure we don't print an unreasonable amount of COPY data in a message.
331 : : *
332 : : * Returns a pstrdup'd copy of the input.
333 : : */
334 : : char *
335 : 215 : CopyLimitPrintoutLength(const char *str)
336 : : {
337 : : #define MAX_COPY_DATA_DISPLAY 100
338 : :
339 : 215 : int slen = strlen(str);
340 : : int len;
341 : : char *res;
342 : :
343 : : /* Fast path if definitely okay */
344 [ + - ]: 215 : if (slen <= MAX_COPY_DATA_DISPLAY)
345 : 215 : return pstrdup(str);
346 : :
347 : : /* Apply encoding-dependent truncation */
348 : 0 : len = pg_mbcliplen(str, slen, MAX_COPY_DATA_DISPLAY);
349 : :
350 : : /*
351 : : * Truncate, and add "..." to show we truncated the input.
352 : : */
353 : 0 : res = (char *) palloc(len + 4);
354 : 0 : memcpy(res, str, len);
355 : 0 : strcpy(res + len, "...");
356 : :
357 : 0 : return res;
358 : : }
359 : :
360 : : /*
361 : : * Allocate memory and initialize a new CopyMultiInsertBuffer for this
362 : : * ResultRelInfo.
363 : : */
364 : : static CopyMultiInsertBuffer *
365 : 1096 : CopyMultiInsertBufferInit(ResultRelInfo *rri)
366 : : {
367 : : CopyMultiInsertBuffer *buffer;
368 : :
369 : 1096 : buffer = palloc_object(CopyMultiInsertBuffer);
370 : 1096 : memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
371 : 1096 : buffer->resultRelInfo = rri;
372 [ + + ]: 1096 : buffer->bistate = (rri->ri_FdwRoutine == NULL) ? GetBulkInsertState() : NULL;
373 : 1096 : buffer->nused = 0;
374 : :
375 : 1096 : return buffer;
376 : : }
377 : :
378 : : /*
379 : : * Make a new buffer for this ResultRelInfo.
380 : : */
381 : : static inline void
382 : 1096 : CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo,
383 : : ResultRelInfo *rri)
384 : : {
385 : : CopyMultiInsertBuffer *buffer;
386 : :
387 : 1096 : buffer = CopyMultiInsertBufferInit(rri);
388 : :
389 : : /* Setup back-link so we can easily find this buffer again */
390 : 1096 : rri->ri_CopyMultiInsertBuffer = buffer;
391 : : /* Record that we're tracking this buffer */
392 : 1096 : miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
393 : 1096 : }
394 : :
395 : : /*
396 : : * Initialize an already allocated CopyMultiInsertInfo.
397 : : *
398 : : * If rri is a non-partitioned table then a CopyMultiInsertBuffer is set up
399 : : * for that table.
400 : : */
401 : : static void
402 : 1094 : CopyMultiInsertInfoInit(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
403 : : CopyFromState cstate, EState *estate, CommandId mycid,
404 : : uint32 ti_options)
405 : : {
406 : 1094 : miinfo->multiInsertBuffers = NIL;
407 : 1094 : miinfo->bufferedTuples = 0;
408 : 1094 : miinfo->bufferedBytes = 0;
409 : 1094 : miinfo->cstate = cstate;
410 : 1094 : miinfo->estate = estate;
411 : 1094 : miinfo->mycid = mycid;
412 : 1094 : miinfo->ti_options = ti_options;
413 : :
414 : : /*
415 : : * Only setup the buffer when not dealing with a partitioned table.
416 : : * Buffers for partitioned tables will just be setup when we need to send
417 : : * tuples their way for the first time.
418 : : */
419 [ + + ]: 1094 : if (rri->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
420 : 1040 : CopyMultiInsertInfoSetupBuffer(miinfo, rri);
421 : 1094 : }
422 : :
423 : : /*
424 : : * Returns true if the buffers are full
425 : : */
426 : : static inline bool
427 : 712766 : CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
428 : : {
429 [ + + ]: 712766 : if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
430 [ + + ]: 712183 : miinfo->bufferedBytes >= MAX_BUFFERED_BYTES)
431 : 653 : return true;
432 : 712113 : return false;
433 : : }
434 : :
435 : : /*
436 : : * Returns true if we have no buffered tuples
437 : : */
438 : : static inline bool
439 : 964 : CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
440 : : {
441 : 964 : return miinfo->bufferedTuples == 0;
442 : : }
443 : :
444 : : /*
445 : : * Write the tuples stored in 'buffer' out to the table.
446 : : */
447 : : static inline void
448 : 1513 : CopyMultiInsertBufferFlush(CopyMultiInsertInfo *miinfo,
449 : : CopyMultiInsertBuffer *buffer,
450 : : int64 *processed)
451 : : {
452 : 1513 : CopyFromState cstate = miinfo->cstate;
453 : 1513 : EState *estate = miinfo->estate;
454 : 1513 : int nused = buffer->nused;
455 : 1513 : ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
456 : 1513 : TupleTableSlot **slots = buffer->slots;
457 : : int i;
458 : :
459 [ + + ]: 1513 : if (resultRelInfo->ri_FdwRoutine)
460 : : {
461 : 7 : int batch_size = resultRelInfo->ri_BatchSize;
462 : 7 : int sent = 0;
463 : :
464 : : Assert(buffer->bistate == NULL);
465 : :
466 : : /* Ensure that the FDW supports batching and it's enabled */
467 : : Assert(resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert);
468 : : Assert(batch_size > 1);
469 : :
470 : : /*
471 : : * We suppress error context information other than the relation name,
472 : : * if one of the operations below fails.
473 : : */
474 : : Assert(!cstate->relname_only);
475 : 7 : cstate->relname_only = true;
476 : :
477 [ + + ]: 19 : while (sent < nused)
478 : : {
479 : 13 : int size = (batch_size < nused - sent) ? batch_size : (nused - sent);
480 : 13 : int inserted = size;
481 : : TupleTableSlot **rslots;
482 : :
483 : : /* insert into foreign table: let the FDW do it */
484 : : rslots =
485 : 13 : resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
486 : : resultRelInfo,
487 : 13 : &slots[sent],
488 : : NULL,
489 : : &inserted);
490 : :
491 : : /* XXX See the comment in ExecBatchInsert() */
492 : 12 : inserted = Min(inserted, size);
493 : :
494 : 12 : sent += size;
495 : :
496 : : /* No need to do anything if there are no inserted rows */
497 [ + + ]: 12 : if (inserted <= 0)
498 : 2 : continue;
499 : :
500 : : /* Triggers on foreign tables should not have transition tables */
501 : : Assert(resultRelInfo->ri_TrigDesc == NULL ||
502 : : resultRelInfo->ri_TrigDesc->trig_insert_new_table == false);
503 : :
504 : : /* Run AFTER ROW INSERT triggers */
505 [ - + ]: 10 : if (resultRelInfo->ri_TrigDesc != NULL &&
506 [ # # ]: 0 : resultRelInfo->ri_TrigDesc->trig_insert_after_row)
507 : : {
508 : 0 : Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
509 : :
510 [ # # ]: 0 : for (i = 0; i < inserted; i++)
511 : : {
512 : 0 : TupleTableSlot *slot = rslots[i];
513 : :
514 : : /*
515 : : * AFTER ROW Triggers might reference the tableoid column,
516 : : * so (re-)initialize tts_tableOid before evaluating them.
517 : : */
518 : 0 : slot->tts_tableOid = relid;
519 : :
520 : 0 : ExecARInsertTriggers(estate, resultRelInfo,
521 : : slot, NULL, NIL,
522 : : cstate->transition_capture);
523 : : }
524 : : }
525 : :
526 : : /* Update the row counter and progress of the COPY command */
527 : 10 : *processed += inserted;
528 : 10 : pgstat_progress_update_param(PROGRESS_COPY_TUPLES_PROCESSED,
529 : : *processed);
530 : : }
531 : :
532 [ + + ]: 24 : for (i = 0; i < nused; i++)
533 : 18 : ExecClearTuple(slots[i]);
534 : :
535 : : /* reset relname_only */
536 : 6 : cstate->relname_only = false;
537 : : }
538 : : else
539 : : {
540 : 1506 : CommandId mycid = miinfo->mycid;
541 : 1506 : uint32 ti_options = miinfo->ti_options;
542 : 1506 : bool line_buf_valid = cstate->line_buf_valid;
543 : 1506 : uint64 save_cur_lineno = cstate->cur_lineno;
544 : : MemoryContext oldcontext;
545 : :
546 : : Assert(buffer->bistate != NULL);
547 : :
548 : : /*
549 : : * Print error context information correctly, if one of the operations
550 : : * below fails.
551 : : */
552 : 1506 : cstate->line_buf_valid = false;
553 : :
554 : : /*
555 : : * table_multi_insert may leak memory, so switch to short-lived memory
556 : : * context before calling it.
557 : : */
558 [ + - ]: 1506 : oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
559 : 1506 : table_multi_insert(resultRelInfo->ri_RelationDesc,
560 : : slots,
561 : : nused,
562 : : mycid,
563 : : ti_options,
564 : 1506 : buffer->bistate);
565 : 1506 : MemoryContextSwitchTo(oldcontext);
566 : :
567 [ + + ]: 714185 : for (i = 0; i < nused; i++)
568 : : {
569 : : /*
570 : : * If there are any indexes, update them for all the inserted
571 : : * tuples, and run AFTER ROW INSERT triggers.
572 : : */
573 [ + + ]: 712687 : if (resultRelInfo->ri_NumIndices > 0)
574 : : {
575 : : List *recheckIndexes;
576 : :
577 : 101021 : cstate->cur_lineno = buffer->linenos[i];
578 : : recheckIndexes =
579 : 101021 : ExecInsertIndexTuples(resultRelInfo,
580 : : estate, 0, buffer->slots[i],
581 : : NIL, NULL);
582 : 101013 : ExecARInsertTriggers(estate, resultRelInfo,
583 : 101013 : slots[i], NULL, recheckIndexes,
584 : : cstate->transition_capture);
585 : 101013 : list_free(recheckIndexes);
586 : : }
587 : :
588 : : /*
589 : : * There's no indexes, but see if we need to run AFTER ROW INSERT
590 : : * triggers anyway.
591 : : */
592 [ + + ]: 611666 : else if (resultRelInfo->ri_TrigDesc != NULL &&
593 [ + + ]: 56 : (resultRelInfo->ri_TrigDesc->trig_insert_after_row ||
594 [ + + ]: 44 : resultRelInfo->ri_TrigDesc->trig_insert_new_table))
595 : : {
596 : 24 : cstate->cur_lineno = buffer->linenos[i];
597 : 24 : ExecARInsertTriggers(estate, resultRelInfo,
598 : 24 : slots[i], NULL, NIL,
599 : : cstate->transition_capture);
600 : : }
601 : :
602 : 712679 : ExecClearTuple(slots[i]);
603 : : }
604 : :
605 : : /* Update the row counter and progress of the COPY command */
606 : 1498 : *processed += nused;
607 : 1498 : pgstat_progress_update_param(PROGRESS_COPY_TUPLES_PROCESSED,
608 : : *processed);
609 : :
610 : : /* reset cur_lineno and line_buf_valid to what they were */
611 : 1498 : cstate->line_buf_valid = line_buf_valid;
612 : 1498 : cstate->cur_lineno = save_cur_lineno;
613 : : }
614 : :
615 : : /* Mark that all slots are free */
616 : 1504 : buffer->nused = 0;
617 : 1504 : }
618 : :
619 : : /*
620 : : * Drop used slots and free member for this buffer.
621 : : *
622 : : * The buffer must be flushed before cleanup.
623 : : */
624 : : static inline void
625 : 939 : CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo,
626 : : CopyMultiInsertBuffer *buffer)
627 : : {
628 : 939 : ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
629 : : int i;
630 : :
631 : : /* Ensure buffer was flushed */
632 : : Assert(buffer->nused == 0);
633 : :
634 : : /* Remove back-link to ourself */
635 : 939 : resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
636 : :
637 [ + + ]: 939 : if (resultRelInfo->ri_FdwRoutine == NULL)
638 : : {
639 : : Assert(buffer->bistate != NULL);
640 : 933 : FreeBulkInsertState(buffer->bistate);
641 : : }
642 : : else
643 : : Assert(buffer->bistate == NULL);
644 : :
645 : : /* Since we only create slots on demand, just drop the non-null ones. */
646 [ + + + + ]: 148546 : for (i = 0; i < MAX_BUFFERED_TUPLES && buffer->slots[i] != NULL; i++)
647 : 147607 : ExecDropSingleTupleTableSlot(buffer->slots[i]);
648 : :
649 [ + + ]: 939 : if (resultRelInfo->ri_FdwRoutine == NULL)
650 : 933 : table_finish_bulk_insert(resultRelInfo->ri_RelationDesc,
651 : : miinfo->ti_options);
652 : :
653 : 939 : pfree(buffer);
654 : 939 : }
655 : :
656 : : /*
657 : : * Write out all stored tuples in all buffers out to the tables.
658 : : *
659 : : * Once flushed we also trim the tracked buffers list down to size by removing
660 : : * the buffers created earliest first.
661 : : *
662 : : * Callers should pass 'curr_rri' as the ResultRelInfo that's currently being
663 : : * used. When cleaning up old buffers we'll never remove the one for
664 : : * 'curr_rri'.
665 : : */
666 : : static inline void
667 : 1398 : CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri,
668 : : int64 *processed)
669 : : {
670 : : ListCell *lc;
671 : :
672 [ + - + + : 2902 : foreach(lc, miinfo->multiInsertBuffers)
+ + ]
673 : : {
674 : 1513 : CopyMultiInsertBuffer *buffer = (CopyMultiInsertBuffer *) lfirst(lc);
675 : :
676 : 1513 : CopyMultiInsertBufferFlush(miinfo, buffer, processed);
677 : : }
678 : :
679 : 1389 : miinfo->bufferedTuples = 0;
680 : 1389 : miinfo->bufferedBytes = 0;
681 : :
682 : : /*
683 : : * Trim the list of tracked buffers down if it exceeds the limit. Here we
684 : : * remove buffers starting with the ones we created first. It seems less
685 : : * likely that these older ones will be needed than the ones that were
686 : : * just created.
687 : : */
688 [ - + ]: 1389 : while (list_length(miinfo->multiInsertBuffers) > MAX_PARTITION_BUFFERS)
689 : : {
690 : : CopyMultiInsertBuffer *buffer;
691 : :
692 : 0 : buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
693 : :
694 : : /*
695 : : * We never want to remove the buffer that's currently being used, so
696 : : * if we happen to find that then move it to the end of the list.
697 : : */
698 [ # # ]: 0 : if (buffer->resultRelInfo == curr_rri)
699 : : {
700 : : /*
701 : : * The code below would misbehave if we were trying to reduce the
702 : : * list to less than two items.
703 : : */
704 : : StaticAssertDecl(MAX_PARTITION_BUFFERS >= 2,
705 : : "MAX_PARTITION_BUFFERS must be >= 2");
706 : :
707 : 0 : miinfo->multiInsertBuffers = list_delete_first(miinfo->multiInsertBuffers);
708 : 0 : miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
709 : 0 : buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
710 : : }
711 : :
712 : 0 : CopyMultiInsertBufferCleanup(miinfo, buffer);
713 : 0 : miinfo->multiInsertBuffers = list_delete_first(miinfo->multiInsertBuffers);
714 : : }
715 : 1389 : }
716 : :
717 : : /*
718 : : * Cleanup allocated buffers and free memory
719 : : */
720 : : static inline void
721 : 937 : CopyMultiInsertInfoCleanup(CopyMultiInsertInfo *miinfo)
722 : : {
723 : : ListCell *lc;
724 : :
725 [ + + + + : 1876 : foreach(lc, miinfo->multiInsertBuffers)
+ + ]
726 : 939 : CopyMultiInsertBufferCleanup(miinfo, lfirst(lc));
727 : :
728 : 937 : list_free(miinfo->multiInsertBuffers);
729 : 937 : }
730 : :
731 : : /*
732 : : * Get the next TupleTableSlot that the next tuple should be stored in.
733 : : *
734 : : * Callers must ensure that the buffer is not full.
735 : : *
736 : : * Note: 'miinfo' is unused but has been included for consistency with the
737 : : * other functions in this area.
738 : : */
739 : : static inline TupleTableSlot *
740 : 713886 : CopyMultiInsertInfoNextFreeSlot(CopyMultiInsertInfo *miinfo,
741 : : ResultRelInfo *rri)
742 : : {
743 : 713886 : CopyMultiInsertBuffer *buffer = rri->ri_CopyMultiInsertBuffer;
744 : : int nused;
745 : :
746 : : Assert(buffer != NULL);
747 : : Assert(buffer->nused < MAX_BUFFERED_TUPLES);
748 : :
749 : 713886 : nused = buffer->nused;
750 : :
751 [ + + ]: 713886 : if (buffer->slots[nused] == NULL)
752 : 147832 : buffer->slots[nused] = table_slot_create(rri->ri_RelationDesc, NULL);
753 : 713886 : return buffer->slots[nused];
754 : : }
755 : :
756 : : /*
757 : : * Record the previously reserved TupleTableSlot that was reserved by
758 : : * CopyMultiInsertInfoNextFreeSlot as being consumed.
759 : : */
760 : : static inline void
761 : 712766 : CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
762 : : TupleTableSlot *slot, int tuplen, uint64 lineno)
763 : : {
764 : 712766 : CopyMultiInsertBuffer *buffer = rri->ri_CopyMultiInsertBuffer;
765 : :
766 : : Assert(buffer != NULL);
767 : : Assert(slot == buffer->slots[buffer->nused]);
768 : :
769 : : /* Store the line number so we can properly report any errors later */
770 : 712766 : buffer->linenos[buffer->nused] = lineno;
771 : :
772 : : /* Record this slot as being used */
773 : 712766 : buffer->nused++;
774 : :
775 : : /* Update how many tuples are stored and their size */
776 : 712766 : miinfo->bufferedTuples++;
777 : 712766 : miinfo->bufferedBytes += tuplen;
778 : 712766 : }
779 : :
780 : : /*
781 : : * Copy FROM file to relation.
782 : : */
783 : : uint64
784 : 1218 : CopyFrom(CopyFromState cstate)
785 : : {
786 : : ResultRelInfo *resultRelInfo;
787 : : ResultRelInfo *target_resultRelInfo;
788 : 1218 : ResultRelInfo *prevResultRelInfo = NULL;
789 : 1218 : EState *estate = CreateExecutorState(); /* for ExecConstraints() */
790 : : ModifyTableState *mtstate;
791 : : ExprContext *econtext;
792 : 1218 : TupleTableSlot *singleslot = NULL;
793 : 1218 : MemoryContext oldcontext = CurrentMemoryContext;
794 : :
795 : 1218 : PartitionTupleRouting *proute = NULL;
796 : : ErrorContextCallback errcallback;
797 : 1218 : CommandId mycid = GetCurrentCommandId(true);
798 : 1218 : uint32 ti_options = 0; /* start with default options for insert */
799 : 1218 : BulkInsertState bistate = NULL;
800 : : CopyInsertMethod insertMethod;
801 : 1218 : CopyMultiInsertInfo multiInsertInfo = {0}; /* pacify compiler */
802 : 1218 : int64 processed = 0;
803 : 1218 : int64 excluded = 0;
804 : : bool has_before_insert_row_trig;
805 : : bool has_instead_insert_row_trig;
806 : 1218 : bool leafpart_use_multi_insert = false;
807 : :
808 : : Assert(cstate->rel);
809 : : Assert(list_length(cstate->range_table) == 1);
810 : :
811 : 1218 : if (cstate->opts.on_error != COPY_ON_ERROR_STOP)
812 : : Assert(cstate->escontext);
813 : :
814 : : /*
815 : : * The target must be a plain, foreign, or partitioned relation, or have
816 : : * an INSTEAD OF INSERT row trigger. (Currently, such triggers are only
817 : : * allowed on views, so we only hint about them in the view case.)
818 : : */
819 [ + + ]: 1218 : if (cstate->rel->rd_rel->relkind != RELKIND_RELATION &&
820 [ + + ]: 111 : cstate->rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
821 [ + + ]: 88 : cstate->rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
822 [ + + ]: 12 : !(cstate->rel->trigdesc &&
823 [ - + ]: 8 : cstate->rel->trigdesc->trig_insert_instead_row))
824 : : {
825 [ + - ]: 4 : if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
826 [ + - ]: 4 : ereport(ERROR,
827 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
828 : : errmsg("cannot copy to view \"%s\"",
829 : : RelationGetRelationName(cstate->rel)),
830 : : errhint("To enable copying to a view, provide an INSTEAD OF INSERT trigger.")));
831 [ # # ]: 0 : else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
832 [ # # ]: 0 : ereport(ERROR,
833 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
834 : : errmsg("cannot copy to materialized view \"%s\"",
835 : : RelationGetRelationName(cstate->rel))));
836 [ # # ]: 0 : else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
837 [ # # ]: 0 : ereport(ERROR,
838 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
839 : : errmsg("cannot copy to sequence \"%s\"",
840 : : RelationGetRelationName(cstate->rel))));
841 : : else
842 [ # # ]: 0 : ereport(ERROR,
843 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
844 : : errmsg("cannot copy to non-table relation \"%s\"",
845 : : RelationGetRelationName(cstate->rel))));
846 : : }
847 : :
848 : : /*
849 : : * If the target file is new-in-transaction, we assume that checking FSM
850 : : * for free space is a waste of time. This could possibly be wrong, but
851 : : * it's unlikely.
852 : : */
853 [ + + + - : 1214 : if (RELKIND_HAS_STORAGE(cstate->rel->rd_rel->relkind) &&
+ - + - -
+ ]
854 [ + + ]: 1107 : (cstate->rel->rd_createSubid != InvalidSubTransactionId ||
855 [ + + ]: 1095 : cstate->rel->rd_firstRelfilelocatorSubid != InvalidSubTransactionId))
856 : 57 : ti_options |= TABLE_INSERT_SKIP_FSM;
857 : :
858 : : /*
859 : : * Optimize if new relation storage was created in this subxact or one of
860 : : * its committed children and we won't see those rows later as part of an
861 : : * earlier scan or command. The subxact test ensures that if this subxact
862 : : * aborts then the frozen rows won't be visible after xact cleanup. Note
863 : : * that the stronger test of exactly which subtransaction created it is
864 : : * crucial for correctness of this optimization. The test for an earlier
865 : : * scan or command tolerates false negatives. FREEZE causes other sessions
866 : : * to see rows they would not see under MVCC, and a false negative merely
867 : : * spreads that anomaly to the current session.
868 : : */
869 [ + + ]: 1214 : if (cstate->opts.freeze)
870 : : {
871 : : /*
872 : : * We currently disallow COPY FREEZE on partitioned tables. The
873 : : * reason for this is that we've simply not yet opened the partitions
874 : : * to determine if the optimization can be applied to them. We could
875 : : * go and open them all here, but doing so may be quite a costly
876 : : * overhead for small copies. In any case, we may just end up routing
877 : : * tuples to a small number of partitions. It seems better just to
878 : : * raise an ERROR for partitioned tables.
879 : : */
880 [ + + ]: 46 : if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
881 : : {
882 [ + - ]: 4 : ereport(ERROR,
883 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
884 : : errmsg("cannot perform COPY FREEZE on a partitioned table")));
885 : : }
886 : :
887 : : /* There's currently no support for COPY FREEZE on foreign tables. */
888 [ + + ]: 42 : if (cstate->rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
889 [ + - ]: 4 : ereport(ERROR,
890 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
891 : : errmsg("cannot perform COPY FREEZE on a foreign table")));
892 : :
893 : : /*
894 : : * Tolerate one registration for the benefit of FirstXactSnapshot.
895 : : * Scan-bearing queries generally create at least two registrations,
896 : : * though relying on that is fragile, as is ignoring ActiveSnapshot.
897 : : * Clear CatalogSnapshot to avoid counting its registration. We'll
898 : : * still detect ongoing catalog scans, each of which separately
899 : : * registers the snapshot it uses.
900 : : */
901 : 38 : InvalidateCatalogSnapshot();
902 [ + - - + ]: 38 : if (!ThereAreNoPriorRegisteredSnapshots() || !ThereAreNoReadyPortals())
903 [ # # ]: 0 : ereport(ERROR,
904 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
905 : : errmsg("cannot perform COPY FREEZE because of prior transaction activity")));
906 : :
907 [ + + + + ]: 75 : if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
908 : 37 : cstate->rel->rd_newRelfilelocatorSubid != GetCurrentSubTransactionId())
909 [ + - ]: 12 : ereport(ERROR,
910 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
911 : : errmsg("cannot perform COPY FREEZE because the table was not created or truncated in the current subtransaction")));
912 : :
913 : 26 : ti_options |= TABLE_INSERT_FROZEN;
914 : : }
915 : :
916 : : /*
917 : : * We need a ResultRelInfo so we can use the regular executor's
918 : : * index-entry-making machinery. (There used to be a huge amount of code
919 : : * here that basically duplicated execUtils.c ...)
920 : : */
921 : 1194 : ExecInitRangeTable(estate, cstate->range_table, cstate->rteperminfos,
922 : : bms_make_singleton(1));
923 : 1194 : resultRelInfo = target_resultRelInfo = makeNode(ResultRelInfo);
924 : 1194 : ExecInitResultRelation(estate, resultRelInfo, 1);
925 : :
926 : : /* Verify the named relation is a valid target for INSERT */
927 : 1194 : CheckValidResultRel(resultRelInfo, CMD_INSERT, ONCONFLICT_NONE, NIL);
928 : :
929 : 1193 : ExecOpenIndices(resultRelInfo, false);
930 : :
931 : : /*
932 : : * Set up a ModifyTableState so we can let FDW(s) init themselves for
933 : : * foreign-table result relation(s).
934 : : */
935 : 1193 : mtstate = makeNode(ModifyTableState);
936 : 1193 : mtstate->ps.plan = NULL;
937 : 1193 : mtstate->ps.state = estate;
938 : 1193 : mtstate->operation = CMD_INSERT;
939 : 1193 : mtstate->mt_nrels = 1;
940 : 1193 : mtstate->resultRelInfo = resultRelInfo;
941 : 1193 : mtstate->rootResultRelInfo = resultRelInfo;
942 : :
943 [ + + ]: 1193 : if (resultRelInfo->ri_FdwRoutine != NULL &&
944 [ + - ]: 18 : resultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)
945 : 18 : resultRelInfo->ri_FdwRoutine->BeginForeignInsert(mtstate,
946 : : resultRelInfo);
947 : :
948 : : /*
949 : : * Also, if the named relation is a foreign table, determine if the FDW
950 : : * supports batch insert and determine the batch size (a FDW may support
951 : : * batching, but it may be disabled for the server/table).
952 : : *
953 : : * If the FDW does not support batching, we set the batch size to 1.
954 : : */
955 [ + + ]: 1193 : if (resultRelInfo->ri_FdwRoutine != NULL &&
956 [ + - ]: 18 : resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
957 [ + - ]: 18 : resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
958 : 18 : resultRelInfo->ri_BatchSize =
959 : 18 : resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
960 : : else
961 : 1175 : resultRelInfo->ri_BatchSize = 1;
962 : :
963 : : Assert(resultRelInfo->ri_BatchSize >= 1);
964 : :
965 : : /* Prepare to catch AFTER triggers. */
966 : 1193 : AfterTriggerBeginQuery();
967 : :
968 : : /*
969 : : * If there are any triggers with transition tables on the named relation,
970 : : * we need to be prepared to capture transition tuples.
971 : : *
972 : : * Because partition tuple routing would like to know about whether
973 : : * transition capture is active, we also set it in mtstate, which is
974 : : * passed to ExecFindPartition() below.
975 : : */
976 : 1193 : cstate->transition_capture = mtstate->mt_transition_capture =
977 : 1193 : MakeTransitionCaptureState(cstate->rel->trigdesc,
978 : 1193 : RelationGetRelid(cstate->rel),
979 : : CMD_INSERT);
980 : :
981 : : /*
982 : : * If the named relation is a partitioned table, initialize state for
983 : : * CopyFrom tuple routing.
984 : : */
985 [ + + ]: 1193 : if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
986 : 72 : proute = ExecSetupPartitionTupleRouting(estate, cstate->rel);
987 : :
988 [ + + ]: 1193 : if (cstate->whereClause)
989 : 16 : cstate->qualexpr = ExecInitQual(castNode(List, cstate->whereClause),
990 : : &mtstate->ps);
991 : :
992 : : /*
993 : : * It's generally more efficient to prepare a bunch of tuples for
994 : : * insertion, and insert them in one
995 : : * table_multi_insert()/ExecForeignBatchInsert() call, than call
996 : : * table_tuple_insert()/ExecForeignInsert() separately for every tuple.
997 : : * However, there are a number of reasons why we might not be able to do
998 : : * this. These are explained below.
999 : : */
1000 [ + + ]: 1193 : if (resultRelInfo->ri_TrigDesc != NULL &&
1001 [ + + ]: 122 : (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
1002 [ + + ]: 58 : resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
1003 : : {
1004 : : /*
1005 : : * Can't support multi-inserts when there are any BEFORE/INSTEAD OF
1006 : : * triggers on the table. Such triggers might query the table we're
1007 : : * inserting into and act differently if the tuples that have already
1008 : : * been processed and prepared for insertion are not there.
1009 : : */
1010 : 72 : insertMethod = CIM_SINGLE;
1011 : : }
1012 [ + + ]: 1121 : else if (resultRelInfo->ri_FdwRoutine != NULL &&
1013 [ + + ]: 14 : resultRelInfo->ri_BatchSize == 1)
1014 : : {
1015 : : /*
1016 : : * Can't support multi-inserts to a foreign table if the FDW does not
1017 : : * support batching, or it's disabled for the server or foreign table.
1018 : : */
1019 : 9 : insertMethod = CIM_SINGLE;
1020 : : }
1021 [ + + + + ]: 1112 : else if (proute != NULL && resultRelInfo->ri_TrigDesc != NULL &&
1022 [ + + ]: 19 : resultRelInfo->ri_TrigDesc->trig_insert_new_table)
1023 : : {
1024 : : /*
1025 : : * For partitioned tables we can't support multi-inserts when there
1026 : : * are any statement level insert triggers. It might be possible to
1027 : : * allow partitioned tables with such triggers in the future, but for
1028 : : * now, CopyMultiInsertInfoFlush expects that any after row insert and
1029 : : * statement level insert triggers are on the same relation.
1030 : : */
1031 : 14 : insertMethod = CIM_SINGLE;
1032 : : }
1033 [ + + ]: 1098 : else if (cstate->volatile_defexprs)
1034 : : {
1035 : : /*
1036 : : * Can't support multi-inserts if there are any volatile default
1037 : : * expressions in the table. Similarly to the trigger case above,
1038 : : * such expressions may query the table we're inserting into.
1039 : : *
1040 : : * Note: It does not matter if any partitions have any volatile
1041 : : * default expressions as we use the defaults from the target of the
1042 : : * COPY command.
1043 : : */
1044 : 4 : insertMethod = CIM_SINGLE;
1045 : : }
1046 [ - + ]: 1094 : else if (contain_volatile_functions(cstate->whereClause))
1047 : : {
1048 : : /*
1049 : : * Can't support multi-inserts if there are any volatile function
1050 : : * expressions in WHERE clause. Similarly to the trigger case above,
1051 : : * such expressions may query the table we're inserting into.
1052 : : *
1053 : : * Note: the whereClause was already preprocessed in DoCopy(), so it's
1054 : : * okay to use contain_volatile_functions() directly.
1055 : : */
1056 : 0 : insertMethod = CIM_SINGLE;
1057 : : }
1058 : : else
1059 : : {
1060 : : /*
1061 : : * For partitioned tables, we may still be able to perform bulk
1062 : : * inserts. However, the possibility of this depends on which types
1063 : : * of triggers exist on the partition. We must disable bulk inserts
1064 : : * if the partition is a foreign table that can't use batching or it
1065 : : * has any before row insert or insert instead triggers (same as we
1066 : : * checked above for the parent table). Since the partition's
1067 : : * resultRelInfos are initialized only when we actually need to insert
1068 : : * the first tuple into them, we must have the intermediate insert
1069 : : * method of CIM_MULTI_CONDITIONAL to flag that we must later
1070 : : * determine if we can use bulk-inserts for the partition being
1071 : : * inserted into.
1072 : : */
1073 [ + + ]: 1094 : if (proute)
1074 : 54 : insertMethod = CIM_MULTI_CONDITIONAL;
1075 : : else
1076 : 1040 : insertMethod = CIM_MULTI;
1077 : :
1078 : 1094 : CopyMultiInsertInfoInit(&multiInsertInfo, resultRelInfo, cstate,
1079 : : estate, mycid, ti_options);
1080 : : }
1081 : :
1082 : : /*
1083 : : * If not using batch mode (which allocates slots as needed) set up a
1084 : : * tuple slot too. When inserting into a partitioned table, we also need
1085 : : * one, even if we might batch insert, to read the tuple in the root
1086 : : * partition's form.
1087 : : */
1088 [ + + + + ]: 1193 : if (insertMethod == CIM_SINGLE || insertMethod == CIM_MULTI_CONDITIONAL)
1089 : : {
1090 : 153 : singleslot = table_slot_create(resultRelInfo->ri_RelationDesc,
1091 : : &estate->es_tupleTable);
1092 : 153 : bistate = GetBulkInsertState();
1093 : : }
1094 : :
1095 [ + + ]: 1315 : has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1096 [ + + ]: 122 : resultRelInfo->ri_TrigDesc->trig_insert_before_row);
1097 : :
1098 [ + + ]: 1315 : has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1099 [ + + ]: 122 : resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
1100 : :
1101 : : /*
1102 : : * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
1103 : : * should do this for COPY, since it's not really an "INSERT" statement as
1104 : : * such. However, executing these triggers maintains consistency with the
1105 : : * EACH ROW triggers that we already fire on COPY.
1106 : : */
1107 : 1193 : ExecBSInsertTriggers(estate, resultRelInfo);
1108 : :
1109 [ + + ]: 1193 : econtext = GetPerTupleExprContext(estate);
1110 : :
1111 : : /* Set up callback to identify error line number */
1112 : 1193 : errcallback.callback = CopyFromErrorCallback;
1113 : 1193 : errcallback.arg = cstate;
1114 : 1193 : errcallback.previous = error_context_stack;
1115 : 1193 : error_context_stack = &errcallback;
1116 : :
1117 : : for (;;)
1118 : 753116 : {
1119 : : TupleTableSlot *myslot;
1120 : 754309 : TupleTableSlot *original_insert_tuple = NULL;
1121 : : bool skip_tuple;
1122 : :
1123 [ - + ]: 754309 : CHECK_FOR_INTERRUPTS();
1124 : :
1125 : : /*
1126 : : * Reset the per-tuple exprcontext. We do this after every tuple, to
1127 : : * clean-up after expression evaluations etc.
1128 : : */
1129 [ + - ]: 754309 : ResetPerTupleExprContext(estate);
1130 : :
1131 : : /* select slot to (initially) load row into */
1132 [ + + + + ]: 754309 : if (insertMethod == CIM_SINGLE || proute)
1133 : : {
1134 : 149603 : myslot = singleslot;
1135 : 149603 : Assert(myslot != NULL);
1136 : : }
1137 : : else
1138 : : {
1139 : : Assert(resultRelInfo == target_resultRelInfo);
1140 : : Assert(insertMethod == CIM_MULTI);
1141 : :
1142 : 604706 : myslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
1143 : : resultRelInfo);
1144 : : }
1145 : :
1146 : : /*
1147 : : * Switch to per-tuple context before calling NextCopyFrom, which does
1148 : : * evaluate default expressions etc. and requires per-tuple context.
1149 : : */
1150 [ + - ]: 754309 : MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
1151 : :
1152 : 754309 : ExecClearTuple(myslot);
1153 : :
1154 : : /* Directly store the values/nulls array in the slot */
1155 [ + + ]: 754309 : if (!NextCopyFrom(cstate, econtext, myslot->tts_values, myslot->tts_isnull))
1156 : 1026 : break;
1157 : :
1158 [ + + ]: 753144 : if (cstate->opts.on_error == COPY_ON_ERROR_IGNORE &&
1159 [ + + ]: 116 : cstate->escontext->error_occurred)
1160 : : {
1161 : : /*
1162 : : * Soft error occurred, skip this tuple and just make
1163 : : * ErrorSaveContext ready for the next NextCopyFrom. Since we
1164 : : * don't set details_wanted and error_data is not to be filled,
1165 : : * just resetting error_occurred is enough.
1166 : : */
1167 : 80 : cstate->escontext->error_occurred = false;
1168 : :
1169 : : /* Report that this tuple was skipped by the ON_ERROR clause */
1170 : 80 : pgstat_progress_update_param(PROGRESS_COPY_TUPLES_SKIPPED,
1171 : 80 : cstate->num_errors);
1172 : :
1173 [ + + ]: 80 : if (cstate->opts.reject_limit > 0 &&
1174 [ + + ]: 32 : cstate->num_errors > cstate->opts.reject_limit)
1175 [ + - ]: 4 : ereport(ERROR,
1176 : : (errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
1177 : : errmsg("skipped more than REJECT_LIMIT (%" PRId64 ") rows due to data type incompatibility",
1178 : : cstate->opts.reject_limit)));
1179 : :
1180 : : /* Repeat NextCopyFrom() until no soft error occurs */
1181 : 76 : continue;
1182 : : }
1183 : :
1184 : 753064 : ExecStoreVirtualTuple(myslot);
1185 : :
1186 : : /*
1187 : : * Constraints and where clause might reference the tableoid column,
1188 : : * so (re-)initialize tts_tableOid before evaluating them.
1189 : : */
1190 : 753064 : myslot->tts_tableOid = RelationGetRelid(target_resultRelInfo->ri_RelationDesc);
1191 : :
1192 : : /* Triggers and stuff need to be invoked in query context. */
1193 : 753064 : MemoryContextSwitchTo(oldcontext);
1194 : :
1195 [ + + ]: 753064 : if (cstate->whereClause)
1196 : : {
1197 : 56 : econtext->ecxt_scantuple = myslot;
1198 : : /* Skip items that don't match COPY's WHERE clause */
1199 [ + + ]: 56 : if (!ExecQual(cstate->qualexpr, econtext))
1200 : : {
1201 : : /*
1202 : : * Report that this tuple was filtered out by the WHERE
1203 : : * clause.
1204 : : */
1205 : 32 : pgstat_progress_update_param(PROGRESS_COPY_TUPLES_EXCLUDED,
1206 : : ++excluded);
1207 : 32 : continue;
1208 : : }
1209 : : }
1210 : :
1211 : : /* Determine the partition to insert the tuple into */
1212 [ + + ]: 753032 : if (proute)
1213 : : {
1214 : : TupleConversionMap *map;
1215 : :
1216 : : /*
1217 : : * Attempt to find a partition suitable for this tuple.
1218 : : * ExecFindPartition() will raise an error if none can be found or
1219 : : * if the found partition is not suitable for INSERTs.
1220 : : */
1221 : 149273 : resultRelInfo = ExecFindPartition(mtstate, target_resultRelInfo,
1222 : : proute, myslot, estate);
1223 : :
1224 [ + + ]: 149272 : if (prevResultRelInfo != resultRelInfo)
1225 : : {
1226 : : /* Determine which triggers exist on this partition */
1227 [ + + ]: 90822 : has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1228 [ + + ]: 36 : resultRelInfo->ri_TrigDesc->trig_insert_before_row);
1229 : :
1230 [ + + ]: 90822 : has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1231 [ - + ]: 36 : resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
1232 : :
1233 : : /*
1234 : : * Disable multi-inserts when the partition has BEFORE/INSTEAD
1235 : : * OF triggers, or if the partition is a foreign table that
1236 : : * can't use batching.
1237 : : */
1238 : 141534 : leafpart_use_multi_insert = insertMethod == CIM_MULTI_CONDITIONAL &&
1239 [ + + ]: 50748 : !has_before_insert_row_trig &&
1240 [ + + + - ]: 192266 : !has_instead_insert_row_trig &&
1241 [ + + ]: 50732 : (resultRelInfo->ri_FdwRoutine == NULL ||
1242 [ + + ]: 6 : resultRelInfo->ri_BatchSize > 1);
1243 : :
1244 : : /* Set the multi-insert buffer to use for this partition. */
1245 [ + + ]: 90786 : if (leafpart_use_multi_insert)
1246 : : {
1247 [ + + ]: 50730 : if (resultRelInfo->ri_CopyMultiInsertBuffer == NULL)
1248 : 56 : CopyMultiInsertInfoSetupBuffer(&multiInsertInfo,
1249 : : resultRelInfo);
1250 : : }
1251 [ + + ]: 40056 : else if (insertMethod == CIM_MULTI_CONDITIONAL &&
1252 [ - + ]: 18 : !CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
1253 : : {
1254 : : /*
1255 : : * Flush pending inserts if this partition can't use
1256 : : * batching, so rows are visible to triggers etc.
1257 : : */
1258 : 0 : CopyMultiInsertInfoFlush(&multiInsertInfo,
1259 : : resultRelInfo,
1260 : : &processed);
1261 : : }
1262 : :
1263 [ + - ]: 90786 : if (bistate != NULL)
1264 : 90786 : ReleaseBulkInsertStatePin(bistate);
1265 : 90786 : prevResultRelInfo = resultRelInfo;
1266 : : }
1267 : :
1268 : : /*
1269 : : * If we're capturing transition tuples, we might need to convert
1270 : : * from the partition rowtype to root rowtype. But if there are no
1271 : : * BEFORE triggers on the partition that could change the tuple,
1272 : : * we can just remember the original unconverted tuple to avoid a
1273 : : * needless round trip conversion.
1274 : : */
1275 [ + + ]: 149272 : if (!has_before_insert_row_trig)
1276 : 149216 : original_insert_tuple = myslot;
1277 : :
1278 : : /*
1279 : : * We might need to convert from the root rowtype to the partition
1280 : : * rowtype.
1281 : : */
1282 : 149272 : map = ExecGetRootToChildMap(resultRelInfo, estate);
1283 [ + + + + ]: 149272 : if (insertMethod == CIM_SINGLE || !leafpart_use_multi_insert)
1284 : : {
1285 : : /* non batch insert */
1286 [ + + ]: 40092 : if (map != NULL)
1287 : : {
1288 : : TupleTableSlot *new_slot;
1289 : :
1290 : 73 : new_slot = resultRelInfo->ri_PartitionTupleSlot;
1291 : 73 : myslot = execute_attr_map_slot(map->attrMap, myslot, new_slot);
1292 : : }
1293 : : }
1294 : : else
1295 : : {
1296 : : /*
1297 : : * Prepare to queue up tuple for later batch insert into
1298 : : * current partition.
1299 : : */
1300 : : TupleTableSlot *batchslot;
1301 : :
1302 : : /* no other path available for partitioned table */
1303 : : Assert(insertMethod == CIM_MULTI_CONDITIONAL);
1304 : :
1305 : 109180 : batchslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
1306 : : resultRelInfo);
1307 : :
1308 [ + + ]: 109180 : if (map != NULL)
1309 : 8132 : myslot = execute_attr_map_slot(map->attrMap, myslot,
1310 : : batchslot);
1311 : : else
1312 : : {
1313 : : /*
1314 : : * This looks more expensive than it is (Believe me, I
1315 : : * optimized it away. Twice.). The input is in virtual
1316 : : * form, and we'll materialize the slot below - for most
1317 : : * slot types the copy performs the work materialization
1318 : : * would later require anyway.
1319 : : */
1320 : 101048 : ExecCopySlot(batchslot, myslot);
1321 : 101048 : myslot = batchslot;
1322 : : }
1323 : : }
1324 : :
1325 : : /* ensure that triggers etc see the right relation */
1326 : 149272 : myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1327 : : }
1328 : :
1329 : 753031 : skip_tuple = false;
1330 : :
1331 : : /* BEFORE ROW INSERT Triggers */
1332 [ + + ]: 753031 : if (has_before_insert_row_trig)
1333 : : {
1334 [ + + ]: 184 : if (!ExecBRInsertTriggers(estate, resultRelInfo, myslot))
1335 : 10 : skip_tuple = true; /* "do nothing" */
1336 : : }
1337 : :
1338 [ + + ]: 753031 : if (!skip_tuple)
1339 : : {
1340 : : /*
1341 : : * If there is an INSTEAD OF INSERT ROW trigger, let it handle the
1342 : : * tuple. Otherwise, proceed with inserting the tuple into the
1343 : : * table or foreign table.
1344 : : */
1345 [ + + ]: 753021 : if (has_instead_insert_row_trig)
1346 : : {
1347 : 8 : ExecIRInsertTriggers(estate, resultRelInfo, myslot);
1348 : : }
1349 : : else
1350 : : {
1351 : : /* Compute stored generated columns */
1352 [ + + ]: 753013 : if (resultRelInfo->ri_RelationDesc->rd_att->constr &&
1353 [ + + ]: 241155 : resultRelInfo->ri_RelationDesc->rd_att->constr->has_generated_stored)
1354 : 21 : ExecComputeStoredGenerated(resultRelInfo, estate, myslot,
1355 : : CMD_INSERT);
1356 : :
1357 : : /*
1358 : : * If the target is a plain table, check the constraints of
1359 : : * the tuple.
1360 : : */
1361 [ + + ]: 753013 : if (resultRelInfo->ri_FdwRoutine == NULL &&
1362 [ + + ]: 752967 : resultRelInfo->ri_RelationDesc->rd_att->constr)
1363 : 241137 : ExecConstraints(resultRelInfo, myslot, estate);
1364 : :
1365 : : /*
1366 : : * Also check the tuple against the partition constraint, if
1367 : : * there is one; except that if we got here via tuple-routing,
1368 : : * we don't need to if there's no BR trigger defined on the
1369 : : * partition.
1370 : : */
1371 [ + + + + ]: 752993 : if (resultRelInfo->ri_RelationDesc->rd_rel->relispartition &&
1372 [ + + ]: 149264 : (proute == NULL || has_before_insert_row_trig))
1373 : 1167 : ExecPartitionCheck(resultRelInfo, myslot, estate, true);
1374 : :
1375 : : /* Store the slot in the multi-insert buffer, when enabled. */
1376 [ + + + + ]: 752993 : if (insertMethod == CIM_MULTI || leafpart_use_multi_insert)
1377 : : {
1378 : : /*
1379 : : * The slot previously might point into the per-tuple
1380 : : * context. For batching it needs to be longer lived.
1381 : : */
1382 : 712766 : ExecMaterializeSlot(myslot);
1383 : :
1384 : : /* Add this tuple to the tuple buffer */
1385 : 712766 : CopyMultiInsertInfoStore(&multiInsertInfo,
1386 : : resultRelInfo, myslot,
1387 : : cstate->line_buf.len,
1388 : : cstate->cur_lineno);
1389 : :
1390 : : /*
1391 : : * If enough inserts have queued up, then flush all
1392 : : * buffers out to their tables.
1393 : : */
1394 [ + + ]: 712766 : if (CopyMultiInsertInfoIsFull(&multiInsertInfo))
1395 : 653 : CopyMultiInsertInfoFlush(&multiInsertInfo,
1396 : : resultRelInfo,
1397 : : &processed);
1398 : :
1399 : : /*
1400 : : * We delay updating the row counter and progress of the
1401 : : * COPY command until after writing the tuples stored in
1402 : : * the buffer out to the table, as in single insert mode.
1403 : : * See CopyMultiInsertBufferFlush().
1404 : : */
1405 : 712766 : continue; /* next tuple please */
1406 : : }
1407 : : else
1408 : : {
1409 : 40227 : List *recheckIndexes = NIL;
1410 : :
1411 : : /* OK, store the tuple */
1412 [ + + ]: 40227 : if (resultRelInfo->ri_FdwRoutine != NULL)
1413 : : {
1414 : 27 : myslot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
1415 : : resultRelInfo,
1416 : : myslot,
1417 : : NULL);
1418 : :
1419 [ + + ]: 26 : if (myslot == NULL) /* "do nothing" */
1420 : 2 : continue; /* next tuple please */
1421 : :
1422 : : /*
1423 : : * AFTER ROW Triggers might reference the tableoid
1424 : : * column, so (re-)initialize tts_tableOid before
1425 : : * evaluating them.
1426 : : */
1427 : 24 : myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1428 : : }
1429 : : else
1430 : : {
1431 : : /* OK, store the tuple and create index entries for it */
1432 : 40200 : table_tuple_insert(resultRelInfo->ri_RelationDesc,
1433 : : myslot, mycid, ti_options, bistate);
1434 : :
1435 [ - + ]: 40200 : if (resultRelInfo->ri_NumIndices > 0)
1436 : 0 : recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1437 : : estate, 0,
1438 : : myslot, NIL,
1439 : : NULL);
1440 : : }
1441 : :
1442 : : /* AFTER ROW INSERT Triggers */
1443 : 40224 : ExecARInsertTriggers(estate, resultRelInfo,
1444 : : myslot, original_insert_tuple,
1445 : : recheckIndexes, cstate->transition_capture);
1446 : :
1447 : 40222 : list_free(recheckIndexes);
1448 : : }
1449 : : }
1450 : :
1451 : : /*
1452 : : * We count only tuples not suppressed by a BEFORE INSERT trigger
1453 : : * or FDW; this is the same definition used by nodeModifyTable.c
1454 : : * for counting tuples inserted by an INSERT command. Update
1455 : : * progress of the COPY command as well.
1456 : : */
1457 : 40230 : pgstat_progress_update_param(PROGRESS_COPY_TUPLES_PROCESSED,
1458 : : ++processed);
1459 : : }
1460 : : }
1461 : :
1462 : : /* Flush any remaining buffered tuples */
1463 [ + + ]: 1026 : if (insertMethod != CIM_SINGLE)
1464 : : {
1465 [ + + ]: 946 : if (!CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
1466 : 745 : CopyMultiInsertInfoFlush(&multiInsertInfo, NULL, &processed);
1467 : : }
1468 : :
1469 : : /* Done, clean up */
1470 : 1017 : error_context_stack = errcallback.previous;
1471 : :
1472 [ + + ]: 1017 : if (cstate->num_errors > 0 &&
1473 [ + + ]: 24 : cstate->opts.log_verbosity >= COPY_LOG_VERBOSITY_DEFAULT)
1474 : : {
1475 [ + + ]: 20 : if (cstate->opts.on_error == COPY_ON_ERROR_IGNORE)
1476 [ + - ]: 16 : ereport(NOTICE,
1477 : : errmsg_plural("%" PRIu64 " row was skipped due to data type incompatibility",
1478 : : "%" PRIu64 " rows were skipped due to data type incompatibility",
1479 : : cstate->num_errors,
1480 : : cstate->num_errors));
1481 [ + - ]: 4 : else if (cstate->opts.on_error == COPY_ON_ERROR_SET_NULL)
1482 [ + - ]: 4 : ereport(NOTICE,
1483 : : errmsg_plural("in %" PRIu64 " row, columns were set to null due to data type incompatibility",
1484 : : "in %" PRIu64 " rows, columns were set to null due to data type incompatibility",
1485 : : cstate->num_errors,
1486 : : cstate->num_errors));
1487 : : }
1488 : :
1489 [ + + ]: 1017 : if (bistate != NULL)
1490 : 133 : FreeBulkInsertState(bistate);
1491 : :
1492 : 1017 : MemoryContextSwitchTo(oldcontext);
1493 : :
1494 : : /* Execute AFTER STATEMENT insertion triggers */
1495 : 1017 : ExecASInsertTriggers(estate, target_resultRelInfo, cstate->transition_capture);
1496 : :
1497 : : /* Handle queued AFTER triggers */
1498 : 1017 : AfterTriggerEndQuery(estate);
1499 : :
1500 : 1017 : ExecResetTupleTable(estate->es_tupleTable, false);
1501 : :
1502 : : /* Allow the FDW to shut down */
1503 [ + + ]: 1017 : if (target_resultRelInfo->ri_FdwRoutine != NULL &&
1504 [ + - ]: 16 : target_resultRelInfo->ri_FdwRoutine->EndForeignInsert != NULL)
1505 : 16 : target_resultRelInfo->ri_FdwRoutine->EndForeignInsert(estate,
1506 : : target_resultRelInfo);
1507 : :
1508 : : /* Tear down the multi-insert buffer data */
1509 [ + + ]: 1017 : if (insertMethod != CIM_SINGLE)
1510 : 937 : CopyMultiInsertInfoCleanup(&multiInsertInfo);
1511 : :
1512 : : /* Close all the partitioned tables, leaf partitions, and their indices */
1513 [ + + ]: 1017 : if (proute)
1514 : 69 : ExecCleanupTupleRouting(mtstate, proute);
1515 : :
1516 : : /* Close the result relations, including any trigger target relations */
1517 : 1017 : ExecCloseResultRelations(estate);
1518 : 1017 : ExecCloseRangeTableRelations(estate);
1519 : :
1520 : 1017 : FreeExecutorState(estate);
1521 : :
1522 : 1017 : return processed;
1523 : : }
1524 : :
1525 : : /*
1526 : : * Setup to read tuples from a file for COPY FROM.
1527 : : *
1528 : : * 'rel': Used as a template for the tuples
1529 : : * 'whereClause': WHERE clause from the COPY FROM command
1530 : : * 'filename': Name of server-local file to read, NULL for STDIN
1531 : : * 'is_program': true if 'filename' is program to execute
1532 : : * 'data_source_cb': callback that provides the input data
1533 : : * 'attnamelist': List of char *, columns to include. NIL selects all cols.
1534 : : * 'options': List of DefElem. See copy_opt_item in gram.y for selections.
1535 : : *
1536 : : * Returns a CopyFromState, to be passed to NextCopyFrom and related functions.
1537 : : */
1538 : : CopyFromState
1539 : 1455 : BeginCopyFrom(ParseState *pstate,
1540 : : Relation rel,
1541 : : Node *whereClause,
1542 : : const char *filename,
1543 : : bool is_program,
1544 : : copy_data_source_cb data_source_cb,
1545 : : List *attnamelist,
1546 : : List *options)
1547 : : {
1548 : : CopyFromState cstate;
1549 : 1455 : bool pipe = (filename == NULL);
1550 : : TupleDesc tupDesc;
1551 : : AttrNumber num_phys_attrs,
1552 : : num_defaults;
1553 : : FmgrInfo *in_functions;
1554 : : Oid *typioparams;
1555 : : int *defmap;
1556 : : ExprState **defexprs;
1557 : : MemoryContext oldcontext;
1558 : : bool volatile_defexprs;
1559 : 1455 : const int progress_cols[] = {
1560 : : PROGRESS_COPY_COMMAND,
1561 : : PROGRESS_COPY_TYPE,
1562 : : PROGRESS_COPY_BYTES_TOTAL
1563 : : };
1564 : 1455 : int64 progress_vals[] = {
1565 : : PROGRESS_COPY_COMMAND_FROM,
1566 : : 0,
1567 : : 0
1568 : : };
1569 : :
1570 : : /* Allocate workspace and zero all fields */
1571 : 1455 : cstate = palloc0_object(CopyFromStateData);
1572 : :
1573 : : /*
1574 : : * We allocate everything used by a cstate in a new memory context. This
1575 : : * avoids memory leaks during repeated use of COPY in a query.
1576 : : */
1577 : 1455 : cstate->copycontext = AllocSetContextCreate(CurrentMemoryContext,
1578 : : "COPY",
1579 : : ALLOCSET_DEFAULT_SIZES);
1580 : :
1581 : 1455 : oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1582 : :
1583 : : /* Extract options from the statement node tree */
1584 : 1455 : ProcessCopyOptions(pstate, &cstate->opts, true /* is_from */ , options);
1585 : :
1586 : : /* Set the format routine */
1587 : 1274 : cstate->routine = CopyFromGetRoutine(&cstate->opts);
1588 : :
1589 : : /* Process the target relation */
1590 : 1274 : cstate->rel = rel;
1591 : :
1592 : 1274 : tupDesc = RelationGetDescr(cstate->rel);
1593 : :
1594 : : /* process common options or initialization */
1595 : :
1596 : : /* Generate or convert list of attributes to process */
1597 : 1274 : cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1598 : :
1599 : 1274 : num_phys_attrs = tupDesc->natts;
1600 : :
1601 : : /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1602 : 1274 : cstate->opts.force_notnull_flags = palloc0_array(bool, num_phys_attrs);
1603 [ + + ]: 1274 : if (cstate->opts.force_notnull_all)
1604 [ + - - + : 8 : MemSet(cstate->opts.force_notnull_flags, true, num_phys_attrs * sizeof(bool));
- - - - -
- ]
1605 [ + + ]: 1266 : else if (cstate->opts.force_notnull)
1606 : : {
1607 : : List *attnums;
1608 : : ListCell *cur;
1609 : :
1610 : 17 : attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_notnull);
1611 : :
1612 [ + - + + : 34 : foreach(cur, attnums)
+ + ]
1613 : : {
1614 : 21 : int attnum = lfirst_int(cur);
1615 : 21 : Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1616 : :
1617 [ + + ]: 21 : if (!list_member_int(cstate->attnumlist, attnum))
1618 [ + - ]: 4 : ereport(ERROR,
1619 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1620 : : /*- translator: first %s is the name of a COPY option, e.g. FORCE_NOT_NULL */
1621 : : errmsg("%s column \"%s\" not referenced by COPY",
1622 : : "FORCE_NOT_NULL", NameStr(attr->attname))));
1623 : 17 : cstate->opts.force_notnull_flags[attnum - 1] = true;
1624 : : }
1625 : : }
1626 : :
1627 : : /* Set up soft error handler for ON_ERROR */
1628 [ + + ]: 1270 : if (cstate->opts.on_error != COPY_ON_ERROR_STOP)
1629 : : {
1630 : 82 : cstate->escontext = makeNode(ErrorSaveContext);
1631 : 82 : cstate->escontext->type = T_ErrorSaveContext;
1632 : 82 : cstate->escontext->error_occurred = false;
1633 : :
1634 [ + + ]: 82 : if (cstate->opts.on_error == COPY_ON_ERROR_IGNORE ||
1635 [ + - ]: 33 : cstate->opts.on_error == COPY_ON_ERROR_SET_NULL)
1636 : 82 : cstate->escontext->details_wanted = false;
1637 : : }
1638 : : else
1639 : 1188 : cstate->escontext = NULL;
1640 : :
1641 [ + + ]: 1270 : if (cstate->opts.on_error == COPY_ON_ERROR_SET_NULL)
1642 : : {
1643 : : /*
1644 : : * When data type conversion fails and ON_ERROR is SET_NULL, we need
1645 : : * ensure that the input column allow null values. ExecConstraints()
1646 : : * will cover most of the cases, but it does not verify domain
1647 : : * constraints. Therefore, for constrained domains, the null value
1648 : : * check must be performed during the initial string-to-datum
1649 : : * conversion (see CopyFromTextLikeOneRow()).
1650 : : */
1651 : 33 : cstate->domain_with_constraint = palloc0_array(bool, num_phys_attrs);
1652 : :
1653 [ + - + + : 160 : foreach_int(attno, cstate->attnumlist)
+ + ]
1654 : : {
1655 : 94 : Form_pg_attribute att = TupleDescAttr(tupDesc, attno - 1);
1656 : :
1657 : 94 : cstate->domain_with_constraint[attno - 1] = DomainHasConstraints(att->atttypid, NULL);
1658 : : }
1659 : : }
1660 : :
1661 : : /* Convert FORCE_NULL name list to per-column flags, check validity */
1662 : 1270 : cstate->opts.force_null_flags = palloc0_array(bool, num_phys_attrs);
1663 [ + + ]: 1270 : if (cstate->opts.force_null_all)
1664 [ + - - + : 8 : MemSet(cstate->opts.force_null_flags, true, num_phys_attrs * sizeof(bool));
- - - - -
- ]
1665 [ + + ]: 1262 : else if (cstate->opts.force_null)
1666 : : {
1667 : : List *attnums;
1668 : : ListCell *cur;
1669 : :
1670 : 17 : attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_null);
1671 : :
1672 [ + - + + : 34 : foreach(cur, attnums)
+ + ]
1673 : : {
1674 : 21 : int attnum = lfirst_int(cur);
1675 : 21 : Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1676 : :
1677 [ + + ]: 21 : if (!list_member_int(cstate->attnumlist, attnum))
1678 [ + - ]: 4 : ereport(ERROR,
1679 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1680 : : /*- translator: first %s is the name of a COPY option, e.g. FORCE_NOT_NULL */
1681 : : errmsg("%s column \"%s\" not referenced by COPY",
1682 : : "FORCE_NULL", NameStr(attr->attname))));
1683 : 17 : cstate->opts.force_null_flags[attnum - 1] = true;
1684 : : }
1685 : : }
1686 : :
1687 : : /* Convert convert_selectively name list to per-column flags */
1688 [ + + ]: 1266 : if (cstate->opts.convert_selectively)
1689 : : {
1690 : : List *attnums;
1691 : : ListCell *cur;
1692 : :
1693 : 3 : cstate->convert_select_flags = palloc0_array(bool, num_phys_attrs);
1694 : :
1695 : 3 : attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.convert_select);
1696 : :
1697 [ + - + + : 7 : foreach(cur, attnums)
+ + ]
1698 : : {
1699 : 4 : int attnum = lfirst_int(cur);
1700 : 4 : Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1701 : :
1702 [ - + ]: 4 : if (!list_member_int(cstate->attnumlist, attnum))
1703 [ # # ]: 0 : ereport(ERROR,
1704 : : (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1705 : : errmsg_internal("selected column \"%s\" not referenced by COPY",
1706 : : NameStr(attr->attname))));
1707 : 4 : cstate->convert_select_flags[attnum - 1] = true;
1708 : : }
1709 : : }
1710 : :
1711 : : /* Use client encoding when ENCODING option is not specified. */
1712 [ + + ]: 1266 : if (cstate->opts.file_encoding < 0)
1713 : 1246 : cstate->file_encoding = pg_get_client_encoding();
1714 : : else
1715 : 20 : cstate->file_encoding = cstate->opts.file_encoding;
1716 : :
1717 : : /*
1718 : : * Look up encoding conversion function.
1719 : : */
1720 [ + + ]: 1266 : if (cstate->file_encoding == GetDatabaseEncoding() ||
1721 [ + + - + ]: 52 : cstate->file_encoding == PG_SQL_ASCII ||
1722 : 24 : GetDatabaseEncoding() == PG_SQL_ASCII)
1723 : : {
1724 : 1242 : cstate->need_transcoding = false;
1725 : : }
1726 : : else
1727 : : {
1728 : 24 : cstate->need_transcoding = true;
1729 : 24 : cstate->conversion_proc = FindDefaultConversionProc(cstate->file_encoding,
1730 : : GetDatabaseEncoding());
1731 [ - + ]: 24 : if (!OidIsValid(cstate->conversion_proc))
1732 [ # # ]: 0 : ereport(ERROR,
1733 : : (errcode(ERRCODE_UNDEFINED_FUNCTION),
1734 : : errmsg("default conversion function for encoding \"%s\" to \"%s\" does not exist",
1735 : : pg_encoding_to_char(cstate->file_encoding),
1736 : : pg_encoding_to_char(GetDatabaseEncoding()))));
1737 : : }
1738 : :
1739 : 1266 : cstate->copy_src = COPY_FILE; /* default */
1740 : :
1741 : 1266 : cstate->whereClause = whereClause;
1742 : :
1743 : : /* Initialize state variables */
1744 : 1266 : cstate->eol_type = EOL_UNKNOWN;
1745 : 1266 : cstate->cur_relname = RelationGetRelationName(cstate->rel);
1746 : 1266 : cstate->cur_lineno = 0;
1747 : 1266 : cstate->cur_attname = NULL;
1748 : 1266 : cstate->cur_attval = NULL;
1749 : 1266 : cstate->relname_only = false;
1750 : 1266 : cstate->simd_enabled = true;
1751 : :
1752 : : /*
1753 : : * Allocate buffers for the input pipeline.
1754 : : *
1755 : : * attribute_buf and raw_buf are used in both text and binary modes, but
1756 : : * input_buf and line_buf only in text mode.
1757 : : */
1758 : 1266 : cstate->raw_buf = palloc(RAW_BUF_SIZE + 1);
1759 : 1266 : cstate->raw_buf_index = cstate->raw_buf_len = 0;
1760 : 1266 : cstate->raw_reached_eof = false;
1761 : :
1762 : 1266 : initStringInfo(&cstate->attribute_buf);
1763 : :
1764 : : /* Assign range table and rteperminfos, we'll need them in CopyFrom. */
1765 [ + + ]: 1266 : if (pstate)
1766 : : {
1767 : 1227 : cstate->range_table = pstate->p_rtable;
1768 : 1227 : cstate->rteperminfos = pstate->p_rteperminfos;
1769 : : }
1770 : :
1771 : 1266 : num_defaults = 0;
1772 : 1266 : volatile_defexprs = false;
1773 : :
1774 : : /*
1775 : : * Pick up the required catalog information for each attribute in the
1776 : : * relation, including the input function, the element type (to pass to
1777 : : * the input function), and info about defaults and constraints. (Which
1778 : : * input function we use depends on text/binary format choice.)
1779 : : */
1780 : 1266 : in_functions = palloc_array(FmgrInfo, num_phys_attrs);
1781 : 1266 : typioparams = palloc_array(Oid, num_phys_attrs);
1782 : 1266 : defmap = palloc_array(int, num_phys_attrs);
1783 : 1266 : defexprs = palloc_array(ExprState *, num_phys_attrs);
1784 : :
1785 [ + + ]: 5046 : for (int attnum = 1; attnum <= num_phys_attrs; attnum++)
1786 : : {
1787 : 3789 : Form_pg_attribute att = TupleDescAttr(tupDesc, attnum - 1);
1788 : :
1789 : : /* We don't need info for dropped attributes */
1790 [ + + ]: 3789 : if (att->attisdropped)
1791 : 82 : continue;
1792 : :
1793 : : /* Fetch the input function and typioparam info */
1794 : 3707 : cstate->routine->CopyFromInFunc(cstate, att->atttypid,
1795 : 3707 : &in_functions[attnum - 1],
1796 : 3707 : &typioparams[attnum - 1]);
1797 : :
1798 : : /* Get default info if available */
1799 : 3706 : defexprs[attnum - 1] = NULL;
1800 : :
1801 : : /*
1802 : : * We only need the default values for columns that do not appear in
1803 : : * the column list, unless the DEFAULT option was given. We never need
1804 : : * default values for generated columns.
1805 : : */
1806 [ + + ]: 3706 : if ((cstate->opts.default_print != NULL ||
1807 [ + + ]: 3621 : !list_member_int(cstate->attnumlist, attnum)) &&
1808 [ + + ]: 450 : !att->attgenerated)
1809 : : {
1810 : 410 : Expr *defexpr = (Expr *) build_column_default(cstate->rel,
1811 : : attnum);
1812 : :
1813 [ + + ]: 410 : if (defexpr != NULL)
1814 : : {
1815 : : /* Run the expression through planner */
1816 : 169 : defexpr = expression_planner(defexpr);
1817 : :
1818 : : /* Initialize executable expression in copycontext */
1819 : 161 : defexprs[attnum - 1] = ExecInitExpr(defexpr, NULL);
1820 : :
1821 : : /* if NOT copied from input */
1822 : : /* use default value if one exists */
1823 [ + + ]: 161 : if (!list_member_int(cstate->attnumlist, attnum))
1824 : : {
1825 : 107 : defmap[num_defaults] = attnum - 1;
1826 : 107 : num_defaults++;
1827 : : }
1828 : :
1829 : : /*
1830 : : * If a default expression looks at the table being loaded,
1831 : : * then it could give the wrong answer when using
1832 : : * multi-insert. Since database access can be dynamic this is
1833 : : * hard to test for exactly, so we use the much wider test of
1834 : : * whether the default expression is volatile. We allow for
1835 : : * the special case of when the default expression is the
1836 : : * nextval() of a sequence which in this specific case is
1837 : : * known to be safe for use with the multi-insert
1838 : : * optimization. Hence we use this special case function
1839 : : * checker rather than the standard check for
1840 : : * contain_volatile_functions(). Note also that we already
1841 : : * ran the expression through expression_planner().
1842 : : */
1843 [ + - ]: 161 : if (!volatile_defexprs)
1844 : 161 : volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
1845 : : }
1846 : : }
1847 : : }
1848 : :
1849 : 1257 : cstate->defaults = palloc0_array(bool, tupDesc->natts);
1850 : :
1851 : : /* initialize progress */
1852 : 1257 : pgstat_progress_start_command(PROGRESS_COMMAND_COPY,
1853 [ + - ]: 1257 : cstate->rel ? RelationGetRelid(cstate->rel) : InvalidOid);
1854 : 1257 : cstate->bytes_processed = 0;
1855 : :
1856 : : /* We keep those variables in cstate. */
1857 : 1257 : cstate->in_functions = in_functions;
1858 : 1257 : cstate->typioparams = typioparams;
1859 : 1257 : cstate->defmap = defmap;
1860 : 1257 : cstate->defexprs = defexprs;
1861 : 1257 : cstate->volatile_defexprs = volatile_defexprs;
1862 : 1257 : cstate->num_defaults = num_defaults;
1863 : 1257 : cstate->is_program = is_program;
1864 : :
1865 [ + + ]: 1257 : if (data_source_cb)
1866 : : {
1867 : 217 : progress_vals[1] = PROGRESS_COPY_TYPE_CALLBACK;
1868 : 217 : cstate->copy_src = COPY_CALLBACK;
1869 : 217 : cstate->data_source_cb = data_source_cb;
1870 : : }
1871 [ + + ]: 1040 : else if (pipe)
1872 : : {
1873 : 740 : progress_vals[1] = PROGRESS_COPY_TYPE_PIPE;
1874 : : Assert(!is_program); /* the grammar does not allow this */
1875 [ + - ]: 740 : if (whereToSendOutput == DestRemote)
1876 : 740 : ReceiveCopyBegin(cstate);
1877 : : else
1878 : 0 : cstate->copy_file = stdin;
1879 : : }
1880 : : else
1881 : : {
1882 : 300 : cstate->filename = pstrdup(filename);
1883 : :
1884 [ + + ]: 300 : if (cstate->is_program)
1885 : : {
1886 : 1 : progress_vals[1] = PROGRESS_COPY_TYPE_PROGRAM;
1887 : 1 : cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
1888 [ - + ]: 1 : if (cstate->copy_file == NULL)
1889 [ # # ]: 0 : ereport(ERROR,
1890 : : (errcode_for_file_access(),
1891 : : errmsg("could not execute command \"%s\": %m",
1892 : : cstate->filename)));
1893 : : }
1894 : : else
1895 : : {
1896 : : struct stat st;
1897 : :
1898 : 299 : progress_vals[1] = PROGRESS_COPY_TYPE_FILE;
1899 : 299 : cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
1900 [ - + ]: 299 : if (cstate->copy_file == NULL)
1901 : : {
1902 : : /* copy errno because ereport subfunctions might change it */
1903 : 0 : int save_errno = errno;
1904 : :
1905 [ # # # # : 0 : ereport(ERROR,
# # ]
1906 : : (errcode_for_file_access(),
1907 : : errmsg("could not open file \"%s\" for reading: %m",
1908 : : cstate->filename),
1909 : : (save_errno == ENOENT || save_errno == EACCES) ?
1910 : : errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
1911 : : "You may want a client-side facility such as psql's \\copy.") : 0));
1912 : : }
1913 : :
1914 [ - + ]: 299 : if (fstat(fileno(cstate->copy_file), &st))
1915 [ # # ]: 0 : ereport(ERROR,
1916 : : (errcode_for_file_access(),
1917 : : errmsg("could not stat file \"%s\": %m",
1918 : : cstate->filename)));
1919 : :
1920 [ - + ]: 299 : if (S_ISDIR(st.st_mode))
1921 [ # # ]: 0 : ereport(ERROR,
1922 : : (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1923 : : errmsg("\"%s\" is a directory", cstate->filename)));
1924 : :
1925 : 299 : progress_vals[2] = st.st_size;
1926 : : }
1927 : : }
1928 : :
1929 : 1257 : pgstat_progress_update_multi_param(3, progress_cols, progress_vals);
1930 : :
1931 : 1257 : cstate->routine->CopyFromStart(cstate, tupDesc);
1932 : :
1933 : 1257 : MemoryContextSwitchTo(oldcontext);
1934 : :
1935 : 1257 : return cstate;
1936 : : }
1937 : :
1938 : : /*
1939 : : * Clean up storage and release resources for COPY FROM.
1940 : : */
1941 : : void
1942 : 1053 : EndCopyFrom(CopyFromState cstate)
1943 : : {
1944 : : /* Invoke the end callback */
1945 : 1053 : cstate->routine->CopyFromEnd(cstate);
1946 : :
1947 : : /* No COPY FROM related resources except memory. */
1948 [ + + ]: 1053 : if (cstate->is_program)
1949 : : {
1950 : 1 : ClosePipeFromProgram(cstate);
1951 : : }
1952 : : else
1953 : : {
1954 [ + + - + ]: 1052 : if (cstate->filename != NULL && FreeFile(cstate->copy_file))
1955 [ # # ]: 0 : ereport(ERROR,
1956 : : (errcode_for_file_access(),
1957 : : errmsg("could not close file \"%s\": %m",
1958 : : cstate->filename)));
1959 : : }
1960 : :
1961 : 1053 : pgstat_progress_end_command();
1962 : :
1963 : 1053 : MemoryContextDelete(cstate->copycontext);
1964 : 1053 : pfree(cstate);
1965 : 1053 : }
1966 : :
1967 : : /*
1968 : : * Closes the pipe from an external program, checking the pclose() return code.
1969 : : */
1970 : : static void
1971 : 1 : ClosePipeFromProgram(CopyFromState cstate)
1972 : : {
1973 : : int pclose_rc;
1974 : :
1975 : : Assert(cstate->is_program);
1976 : :
1977 : 1 : pclose_rc = ClosePipeStream(cstate->copy_file);
1978 [ - + ]: 1 : if (pclose_rc == -1)
1979 [ # # ]: 0 : ereport(ERROR,
1980 : : (errcode_for_file_access(),
1981 : : errmsg("could not close pipe to external command: %m")));
1982 [ - + ]: 1 : else if (pclose_rc != 0)
1983 : : {
1984 : : /*
1985 : : * If we ended a COPY FROM PROGRAM before reaching EOF, then it's
1986 : : * expectable for the called program to fail with SIGPIPE, and we
1987 : : * should not report that as an error. Otherwise, SIGPIPE indicates a
1988 : : * problem.
1989 : : */
1990 [ # # # # ]: 0 : if (!cstate->raw_reached_eof &&
1991 : 0 : wait_result_is_signal(pclose_rc, SIGPIPE))
1992 : 0 : return;
1993 : :
1994 [ # # ]: 0 : ereport(ERROR,
1995 : : (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1996 : : errmsg("program \"%s\" failed",
1997 : : cstate->filename),
1998 : : errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1999 : : }
2000 : : }
|