PostgreSQL Source Code  git master
copyfrom.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/namespace.h"
#include "commands/copy.h"
#include "commands/copyfrom_internal.h"
#include "commands/progress.h"
#include "commands/trigger.h"
#include "executor/execPartition.h"
#include "executor/executor.h"
#include "executor/nodeModifyTable.h"
#include "executor/tuptable.h"
#include "foreign/fdwapi.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "miscadmin.h"
#include "optimizer/optimizer.h"
#include "pgstat.h"
#include "rewrite/rewriteHandler.h"
#include "storage/fd.h"
#include "tcop/tcopprot.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/portal.h"
#include "utils/rel.h"
#include "utils/snapmgr.h"
Include dependency graph for copyfrom.c:

Go to the source code of this file.

Data Structures

struct  CopyMultiInsertBuffer
 
struct  CopyMultiInsertInfo
 

Macros

#define MAX_BUFFERED_TUPLES   1000
 
#define MAX_BUFFERED_BYTES   65535
 
#define MAX_PARTITION_BUFFERS   32
 
#define MAX_COPY_DATA_DISPLAY   100
 

Typedefs

typedef struct CopyMultiInsertBuffer CopyMultiInsertBuffer
 
typedef struct CopyMultiInsertInfo CopyMultiInsertInfo
 

Functions

static char * limit_printout_length (const char *str)
 
static void ClosePipeFromProgram (CopyFromState cstate)
 
void CopyFromErrorCallback (void *arg)
 
static CopyMultiInsertBufferCopyMultiInsertBufferInit (ResultRelInfo *rri)
 
static void CopyMultiInsertInfoSetupBuffer (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
 
static void CopyMultiInsertInfoInit (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, CopyFromState cstate, EState *estate, CommandId mycid, int ti_options)
 
static bool CopyMultiInsertInfoIsFull (CopyMultiInsertInfo *miinfo)
 
static bool CopyMultiInsertInfoIsEmpty (CopyMultiInsertInfo *miinfo)
 
static void CopyMultiInsertBufferFlush (CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer, int64 *processed)
 
static void CopyMultiInsertBufferCleanup (CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
 
static void CopyMultiInsertInfoFlush (CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri, int64 *processed)
 
static void CopyMultiInsertInfoCleanup (CopyMultiInsertInfo *miinfo)
 
static TupleTableSlotCopyMultiInsertInfoNextFreeSlot (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
 
static void CopyMultiInsertInfoStore (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, TupleTableSlot *slot, int tuplen, uint64 lineno)
 
uint64 CopyFrom (CopyFromState cstate)
 
CopyFromState BeginCopyFrom (ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
 
void EndCopyFrom (CopyFromState cstate)
 

Macro Definition Documentation

◆ MAX_BUFFERED_BYTES

#define MAX_BUFFERED_BYTES   65535

Definition at line 71 of file copyfrom.c.

◆ MAX_BUFFERED_TUPLES

#define MAX_BUFFERED_TUPLES   1000

Definition at line 65 of file copyfrom.c.

◆ MAX_COPY_DATA_DISPLAY

#define MAX_COPY_DATA_DISPLAY   100

◆ MAX_PARTITION_BUFFERS

#define MAX_PARTITION_BUFFERS   32

Definition at line 74 of file copyfrom.c.

Typedef Documentation

◆ CopyMultiInsertBuffer

◆ CopyMultiInsertInfo

Function Documentation

◆ BeginCopyFrom()

CopyFromState BeginCopyFrom ( ParseState pstate,
Relation  rel,
Node whereClause,
const char *  filename,
bool  is_program,
copy_data_source_cb  data_source_cb,
List attnamelist,
List options 
)

Definition at line 1334 of file copyfrom.c.

1342 {
1343  CopyFromState cstate;
1344  bool pipe = (filename == NULL);
1345  TupleDesc tupDesc;
1346  AttrNumber num_phys_attrs,
1347  num_defaults;
1348  FmgrInfo *in_functions;
1349  Oid *typioparams;
1350  Oid in_func_oid;
1351  int *defmap;
1352  ExprState **defexprs;
1353  MemoryContext oldcontext;
1354  bool volatile_defexprs;
1355  const int progress_cols[] = {
1359  };
1360  int64 progress_vals[] = {
1362  0,
1363  0
1364  };
1365 
1366  /* Allocate workspace and zero all fields */
1367  cstate = (CopyFromStateData *) palloc0(sizeof(CopyFromStateData));
1368 
1369  /*
1370  * We allocate everything used by a cstate in a new memory context. This
1371  * avoids memory leaks during repeated use of COPY in a query.
1372  */
1374  "COPY",
1376 
1377  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1378 
1379  /* Extract options from the statement node tree */
1380  ProcessCopyOptions(pstate, &cstate->opts, true /* is_from */ , options);
1381 
1382  /* Process the target relation */
1383  cstate->rel = rel;
1384 
1385  tupDesc = RelationGetDescr(cstate->rel);
1386 
1387  /* process common options or initialization */
1388 
1389  /* Generate or convert list of attributes to process */
1390  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1391 
1392  num_phys_attrs = tupDesc->natts;
1393 
1394  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1395  cstate->opts.force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1396  if (cstate->opts.force_notnull_all)
1397  MemSet(cstate->opts.force_notnull_flags, true, num_phys_attrs * sizeof(bool));
1398  else if (cstate->opts.force_notnull)
1399  {
1400  List *attnums;
1401  ListCell *cur;
1402 
1403  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_notnull);
1404 
1405  foreach(cur, attnums)
1406  {
1407  int attnum = lfirst_int(cur);
1408  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1409 
1410  if (!list_member_int(cstate->attnumlist, attnum))
1411  ereport(ERROR,
1412  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1413  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
1414  NameStr(attr->attname))));
1415  cstate->opts.force_notnull_flags[attnum - 1] = true;
1416  }
1417  }
1418 
1419  /* Convert FORCE_NULL name list to per-column flags, check validity */
1420  cstate->opts.force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1421  if (cstate->opts.force_null_all)
1422  MemSet(cstate->opts.force_null_flags, true, num_phys_attrs * sizeof(bool));
1423  else if (cstate->opts.force_null)
1424  {
1425  List *attnums;
1426  ListCell *cur;
1427 
1428  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_null);
1429 
1430  foreach(cur, attnums)
1431  {
1432  int attnum = lfirst_int(cur);
1433  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1434 
1435  if (!list_member_int(cstate->attnumlist, attnum))
1436  ereport(ERROR,
1437  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1438  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
1439  NameStr(attr->attname))));
1440  cstate->opts.force_null_flags[attnum - 1] = true;
1441  }
1442  }
1443 
1444  /* Convert convert_selectively name list to per-column flags */
1445  if (cstate->opts.convert_selectively)
1446  {
1447  List *attnums;
1448  ListCell *cur;
1449 
1450  cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1451 
1452  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.convert_select);
1453 
1454  foreach(cur, attnums)
1455  {
1456  int attnum = lfirst_int(cur);
1457  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1458 
1459  if (!list_member_int(cstate->attnumlist, attnum))
1460  ereport(ERROR,
1461  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1462  errmsg_internal("selected column \"%s\" not referenced by COPY",
1463  NameStr(attr->attname))));
1464  cstate->convert_select_flags[attnum - 1] = true;
1465  }
1466  }
1467 
1468  /* Use client encoding when ENCODING option is not specified. */
1469  if (cstate->opts.file_encoding < 0)
1471  else
1472  cstate->file_encoding = cstate->opts.file_encoding;
1473 
1474  /*
1475  * Look up encoding conversion function.
1476  */
1477  if (cstate->file_encoding == GetDatabaseEncoding() ||
1478  cstate->file_encoding == PG_SQL_ASCII ||
1480  {
1481  cstate->need_transcoding = false;
1482  }
1483  else
1484  {
1485  cstate->need_transcoding = true;
1488  }
1489 
1490  cstate->copy_src = COPY_FILE; /* default */
1491 
1492  cstate->whereClause = whereClause;
1493 
1494  /* Initialize state variables */
1495  cstate->eol_type = EOL_UNKNOWN;
1496  cstate->cur_relname = RelationGetRelationName(cstate->rel);
1497  cstate->cur_lineno = 0;
1498  cstate->cur_attname = NULL;
1499  cstate->cur_attval = NULL;
1500  cstate->relname_only = false;
1501 
1502  /*
1503  * Allocate buffers for the input pipeline.
1504  *
1505  * attribute_buf and raw_buf are used in both text and binary modes, but
1506  * input_buf and line_buf only in text mode.
1507  */
1508  cstate->raw_buf = palloc(RAW_BUF_SIZE + 1);
1509  cstate->raw_buf_index = cstate->raw_buf_len = 0;
1510  cstate->raw_reached_eof = false;
1511 
1512  if (!cstate->opts.binary)
1513  {
1514  /*
1515  * If encoding conversion is needed, we need another buffer to hold
1516  * the converted input data. Otherwise, we can just point input_buf
1517  * to the same buffer as raw_buf.
1518  */
1519  if (cstate->need_transcoding)
1520  {
1521  cstate->input_buf = (char *) palloc(INPUT_BUF_SIZE + 1);
1522  cstate->input_buf_index = cstate->input_buf_len = 0;
1523  }
1524  else
1525  cstate->input_buf = cstate->raw_buf;
1526  cstate->input_reached_eof = false;
1527 
1528  initStringInfo(&cstate->line_buf);
1529  }
1530 
1531  initStringInfo(&cstate->attribute_buf);
1532 
1533  /* Assign range table and rteperminfos, we'll need them in CopyFrom. */
1534  if (pstate)
1535  {
1536  cstate->range_table = pstate->p_rtable;
1537  cstate->rteperminfos = pstate->p_rteperminfos;
1538  }
1539 
1540  num_defaults = 0;
1541  volatile_defexprs = false;
1542 
1543  /*
1544  * Pick up the required catalog information for each attribute in the
1545  * relation, including the input function, the element type (to pass to
1546  * the input function), and info about defaults and constraints. (Which
1547  * input function we use depends on text/binary format choice.)
1548  */
1549  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1550  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
1551  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
1552  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
1553 
1554  for (int attnum = 1; attnum <= num_phys_attrs; attnum++)
1555  {
1556  Form_pg_attribute att = TupleDescAttr(tupDesc, attnum - 1);
1557 
1558  /* We don't need info for dropped attributes */
1559  if (att->attisdropped)
1560  continue;
1561 
1562  /* Fetch the input function and typioparam info */
1563  if (cstate->opts.binary)
1564  getTypeBinaryInputInfo(att->atttypid,
1565  &in_func_oid, &typioparams[attnum - 1]);
1566  else
1567  getTypeInputInfo(att->atttypid,
1568  &in_func_oid, &typioparams[attnum - 1]);
1569  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
1570 
1571  /* Get default info if available */
1572  defexprs[attnum - 1] = NULL;
1573 
1574  if (!att->attgenerated)
1575  {
1576  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
1577  attnum);
1578 
1579  if (defexpr != NULL)
1580  {
1581  /* Run the expression through planner */
1582  defexpr = expression_planner(defexpr);
1583 
1584  /* Initialize executable expression in copycontext */
1585  defexprs[attnum - 1] = ExecInitExpr(defexpr, NULL);
1586 
1587  /* if NOT copied from input */
1588  /* use default value if one exists */
1589  if (!list_member_int(cstate->attnumlist, attnum))
1590  {
1591  defmap[num_defaults] = attnum - 1;
1592  num_defaults++;
1593  }
1594 
1595  /*
1596  * If a default expression looks at the table being loaded,
1597  * then it could give the wrong answer when using
1598  * multi-insert. Since database access can be dynamic this is
1599  * hard to test for exactly, so we use the much wider test of
1600  * whether the default expression is volatile. We allow for
1601  * the special case of when the default expression is the
1602  * nextval() of a sequence which in this specific case is
1603  * known to be safe for use with the multi-insert
1604  * optimization. Hence we use this special case function
1605  * checker rather than the standard check for
1606  * contain_volatile_functions().
1607  */
1608  if (!volatile_defexprs)
1609  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
1610  }
1611  }
1612  }
1613 
1614  cstate->defaults = (bool *) palloc0(tupDesc->natts * sizeof(bool));
1615 
1616  /* initialize progress */
1618  cstate->rel ? RelationGetRelid(cstate->rel) : InvalidOid);
1619  cstate->bytes_processed = 0;
1620 
1621  /* We keep those variables in cstate. */
1622  cstate->in_functions = in_functions;
1623  cstate->typioparams = typioparams;
1624  cstate->defmap = defmap;
1625  cstate->defexprs = defexprs;
1626  cstate->volatile_defexprs = volatile_defexprs;
1627  cstate->num_defaults = num_defaults;
1628  cstate->is_program = is_program;
1629 
1630  if (data_source_cb)
1631  {
1632  progress_vals[1] = PROGRESS_COPY_TYPE_CALLBACK;
1633  cstate->copy_src = COPY_CALLBACK;
1634  cstate->data_source_cb = data_source_cb;
1635  }
1636  else if (pipe)
1637  {
1638  progress_vals[1] = PROGRESS_COPY_TYPE_PIPE;
1639  Assert(!is_program); /* the grammar does not allow this */
1641  ReceiveCopyBegin(cstate);
1642  else
1643  cstate->copy_file = stdin;
1644  }
1645  else
1646  {
1647  cstate->filename = pstrdup(filename);
1648 
1649  if (cstate->is_program)
1650  {
1651  progress_vals[1] = PROGRESS_COPY_TYPE_PROGRAM;
1652  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
1653  if (cstate->copy_file == NULL)
1654  ereport(ERROR,
1656  errmsg("could not execute command \"%s\": %m",
1657  cstate->filename)));
1658  }
1659  else
1660  {
1661  struct stat st;
1662 
1663  progress_vals[1] = PROGRESS_COPY_TYPE_FILE;
1664  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
1665  if (cstate->copy_file == NULL)
1666  {
1667  /* copy errno because ereport subfunctions might change it */
1668  int save_errno = errno;
1669 
1670  ereport(ERROR,
1672  errmsg("could not open file \"%s\" for reading: %m",
1673  cstate->filename),
1674  (save_errno == ENOENT || save_errno == EACCES) ?
1675  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
1676  "You may want a client-side facility such as psql's \\copy.") : 0));
1677  }
1678 
1679  if (fstat(fileno(cstate->copy_file), &st))
1680  ereport(ERROR,
1682  errmsg("could not stat file \"%s\": %m",
1683  cstate->filename)));
1684 
1685  if (S_ISDIR(st.st_mode))
1686  ereport(ERROR,
1687  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1688  errmsg("\"%s\" is a directory", cstate->filename)));
1689 
1690  progress_vals[2] = st.st_size;
1691  }
1692  }
1693 
1694  pgstat_progress_update_multi_param(3, progress_cols, progress_vals);
1695 
1696  if (cstate->opts.binary)
1697  {
1698  /* Read and verify binary header */
1699  ReceiveCopyBinaryHeader(cstate);
1700  }
1701 
1702  /* create workspace for CopyReadAttributes results */
1703  if (!cstate->opts.binary)
1704  {
1705  AttrNumber attr_count = list_length(cstate->attnumlist);
1706 
1707  cstate->max_fields = attr_count;
1708  cstate->raw_fields = (char **) palloc(attr_count * sizeof(char *));
1709  }
1710 
1711  MemoryContextSwitchTo(oldcontext);
1712 
1713  return cstate;
1714 }
int16 AttrNumber
Definition: attnum.h:21
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:786
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:414
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
void pgstat_progress_update_multi_param(int nparam, const int *index, const int64 *val)
@ PROGRESS_COMMAND_COPY
#define NameStr(name)
Definition: c.h:735
#define PG_BINARY_R
Definition: c.h:1285
#define MemSet(start, val, len)
Definition: c.h:1009
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:590
#define INPUT_BUF_SIZE
@ EOL_UNKNOWN
#define RAW_BUF_SIZE
void ReceiveCopyBinaryHeader(CopyFromState cstate)
void ReceiveCopyBegin(CopyFromState cstate)
@ COPY_FILE
Definition: copyto.c:52
@ COPY_CALLBACK
Definition: copyto.c:54
@ DestRemote
Definition: dest.h:89
struct cursor * cur
Definition: ecpg.c:28
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errcode_for_file_access(void)
Definition: elog.c:881
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:128
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2528
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2631
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
Assert(fmt[strlen(fmt) - 1] !='\n')
bool list_member_int(const List *list, int datum)
Definition: list.c:701
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2856
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2922
int GetDatabaseEncoding(void)
Definition: mbutils.c:1268
int pg_get_client_encoding(void)
Definition: mbutils.c:337
char * pstrdup(const char *in)
Definition: mcxt.c:1644
void * palloc0(Size size)
Definition: mcxt.c:1257
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void * palloc(Size size)
Definition: mcxt.c:1226
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Oid FindDefaultConversionProc(int32 for_encoding, int32 to_encoding)
Definition: namespace.c:3612
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
int16 attnum
Definition: pg_attribute.h:74
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:209
static char * filename
Definition: pg_dumpall.c:119
static int list_length(const List *l)
Definition: pg_list.h:152
#define lfirst_int(lc)
Definition: pg_list.h:173
@ PG_SQL_ASCII
Definition: pg_wchar.h:226
Expr * expression_planner(Expr *expr)
Definition: planner.c:6489
CommandDest whereToSendOutput
Definition: postgres.c:88
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define PROGRESS_COPY_COMMAND
Definition: progress.h:143
#define PROGRESS_COPY_TYPE_FILE
Definition: progress.h:151
#define PROGRESS_COPY_COMMAND_FROM
Definition: progress.h:147
#define PROGRESS_COPY_TYPE
Definition: progress.h:144
#define PROGRESS_COPY_TYPE_PROGRAM
Definition: progress.h:152
#define PROGRESS_COPY_BYTES_TOTAL
Definition: progress.h:140
#define PROGRESS_COPY_TYPE_CALLBACK
Definition: progress.h:154
#define PROGRESS_COPY_TYPE_PIPE
Definition: progress.h:153
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetRelationName(relation)
Definition: rel.h:538
Node * build_column_default(Relation rel, int attrno)
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
bool force_notnull_all
Definition: copy.h:59
bool binary
Definition: copy.h:43
bool convert_selectively
Definition: copy.h:64
List * force_null
Definition: copy.h:61
List * convert_select
Definition: copy.h:65
bool force_null_all
Definition: copy.h:62
bool * force_notnull_flags
Definition: copy.h:60
int file_encoding
Definition: copy.h:41
bool * force_null_flags
Definition: copy.h:63
List * force_notnull
Definition: copy.h:58
ExprState ** defexprs
copy_data_source_cb data_source_cb
StringInfoData line_buf
CopyFormatOptions opts
StringInfoData attribute_buf
MemoryContext copycontext
const char * cur_attval
const char * cur_attname
const char * cur_relname
Definition: fmgr.h:57
Definition: pg_list.h:54
Definition: nodes.h:129
List * p_rteperminfos
Definition: parse_node.h:194
List * p_rtable
Definition: parse_node.h:193
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define S_ISDIR(m)
Definition: win32_port.h:325
#define fstat
Definition: win32_port.h:283

References AllocateFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert(), attnum, CopyFromStateData::attnumlist, CopyFromStateData::attribute_buf, CopyFormatOptions::binary, build_column_default(), CopyFromStateData::bytes_processed, contain_volatile_functions_not_nextval(), CopyFromStateData::conversion_proc, CopyFormatOptions::convert_select, CopyFromStateData::convert_select_flags, CopyFormatOptions::convert_selectively, COPY_CALLBACK, COPY_FILE, CopyFromStateData::copy_file, CopyFromStateData::copy_src, CopyFromStateData::copycontext, CopyGetAttnums(), cur, CopyFromStateData::cur_attname, CopyFromStateData::cur_attval, CopyFromStateData::cur_lineno, CopyFromStateData::cur_relname, CurrentMemoryContext, CopyFromStateData::data_source_cb, CopyFromStateData::defaults, CopyFromStateData::defexprs, CopyFromStateData::defmap, DestRemote, CopyFromStateData::eol_type, EOL_UNKNOWN, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExecInitExpr(), expression_planner(), CopyFormatOptions::file_encoding, CopyFromStateData::file_encoding, filename, CopyFromStateData::filename, FindDefaultConversionProc(), fmgr_info(), CopyFormatOptions::force_notnull, CopyFormatOptions::force_notnull_all, CopyFormatOptions::force_notnull_flags, CopyFormatOptions::force_null, CopyFormatOptions::force_null_all, CopyFormatOptions::force_null_flags, fstat, GetDatabaseEncoding(), getTypeBinaryInputInfo(), getTypeInputInfo(), CopyFromStateData::in_functions, initStringInfo(), CopyFromStateData::input_buf, CopyFromStateData::input_buf_index, CopyFromStateData::input_buf_len, INPUT_BUF_SIZE, CopyFromStateData::input_reached_eof, InvalidOid, CopyFromStateData::is_program, lfirst_int, CopyFromStateData::line_buf, list_length(), list_member_int(), CopyFromStateData::max_fields, MemoryContextSwitchTo(), MemSet, NameStr, TupleDescData::natts, CopyFromStateData::need_transcoding, CopyFromStateData::num_defaults, OpenPipeStream(), CopyFromStateData::opts, ParseState::p_rtable, ParseState::p_rteperminfos, palloc(), palloc0(), PG_BINARY_R, pg_get_client_encoding(), PG_SQL_ASCII, pgstat_progress_start_command(), pgstat_progress_update_multi_param(), ProcessCopyOptions(), PROGRESS_COMMAND_COPY, PROGRESS_COPY_BYTES_TOTAL, PROGRESS_COPY_COMMAND, PROGRESS_COPY_COMMAND_FROM, PROGRESS_COPY_TYPE, PROGRESS_COPY_TYPE_CALLBACK, PROGRESS_COPY_TYPE_FILE, PROGRESS_COPY_TYPE_PIPE, PROGRESS_COPY_TYPE_PROGRAM, pstrdup(), CopyFromStateData::range_table, CopyFromStateData::raw_buf, CopyFromStateData::raw_buf_index, CopyFromStateData::raw_buf_len, RAW_BUF_SIZE, CopyFromStateData::raw_fields, CopyFromStateData::raw_reached_eof, ReceiveCopyBegin(), ReceiveCopyBinaryHeader(), CopyFromStateData::rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, CopyFromStateData::relname_only, CopyFromStateData::rteperminfos, S_ISDIR, stat::st_mode, stat::st_size, TupleDescAttr, CopyFromStateData::typioparams, CopyFromStateData::volatile_defexprs, CopyFromStateData::whereClause, and whereToSendOutput.

Referenced by copy_table(), DoCopy(), file_acquire_sample_rows(), fileBeginForeignScan(), and fileReScanForeignScan().

◆ ClosePipeFromProgram()

static void ClosePipeFromProgram ( CopyFromState  cstate)
static

Definition at line 1746 of file copyfrom.c.

1747 {
1748  int pclose_rc;
1749 
1750  Assert(cstate->is_program);
1751 
1752  pclose_rc = ClosePipeStream(cstate->copy_file);
1753  if (pclose_rc == -1)
1754  ereport(ERROR,
1756  errmsg("could not close pipe to external command: %m")));
1757  else if (pclose_rc != 0)
1758  {
1759  /*
1760  * If we ended a COPY FROM PROGRAM before reaching EOF, then it's
1761  * expectable for the called program to fail with SIGPIPE, and we
1762  * should not report that as an error. Otherwise, SIGPIPE indicates a
1763  * problem.
1764  */
1765  if (!cstate->raw_reached_eof &&
1766  wait_result_is_signal(pclose_rc, SIGPIPE))
1767  return;
1768 
1769  ereport(ERROR,
1770  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1771  errmsg("program \"%s\" failed",
1772  cstate->filename),
1773  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1774  }
1775 }
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
int ClosePipeStream(FILE *file)
Definition: fd.c:2936
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33
bool wait_result_is_signal(int exit_status, int signum)
Definition: wait_error.c:102
#define SIGPIPE
Definition: win32_port.h:173

References Assert(), ClosePipeStream(), CopyFromStateData::copy_file, ereport, errcode(), errcode_for_file_access(), errdetail_internal(), errmsg(), ERROR, CopyFromStateData::filename, CopyFromStateData::is_program, CopyFromStateData::raw_reached_eof, SIGPIPE, wait_result_is_signal(), and wait_result_to_str().

Referenced by EndCopyFrom().

◆ CopyFrom()

uint64 CopyFrom ( CopyFromState  cstate)

Definition at line 632 of file copyfrom.c.

633 {
634  ResultRelInfo *resultRelInfo;
635  ResultRelInfo *target_resultRelInfo;
636  ResultRelInfo *prevResultRelInfo = NULL;
637  EState *estate = CreateExecutorState(); /* for ExecConstraints() */
638  ModifyTableState *mtstate;
639  ExprContext *econtext;
640  TupleTableSlot *singleslot = NULL;
641  MemoryContext oldcontext = CurrentMemoryContext;
642 
643  PartitionTupleRouting *proute = NULL;
644  ErrorContextCallback errcallback;
645  CommandId mycid = GetCurrentCommandId(true);
646  int ti_options = 0; /* start with default options for insert */
647  BulkInsertState bistate = NULL;
648  CopyInsertMethod insertMethod;
649  CopyMultiInsertInfo multiInsertInfo = {0}; /* pacify compiler */
650  int64 processed = 0;
651  int64 excluded = 0;
652  bool has_before_insert_row_trig;
653  bool has_instead_insert_row_trig;
654  bool leafpart_use_multi_insert = false;
655 
656  Assert(cstate->rel);
657  Assert(list_length(cstate->range_table) == 1);
658 
659  /*
660  * The target must be a plain, foreign, or partitioned relation, or have
661  * an INSTEAD OF INSERT row trigger. (Currently, such triggers are only
662  * allowed on views, so we only hint about them in the view case.)
663  */
664  if (cstate->rel->rd_rel->relkind != RELKIND_RELATION &&
665  cstate->rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
666  cstate->rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
667  !(cstate->rel->trigdesc &&
669  {
670  if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
671  ereport(ERROR,
672  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
673  errmsg("cannot copy to view \"%s\"",
674  RelationGetRelationName(cstate->rel)),
675  errhint("To enable copying to a view, provide an INSTEAD OF INSERT trigger.")));
676  else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
677  ereport(ERROR,
678  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
679  errmsg("cannot copy to materialized view \"%s\"",
680  RelationGetRelationName(cstate->rel))));
681  else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
682  ereport(ERROR,
683  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
684  errmsg("cannot copy to sequence \"%s\"",
685  RelationGetRelationName(cstate->rel))));
686  else
687  ereport(ERROR,
688  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
689  errmsg("cannot copy to non-table relation \"%s\"",
690  RelationGetRelationName(cstate->rel))));
691  }
692 
693  /*
694  * If the target file is new-in-transaction, we assume that checking FSM
695  * for free space is a waste of time. This could possibly be wrong, but
696  * it's unlikely.
697  */
698  if (RELKIND_HAS_STORAGE(cstate->rel->rd_rel->relkind) &&
701  ti_options |= TABLE_INSERT_SKIP_FSM;
702 
703  /*
704  * Optimize if new relation storage was created in this subxact or one of
705  * its committed children and we won't see those rows later as part of an
706  * earlier scan or command. The subxact test ensures that if this subxact
707  * aborts then the frozen rows won't be visible after xact cleanup. Note
708  * that the stronger test of exactly which subtransaction created it is
709  * crucial for correctness of this optimization. The test for an earlier
710  * scan or command tolerates false negatives. FREEZE causes other sessions
711  * to see rows they would not see under MVCC, and a false negative merely
712  * spreads that anomaly to the current session.
713  */
714  if (cstate->opts.freeze)
715  {
716  /*
717  * We currently disallow COPY FREEZE on partitioned tables. The
718  * reason for this is that we've simply not yet opened the partitions
719  * to determine if the optimization can be applied to them. We could
720  * go and open them all here, but doing so may be quite a costly
721  * overhead for small copies. In any case, we may just end up routing
722  * tuples to a small number of partitions. It seems better just to
723  * raise an ERROR for partitioned tables.
724  */
725  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
726  {
727  ereport(ERROR,
728  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
729  errmsg("cannot perform COPY FREEZE on a partitioned table")));
730  }
731 
732  /*
733  * Tolerate one registration for the benefit of FirstXactSnapshot.
734  * Scan-bearing queries generally create at least two registrations,
735  * though relying on that is fragile, as is ignoring ActiveSnapshot.
736  * Clear CatalogSnapshot to avoid counting its registration. We'll
737  * still detect ongoing catalog scans, each of which separately
738  * registers the snapshot it uses.
739  */
742  ereport(ERROR,
743  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
744  errmsg("cannot perform COPY FREEZE because of prior transaction activity")));
745 
746  if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
748  ereport(ERROR,
749  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
750  errmsg("cannot perform COPY FREEZE because the table was not created or truncated in the current subtransaction")));
751 
752  ti_options |= TABLE_INSERT_FROZEN;
753  }
754 
755  /*
756  * We need a ResultRelInfo so we can use the regular executor's
757  * index-entry-making machinery. (There used to be a huge amount of code
758  * here that basically duplicated execUtils.c ...)
759  */
760  ExecInitRangeTable(estate, cstate->range_table, cstate->rteperminfos);
761  resultRelInfo = target_resultRelInfo = makeNode(ResultRelInfo);
762  ExecInitResultRelation(estate, resultRelInfo, 1);
763 
764  /* Verify the named relation is a valid target for INSERT */
765  CheckValidResultRel(resultRelInfo, CMD_INSERT);
766 
767  ExecOpenIndices(resultRelInfo, false);
768 
769  /*
770  * Set up a ModifyTableState so we can let FDW(s) init themselves for
771  * foreign-table result relation(s).
772  */
773  mtstate = makeNode(ModifyTableState);
774  mtstate->ps.plan = NULL;
775  mtstate->ps.state = estate;
776  mtstate->operation = CMD_INSERT;
777  mtstate->mt_nrels = 1;
778  mtstate->resultRelInfo = resultRelInfo;
779  mtstate->rootResultRelInfo = resultRelInfo;
780 
781  if (resultRelInfo->ri_FdwRoutine != NULL &&
782  resultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)
783  resultRelInfo->ri_FdwRoutine->BeginForeignInsert(mtstate,
784  resultRelInfo);
785 
786  /*
787  * Also, if the named relation is a foreign table, determine if the FDW
788  * supports batch insert and determine the batch size (a FDW may support
789  * batching, but it may be disabled for the server/table).
790  *
791  * If the FDW does not support batching, we set the batch size to 1.
792  */
793  if (resultRelInfo->ri_FdwRoutine != NULL &&
794  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize &&
795  resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert)
796  resultRelInfo->ri_BatchSize =
797  resultRelInfo->ri_FdwRoutine->GetForeignModifyBatchSize(resultRelInfo);
798  else
799  resultRelInfo->ri_BatchSize = 1;
800 
801  Assert(resultRelInfo->ri_BatchSize >= 1);
802 
803  /* Prepare to catch AFTER triggers. */
805 
806  /*
807  * If there are any triggers with transition tables on the named relation,
808  * we need to be prepared to capture transition tuples.
809  *
810  * Because partition tuple routing would like to know about whether
811  * transition capture is active, we also set it in mtstate, which is
812  * passed to ExecFindPartition() below.
813  */
814  cstate->transition_capture = mtstate->mt_transition_capture =
816  RelationGetRelid(cstate->rel),
817  CMD_INSERT);
818 
819  /*
820  * If the named relation is a partitioned table, initialize state for
821  * CopyFrom tuple routing.
822  */
823  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
824  proute = ExecSetupPartitionTupleRouting(estate, cstate->rel);
825 
826  if (cstate->whereClause)
827  cstate->qualexpr = ExecInitQual(castNode(List, cstate->whereClause),
828  &mtstate->ps);
829 
830  /*
831  * It's generally more efficient to prepare a bunch of tuples for
832  * insertion, and insert them in one
833  * table_multi_insert()/ExecForeignBatchInsert() call, than call
834  * table_tuple_insert()/ExecForeignInsert() separately for every tuple.
835  * However, there are a number of reasons why we might not be able to do
836  * this. These are explained below.
837  */
838  if (resultRelInfo->ri_TrigDesc != NULL &&
839  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
840  resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
841  {
842  /*
843  * Can't support multi-inserts when there are any BEFORE/INSTEAD OF
844  * triggers on the table. Such triggers might query the table we're
845  * inserting into and act differently if the tuples that have already
846  * been processed and prepared for insertion are not there.
847  */
848  insertMethod = CIM_SINGLE;
849  }
850  else if (resultRelInfo->ri_FdwRoutine != NULL &&
851  resultRelInfo->ri_BatchSize == 1)
852  {
853  /*
854  * Can't support multi-inserts to a foreign table if the FDW does not
855  * support batching, or it's disabled for the server or foreign table.
856  */
857  insertMethod = CIM_SINGLE;
858  }
859  else if (proute != NULL && resultRelInfo->ri_TrigDesc != NULL &&
860  resultRelInfo->ri_TrigDesc->trig_insert_new_table)
861  {
862  /*
863  * For partitioned tables we can't support multi-inserts when there
864  * are any statement level insert triggers. It might be possible to
865  * allow partitioned tables with such triggers in the future, but for
866  * now, CopyMultiInsertInfoFlush expects that any after row insert and
867  * statement level insert triggers are on the same relation.
868  */
869  insertMethod = CIM_SINGLE;
870  }
871  else if (cstate->volatile_defexprs)
872  {
873  /*
874  * Can't support multi-inserts if there are any volatile default
875  * expressions in the table. Similarly to the trigger case above,
876  * such expressions may query the table we're inserting into.
877  *
878  * Note: It does not matter if any partitions have any volatile
879  * default expressions as we use the defaults from the target of the
880  * COPY command.
881  */
882  insertMethod = CIM_SINGLE;
883  }
884  else if (contain_volatile_functions(cstate->whereClause))
885  {
886  /*
887  * Can't support multi-inserts if there are any volatile function
888  * expressions in WHERE clause. Similarly to the trigger case above,
889  * such expressions may query the table we're inserting into.
890  */
891  insertMethod = CIM_SINGLE;
892  }
893  else
894  {
895  /*
896  * For partitioned tables, we may still be able to perform bulk
897  * inserts. However, the possibility of this depends on which types
898  * of triggers exist on the partition. We must disable bulk inserts
899  * if the partition is a foreign table that can't use batching or it
900  * has any before row insert or insert instead triggers (same as we
901  * checked above for the parent table). Since the partition's
902  * resultRelInfos are initialized only when we actually need to insert
903  * the first tuple into them, we must have the intermediate insert
904  * method of CIM_MULTI_CONDITIONAL to flag that we must later
905  * determine if we can use bulk-inserts for the partition being
906  * inserted into.
907  */
908  if (proute)
909  insertMethod = CIM_MULTI_CONDITIONAL;
910  else
911  insertMethod = CIM_MULTI;
912 
913  CopyMultiInsertInfoInit(&multiInsertInfo, resultRelInfo, cstate,
914  estate, mycid, ti_options);
915  }
916 
917  /*
918  * If not using batch mode (which allocates slots as needed) set up a
919  * tuple slot too. When inserting into a partitioned table, we also need
920  * one, even if we might batch insert, to read the tuple in the root
921  * partition's form.
922  */
923  if (insertMethod == CIM_SINGLE || insertMethod == CIM_MULTI_CONDITIONAL)
924  {
925  singleslot = table_slot_create(resultRelInfo->ri_RelationDesc,
926  &estate->es_tupleTable);
927  bistate = GetBulkInsertState();
928  }
929 
930  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
931  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
932 
933  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
934  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
935 
936  /*
937  * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
938  * should do this for COPY, since it's not really an "INSERT" statement as
939  * such. However, executing these triggers maintains consistency with the
940  * EACH ROW triggers that we already fire on COPY.
941  */
942  ExecBSInsertTriggers(estate, resultRelInfo);
943 
944  econtext = GetPerTupleExprContext(estate);
945 
946  /* Set up callback to identify error line number */
947  errcallback.callback = CopyFromErrorCallback;
948  errcallback.arg = (void *) cstate;
949  errcallback.previous = error_context_stack;
950  error_context_stack = &errcallback;
951 
952  for (;;)
953  {
954  TupleTableSlot *myslot;
955  bool skip_tuple;
956 
958 
959  /*
960  * Reset the per-tuple exprcontext. We do this after every tuple, to
961  * clean-up after expression evaluations etc.
962  */
963  ResetPerTupleExprContext(estate);
964 
965  /* select slot to (initially) load row into */
966  if (insertMethod == CIM_SINGLE || proute)
967  {
968  myslot = singleslot;
969  Assert(myslot != NULL);
970  }
971  else
972  {
973  Assert(resultRelInfo == target_resultRelInfo);
974  Assert(insertMethod == CIM_MULTI);
975 
976  myslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
977  resultRelInfo);
978  }
979 
980  /*
981  * Switch to per-tuple context before calling NextCopyFrom, which does
982  * evaluate default expressions etc. and requires per-tuple context.
983  */
985 
986  ExecClearTuple(myslot);
987 
988  /* Directly store the values/nulls array in the slot */
989  if (!NextCopyFrom(cstate, econtext, myslot->tts_values, myslot->tts_isnull))
990  break;
991 
992  ExecStoreVirtualTuple(myslot);
993 
994  /*
995  * Constraints and where clause might reference the tableoid column,
996  * so (re-)initialize tts_tableOid before evaluating them.
997  */
998  myslot->tts_tableOid = RelationGetRelid(target_resultRelInfo->ri_RelationDesc);
999 
1000  /* Triggers and stuff need to be invoked in query context. */
1001  MemoryContextSwitchTo(oldcontext);
1002 
1003  if (cstate->whereClause)
1004  {
1005  econtext->ecxt_scantuple = myslot;
1006  /* Skip items that don't match COPY's WHERE clause */
1007  if (!ExecQual(cstate->qualexpr, econtext))
1008  {
1009  /*
1010  * Report that this tuple was filtered out by the WHERE
1011  * clause.
1012  */
1014  ++excluded);
1015  continue;
1016  }
1017  }
1018 
1019  /* Determine the partition to insert the tuple into */
1020  if (proute)
1021  {
1022  TupleConversionMap *map;
1023 
1024  /*
1025  * Attempt to find a partition suitable for this tuple.
1026  * ExecFindPartition() will raise an error if none can be found or
1027  * if the found partition is not suitable for INSERTs.
1028  */
1029  resultRelInfo = ExecFindPartition(mtstate, target_resultRelInfo,
1030  proute, myslot, estate);
1031 
1032  if (prevResultRelInfo != resultRelInfo)
1033  {
1034  /* Determine which triggers exist on this partition */
1035  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1036  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
1037 
1038  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
1039  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
1040 
1041  /*
1042  * Disable multi-inserts when the partition has BEFORE/INSTEAD
1043  * OF triggers, or if the partition is a foreign table that
1044  * can't use batching.
1045  */
1046  leafpart_use_multi_insert = insertMethod == CIM_MULTI_CONDITIONAL &&
1047  !has_before_insert_row_trig &&
1048  !has_instead_insert_row_trig &&
1049  (resultRelInfo->ri_FdwRoutine == NULL ||
1050  resultRelInfo->ri_BatchSize > 1);
1051 
1052  /* Set the multi-insert buffer to use for this partition. */
1053  if (leafpart_use_multi_insert)
1054  {
1055  if (resultRelInfo->ri_CopyMultiInsertBuffer == NULL)
1056  CopyMultiInsertInfoSetupBuffer(&multiInsertInfo,
1057  resultRelInfo);
1058  }
1059  else if (insertMethod == CIM_MULTI_CONDITIONAL &&
1060  !CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
1061  {
1062  /*
1063  * Flush pending inserts if this partition can't use
1064  * batching, so rows are visible to triggers etc.
1065  */
1066  CopyMultiInsertInfoFlush(&multiInsertInfo,
1067  resultRelInfo,
1068  &processed);
1069  }
1070 
1071  if (bistate != NULL)
1072  ReleaseBulkInsertStatePin(bistate);
1073  prevResultRelInfo = resultRelInfo;
1074  }
1075 
1076  /*
1077  * If we're capturing transition tuples, we might need to convert
1078  * from the partition rowtype to root rowtype. But if there are no
1079  * BEFORE triggers on the partition that could change the tuple,
1080  * we can just remember the original unconverted tuple to avoid a
1081  * needless round trip conversion.
1082  */
1083  if (cstate->transition_capture != NULL)
1085  !has_before_insert_row_trig ? myslot : NULL;
1086 
1087  /*
1088  * We might need to convert from the root rowtype to the partition
1089  * rowtype.
1090  */
1091  map = ExecGetRootToChildMap(resultRelInfo, estate);
1092  if (insertMethod == CIM_SINGLE || !leafpart_use_multi_insert)
1093  {
1094  /* non batch insert */
1095  if (map != NULL)
1096  {
1097  TupleTableSlot *new_slot;
1098 
1099  new_slot = resultRelInfo->ri_PartitionTupleSlot;
1100  myslot = execute_attr_map_slot(map->attrMap, myslot, new_slot);
1101  }
1102  }
1103  else
1104  {
1105  /*
1106  * Prepare to queue up tuple for later batch insert into
1107  * current partition.
1108  */
1109  TupleTableSlot *batchslot;
1110 
1111  /* no other path available for partitioned table */
1112  Assert(insertMethod == CIM_MULTI_CONDITIONAL);
1113 
1114  batchslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
1115  resultRelInfo);
1116 
1117  if (map != NULL)
1118  myslot = execute_attr_map_slot(map->attrMap, myslot,
1119  batchslot);
1120  else
1121  {
1122  /*
1123  * This looks more expensive than it is (Believe me, I
1124  * optimized it away. Twice.). The input is in virtual
1125  * form, and we'll materialize the slot below - for most
1126  * slot types the copy performs the work materialization
1127  * would later require anyway.
1128  */
1129  ExecCopySlot(batchslot, myslot);
1130  myslot = batchslot;
1131  }
1132  }
1133 
1134  /* ensure that triggers etc see the right relation */
1135  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1136  }
1137 
1138  skip_tuple = false;
1139 
1140  /* BEFORE ROW INSERT Triggers */
1141  if (has_before_insert_row_trig)
1142  {
1143  if (!ExecBRInsertTriggers(estate, resultRelInfo, myslot))
1144  skip_tuple = true; /* "do nothing" */
1145  }
1146 
1147  if (!skip_tuple)
1148  {
1149  /*
1150  * If there is an INSTEAD OF INSERT ROW trigger, let it handle the
1151  * tuple. Otherwise, proceed with inserting the tuple into the
1152  * table or foreign table.
1153  */
1154  if (has_instead_insert_row_trig)
1155  {
1156  ExecIRInsertTriggers(estate, resultRelInfo, myslot);
1157  }
1158  else
1159  {
1160  /* Compute stored generated columns */
1161  if (resultRelInfo->ri_RelationDesc->rd_att->constr &&
1163  ExecComputeStoredGenerated(resultRelInfo, estate, myslot,
1164  CMD_INSERT);
1165 
1166  /*
1167  * If the target is a plain table, check the constraints of
1168  * the tuple.
1169  */
1170  if (resultRelInfo->ri_FdwRoutine == NULL &&
1171  resultRelInfo->ri_RelationDesc->rd_att->constr)
1172  ExecConstraints(resultRelInfo, myslot, estate);
1173 
1174  /*
1175  * Also check the tuple against the partition constraint, if
1176  * there is one; except that if we got here via tuple-routing,
1177  * we don't need to if there's no BR trigger defined on the
1178  * partition.
1179  */
1180  if (resultRelInfo->ri_RelationDesc->rd_rel->relispartition &&
1181  (proute == NULL || has_before_insert_row_trig))
1182  ExecPartitionCheck(resultRelInfo, myslot, estate, true);
1183 
1184  /* Store the slot in the multi-insert buffer, when enabled. */
1185  if (insertMethod == CIM_MULTI || leafpart_use_multi_insert)
1186  {
1187  /*
1188  * The slot previously might point into the per-tuple
1189  * context. For batching it needs to be longer lived.
1190  */
1191  ExecMaterializeSlot(myslot);
1192 
1193  /* Add this tuple to the tuple buffer */
1194  CopyMultiInsertInfoStore(&multiInsertInfo,
1195  resultRelInfo, myslot,
1196  cstate->line_buf.len,
1197  cstate->cur_lineno);
1198 
1199  /*
1200  * If enough inserts have queued up, then flush all
1201  * buffers out to their tables.
1202  */
1203  if (CopyMultiInsertInfoIsFull(&multiInsertInfo))
1204  CopyMultiInsertInfoFlush(&multiInsertInfo,
1205  resultRelInfo,
1206  &processed);
1207 
1208  /*
1209  * We delay updating the row counter and progress of the
1210  * COPY command until after writing the tuples stored in
1211  * the buffer out to the table, as in single insert mode.
1212  * See CopyMultiInsertBufferFlush().
1213  */
1214  continue; /* next tuple please */
1215  }
1216  else
1217  {
1218  List *recheckIndexes = NIL;
1219 
1220  /* OK, store the tuple */
1221  if (resultRelInfo->ri_FdwRoutine != NULL)
1222  {
1223  myslot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
1224  resultRelInfo,
1225  myslot,
1226  NULL);
1227 
1228  if (myslot == NULL) /* "do nothing" */
1229  continue; /* next tuple please */
1230 
1231  /*
1232  * AFTER ROW Triggers might reference the tableoid
1233  * column, so (re-)initialize tts_tableOid before
1234  * evaluating them.
1235  */
1236  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1237  }
1238  else
1239  {
1240  /* OK, store the tuple and create index entries for it */
1241  table_tuple_insert(resultRelInfo->ri_RelationDesc,
1242  myslot, mycid, ti_options, bistate);
1243 
1244  if (resultRelInfo->ri_NumIndices > 0)
1245  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1246  myslot,
1247  estate,
1248  false,
1249  false,
1250  NULL,
1251  NIL,
1252  false);
1253  }
1254 
1255  /* AFTER ROW INSERT Triggers */
1256  ExecARInsertTriggers(estate, resultRelInfo, myslot,
1257  recheckIndexes, cstate->transition_capture);
1258 
1259  list_free(recheckIndexes);
1260  }
1261  }
1262 
1263  /*
1264  * We count only tuples not suppressed by a BEFORE INSERT trigger
1265  * or FDW; this is the same definition used by nodeModifyTable.c
1266  * for counting tuples inserted by an INSERT command. Update
1267  * progress of the COPY command as well.
1268  */
1270  ++processed);
1271  }
1272  }
1273 
1274  /* Flush any remaining buffered tuples */
1275  if (insertMethod != CIM_SINGLE)
1276  {
1277  if (!CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
1278  CopyMultiInsertInfoFlush(&multiInsertInfo, NULL, &processed);
1279  }
1280 
1281  /* Done, clean up */
1282  error_context_stack = errcallback.previous;
1283 
1284  if (bistate != NULL)
1285  FreeBulkInsertState(bistate);
1286 
1287  MemoryContextSwitchTo(oldcontext);
1288 
1289  /* Execute AFTER STATEMENT insertion triggers */
1290  ExecASInsertTriggers(estate, target_resultRelInfo, cstate->transition_capture);
1291 
1292  /* Handle queued AFTER triggers */
1293  AfterTriggerEndQuery(estate);
1294 
1295  ExecResetTupleTable(estate->es_tupleTable, false);
1296 
1297  /* Allow the FDW to shut down */
1298  if (target_resultRelInfo->ri_FdwRoutine != NULL &&
1299  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert != NULL)
1300  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert(estate,
1301  target_resultRelInfo);
1302 
1303  /* Tear down the multi-insert buffer data */
1304  if (insertMethod != CIM_SINGLE)
1305  CopyMultiInsertInfoCleanup(&multiInsertInfo);
1306 
1307  /* Close all the partitioned tables, leaf partitions, and their indices */
1308  if (proute)
1309  ExecCleanupTupleRouting(mtstate, proute);
1310 
1311  /* Close the result relations, including any trigger target relations */
1312  ExecCloseResultRelations(estate);
1314 
1315  FreeExecutorState(estate);
1316 
1317  return processed;
1318 }
void pgstat_progress_update_param(int index, int64 val)
#define InvalidSubTransactionId
Definition: c.h:647
uint32 CommandId
Definition: c.h:655
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:483
static void CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copyfrom.c:242
static void CopyMultiInsertInfoInit(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, CopyFromState cstate, EState *estate, CommandId mycid, int ti_options)
Definition: copyfrom.c:262
static void CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri, int64 *processed)
Definition: copyfrom.c:524
static void CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, TupleTableSlot *slot, int tuplen, uint64 lineno)
Definition: copyfrom.c:609
static void CopyMultiInsertInfoCleanup(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:571
static bool CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:287
static TupleTableSlot * CopyMultiInsertInfoNextFreeSlot(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copyfrom.c:590
static bool CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:299
void CopyFromErrorCallback(void *arg)
Definition: copyfrom.c:116
CopyInsertMethod
@ CIM_SINGLE
@ CIM_MULTI_CONDITIONAL
@ CIM_MULTI
bool NextCopyFrom(CopyFromState cstate, ExprContext *econtext, Datum *values, bool *nulls)
ErrorContextCallback * error_context_stack
Definition: elog.c:95
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:214
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes, bool onlySummarizing)
Definition: execIndexing.c:293
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:156
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1816
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1541
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1601
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1940
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1024
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, Relation rel)
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1192
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1553
void ExecInitRangeTable(EState *estate, List *rangeTable, List *permInfos)
Definition: execUtils.c:733
void ExecInitResultRelation(EState *estate, ResultRelInfo *resultRelInfo, Index rti)
Definition: execUtils.c:819
EState * CreateExecutorState(void)
Definition: execUtils.c:93
TupleConversionMap * ExecGetRootToChildMap(ResultRelInfo *resultRelInfo, EState *estate)
Definition: execUtils.c:1237
void FreeExecutorState(EState *estate)
Definition: execUtils.c:194
#define ResetPerTupleExprContext(estate)
Definition: executor.h:558
#define GetPerTupleExprContext(estate)
Definition: executor.h:549
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:554
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:412
void ReleaseBulkInsertStatePin(BulkInsertState bistate)
Definition: heapam.c:1790
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1761
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1778
void list_free(List *list)
Definition: list.c:1545
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
void ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
@ CMD_INSERT
Definition: nodes.h:278
#define makeNode(_type_)
Definition: nodes.h:176
#define castNode(_type_, nodeptr)
Definition: nodes.h:197
#define NIL
Definition: pg_list.h:68
bool ThereAreNoReadyPortals(void)
Definition: portalmem.c:1169
#define PROGRESS_COPY_TUPLES_PROCESSED
Definition: progress.h:141
#define PROGRESS_COPY_TUPLES_EXCLUDED
Definition: progress.h:142
bool ThereAreNoPriorRegisteredSnapshots(void)
Definition: snapmgr.c:1581
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:403
bool freeze
Definition: copy.h:44
TransitionCaptureState * transition_capture
List * es_tupleTable
Definition: execnodes.h:661
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:249
EndForeignInsert_function EndForeignInsert
Definition: fdwapi.h:239
BeginForeignInsert_function BeginForeignInsert
Definition: fdwapi.h:238
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:232
ExecForeignBatchInsert_function ExecForeignBatchInsert
Definition: fdwapi.h:233
GetForeignModifyBatchSize_function GetForeignModifyBatchSize
Definition: fdwapi.h:234
CmdType operation
Definition: execnodes.h:1276
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1280
PlanState ps
Definition: execnodes.h:1275
ResultRelInfo * rootResultRelInfo
Definition: execnodes.h:1288
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1314
Plan * plan
Definition: execnodes.h:1037
EState * state
Definition: execnodes.h:1039
SubTransactionId rd_firstRelfilelocatorSubid
Definition: rel.h:106
TriggerDesc * trigdesc
Definition: rel.h:117
TupleDesc rd_att
Definition: rel.h:112
SubTransactionId rd_newRelfilelocatorSubid
Definition: rel.h:104
SubTransactionId rd_createSubid
Definition: rel.h:103
Form_pg_class rd_rel
Definition: rel.h:111
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:575
int ri_NumIndices
Definition: execnodes.h:453
Relation ri_RelationDesc
Definition: execnodes.h:450
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:578
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:480
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:497
int ri_BatchSize
Definition: execnodes.h:508
TupleTableSlot * tcs_original_insert_tuple
Definition: trigger.h:76
bool trig_insert_instead_row
Definition: reltrigger.h:58
bool trig_insert_new_table
Definition: reltrigger.h:75
bool trig_insert_before_row
Definition: reltrigger.h:56
bool has_generated_stored
Definition: tupdesc.h:45
AttrMap * attrMap
Definition: tupconvert.h:28
TupleConstr * constr
Definition: tupdesc.h:85
Oid tts_tableOid
Definition: tuptable.h:130
bool * tts_isnull
Definition: tuptable.h:127
Datum * tts_values
Definition: tuptable.h:125
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
#define TABLE_INSERT_FROZEN
Definition: tableam.h:253
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:252
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1397
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2400
bool ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2464
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2557
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2540
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4870
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2451
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:5026
void AfterTriggerBeginQuery(void)
Definition: trigger.c:5006
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:192
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:432
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:482
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:450
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:780
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:818

References AfterTriggerBeginQuery(), AfterTriggerEndQuery(), ErrorContextCallback::arg, Assert(), TupleConversionMap::attrMap, FdwRoutine::BeginForeignInsert, ErrorContextCallback::callback, castNode, CHECK_FOR_INTERRUPTS, CheckValidResultRel(), CIM_MULTI, CIM_MULTI_CONDITIONAL, CIM_SINGLE, CMD_INSERT, TupleDescData::constr, contain_volatile_functions(), CopyFromErrorCallback(), CopyMultiInsertInfoCleanup(), CopyMultiInsertInfoFlush(), CopyMultiInsertInfoInit(), CopyMultiInsertInfoIsEmpty(), CopyMultiInsertInfoIsFull(), CopyMultiInsertInfoNextFreeSlot(), CopyMultiInsertInfoSetupBuffer(), CopyMultiInsertInfoStore(), CreateExecutorState(), CopyFromStateData::cur_lineno, CurrentMemoryContext, ExprContext::ecxt_scantuple, FdwRoutine::EndForeignInsert, ereport, errcode(), errhint(), errmsg(), ERROR, error_context_stack, EState::es_tupleTable, ExecARInsertTriggers(), ExecASInsertTriggers(), ExecBRInsertTriggers(), ExecBSInsertTriggers(), ExecCleanupTupleRouting(), ExecClearTuple(), ExecCloseRangeTableRelations(), ExecCloseResultRelations(), ExecComputeStoredGenerated(), ExecConstraints(), ExecCopySlot(), ExecFindPartition(), FdwRoutine::ExecForeignBatchInsert, FdwRoutine::ExecForeignInsert, ExecGetRootToChildMap(), ExecInitQual(), ExecInitRangeTable(), ExecInitResultRelation(), ExecInsertIndexTuples(), ExecIRInsertTriggers(), ExecMaterializeSlot(), ExecOpenIndices(), ExecPartitionCheck(), ExecQual(), ExecResetTupleTable(), ExecSetupPartitionTupleRouting(), ExecStoreVirtualTuple(), execute_attr_map_slot(), FreeBulkInsertState(), FreeExecutorState(), CopyFormatOptions::freeze, GetBulkInsertState(), GetCurrentCommandId(), GetCurrentSubTransactionId(), FdwRoutine::GetForeignModifyBatchSize, GetPerTupleExprContext, GetPerTupleMemoryContext, TupleConstr::has_generated_stored, InvalidateCatalogSnapshot(), InvalidSubTransactionId, StringInfoData::len, CopyFromStateData::line_buf, list_free(), list_length(), makeNode, MakeTransitionCaptureState(), MemoryContextSwitchTo(), ModifyTableState::mt_nrels, ModifyTableState::mt_transition_capture, NextCopyFrom(), NIL, ModifyTableState::operation, CopyFromStateData::opts, pgstat_progress_update_param(), PlanState::plan, ErrorContextCallback::previous, PROGRESS_COPY_TUPLES_EXCLUDED, PROGRESS_COPY_TUPLES_PROCESSED, ModifyTableState::ps, CopyFromStateData::qualexpr, CopyFromStateData::range_table, RelationData::rd_att, RelationData::rd_createSubid, RelationData::rd_firstRelfilelocatorSubid, RelationData::rd_newRelfilelocatorSubid, RelationData::rd_rel, CopyFromStateData::rel, RelationGetRelationName, RelationGetRelid, ReleaseBulkInsertStatePin(), ResetPerTupleExprContext, ModifyTableState::resultRelInfo, ResultRelInfo::ri_BatchSize, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionTupleSlot, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, ModifyTableState::rootResultRelInfo, CopyFromStateData::rteperminfos, PlanState::state, TABLE_INSERT_FROZEN, TABLE_INSERT_SKIP_FSM, table_slot_create(), table_tuple_insert(), TransitionCaptureState::tcs_original_insert_tuple, ThereAreNoPriorRegisteredSnapshots(), ThereAreNoReadyPortals(), CopyFromStateData::transition_capture, TriggerDesc::trig_insert_before_row, TriggerDesc::trig_insert_instead_row, TriggerDesc::trig_insert_new_table, RelationData::trigdesc, TupleTableSlot::tts_isnull, TupleTableSlot::tts_tableOid, TupleTableSlot::tts_values, CopyFromStateData::volatile_defexprs, and CopyFromStateData::whereClause.

Referenced by copy_table(), and DoCopy().

◆ CopyFromErrorCallback()

void CopyFromErrorCallback ( void *  arg)

Definition at line 116 of file copyfrom.c.

117 {
118  CopyFromState cstate = (CopyFromState) arg;
119 
120  if (cstate->relname_only)
121  {
122  errcontext("COPY %s",
123  cstate->cur_relname);
124  return;
125  }
126  if (cstate->opts.binary)
127  {
128  /* can't usefully display the data */
129  if (cstate->cur_attname)
130  errcontext("COPY %s, line %llu, column %s",
131  cstate->cur_relname,
132  (unsigned long long) cstate->cur_lineno,
133  cstate->cur_attname);
134  else
135  errcontext("COPY %s, line %llu",
136  cstate->cur_relname,
137  (unsigned long long) cstate->cur_lineno);
138  }
139  else
140  {
141  if (cstate->cur_attname && cstate->cur_attval)
142  {
143  /* error is relevant to a particular column */
144  char *attval;
145 
146  attval = limit_printout_length(cstate->cur_attval);
147  errcontext("COPY %s, line %llu, column %s: \"%s\"",
148  cstate->cur_relname,
149  (unsigned long long) cstate->cur_lineno,
150  cstate->cur_attname,
151  attval);
152  pfree(attval);
153  }
154  else if (cstate->cur_attname)
155  {
156  /* error is relevant to a particular column, value is NULL */
157  errcontext("COPY %s, line %llu, column %s: null input",
158  cstate->cur_relname,
159  (unsigned long long) cstate->cur_lineno,
160  cstate->cur_attname);
161  }
162  else
163  {
164  /*
165  * Error is relevant to a particular line.
166  *
167  * If line_buf still contains the correct line, print it.
168  */
169  if (cstate->line_buf_valid)
170  {
171  char *lineval;
172 
173  lineval = limit_printout_length(cstate->line_buf.data);
174  errcontext("COPY %s, line %llu: \"%s\"",
175  cstate->cur_relname,
176  (unsigned long long) cstate->cur_lineno, lineval);
177  pfree(lineval);
178  }
179  else
180  {
181  errcontext("COPY %s, line %llu",
182  cstate->cur_relname,
183  (unsigned long long) cstate->cur_lineno);
184  }
185  }
186  }
187 }
static char * limit_printout_length(const char *str)
Definition: copyfrom.c:195
#define errcontext
Definition: elog.h:196
struct CopyFromStateData * CopyFromState
Definition: copy.h:69
void pfree(void *pointer)
Definition: mcxt.c:1456
void * arg

References arg, CopyFormatOptions::binary, CopyFromStateData::cur_attname, CopyFromStateData::cur_attval, CopyFromStateData::cur_lineno, CopyFromStateData::cur_relname, StringInfoData::data, errcontext, limit_printout_length(), CopyFromStateData::line_buf, CopyFromStateData::line_buf_valid, CopyFromStateData::opts, pfree(), and CopyFromStateData::relname_only.

Referenced by CopyFrom(), file_acquire_sample_rows(), and fileIterateForeignScan().

◆ CopyMultiInsertBufferCleanup()

static void CopyMultiInsertBufferCleanup ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer 
)
inlinestatic

Definition at line 482 of file copyfrom.c.

484 {
485  ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
486  int i;
487 
488  /* Ensure buffer was flushed */
489  Assert(buffer->nused == 0);
490 
491  /* Remove back-link to ourself */
492  resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
493 
494  if (resultRelInfo->ri_FdwRoutine == NULL)
495  {
496  Assert(buffer->bistate != NULL);
497  FreeBulkInsertState(buffer->bistate);
498  }
499  else
500  Assert(buffer->bistate == NULL);
501 
502  /* Since we only create slots on demand, just drop the non-null ones. */
503  for (i = 0; i < MAX_BUFFERED_TUPLES && buffer->slots[i] != NULL; i++)
505 
506  if (resultRelInfo->ri_FdwRoutine == NULL)
508  miinfo->ti_options);
509 
510  pfree(buffer);
511 }
#define MAX_BUFFERED_TUPLES
Definition: copyfrom.c:65
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1255
int i
Definition: isn.c:73
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copyfrom.c:79
ResultRelInfo * resultRelInfo
Definition: copyfrom.c:80
BulkInsertState bistate
Definition: copyfrom.c:81
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1590

References Assert(), CopyMultiInsertBuffer::bistate, ExecDropSingleTupleTableSlot(), FreeBulkInsertState(), i, MAX_BUFFERED_TUPLES, CopyMultiInsertBuffer::nused, pfree(), CopyMultiInsertBuffer::resultRelInfo, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_RelationDesc, CopyMultiInsertBuffer::slots, table_finish_bulk_insert(), and CopyMultiInsertInfo::ti_options.

Referenced by CopyMultiInsertInfoCleanup(), and CopyMultiInsertInfoFlush().

◆ CopyMultiInsertBufferFlush()

static void CopyMultiInsertBufferFlush ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer,
int64 *  processed 
)
inlinestatic

Definition at line 308 of file copyfrom.c.

311 {
312  CopyFromState cstate = miinfo->cstate;
313  EState *estate = miinfo->estate;
314  int nused = buffer->nused;
315  ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
316  TupleTableSlot **slots = buffer->slots;
317  int i;
318 
319  if (resultRelInfo->ri_FdwRoutine)
320  {
321  int batch_size = resultRelInfo->ri_BatchSize;
322  int sent = 0;
323 
324  Assert(buffer->bistate == NULL);
325 
326  /* Ensure that the FDW supports batching and it's enabled */
328  Assert(batch_size > 1);
329 
330  /*
331  * We suppress error context information other than the relation name,
332  * if one of the operations below fails.
333  */
334  Assert(!cstate->relname_only);
335  cstate->relname_only = true;
336 
337  while (sent < nused)
338  {
339  int size = (batch_size < nused - sent) ? batch_size : (nused - sent);
340  int inserted = size;
341  TupleTableSlot **rslots;
342 
343  /* insert into foreign table: let the FDW do it */
344  rslots =
345  resultRelInfo->ri_FdwRoutine->ExecForeignBatchInsert(estate,
346  resultRelInfo,
347  &slots[sent],
348  NULL,
349  &inserted);
350 
351  sent += size;
352 
353  /* No need to do anything if there are no inserted rows */
354  if (inserted <= 0)
355  continue;
356 
357  /* Triggers on foreign tables should not have transition tables */
358  Assert(resultRelInfo->ri_TrigDesc == NULL ||
359  resultRelInfo->ri_TrigDesc->trig_insert_new_table == false);
360 
361  /* Run AFTER ROW INSERT triggers */
362  if (resultRelInfo->ri_TrigDesc != NULL &&
363  resultRelInfo->ri_TrigDesc->trig_insert_after_row)
364  {
365  Oid relid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
366 
367  for (i = 0; i < inserted; i++)
368  {
369  TupleTableSlot *slot = rslots[i];
370 
371  /*
372  * AFTER ROW Triggers might reference the tableoid column,
373  * so (re-)initialize tts_tableOid before evaluating them.
374  */
375  slot->tts_tableOid = relid;
376 
377  ExecARInsertTriggers(estate, resultRelInfo,
378  slot, NIL,
379  cstate->transition_capture);
380  }
381  }
382 
383  /* Update the row counter and progress of the COPY command */
384  *processed += inserted;
386  *processed);
387  }
388 
389  for (i = 0; i < nused; i++)
390  ExecClearTuple(slots[i]);
391 
392  /* reset relname_only */
393  cstate->relname_only = false;
394  }
395  else
396  {
397  CommandId mycid = miinfo->mycid;
398  int ti_options = miinfo->ti_options;
399  bool line_buf_valid = cstate->line_buf_valid;
400  uint64 save_cur_lineno = cstate->cur_lineno;
401  MemoryContext oldcontext;
402 
403  Assert(buffer->bistate != NULL);
404 
405  /*
406  * Print error context information correctly, if one of the operations
407  * below fails.
408  */
409  cstate->line_buf_valid = false;
410 
411  /*
412  * table_multi_insert may leak memory, so switch to short-lived memory
413  * context before calling it.
414  */
415  oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
416  table_multi_insert(resultRelInfo->ri_RelationDesc,
417  slots,
418  nused,
419  mycid,
420  ti_options,
421  buffer->bistate);
422  MemoryContextSwitchTo(oldcontext);
423 
424  for (i = 0; i < nused; i++)
425  {
426  /*
427  * If there are any indexes, update them for all the inserted
428  * tuples, and run AFTER ROW INSERT triggers.
429  */
430  if (resultRelInfo->ri_NumIndices > 0)
431  {
432  List *recheckIndexes;
433 
434  cstate->cur_lineno = buffer->linenos[i];
435  recheckIndexes =
436  ExecInsertIndexTuples(resultRelInfo,
437  buffer->slots[i], estate, false,
438  false, NULL, NIL, false);
439  ExecARInsertTriggers(estate, resultRelInfo,
440  slots[i], recheckIndexes,
441  cstate->transition_capture);
442  list_free(recheckIndexes);
443  }
444 
445  /*
446  * There's no indexes, but see if we need to run AFTER ROW INSERT
447  * triggers anyway.
448  */
449  else if (resultRelInfo->ri_TrigDesc != NULL &&
450  (resultRelInfo->ri_TrigDesc->trig_insert_after_row ||
451  resultRelInfo->ri_TrigDesc->trig_insert_new_table))
452  {
453  cstate->cur_lineno = buffer->linenos[i];
454  ExecARInsertTriggers(estate, resultRelInfo,
455  slots[i], NIL,
456  cstate->transition_capture);
457  }
458 
459  ExecClearTuple(slots[i]);
460  }
461 
462  /* Update the row counter and progress of the COPY command */
463  *processed += nused;
465  *processed);
466 
467  /* reset cur_lineno and line_buf_valid to what they were */
468  cstate->line_buf_valid = line_buf_valid;
469  cstate->cur_lineno = save_cur_lineno;
470  }
471 
472  /* Mark that all slots are free */
473  buffer->nused = 0;
474 }
uint64 linenos[MAX_BUFFERED_TUPLES]
Definition: copyfrom.c:84
EState * estate
Definition: copyfrom.c:99
CommandId mycid
Definition: copyfrom.c:100
CopyFromState cstate
Definition: copyfrom.c:98
bool trig_insert_after_row
Definition: reltrigger.h:57
static void table_multi_insert(Relation rel, TupleTableSlot **slots, int nslots, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1452

References Assert(), CopyMultiInsertBuffer::bistate, CopyMultiInsertInfo::cstate, CopyFromStateData::cur_lineno, CopyMultiInsertInfo::estate, ExecARInsertTriggers(), ExecClearTuple(), FdwRoutine::ExecForeignBatchInsert, ExecInsertIndexTuples(), GetPerTupleMemoryContext, i, CopyFromStateData::line_buf_valid, CopyMultiInsertBuffer::linenos, list_free(), MemoryContextSwitchTo(), CopyMultiInsertInfo::mycid, NIL, CopyMultiInsertBuffer::nused, pgstat_progress_update_param(), PROGRESS_COPY_TUPLES_PROCESSED, RelationGetRelid, CopyFromStateData::relname_only, CopyMultiInsertBuffer::resultRelInfo, ResultRelInfo::ri_BatchSize, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, CopyMultiInsertBuffer::slots, table_multi_insert(), CopyMultiInsertInfo::ti_options, CopyFromStateData::transition_capture, TriggerDesc::trig_insert_after_row, TriggerDesc::trig_insert_new_table, and TupleTableSlot::tts_tableOid.

Referenced by CopyMultiInsertInfoFlush().

◆ CopyMultiInsertBufferInit()

static CopyMultiInsertBuffer* CopyMultiInsertBufferInit ( ResultRelInfo rri)
static

Definition at line 225 of file copyfrom.c.

226 {
227  CopyMultiInsertBuffer *buffer;
228 
229  buffer = (CopyMultiInsertBuffer *) palloc(sizeof(CopyMultiInsertBuffer));
230  memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
231  buffer->resultRelInfo = rri;
232  buffer->bistate = (rri->ri_FdwRoutine == NULL) ? GetBulkInsertState() : NULL;
233  buffer->nused = 0;
234 
235  return buffer;
236 }

References CopyMultiInsertBuffer::bistate, GetBulkInsertState(), MAX_BUFFERED_TUPLES, CopyMultiInsertBuffer::nused, palloc(), CopyMultiInsertBuffer::resultRelInfo, ResultRelInfo::ri_FdwRoutine, and CopyMultiInsertBuffer::slots.

Referenced by CopyMultiInsertInfoSetupBuffer().

◆ CopyMultiInsertInfoCleanup()

static void CopyMultiInsertInfoCleanup ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 571 of file copyfrom.c.

572 {
573  ListCell *lc;
574 
575  foreach(lc, miinfo->multiInsertBuffers)
577 
578  list_free(miinfo->multiInsertBuffers);
579 }
static void CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copyfrom.c:482
#define lfirst(lc)
Definition: pg_list.h:172
List * multiInsertBuffers
Definition: copyfrom.c:95

References CopyMultiInsertBufferCleanup(), lfirst, list_free(), and CopyMultiInsertInfo::multiInsertBuffers.

Referenced by CopyFrom().

◆ CopyMultiInsertInfoFlush()

static void CopyMultiInsertInfoFlush ( CopyMultiInsertInfo miinfo,
ResultRelInfo curr_rri,
int64 *  processed 
)
inlinestatic

Definition at line 524 of file copyfrom.c.

526 {
527  ListCell *lc;
528 
529  foreach(lc, miinfo->multiInsertBuffers)
530  {
532 
533  CopyMultiInsertBufferFlush(miinfo, buffer, processed);
534  }
535 
536  miinfo->bufferedTuples = 0;
537  miinfo->bufferedBytes = 0;
538 
539  /*
540  * Trim the list of tracked buffers down if it exceeds the limit. Here we
541  * remove buffers starting with the ones we created first. It seems less
542  * likely that these older ones will be needed than the ones that were
543  * just created.
544  */
546  {
547  CopyMultiInsertBuffer *buffer;
548 
549  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
550 
551  /*
552  * We never want to remove the buffer that's currently being used, so
553  * if we happen to find that then move it to the end of the list.
554  */
555  if (buffer->resultRelInfo == curr_rri)
556  {
558  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
559  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
560  }
561 
562  CopyMultiInsertBufferCleanup(miinfo, buffer);
564  }
565 }
#define MAX_PARTITION_BUFFERS
Definition: copyfrom.c:74
static void CopyMultiInsertBufferFlush(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer, int64 *processed)
Definition: copyfrom.c:308
List * lappend(List *list, void *datum)
Definition: list.c:338
List * list_delete_first(List *list)
Definition: list.c:942
#define linitial(l)
Definition: pg_list.h:178

References CopyMultiInsertInfo::bufferedBytes, CopyMultiInsertInfo::bufferedTuples, CopyMultiInsertBufferCleanup(), CopyMultiInsertBufferFlush(), lappend(), lfirst, linitial, list_delete_first(), list_length(), MAX_PARTITION_BUFFERS, CopyMultiInsertInfo::multiInsertBuffers, and CopyMultiInsertBuffer::resultRelInfo.

Referenced by CopyFrom().

◆ CopyMultiInsertInfoInit()

static void CopyMultiInsertInfoInit ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri,
CopyFromState  cstate,
EState estate,
CommandId  mycid,
int  ti_options 
)
static

Definition at line 262 of file copyfrom.c.

265 {
266  miinfo->multiInsertBuffers = NIL;
267  miinfo->bufferedTuples = 0;
268  miinfo->bufferedBytes = 0;
269  miinfo->cstate = cstate;
270  miinfo->estate = estate;
271  miinfo->mycid = mycid;
272  miinfo->ti_options = ti_options;
273 
274  /*
275  * Only setup the buffer when not dealing with a partitioned table.
276  * Buffers for partitioned tables will just be setup when we need to send
277  * tuples their way for the first time.
278  */
279  if (rri->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
280  CopyMultiInsertInfoSetupBuffer(miinfo, rri);
281 }

References CopyMultiInsertInfo::bufferedBytes, CopyMultiInsertInfo::bufferedTuples, CopyMultiInsertInfoSetupBuffer(), CopyMultiInsertInfo::cstate, CopyMultiInsertInfo::estate, CopyMultiInsertInfo::multiInsertBuffers, CopyMultiInsertInfo::mycid, NIL, RelationData::rd_rel, ResultRelInfo::ri_RelationDesc, and CopyMultiInsertInfo::ti_options.

Referenced by CopyFrom().

◆ CopyMultiInsertInfoIsEmpty()

static bool CopyMultiInsertInfoIsEmpty ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 299 of file copyfrom.c.

300 {
301  return miinfo->bufferedTuples == 0;
302 }

References CopyMultiInsertInfo::bufferedTuples.

Referenced by CopyFrom().

◆ CopyMultiInsertInfoIsFull()

static bool CopyMultiInsertInfoIsFull ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 287 of file copyfrom.c.

288 {
289  if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
291  return true;
292  return false;
293 }
#define MAX_BUFFERED_BYTES
Definition: copyfrom.c:71

References CopyMultiInsertInfo::bufferedBytes, CopyMultiInsertInfo::bufferedTuples, MAX_BUFFERED_BYTES, and MAX_BUFFERED_TUPLES.

Referenced by CopyFrom().

◆ CopyMultiInsertInfoNextFreeSlot()

static TupleTableSlot* CopyMultiInsertInfoNextFreeSlot ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri 
)
inlinestatic

Definition at line 590 of file copyfrom.c.

592 {
594  int nused = buffer->nused;
595 
596  Assert(buffer != NULL);
597  Assert(nused < MAX_BUFFERED_TUPLES);
598 
599  if (buffer->slots[nused] == NULL)
600  buffer->slots[nused] = table_slot_create(rri->ri_RelationDesc, NULL);
601  return buffer->slots[nused];
602 }

References Assert(), MAX_BUFFERED_TUPLES, CopyMultiInsertBuffer::nused, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_RelationDesc, CopyMultiInsertBuffer::slots, and table_slot_create().

Referenced by CopyFrom().

◆ CopyMultiInsertInfoSetupBuffer()

static void CopyMultiInsertInfoSetupBuffer ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri 
)
inlinestatic

Definition at line 242 of file copyfrom.c.

244 {
245  CopyMultiInsertBuffer *buffer;
246 
247  buffer = CopyMultiInsertBufferInit(rri);
248 
249  /* Setup back-link so we can easily find this buffer again */
250  rri->ri_CopyMultiInsertBuffer = buffer;
251  /* Record that we're tracking this buffer */
252  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
253 }
static CopyMultiInsertBuffer * CopyMultiInsertBufferInit(ResultRelInfo *rri)
Definition: copyfrom.c:225

References CopyMultiInsertBufferInit(), lappend(), CopyMultiInsertInfo::multiInsertBuffers, and ResultRelInfo::ri_CopyMultiInsertBuffer.

Referenced by CopyFrom(), and CopyMultiInsertInfoInit().

◆ CopyMultiInsertInfoStore()

static void CopyMultiInsertInfoStore ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri,
TupleTableSlot slot,
int  tuplen,
uint64  lineno 
)
inlinestatic

Definition at line 609 of file copyfrom.c.

611 {
613 
614  Assert(buffer != NULL);
615  Assert(slot == buffer->slots[buffer->nused]);
616 
617  /* Store the line number so we can properly report any errors later */
618  buffer->linenos[buffer->nused] = lineno;
619 
620  /* Record this slot as being used */
621  buffer->nused++;
622 
623  /* Update how many tuples are stored and their size */
624  miinfo->bufferedTuples++;
625  miinfo->bufferedBytes += tuplen;
626 }

References Assert(), CopyMultiInsertInfo::bufferedBytes, CopyMultiInsertInfo::bufferedTuples, CopyMultiInsertBuffer::linenos, CopyMultiInsertBuffer::nused, ResultRelInfo::ri_CopyMultiInsertBuffer, and CopyMultiInsertBuffer::slots.

Referenced by CopyFrom().

◆ EndCopyFrom()

void EndCopyFrom ( CopyFromState  cstate)

Definition at line 1720 of file copyfrom.c.

1721 {
1722  /* No COPY FROM related resources except memory. */
1723  if (cstate->is_program)
1724  {
1725  ClosePipeFromProgram(cstate);
1726  }
1727  else
1728  {
1729  if (cstate->filename != NULL && FreeFile(cstate->copy_file))
1730  ereport(ERROR,
1732  errmsg("could not close file \"%s\": %m",
1733  cstate->filename)));
1734  }
1735 
1737 
1739  pfree(cstate);
1740 }
void pgstat_progress_end_command(void)
static void ClosePipeFromProgram(CopyFromState cstate)
Definition: copyfrom.c:1746
int FreeFile(FILE *file)
Definition: fd.c:2726
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403

References ClosePipeFromProgram(), CopyFromStateData::copy_file, CopyFromStateData::copycontext, ereport, errcode_for_file_access(), errmsg(), ERROR, CopyFromStateData::filename, FreeFile(), CopyFromStateData::is_program, MemoryContextDelete(), pfree(), and pgstat_progress_end_command().

Referenced by DoCopy(), file_acquire_sample_rows(), fileEndForeignScan(), and fileReScanForeignScan().

◆ limit_printout_length()

static char * limit_printout_length ( const char *  str)
static

Definition at line 195 of file copyfrom.c.

196 {
197 #define MAX_COPY_DATA_DISPLAY 100
198 
199  int slen = strlen(str);
200  int len;
201  char *res;
202 
203  /* Fast path if definitely okay */
204  if (slen <= MAX_COPY_DATA_DISPLAY)
205  return pstrdup(str);
206 
207  /* Apply encoding-dependent truncation */
209 
210  /*
211  * Truncate, and add "..." to show we truncated the input.
212  */
213  res = (char *) palloc(len + 4);
214  memcpy(res, str, len);
215  strcpy(res + len, "...");
216 
217  return res;
218 }
#define MAX_COPY_DATA_DISPLAY
int pg_mbcliplen(const char *mbstr, int len, int limit)
Definition: mbutils.c:1084
const void size_t len

References len, MAX_COPY_DATA_DISPLAY, palloc(), pg_mbcliplen(), pstrdup(), res, and generate_unaccent_rules::str.

Referenced by CopyFromErrorCallback().