PostgreSQL Source Code  git master
copy.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/sysattr.h"
#include "access/tableam.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/dependency.h"
#include "catalog/pg_authid.h"
#include "catalog/pg_type.h"
#include "commands/copy.h"
#include "commands/defrem.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 "mb/pg_wchar.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/optimizer.h"
#include "parser/parse_coerce.h"
#include "parser/parse_collate.h"
#include "parser/parse_expr.h"
#include "parser/parse_relation.h"
#include "port/pg_bswap.h"
#include "rewrite/rewriteHandler.h"
#include "storage/fd.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/partcache.h"
#include "utils/portal.h"
#include "utils/rel.h"
#include "utils/rls.h"
#include "utils/snapmgr.h"
Include dependency graph for copy.c:

Go to the source code of this file.

Data Structures

struct  CopyStateData
 
struct  DR_copy
 
struct  CopyMultiInsertBuffer
 
struct  CopyMultiInsertInfo
 

Macros

#define ISOCTAL(c)   (((c) >= '0') && ((c) <= '7'))
 
#define OCTVALUE(c)   ((c) - '0')
 
#define RAW_BUF_SIZE   65536 /* we palloc RAW_BUF_SIZE+1 bytes */
 
#define RAW_BUF_BYTES(cstate)   ((cstate)->raw_buf_len - (cstate)->raw_buf_index)
 
#define MAX_BUFFERED_TUPLES   1000
 
#define MAX_BUFFERED_BYTES   65535
 
#define MAX_PARTITION_BUFFERS   32
 
#define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen)
 
#define IF_NEED_REFILL_AND_EOF_BREAK(extralen)
 
#define REFILL_LINEBUF
 
#define NO_END_OF_COPY_GOTO
 
#define MAX_COPY_DATA_DISPLAY   100
 
#define DUMPSOFAR()
 

Typedefs

typedef enum CopyDest CopyDest
 
typedef enum EolType EolType
 
typedef enum CopyInsertMethod CopyInsertMethod
 
typedef struct CopyStateData CopyStateData
 
typedef struct CopyMultiInsertBuffer CopyMultiInsertBuffer
 
typedef struct CopyMultiInsertInfo CopyMultiInsertInfo
 

Enumerations

enum  CopyDest { COPY_FILE, COPY_OLD_FE, COPY_NEW_FE, COPY_CALLBACK }
 
enum  EolType { EOL_UNKNOWN, EOL_NL, EOL_CR, EOL_CRNL }
 
enum  CopyInsertMethod { CIM_SINGLE, CIM_MULTI, CIM_MULTI_CONDITIONAL }
 

Functions

static CopyState BeginCopy (ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
 
static void EndCopy (CopyState cstate)
 
static void ClosePipeToProgram (CopyState cstate)
 
static CopyState BeginCopyTo (ParseState *pstate, Relation rel, RawStmt *query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
 
static void EndCopyTo (CopyState cstate)
 
static uint64 DoCopyTo (CopyState cstate)
 
static uint64 CopyTo (CopyState cstate)
 
static void CopyOneRowTo (CopyState cstate, TupleTableSlot *slot)
 
static bool CopyReadLine (CopyState cstate)
 
static bool CopyReadLineText (CopyState cstate)
 
static int CopyReadAttributesText (CopyState cstate)
 
static int CopyReadAttributesCSV (CopyState cstate)
 
static Datum CopyReadBinaryAttribute (CopyState cstate, FmgrInfo *flinfo, Oid typioparam, int32 typmod, bool *isnull)
 
static void CopyAttributeOutText (CopyState cstate, char *string)
 
static void CopyAttributeOutCSV (CopyState cstate, char *string, bool use_quote, bool single_attr)
 
static ListCopyGetAttnums (TupleDesc tupDesc, Relation rel, List *attnamelist)
 
static char * limit_printout_length (const char *str)
 
static void SendCopyBegin (CopyState cstate)
 
static void ReceiveCopyBegin (CopyState cstate)
 
static void SendCopyEnd (CopyState cstate)
 
static void CopySendData (CopyState cstate, const void *databuf, int datasize)
 
static void CopySendString (CopyState cstate, const char *str)
 
static void CopySendChar (CopyState cstate, char c)
 
static void CopySendEndOfRow (CopyState cstate)
 
static int CopyGetData (CopyState cstate, void *databuf, int minread, int maxread)
 
static void CopySendInt32 (CopyState cstate, int32 val)
 
static bool CopyGetInt32 (CopyState cstate, int32 *val)
 
static void CopySendInt16 (CopyState cstate, int16 val)
 
static bool CopyGetInt16 (CopyState cstate, int16 *val)
 
static bool CopyLoadRawBuf (CopyState cstate)
 
static int CopyReadBinaryData (CopyState cstate, char *dest, int nbytes)
 
void DoCopy (ParseState *pstate, const CopyStmt *stmt, int stmt_location, int stmt_len, uint64 *processed)
 
void ProcessCopyOptions (ParseState *pstate, CopyState cstate, bool is_from, List *options)
 
void CopyFromErrorCallback (void *arg)
 
static CopyMultiInsertBufferCopyMultiInsertBufferInit (ResultRelInfo *rri)
 
static void CopyMultiInsertInfoSetupBuffer (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
 
static void CopyMultiInsertInfoInit (CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, CopyState 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)
 
static void CopyMultiInsertBufferCleanup (CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
 
static void CopyMultiInsertInfoFlush (CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri)
 
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 (CopyState cstate)
 
CopyState BeginCopyFrom (ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
 
bool NextCopyFromRawFields (CopyState cstate, char ***fields, int *nfields)
 
bool NextCopyFrom (CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls)
 
void EndCopyFrom (CopyState cstate)
 
static int GetDecimalFromHex (char hex)
 
static void copy_dest_startup (DestReceiver *self, int operation, TupleDesc typeinfo)
 
static bool copy_dest_receive (TupleTableSlot *slot, DestReceiver *self)
 
static void copy_dest_shutdown (DestReceiver *self)
 
static void copy_dest_destroy (DestReceiver *self)
 
DestReceiverCreateCopyDestReceiver (void)
 

Variables

static const char BinarySignature [11] = "PGCOPY\n\377\r\n\0"
 

Macro Definition Documentation

◆ DUMPSOFAR

#define DUMPSOFAR ( )
Value:
do { \
if (ptr > start) \
CopySendData(cstate, start, ptr - start); \
} while (0)

Definition at line 4821 of file copy.c.

Referenced by CopyAttributeOutCSV(), and CopyAttributeOutText().

◆ IF_NEED_REFILL_AND_EOF_BREAK

#define IF_NEED_REFILL_AND_EOF_BREAK (   extralen)
Value:
if (1) \
{ \
if (raw_buf_ptr + (extralen) >= copy_buf_len && hit_eof) \
{ \
if (extralen) \
raw_buf_ptr = copy_buf_len; /* consume the partial character */ \
/* backslash just before EOF, treat as data char */ \
result = true; \
break; \
} \
} else ((void) 0)

Definition at line 320 of file copy.c.

Referenced by CopyReadLineText().

◆ IF_NEED_REFILL_AND_NOT_EOF_CONTINUE

#define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE (   extralen)
Value:
if (1) \
{ \
if (raw_buf_ptr + (extralen) >= copy_buf_len && !hit_eof) \
{ \
raw_buf_ptr = prev_raw_ptr; /* undo fetch */ \
need_data = true; \
continue; \
} \
} else ((void) 0)

Definition at line 308 of file copy.c.

Referenced by CopyReadLineText().

◆ ISOCTAL

#define ISOCTAL (   c)    (((c) >= '0') && ((c) <= '7'))

Definition at line 62 of file copy.c.

Referenced by CopyReadAttributesText().

◆ MAX_BUFFERED_BYTES

#define MAX_BUFFERED_BYTES   65535

Definition at line 259 of file copy.c.

Referenced by CopyMultiInsertInfoIsFull().

◆ MAX_BUFFERED_TUPLES

#define MAX_BUFFERED_TUPLES   1000

◆ MAX_COPY_DATA_DISPLAY

#define MAX_COPY_DATA_DISPLAY   100

Referenced by limit_printout_length().

◆ MAX_PARTITION_BUFFERS

#define MAX_PARTITION_BUFFERS   32

Definition at line 262 of file copy.c.

Referenced by CopyMultiInsertInfoFlush().

◆ NO_END_OF_COPY_GOTO

#define NO_END_OF_COPY_GOTO
Value:
if (1) \
{ \
raw_buf_ptr = prev_raw_ptr + 1; \
goto not_end_of_copy; \
} else ((void) 0)

Definition at line 350 of file copy.c.

Referenced by CopyReadLineText().

◆ OCTVALUE

#define OCTVALUE (   c)    ((c) - '0')

Definition at line 63 of file copy.c.

Referenced by CopyReadAttributesText().

◆ RAW_BUF_BYTES

#define RAW_BUF_BYTES (   cstate)    ((cstate)->raw_buf_len - (cstate)->raw_buf_index)

Definition at line 232 of file copy.c.

Referenced by CopyLoadRawBuf(), and CopyReadBinaryData().

◆ RAW_BUF_SIZE

#define RAW_BUF_SIZE   65536 /* we palloc RAW_BUF_SIZE+1 bytes */

Definition at line 227 of file copy.c.

Referenced by BeginCopyFrom(), and CopyLoadRawBuf().

◆ REFILL_LINEBUF

#define REFILL_LINEBUF
Value:
if (1) \
{ \
if (raw_buf_ptr > cstate->raw_buf_index) \
{ \
appendBinaryStringInfo(&cstate->line_buf, \
cstate->raw_buf + cstate->raw_buf_index, \
raw_buf_ptr - cstate->raw_buf_index); \
cstate->raw_buf_index = raw_buf_ptr; \
} \
} else ((void) 0)

Definition at line 337 of file copy.c.

Referenced by CopyReadLineText().

Typedef Documentation

◆ CopyDest

typedef enum CopyDest CopyDest

◆ CopyInsertMethod

◆ CopyMultiInsertBuffer

◆ CopyMultiInsertInfo

◆ CopyStateData

typedef struct CopyStateData CopyStateData

◆ EolType

typedef enum EolType EolType

Enumeration Type Documentation

◆ CopyDest

enum CopyDest
Enumerator
COPY_FILE 
COPY_OLD_FE 
COPY_NEW_FE 
COPY_CALLBACK 

Definition at line 69 of file copy.c.

70 {
71  COPY_FILE, /* to/from file (or a piped program) */
72  COPY_OLD_FE, /* to/from frontend (2.0 protocol) */
73  COPY_NEW_FE, /* to/from frontend (3.0 protocol) */
74  COPY_CALLBACK /* to/from callback function */
75 } CopyDest;
Definition: copy.c:71
CopyDest
Definition: copy.c:69

◆ CopyInsertMethod

Enumerator
CIM_SINGLE 
CIM_MULTI 
CIM_MULTI_CONDITIONAL 

Definition at line 91 of file copy.c.

92 {
93  CIM_SINGLE, /* use table_tuple_insert or fdw routine */
94  CIM_MULTI, /* always use table_multi_insert */
95  CIM_MULTI_CONDITIONAL /* use table_multi_insert only if valid */
Definition: copy.c:94
CopyInsertMethod
Definition: copy.c:91

◆ EolType

enum EolType
Enumerator
EOL_UNKNOWN 
EOL_NL 
EOL_CR 
EOL_CRNL 

Definition at line 80 of file copy.c.

81 {
83  EOL_NL,
84  EOL_CR,
85  EOL_CRNL
86 } EolType;
Definition: copy.c:83
EolType
Definition: copy.c:80
Definition: copy.c:84
Definition: copy.c:85

Function Documentation

◆ BeginCopy()

static CopyState BeginCopy ( ParseState pstate,
bool  is_from,
Relation  rel,
RawStmt raw_query,
Oid  queryRelId,
List attnamelist,
List options 
)
static

Definition at line 1507 of file copy.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, attnum, CopyStateData::attnumlist, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, Query::commandType, CopyStateData::convert_select, CopyStateData::convert_select_flags, CopyStateData::convert_selectively, CopyStateData::copy_dest, COPY_FILE, CopyStateData::copycontext, CopyGetAttnums(), copyObject, CreateDestReceiver(), CreateQueryDesc(), cur, CurrentMemoryContext, CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, DestCopyOut, CopyStateData::encoding_embeds_ascii, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, ExecutorStart(), CopyStateData::file_encoding, CopyStateData::force_notnull, CopyStateData::force_notnull_flags, CopyStateData::force_null, CopyStateData::force_null_flags, CopyStateData::force_quote, CopyStateData::force_quote_all, CopyStateData::force_quote_flags, GetActiveSnapshot(), GetDatabaseEncoding(), i, InvalidOid, InvalidSnapshot, IsA, lfirst_int, lfirst_node, linitial_node, list_length(), list_member_int(), list_member_oid(), MemoryContextSwitchTo(), NameStr, TupleDescData::natts, CopyStateData::need_transcoding, NIL, ParseState::p_sourcetext, palloc0(), pg_analyze_and_rewrite(), pg_database_encoding_max_length(), PG_ENCODING_IS_CLIENT_ONLY, pg_get_client_encoding(), pg_plan_query(), ProcessCopyOptions(), PushCopiedSnapshot(), QSRC_NON_INSTEAD_RULE, QSRC_QUAL_INSTEAD_RULE, CopyStateData::queryDesc, Query::querySource, CopyStateData::rel, RelationGetDescr, PlannedStmt::relationOids, Query::returningList, QueryDesc::tupDesc, TupleDescAttr, UpdateActiveSnapshotCommandId(), and Query::utilityStmt.

Referenced by BeginCopyFrom(), and BeginCopyTo().

1514 {
1515  CopyState cstate;
1516  TupleDesc tupDesc;
1517  int num_phys_attrs;
1518  MemoryContext oldcontext;
1519 
1520  /* Allocate workspace and zero all fields */
1521  cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1522 
1523  /*
1524  * We allocate everything used by a cstate in a new memory context. This
1525  * avoids memory leaks during repeated use of COPY in a query.
1526  */
1528  "COPY",
1530 
1531  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1532 
1533  /* Extract options from the statement node tree */
1534  ProcessCopyOptions(pstate, cstate, is_from, options);
1535 
1536  /* Process the source/target relation or query */
1537  if (rel)
1538  {
1539  Assert(!raw_query);
1540 
1541  cstate->rel = rel;
1542 
1543  tupDesc = RelationGetDescr(cstate->rel);
1544  }
1545  else
1546  {
1547  List *rewritten;
1548  Query *query;
1549  PlannedStmt *plan;
1550  DestReceiver *dest;
1551 
1552  Assert(!is_from);
1553  cstate->rel = NULL;
1554 
1555  /*
1556  * Run parse analysis and rewrite. Note this also acquires sufficient
1557  * locks on the source table(s).
1558  *
1559  * Because the parser and planner tend to scribble on their input, we
1560  * make a preliminary copy of the source querytree. This prevents
1561  * problems in the case that the COPY is in a portal or plpgsql
1562  * function and is executed repeatedly. (See also the same hack in
1563  * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
1564  */
1565  rewritten = pg_analyze_and_rewrite(copyObject(raw_query),
1566  pstate->p_sourcetext, NULL, 0,
1567  NULL);
1568 
1569  /* check that we got back something we can work with */
1570  if (rewritten == NIL)
1571  {
1572  ereport(ERROR,
1573  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1574  errmsg("DO INSTEAD NOTHING rules are not supported for COPY")));
1575  }
1576  else if (list_length(rewritten) > 1)
1577  {
1578  ListCell *lc;
1579 
1580  /* examine queries to determine which error message to issue */
1581  foreach(lc, rewritten)
1582  {
1583  Query *q = lfirst_node(Query, lc);
1584 
1586  ereport(ERROR,
1587  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1588  errmsg("conditional DO INSTEAD rules are not supported for COPY")));
1590  ereport(ERROR,
1591  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1592  errmsg("DO ALSO rules are not supported for the COPY")));
1593  }
1594 
1595  ereport(ERROR,
1596  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1597  errmsg("multi-statement DO INSTEAD rules are not supported for COPY")));
1598  }
1599 
1600  query = linitial_node(Query, rewritten);
1601 
1602  /* The grammar allows SELECT INTO, but we don't support that */
1603  if (query->utilityStmt != NULL &&
1605  ereport(ERROR,
1606  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1607  errmsg("COPY (SELECT INTO) is not supported")));
1608 
1609  Assert(query->utilityStmt == NULL);
1610 
1611  /*
1612  * Similarly the grammar doesn't enforce the presence of a RETURNING
1613  * clause, but this is required here.
1614  */
1615  if (query->commandType != CMD_SELECT &&
1616  query->returningList == NIL)
1617  {
1618  Assert(query->commandType == CMD_INSERT ||
1619  query->commandType == CMD_UPDATE ||
1620  query->commandType == CMD_DELETE);
1621 
1622  ereport(ERROR,
1623  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1624  errmsg("COPY query must have a RETURNING clause")));
1625  }
1626 
1627  /* plan the query */
1628  plan = pg_plan_query(query, pstate->p_sourcetext,
1629  CURSOR_OPT_PARALLEL_OK, NULL);
1630 
1631  /*
1632  * With row level security and a user using "COPY relation TO", we
1633  * have to convert the "COPY relation TO" to a query-based COPY (eg:
1634  * "COPY (SELECT * FROM relation) TO"), to allow the rewriter to add
1635  * in any RLS clauses.
1636  *
1637  * When this happens, we are passed in the relid of the originally
1638  * found relation (which we have locked). As the planner will look up
1639  * the relation again, we double-check here to make sure it found the
1640  * same one that we have locked.
1641  */
1642  if (queryRelId != InvalidOid)
1643  {
1644  /*
1645  * Note that with RLS involved there may be multiple relations,
1646  * and while the one we need is almost certainly first, we don't
1647  * make any guarantees of that in the planner, so check the whole
1648  * list and make sure we find the original relation.
1649  */
1650  if (!list_member_oid(plan->relationOids, queryRelId))
1651  ereport(ERROR,
1652  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1653  errmsg("relation referenced by COPY statement has changed")));
1654  }
1655 
1656  /*
1657  * Use a snapshot with an updated command ID to ensure this query sees
1658  * results of any previously executed queries.
1659  */
1662 
1663  /* Create dest receiver for COPY OUT */
1665  ((DR_copy *) dest)->cstate = cstate;
1666 
1667  /* Create a QueryDesc requesting no output */
1668  cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
1671  dest, NULL, NULL, 0);
1672 
1673  /*
1674  * Call ExecutorStart to prepare the plan for execution.
1675  *
1676  * ExecutorStart computes a result tupdesc for us
1677  */
1678  ExecutorStart(cstate->queryDesc, 0);
1679 
1680  tupDesc = cstate->queryDesc->tupDesc;
1681  }
1682 
1683  /* Generate or convert list of attributes to process */
1684  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1685 
1686  num_phys_attrs = tupDesc->natts;
1687 
1688  /* Convert FORCE_QUOTE name list to per-column flags, check validity */
1689  cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1690  if (cstate->force_quote_all)
1691  {
1692  int i;
1693 
1694  for (i = 0; i < num_phys_attrs; i++)
1695  cstate->force_quote_flags[i] = true;
1696  }
1697  else if (cstate->force_quote)
1698  {
1699  List *attnums;
1700  ListCell *cur;
1701 
1702  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_quote);
1703 
1704  foreach(cur, attnums)
1705  {
1706  int attnum = lfirst_int(cur);
1707  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1708 
1709  if (!list_member_int(cstate->attnumlist, attnum))
1710  ereport(ERROR,
1711  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1712  errmsg("FORCE_QUOTE column \"%s\" not referenced by COPY",
1713  NameStr(attr->attname))));
1714  cstate->force_quote_flags[attnum - 1] = true;
1715  }
1716  }
1717 
1718  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1719  cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1720  if (cstate->force_notnull)
1721  {
1722  List *attnums;
1723  ListCell *cur;
1724 
1725  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_notnull);
1726 
1727  foreach(cur, attnums)
1728  {
1729  int attnum = lfirst_int(cur);
1730  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1731 
1732  if (!list_member_int(cstate->attnumlist, attnum))
1733  ereport(ERROR,
1734  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1735  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
1736  NameStr(attr->attname))));
1737  cstate->force_notnull_flags[attnum - 1] = true;
1738  }
1739  }
1740 
1741  /* Convert FORCE_NULL name list to per-column flags, check validity */
1742  cstate->force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1743  if (cstate->force_null)
1744  {
1745  List *attnums;
1746  ListCell *cur;
1747 
1748  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_null);
1749 
1750  foreach(cur, attnums)
1751  {
1752  int attnum = lfirst_int(cur);
1753  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1754 
1755  if (!list_member_int(cstate->attnumlist, attnum))
1756  ereport(ERROR,
1757  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1758  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
1759  NameStr(attr->attname))));
1760  cstate->force_null_flags[attnum - 1] = true;
1761  }
1762  }
1763 
1764  /* Convert convert_selectively name list to per-column flags */
1765  if (cstate->convert_selectively)
1766  {
1767  List *attnums;
1768  ListCell *cur;
1769 
1770  cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1771 
1772  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->convert_select);
1773 
1774  foreach(cur, attnums)
1775  {
1776  int attnum = lfirst_int(cur);
1777  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1778 
1779  if (!list_member_int(cstate->attnumlist, attnum))
1780  ereport(ERROR,
1781  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1782  errmsg_internal("selected column \"%s\" not referenced by COPY",
1783  NameStr(attr->attname))));
1784  cstate->convert_select_flags[attnum - 1] = true;
1785  }
1786  }
1787 
1788  /* Use client encoding when ENCODING option is not specified. */
1789  if (cstate->file_encoding < 0)
1791 
1792  /*
1793  * Set up encoding conversion info. Even if the file and server encodings
1794  * are the same, we must apply pg_any_to_server() to validate data in
1795  * multibyte encodings.
1796  */
1797  cstate->need_transcoding =
1798  (cstate->file_encoding != GetDatabaseEncoding() ||
1800  /* See Multibyte encoding comment above */
1802 
1803  cstate->copy_dest = COPY_FILE; /* default */
1804 
1805  MemoryContextSwitchTo(oldcontext);
1806 
1807  return cstate;
1808 }
#define NIL
Definition: pg_list.h:65
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:580
#define AllocSetContextCreate
Definition: memutils.h:170
#define RelationGetDescr(relation)
Definition: rel.h:482
bool need_transcoding
Definition: copy.c:126
List * attnumlist
Definition: copy.c:132
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * relationOids
Definition: plannodes.h:86
Definition: copy.c:236
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
void ProcessCopyOptions(ParseState *pstate, CopyState cstate, bool is_from, List *options)
Definition: copy.c:1156
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:610
bool * force_quote_flags
Definition: copy.c:148
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:676
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial_node(type, l)
Definition: pg_list.h:198
bool * force_null_flags
Definition: copy.c:152
bool * convert_select_flags
Definition: copy.c:155
CopyDest copy_dest
Definition: copy.c:117
Definition: copy.c:71
Relation rel
Definition: copy.c:130
MemoryContext copycontext
Definition: copy.c:167
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:193
QueryDesc * queryDesc
Definition: copy.c:131
bool list_member_int(const List *list, int datum)
Definition: list.c:654
bool encoding_embeds_ascii
Definition: copy.c:127
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:179
List * returningList
Definition: parsenodes.h:146
List * force_null
Definition: copy.c:151
int file_encoding
Definition: copy.c:125
static List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:5077
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
void * palloc0(Size size)
Definition: mcxt.c:981
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
int pg_get_client_encoding(void)
Definition: mbutils.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
bool * force_notnull_flags
Definition: copy.c:150
CmdType commandType
Definition: parsenodes.h:112
List * force_notnull
Definition: copy.c:149
int errmsg_internal(const char *fmt,...)
Definition: elog.c:911
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:674
QuerySource querySource
Definition: parsenodes.h:114
#define Assert(condition)
Definition: c.h:745
List * convert_select
Definition: copy.c:154
static int list_length(const List *l)
Definition: pg_list.h:169
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1436
bool force_quote_all
Definition: copy.c:147
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2717
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
#define NameStr(name)
Definition: c.h:622
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:857
#define copyObject(obj)
Definition: nodes.h:645
Definition: pg_list.h:50
List * force_quote
Definition: copy.c:146
bool convert_selectively
Definition: copy.c:153

◆ BeginCopyFrom()

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

Definition at line 3383 of file copy.c.

References AllocateFile(), Assert, attnum, CopyStateData::attnumlist, CopyStateData::attribute_buf, BeginCopy(), CopyStateData::binary, BinarySignature, build_column_default(), contain_volatile_functions_not_nextval(), COPY_CALLBACK, CopyStateData::copy_dest, CopyStateData::copy_file, CopyStateData::copycontext, CopyGetInt32(), CopyReadBinaryData(), CopyStateData::cur_attname, CopyStateData::cur_attval, CopyStateData::cur_lineno, CopyStateData::cur_relname, CopyStateData::data_source_cb, CopyStateData::defexprs, CopyStateData::defmap, DestRemote, CopyStateData::eol_type, EOL_UNKNOWN, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, ExecInitExpr(), expression_planner(), CopyStateData::filename, fmgr_info(), getTypeBinaryInputInfo(), getTypeInputInfo(), CopyStateData::in_functions, initStringInfo(), InvalidOid, CopyStateData::is_program, CopyStateData::line_buf, CopyStateData::line_buf_converted, list_length(), list_member_int(), CopyStateData::max_fields, MemoryContextSwitchTo(), TupleDescData::natts, CopyStateData::num_defaults, OpenPipeStream(), ParseState::p_rtable, palloc(), PG_BINARY_R, pstrdup(), CopyStateData::range_table, CopyStateData::raw_buf, CopyStateData::raw_buf_index, CopyStateData::raw_buf_len, RAW_BUF_SIZE, CopyStateData::raw_fields, CopyStateData::reached_eof, ReceiveCopyBegin(), CopyStateData::rel, RelationGetDescr, RelationGetRelationName, S_ISDIR, stat, TupleDescAttr, CopyStateData::typioparams, CopyStateData::volatile_defexprs, and whereToSendOutput.

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

3390 {
3391  CopyState cstate;
3392  bool pipe = (filename == NULL);
3393  TupleDesc tupDesc;
3394  AttrNumber num_phys_attrs,
3395  num_defaults;
3396  FmgrInfo *in_functions;
3397  Oid *typioparams;
3398  int attnum;
3399  Oid in_func_oid;
3400  int *defmap;
3401  ExprState **defexprs;
3402  MemoryContext oldcontext;
3403  bool volatile_defexprs;
3404 
3405  cstate = BeginCopy(pstate, true, rel, NULL, InvalidOid, attnamelist, options);
3406  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
3407 
3408  /* Initialize state variables */
3409  cstate->reached_eof = false;
3410  cstate->eol_type = EOL_UNKNOWN;
3411  cstate->cur_relname = RelationGetRelationName(cstate->rel);
3412  cstate->cur_lineno = 0;
3413  cstate->cur_attname = NULL;
3414  cstate->cur_attval = NULL;
3415 
3416  /*
3417  * Set up variables to avoid per-attribute overhead. attribute_buf and
3418  * raw_buf are used in both text and binary modes, but we use line_buf
3419  * only in text mode.
3420  */
3421  initStringInfo(&cstate->attribute_buf);
3422  cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
3423  cstate->raw_buf_index = cstate->raw_buf_len = 0;
3424  if (!cstate->binary)
3425  {
3426  initStringInfo(&cstate->line_buf);
3427  cstate->line_buf_converted = false;
3428  }
3429 
3430  /* Assign range table, we'll need it in CopyFrom. */
3431  if (pstate)
3432  cstate->range_table = pstate->p_rtable;
3433 
3434  tupDesc = RelationGetDescr(cstate->rel);
3435  num_phys_attrs = tupDesc->natts;
3436  num_defaults = 0;
3437  volatile_defexprs = false;
3438 
3439  /*
3440  * Pick up the required catalog information for each attribute in the
3441  * relation, including the input function, the element type (to pass to
3442  * the input function), and info about defaults and constraints. (Which
3443  * input function we use depends on text/binary format choice.)
3444  */
3445  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3446  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
3447  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
3448  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
3449 
3450  for (attnum = 1; attnum <= num_phys_attrs; attnum++)
3451  {
3452  Form_pg_attribute att = TupleDescAttr(tupDesc, attnum - 1);
3453 
3454  /* We don't need info for dropped attributes */
3455  if (att->attisdropped)
3456  continue;
3457 
3458  /* Fetch the input function and typioparam info */
3459  if (cstate->binary)
3460  getTypeBinaryInputInfo(att->atttypid,
3461  &in_func_oid, &typioparams[attnum - 1]);
3462  else
3463  getTypeInputInfo(att->atttypid,
3464  &in_func_oid, &typioparams[attnum - 1]);
3465  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
3466 
3467  /* Get default info if needed */
3468  if (!list_member_int(cstate->attnumlist, attnum) && !att->attgenerated)
3469  {
3470  /* attribute is NOT to be copied from input */
3471  /* use default value if one exists */
3472  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
3473  attnum);
3474 
3475  if (defexpr != NULL)
3476  {
3477  /* Run the expression through planner */
3478  defexpr = expression_planner(defexpr);
3479 
3480  /* Initialize executable expression in copycontext */
3481  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
3482  defmap[num_defaults] = attnum - 1;
3483  num_defaults++;
3484 
3485  /*
3486  * If a default expression looks at the table being loaded,
3487  * then it could give the wrong answer when using
3488  * multi-insert. Since database access can be dynamic this is
3489  * hard to test for exactly, so we use the much wider test of
3490  * whether the default expression is volatile. We allow for
3491  * the special case of when the default expression is the
3492  * nextval() of a sequence which in this specific case is
3493  * known to be safe for use with the multi-insert
3494  * optimization. Hence we use this special case function
3495  * checker rather than the standard check for
3496  * contain_volatile_functions().
3497  */
3498  if (!volatile_defexprs)
3499  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
3500  }
3501  }
3502  }
3503 
3504  /* We keep those variables in cstate. */
3505  cstate->in_functions = in_functions;
3506  cstate->typioparams = typioparams;
3507  cstate->defmap = defmap;
3508  cstate->defexprs = defexprs;
3509  cstate->volatile_defexprs = volatile_defexprs;
3510  cstate->num_defaults = num_defaults;
3511  cstate->is_program = is_program;
3512 
3513  if (data_source_cb)
3514  {
3515  cstate->copy_dest = COPY_CALLBACK;
3516  cstate->data_source_cb = data_source_cb;
3517  }
3518  else if (pipe)
3519  {
3520  Assert(!is_program); /* the grammar does not allow this */
3522  ReceiveCopyBegin(cstate);
3523  else
3524  cstate->copy_file = stdin;
3525  }
3526  else
3527  {
3528  cstate->filename = pstrdup(filename);
3529 
3530  if (cstate->is_program)
3531  {
3532  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
3533  if (cstate->copy_file == NULL)
3534  ereport(ERROR,
3536  errmsg("could not execute command \"%s\": %m",
3537  cstate->filename)));
3538  }
3539  else
3540  {
3541  struct stat st;
3542 
3543  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
3544  if (cstate->copy_file == NULL)
3545  {
3546  /* copy errno because ereport subfunctions might change it */
3547  int save_errno = errno;
3548 
3549  ereport(ERROR,
3551  errmsg("could not open file \"%s\" for reading: %m",
3552  cstate->filename),
3553  (save_errno == ENOENT || save_errno == EACCES) ?
3554  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
3555  "You may want a client-side facility such as psql's \\copy.") : 0));
3556  }
3557 
3558  if (fstat(fileno(cstate->copy_file), &st))
3559  ereport(ERROR,
3561  errmsg("could not stat file \"%s\": %m",
3562  cstate->filename)));
3563 
3564  if (S_ISDIR(st.st_mode))
3565  ereport(ERROR,
3566  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3567  errmsg("\"%s\" is a directory", cstate->filename)));
3568  }
3569  }
3570 
3571  if (cstate->binary)
3572  {
3573  /* Read and verify binary header */
3574  char readSig[11];
3575  int32 tmp;
3576 
3577  /* Signature */
3578  if (CopyReadBinaryData(cstate, readSig, 11) != 11 ||
3579  memcmp(readSig, BinarySignature, 11) != 0)
3580  ereport(ERROR,
3581  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3582  errmsg("COPY file signature not recognized")));
3583  /* Flags field */
3584  if (!CopyGetInt32(cstate, &tmp))
3585  ereport(ERROR,
3586  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3587  errmsg("invalid COPY file header (missing flags)")));
3588  if ((tmp & (1 << 16)) != 0)
3589  ereport(ERROR,
3590  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3591  errmsg("invalid COPY file header (WITH OIDS)")));
3592  tmp &= ~(1 << 16);
3593  if ((tmp >> 16) != 0)
3594  ereport(ERROR,
3595  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3596  errmsg("unrecognized critical flags in COPY file header")));
3597  /* Header extension length */
3598  if (!CopyGetInt32(cstate, &tmp) ||
3599  tmp < 0)
3600  ereport(ERROR,
3601  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3602  errmsg("invalid COPY file header (missing length)")));
3603  /* Skip extension header, if present */
3604  while (tmp-- > 0)
3605  {
3606  if (CopyReadBinaryData(cstate, readSig, 1) != 1)
3607  ereport(ERROR,
3608  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3609  errmsg("invalid COPY file header (wrong length)")));
3610  }
3611  }
3612 
3613  /* create workspace for CopyReadAttributes results */
3614  if (!cstate->binary)
3615  {
3616  AttrNumber attr_count = list_length(cstate->attnumlist);
3617 
3618  cstate->max_fields = attr_count;
3619  cstate->raw_fields = (char **) palloc(attr_count * sizeof(char *));
3620  }
3621 
3622  MemoryContextSwitchTo(oldcontext);
3623 
3624  return cstate;
3625 }
Definition: fmgr.h:56
List * range_table
Definition: copy.c:184
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1507
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:774
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:747
int errhint(const char *fmt,...)
Definition: elog.c:1071
char ** raw_fields
Definition: copy.c:205
bool binary
Definition: copy.c:136
#define RelationGetDescr(relation)
Definition: rel.h:482
AttrNumber num_defaults
Definition: copy.c:178
FmgrInfo * in_functions
Definition: copy.c:179
List * attnumlist
Definition: copy.c:132
char * filename
Definition: copy.c:133
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
char * pstrdup(const char *in)
Definition: mcxt.c:1187
static void ReceiveCopyBegin(CopyState cstate)
Definition: copy.c:443
Expr * expression_planner(Expr *expr)
Definition: planner.c:6178
StringInfoData line_buf
Definition: copy.c:215
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:529
int raw_buf_index
Definition: copy.c:229
int errcode(int sqlerrcode)
Definition: elog.c:610
unsigned int Oid
Definition: postgres_ext.h:31
bool volatile_defexprs
Definition: copy.c:183
#define PG_BINARY_R
Definition: c.h:1213
bool line_buf_converted
Definition: copy.c:216
signed int int32
Definition: c.h:362
CopyDest copy_dest
Definition: copy.c:117
uint64 cur_lineno
Definition: copy.c:160
const char * cur_attname
Definition: copy.c:161
Relation rel
Definition: copy.c:130
MemoryContext copycontext
Definition: copy.c:167
copy_data_source_cb data_source_cb
Definition: copy.c:135
#define ERROR
Definition: elog.h:43
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
bool list_member_int(const List *list, int datum)
Definition: list.c:654
char * raw_buf
Definition: copy.c:228
ExprState ** defexprs
Definition: copy.c:182
const char * cur_relname
Definition: copy.c:159
int errcode_for_file_access(void)
Definition: elog.c:633
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define RelationGetRelationName(relation)
Definition: rel.h:490
static const char BinarySignature[11]
Definition: copy.c:357
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
int raw_buf_len
Definition: copy.c:230
static int CopyReadBinaryData(CopyState cstate, char *dest, int nbytes)
Definition: copy.c:827
int max_fields
Definition: copy.c:204
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2425
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2817
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2751
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define stat(a, b)
Definition: win32_port.h:255
Oid * typioparams
Definition: copy.c:180
bool is_program
Definition: copy.c:134
Node * build_column_default(Relation rel, int attrno)
#define RAW_BUF_SIZE
Definition: copy.c:227
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
EolType eol_type
Definition: copy.c:124
#define Assert(condition)
Definition: c.h:745
bool reached_eof
Definition: copy.c:122
static int list_length(const List *l)
Definition: pg_list.h:169
#define S_ISDIR(m)
Definition: win32_port.h:296
static char * filename
Definition: pg_dumpall.c:91
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:824
FILE * copy_file
Definition: copy.c:118
StringInfoData attribute_buf
Definition: copy.c:200
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:123
const char * cur_attval
Definition: copy.c:162
CommandDest whereToSendOutput
Definition: postgres.c:91
int16 AttrNumber
Definition: attnum.h:21
int * defmap
Definition: copy.c:181
List * p_rtable
Definition: parse_node.h:180

◆ BeginCopyTo()

static CopyState BeginCopyTo ( ParseState pstate,
Relation  rel,
RawStmt query,
Oid  queryRelId,
const char *  filename,
bool  is_program,
List attnamelist,
List options 
)
static

Definition at line 1872 of file copy.c.

References AllocateFile(), Assert, BeginCopy(), CopyStateData::copy_file, CopyStateData::copycontext, DestRemote, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, CopyStateData::filename, is_absolute_path, CopyStateData::is_program, MemoryContextSwitchTo(), OpenPipeStream(), PG_BINARY_W, PG_END_TRY, PG_FINALLY, PG_TRY, pstrdup(), RelationData::rd_rel, RelationGetRelationName, S_ISDIR, S_IWGRP, S_IWOTH, stat, generate_unaccent_rules::stdout, and whereToSendOutput.

Referenced by DoCopy().

1880 {
1881  CopyState cstate;
1882  bool pipe = (filename == NULL);
1883  MemoryContext oldcontext;
1884 
1885  if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
1886  {
1887  if (rel->rd_rel->relkind == RELKIND_VIEW)
1888  ereport(ERROR,
1889  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1890  errmsg("cannot copy from view \"%s\"",
1892  errhint("Try the COPY (SELECT ...) TO variant.")));
1893  else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
1894  ereport(ERROR,
1895  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1896  errmsg("cannot copy from materialized view \"%s\"",
1898  errhint("Try the COPY (SELECT ...) TO variant.")));
1899  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1900  ereport(ERROR,
1901  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1902  errmsg("cannot copy from foreign table \"%s\"",
1904  errhint("Try the COPY (SELECT ...) TO variant.")));
1905  else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
1906  ereport(ERROR,
1907  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1908  errmsg("cannot copy from sequence \"%s\"",
1909  RelationGetRelationName(rel))));
1910  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1911  ereport(ERROR,
1912  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1913  errmsg("cannot copy from partitioned table \"%s\"",
1915  errhint("Try the COPY (SELECT ...) TO variant.")));
1916  else
1917  ereport(ERROR,
1918  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1919  errmsg("cannot copy from non-table relation \"%s\"",
1920  RelationGetRelationName(rel))));
1921  }
1922 
1923  cstate = BeginCopy(pstate, false, rel, query, queryRelId, attnamelist,
1924  options);
1925  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1926 
1927  if (pipe)
1928  {
1929  Assert(!is_program); /* the grammar does not allow this */
1931  cstate->copy_file = stdout;
1932  }
1933  else
1934  {
1935  cstate->filename = pstrdup(filename);
1936  cstate->is_program = is_program;
1937 
1938  if (is_program)
1939  {
1940  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
1941  if (cstate->copy_file == NULL)
1942  ereport(ERROR,
1944  errmsg("could not execute command \"%s\": %m",
1945  cstate->filename)));
1946  }
1947  else
1948  {
1949  mode_t oumask; /* Pre-existing umask value */
1950  struct stat st;
1951 
1952  /*
1953  * Prevent write to relative path ... too easy to shoot oneself in
1954  * the foot by overwriting a database file ...
1955  */
1956  if (!is_absolute_path(filename))
1957  ereport(ERROR,
1958  (errcode(ERRCODE_INVALID_NAME),
1959  errmsg("relative path not allowed for COPY to file")));
1960 
1961  oumask = umask(S_IWGRP | S_IWOTH);
1962  PG_TRY();
1963  {
1964  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
1965  }
1966  PG_FINALLY();
1967  {
1968  umask(oumask);
1969  }
1970  PG_END_TRY();
1971  if (cstate->copy_file == NULL)
1972  {
1973  /* copy errno because ereport subfunctions might change it */
1974  int save_errno = errno;
1975 
1976  ereport(ERROR,
1978  errmsg("could not open file \"%s\" for writing: %m",
1979  cstate->filename),
1980  (save_errno == ENOENT || save_errno == EACCES) ?
1981  errhint("COPY TO instructs the PostgreSQL server process to write a file. "
1982  "You may want a client-side facility such as psql's \\copy.") : 0));
1983  }
1984 
1985  if (fstat(fileno(cstate->copy_file), &st))
1986  ereport(ERROR,
1988  errmsg("could not stat file \"%s\": %m",
1989  cstate->filename)));
1990 
1991  if (S_ISDIR(st.st_mode))
1992  ereport(ERROR,
1993  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1994  errmsg("\"%s\" is a directory", cstate->filename)));
1995  }
1996  }
1997 
1998  MemoryContextSwitchTo(oldcontext);
1999 
2000  return cstate;
2001 }
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1507
int errhint(const char *fmt,...)
Definition: elog.c:1071
char * filename
Definition: copy.c:133
char * pstrdup(const char *in)
Definition: mcxt.c:1187
#define S_IWOTH
Definition: win32_port.h:287
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:610
#define PG_BINARY_W
Definition: c.h:1214
Form_pg_class rd_rel
Definition: rel.h:109
MemoryContext copycontext
Definition: copy.c:167
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:633
#define is_absolute_path(filename)
Definition: port.h:86
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2322
#define RelationGetRelationName(relation)
Definition: rel.h:490
#define S_IWGRP
Definition: win32_port.h:275
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2425
#define stat(a, b)
Definition: win32_port.h:255
bool is_program
Definition: copy.c:134
#define PG_FINALLY()
Definition: elog.h:312
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
#define S_ISDIR(m)
Definition: win32_port.h:296
static char * filename
Definition: pg_dumpall.c:91
int errmsg(const char *fmt,...)
Definition: elog.c:824
FILE * copy_file
Definition: copy.c:118
CommandDest whereToSendOutput
Definition: postgres.c:91
#define PG_TRY()
Definition: elog.h:295
#define PG_END_TRY()
Definition: elog.h:320

◆ ClosePipeToProgram()

static void ClosePipeToProgram ( CopyState  cstate)
static

Definition at line 1814 of file copy.c.

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

Referenced by CopySendEndOfRow(), and EndCopy().

1815 {
1816  int pclose_rc;
1817 
1818  Assert(cstate->is_program);
1819 
1820  pclose_rc = ClosePipeStream(cstate->copy_file);
1821  if (pclose_rc == -1)
1822  ereport(ERROR,
1824  errmsg("could not close pipe to external command: %m")));
1825  else if (pclose_rc != 0)
1826  {
1827  /*
1828  * If we ended a COPY FROM PROGRAM before reaching EOF, then it's
1829  * expectable for the called program to fail with SIGPIPE, and we
1830  * should not report that as an error. Otherwise, SIGPIPE indicates a
1831  * problem.
1832  */
1833  if (cstate->is_copy_from && !cstate->reached_eof &&
1834  wait_result_is_signal(pclose_rc, SIGPIPE))
1835  return;
1836 
1837  ereport(ERROR,
1838  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1839  errmsg("program \"%s\" failed",
1840  cstate->filename),
1841  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1842  }
1843 }
char * filename
Definition: copy.c:133
int errcode(int sqlerrcode)
Definition: elog.c:610
#define SIGPIPE
Definition: win32_port.h:158
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
int ClosePipeStream(FILE *file)
Definition: fd.c:2731
int errdetail_internal(const char *fmt,...)
Definition: elog.c:984
bool wait_result_is_signal(int exit_status, int signum)
Definition: wait_error.c:92
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:633
bool is_copy_from
Definition: copy.c:121
bool is_program
Definition: copy.c:134
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
bool reached_eof
Definition: copy.c:122
int errmsg(const char *fmt,...)
Definition: elog.c:824
FILE * copy_file
Definition: copy.c:118

◆ copy_dest_destroy()

static void copy_dest_destroy ( DestReceiver self)
static

Definition at line 5192 of file copy.c.

References pfree().

Referenced by CreateCopyDestReceiver().

5193 {
5194  pfree(self);
5195 }
void pfree(void *pointer)
Definition: mcxt.c:1057

◆ copy_dest_receive()

static bool copy_dest_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 5167 of file copy.c.

References CopyOneRowTo(), DR_copy::cstate, and DR_copy::processed.

Referenced by CreateCopyDestReceiver().

5168 {
5169  DR_copy *myState = (DR_copy *) self;
5170  CopyState cstate = myState->cstate;
5171 
5172  /* Send the data */
5173  CopyOneRowTo(cstate, slot);
5174  myState->processed++;
5175 
5176  return true;
5177 }
Definition: copy.c:236
CopyState cstate
Definition: copy.c:239
static void CopyOneRowTo(CopyState cstate, TupleTableSlot *slot)
Definition: copy.c:2206
uint64 processed
Definition: copy.c:240

◆ copy_dest_shutdown()

static void copy_dest_shutdown ( DestReceiver self)
static

Definition at line 5183 of file copy.c.

Referenced by CreateCopyDestReceiver().

5184 {
5185  /* no-op */
5186 }

◆ copy_dest_startup()

static void copy_dest_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)
static

Definition at line 5158 of file copy.c.

Referenced by CreateCopyDestReceiver().

5159 {
5160  /* no-op */
5161 }

◆ CopyAttributeOutCSV()

static void CopyAttributeOutCSV ( CopyState  cstate,
char *  string,
bool  use_quote,
bool  single_attr 
)
static

Definition at line 4981 of file copy.c.

References CopySendChar(), CopySendString(), CopyStateData::delim, DUMPSOFAR, CopyStateData::encoding_embeds_ascii, CopyStateData::escape, CopyStateData::file_encoding, IS_HIGHBIT_SET, CopyStateData::need_transcoding, CopyStateData::null_print, pg_encoding_mblen(), pg_server_to_any(), and CopyStateData::quote.

Referenced by CopyOneRowTo(), and CopyTo().

4983 {
4984  char *ptr;
4985  char *start;
4986  char c;
4987  char delimc = cstate->delim[0];
4988  char quotec = cstate->quote[0];
4989  char escapec = cstate->escape[0];
4990 
4991  /* force quoting if it matches null_print (before conversion!) */
4992  if (!use_quote && strcmp(string, cstate->null_print) == 0)
4993  use_quote = true;
4994 
4995  if (cstate->need_transcoding)
4996  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
4997  else
4998  ptr = string;
4999 
5000  /*
5001  * Make a preliminary pass to discover if it needs quoting
5002  */
5003  if (!use_quote)
5004  {
5005  /*
5006  * Because '\.' can be a data value, quote it if it appears alone on a
5007  * line so it is not interpreted as the end-of-data marker.
5008  */
5009  if (single_attr && strcmp(ptr, "\\.") == 0)
5010  use_quote = true;
5011  else
5012  {
5013  char *tptr = ptr;
5014 
5015  while ((c = *tptr) != '\0')
5016  {
5017  if (c == delimc || c == quotec || c == '\n' || c == '\r')
5018  {
5019  use_quote = true;
5020  break;
5021  }
5022  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
5023  tptr += pg_encoding_mblen(cstate->file_encoding, tptr);
5024  else
5025  tptr++;
5026  }
5027  }
5028  }
5029 
5030  if (use_quote)
5031  {
5032  CopySendChar(cstate, quotec);
5033 
5034  /*
5035  * We adopt the same optimization strategy as in CopyAttributeOutText
5036  */
5037  start = ptr;
5038  while ((c = *ptr) != '\0')
5039  {
5040  if (c == quotec || c == escapec)
5041  {
5042  DUMPSOFAR();
5043  CopySendChar(cstate, escapec);
5044  start = ptr; /* we include char in next run */
5045  }
5046  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
5047  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
5048  else
5049  ptr++;
5050  }
5051  DUMPSOFAR();
5052 
5053  CopySendChar(cstate, quotec);
5054  }
5055  else
5056  {
5057  /* If it doesn't need quoting, we can just dump it as-is */
5058  CopySendString(cstate, ptr);
5059  }
5060 }
bool need_transcoding
Definition: copy.c:126
char * delim
Definition: copy.c:143
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:692
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:520
char * null_print
Definition: copy.c:140
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1097
bool encoding_embeds_ascii
Definition: copy.c:127
char * c
char * quote
Definition: copy.c:144
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1554
char string[11]
Definition: preproc-type.c:46
char * escape
Definition: copy.c:145
int file_encoding
Definition: copy.c:125
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:514
#define DUMPSOFAR()
Definition: copy.c:4821

◆ CopyAttributeOutText()

static void CopyAttributeOutText ( CopyState  cstate,
char *  string 
)
static

Definition at line 4828 of file copy.c.

References CopySendChar(), CopyStateData::delim, DUMPSOFAR, CopyStateData::encoding_embeds_ascii, CopyStateData::file_encoding, IS_HIGHBIT_SET, CopyStateData::need_transcoding, pg_encoding_mblen(), and pg_server_to_any().

Referenced by CopyOneRowTo().

4829 {
4830  char *ptr;
4831  char *start;
4832  char c;
4833  char delimc = cstate->delim[0];
4834 
4835  if (cstate->need_transcoding)
4836  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
4837  else
4838  ptr = string;
4839 
4840  /*
4841  * We have to grovel through the string searching for control characters
4842  * and instances of the delimiter character. In most cases, though, these
4843  * are infrequent. To avoid overhead from calling CopySendData once per
4844  * character, we dump out all characters between escaped characters in a
4845  * single call. The loop invariant is that the data from "start" to "ptr"
4846  * can be sent literally, but hasn't yet been.
4847  *
4848  * We can skip pg_encoding_mblen() overhead when encoding is safe, because
4849  * in valid backend encodings, extra bytes of a multibyte character never
4850  * look like ASCII. This loop is sufficiently performance-critical that
4851  * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
4852  * of the normal safe-encoding path.
4853  */
4854  if (cstate->encoding_embeds_ascii)
4855  {
4856  start = ptr;
4857  while ((c = *ptr) != '\0')
4858  {
4859  if ((unsigned char) c < (unsigned char) 0x20)
4860  {
4861  /*
4862  * \r and \n must be escaped, the others are traditional. We
4863  * prefer to dump these using the C-like notation, rather than
4864  * a backslash and the literal character, because it makes the
4865  * dump file a bit more proof against Microsoftish data
4866  * mangling.
4867  */
4868  switch (c)
4869  {
4870  case '\b':
4871  c = 'b';
4872  break;
4873  case '\f':
4874  c = 'f';
4875  break;
4876  case '\n':
4877  c = 'n';
4878  break;
4879  case '\r':
4880  c = 'r';
4881  break;
4882  case '\t':
4883  c = 't';
4884  break;
4885  case '\v':
4886  c = 'v';
4887  break;
4888  default:
4889  /* If it's the delimiter, must backslash it */
4890  if (c == delimc)
4891  break;
4892  /* All ASCII control chars are length 1 */
4893  ptr++;
4894  continue; /* fall to end of loop */
4895  }
4896  /* if we get here, we need to convert the control char */
4897  DUMPSOFAR();
4898  CopySendChar(cstate, '\\');
4899  CopySendChar(cstate, c);
4900  start = ++ptr; /* do not include char in next run */
4901  }
4902  else if (c == '\\' || c == delimc)
4903  {
4904  DUMPSOFAR();
4905  CopySendChar(cstate, '\\');
4906  start = ptr++; /* we include char in next run */
4907  }
4908  else if (IS_HIGHBIT_SET(c))
4909  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
4910  else
4911  ptr++;
4912  }
4913  }
4914  else
4915  {
4916  start = ptr;
4917  while ((c = *ptr) != '\0')
4918  {
4919  if ((unsigned char) c < (unsigned char) 0x20)
4920  {
4921  /*
4922  * \r and \n must be escaped, the others are traditional. We
4923  * prefer to dump these using the C-like notation, rather than
4924  * a backslash and the literal character, because it makes the
4925  * dump file a bit more proof against Microsoftish data
4926  * mangling.
4927  */
4928  switch (c)
4929  {
4930  case '\b':
4931  c = 'b';
4932  break;
4933  case '\f':
4934  c = 'f';
4935  break;
4936  case '\n':
4937  c = 'n';
4938  break;
4939  case '\r':
4940  c = 'r';
4941  break;
4942  case '\t':
4943  c = 't';
4944  break;
4945  case '\v':
4946  c = 'v';
4947  break;
4948  default:
4949  /* If it's the delimiter, must backslash it */
4950  if (c == delimc)
4951  break;
4952  /* All ASCII control chars are length 1 */
4953  ptr++;
4954  continue; /* fall to end of loop */
4955  }
4956  /* if we get here, we need to convert the control char */
4957  DUMPSOFAR();
4958  CopySendChar(cstate, '\\');
4959  CopySendChar(cstate, c);
4960  start = ++ptr; /* do not include char in next run */
4961  }
4962  else if (c == '\\' || c == delimc)
4963  {
4964  DUMPSOFAR();
4965  CopySendChar(cstate, '\\');
4966  start = ptr++; /* we include char in next run */
4967  }
4968  else
4969  ptr++;
4970  }
4971  }
4972 
4973  DUMPSOFAR();
4974 }
bool need_transcoding
Definition: copy.c:126
char * delim
Definition: copy.c:143
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:692
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:520
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1097
bool encoding_embeds_ascii
Definition: copy.c:127
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1554
char string[11]
Definition: preproc-type.c:46
int file_encoding
Definition: copy.c:125
#define DUMPSOFAR()
Definition: copy.c:4821

◆ CopyFrom()

uint64 CopyFrom ( CopyState  cstate)

Definition at line 2702 of file copy.c.

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(), CopyStateData::copy_dest, COPY_OLD_FE, CopyFromErrorCallback(), CopyMultiInsertInfoCleanup(), CopyMultiInsertInfoFlush(), CopyMultiInsertInfoInit(), CopyMultiInsertInfoIsEmpty(), CopyMultiInsertInfoIsFull(), CopyMultiInsertInfoNextFreeSlot(), CopyMultiInsertInfoSetupBuffer(), CopyMultiInsertInfoStore(), CreateExecutorState(), CopyStateData::cur_lineno, CurrentMemoryContext, ExprContext::ecxt_scantuple, FdwRoutine::EndForeignInsert, ereport, errcode(), errhint(), errmsg(), ERROR, error_context_stack, EState::es_num_result_relations, EState::es_result_relation_info, EState::es_result_relations, EState::es_tupleTable, ExecARInsertTriggers(), ExecASInsertTriggers(), ExecBRInsertTriggers(), ExecBSInsertTriggers(), ExecCleanUpTriggerState(), ExecCleanupTupleRouting(), ExecClearTuple(), ExecCloseIndices(), ExecComputeStoredGenerated(), ExecConstraints(), ExecCopySlot(), ExecFindPartition(), FdwRoutine::ExecForeignInsert, ExecInitQual(), ExecInitRangeTable(), ExecInsertIndexTuples(), ExecIRInsertTriggers(), ExecMaterializeSlot(), ExecOpenIndices(), ExecPartitionCheck(), ExecQual(), ExecResetTupleTable(), ExecSetupPartitionTupleRouting(), ExecStoreVirtualTuple(), execute_attr_map_slot(), FreeBulkInsertState(), FreeExecutorState(), CopyStateData::freeze, GetBulkInsertState(), GetCurrentCommandId(), GetCurrentSubTransactionId(), GetPerTupleExprContext, GetPerTupleMemoryContext, TupleConstr::has_generated_stored, InitResultRelInfo(), InvalidateCatalogSnapshot(), InvalidSubTransactionId, StringInfoData::len, CopyStateData::line_buf, list_free(), makeNode, MakeTransitionCaptureState(), MemoryContextSwitchTo(), ModifyTableState::mt_transition_capture, NextCopyFrom(), NIL, ModifyTableState::operation, PartitionRoutingInfo::pi_PartitionToRootMap, PartitionRoutingInfo::pi_PartitionTupleSlot, PartitionRoutingInfo::pi_RootToPartitionMap, PlanState::plan, pq_endmsgread(), ErrorContextCallback::previous, ModifyTableState::ps, CopyStateData::qualexpr, CopyStateData::range_table, RelationData::rd_att, RelationData::rd_createSubid, RelationData::rd_firstRelfilenodeSubid, RelationData::rd_newRelfilenodeSubid, RelationData::rd_rel, CopyStateData::rel, RelationGetRelationName, RelationGetRelid, ReleaseBulkInsertStatePin(), ResetPerTupleExprContext, ModifyTableState::resultRelInfo, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionInfo, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, PlanState::state, TABLE_INSERT_FROZEN, TABLE_INSERT_SKIP_FSM, table_slot_create(), table_tuple_insert(), TransitionCaptureState::tcs_map, TransitionCaptureState::tcs_original_insert_tuple, ThereAreNoPriorRegisteredSnapshots(), ThereAreNoReadyPortals(), CopyStateData::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, CopyStateData::volatile_defexprs, and CopyStateData::whereClause.

Referenced by copy_table(), and DoCopy().

2703 {
2704  ResultRelInfo *resultRelInfo;
2705  ResultRelInfo *target_resultRelInfo;
2706  ResultRelInfo *prevResultRelInfo = NULL;
2707  EState *estate = CreateExecutorState(); /* for ExecConstraints() */
2708  ModifyTableState *mtstate;
2709  ExprContext *econtext;
2710  TupleTableSlot *singleslot = NULL;
2711  MemoryContext oldcontext = CurrentMemoryContext;
2712 
2713  PartitionTupleRouting *proute = NULL;
2714  ErrorContextCallback errcallback;
2715  CommandId mycid = GetCurrentCommandId(true);
2716  int ti_options = 0; /* start with default options for insert */
2717  BulkInsertState bistate = NULL;
2718  CopyInsertMethod insertMethod;
2719  CopyMultiInsertInfo multiInsertInfo = {0}; /* pacify compiler */
2720  uint64 processed = 0;
2721  bool has_before_insert_row_trig;
2722  bool has_instead_insert_row_trig;
2723  bool leafpart_use_multi_insert = false;
2724 
2725  Assert(cstate->rel);
2726 
2727  /*
2728  * The target must be a plain, foreign, or partitioned relation, or have
2729  * an INSTEAD OF INSERT row trigger. (Currently, such triggers are only
2730  * allowed on views, so we only hint about them in the view case.)
2731  */
2732  if (cstate->rel->rd_rel->relkind != RELKIND_RELATION &&
2733  cstate->rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
2734  cstate->rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
2735  !(cstate->rel->trigdesc &&
2737  {
2738  if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
2739  ereport(ERROR,
2740  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2741  errmsg("cannot copy to view \"%s\"",
2742  RelationGetRelationName(cstate->rel)),
2743  errhint("To enable copying to a view, provide an INSTEAD OF INSERT trigger.")));
2744  else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
2745  ereport(ERROR,
2746  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2747  errmsg("cannot copy to materialized view \"%s\"",
2748  RelationGetRelationName(cstate->rel))));
2749  else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
2750  ereport(ERROR,
2751  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2752  errmsg("cannot copy to sequence \"%s\"",
2753  RelationGetRelationName(cstate->rel))));
2754  else
2755  ereport(ERROR,
2756  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2757  errmsg("cannot copy to non-table relation \"%s\"",
2758  RelationGetRelationName(cstate->rel))));
2759  }
2760 
2761  /*
2762  * If the target file is new-in-transaction, we assume that checking FSM
2763  * for free space is a waste of time. This could possibly be wrong, but
2764  * it's unlikely.
2765  */
2766  if (RELKIND_HAS_STORAGE(cstate->rel->rd_rel->relkind) &&
2769  ti_options |= TABLE_INSERT_SKIP_FSM;
2770 
2771  /*
2772  * Optimize if new relfilenode was created in this subxact or one of its
2773  * committed children and we won't see those rows later as part of an
2774  * earlier scan or command. The subxact test ensures that if this subxact
2775  * aborts then the frozen rows won't be visible after xact cleanup. Note
2776  * that the stronger test of exactly which subtransaction created it is
2777  * crucial for correctness of this optimization. The test for an earlier
2778  * scan or command tolerates false negatives. FREEZE causes other sessions
2779  * to see rows they would not see under MVCC, and a false negative merely
2780  * spreads that anomaly to the current session.
2781  */
2782  if (cstate->freeze)
2783  {
2784  /*
2785  * We currently disallow COPY FREEZE on partitioned tables. The
2786  * reason for this is that we've simply not yet opened the partitions
2787  * to determine if the optimization can be applied to them. We could
2788  * go and open them all here, but doing so may be quite a costly
2789  * overhead for small copies. In any case, we may just end up routing
2790  * tuples to a small number of partitions. It seems better just to
2791  * raise an ERROR for partitioned tables.
2792  */
2793  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2794  {
2795  ereport(ERROR,
2796  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2797  errmsg("cannot perform COPY FREEZE on a partitioned table")));
2798  }
2799 
2800  /*
2801  * Tolerate one registration for the benefit of FirstXactSnapshot.
2802  * Scan-bearing queries generally create at least two registrations,
2803  * though relying on that is fragile, as is ignoring ActiveSnapshot.
2804  * Clear CatalogSnapshot to avoid counting its registration. We'll
2805  * still detect ongoing catalog scans, each of which separately
2806  * registers the snapshot it uses.
2807  */
2810  ereport(ERROR,
2811  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2812  errmsg("cannot perform COPY FREEZE because of prior transaction activity")));
2813 
2814  if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
2816  ereport(ERROR,
2817  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2818  errmsg("cannot perform COPY FREEZE because the table was not created or truncated in the current subtransaction")));
2819 
2820  ti_options |= TABLE_INSERT_FROZEN;
2821  }
2822 
2823  /*
2824  * We need a ResultRelInfo so we can use the regular executor's
2825  * index-entry-making machinery. (There used to be a huge amount of code
2826  * here that basically duplicated execUtils.c ...)
2827  */
2828  resultRelInfo = makeNode(ResultRelInfo);
2829  InitResultRelInfo(resultRelInfo,
2830  cstate->rel,
2831  1, /* must match rel's position in range_table */
2832  NULL,
2833  0);
2834  target_resultRelInfo = resultRelInfo;
2835 
2836  /* Verify the named relation is a valid target for INSERT */
2837  CheckValidResultRel(resultRelInfo, CMD_INSERT);
2838 
2839  ExecOpenIndices(resultRelInfo, false);
2840 
2841  estate->es_result_relations = resultRelInfo;
2842  estate->es_num_result_relations = 1;
2843  estate->es_result_relation_info = resultRelInfo;
2844 
2845  ExecInitRangeTable(estate, cstate->range_table);
2846 
2847  /*
2848  * Set up a ModifyTableState so we can let FDW(s) init themselves for
2849  * foreign-table result relation(s).
2850  */
2851  mtstate = makeNode(ModifyTableState);
2852  mtstate->ps.plan = NULL;
2853  mtstate->ps.state = estate;
2854  mtstate->operation = CMD_INSERT;
2855  mtstate->resultRelInfo = estate->es_result_relations;
2856 
2857  if (resultRelInfo->ri_FdwRoutine != NULL &&
2858  resultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)
2859  resultRelInfo->ri_FdwRoutine->BeginForeignInsert(mtstate,
2860  resultRelInfo);
2861 
2862  /* Prepare to catch AFTER triggers. */
2864 
2865  /*
2866  * If there are any triggers with transition tables on the named relation,
2867  * we need to be prepared to capture transition tuples.
2868  *
2869  * Because partition tuple routing would like to know about whether
2870  * transition capture is active, we also set it in mtstate, which is
2871  * passed to ExecFindPartition() below.
2872  */
2873  cstate->transition_capture = mtstate->mt_transition_capture =
2875  RelationGetRelid(cstate->rel),
2876  CMD_INSERT);
2877 
2878  /*
2879  * If the named relation is a partitioned table, initialize state for
2880  * CopyFrom tuple routing.
2881  */
2882  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2883  proute = ExecSetupPartitionTupleRouting(estate, NULL, cstate->rel);
2884 
2885  if (cstate->whereClause)
2886  cstate->qualexpr = ExecInitQual(castNode(List, cstate->whereClause),
2887  &mtstate->ps);
2888 
2889  /*
2890  * It's generally more efficient to prepare a bunch of tuples for
2891  * insertion, and insert them in one table_multi_insert() call, than call
2892  * table_tuple_insert() separately for every tuple. However, there are a
2893  * number of reasons why we might not be able to do this. These are
2894  * explained below.
2895  */
2896  if (resultRelInfo->ri_TrigDesc != NULL &&
2897  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2898  resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
2899  {
2900  /*
2901  * Can't support multi-inserts when there are any BEFORE/INSTEAD OF
2902  * triggers on the table. Such triggers might query the table we're
2903  * inserting into and act differently if the tuples that have already
2904  * been processed and prepared for insertion are not there.
2905  */
2906  insertMethod = CIM_SINGLE;
2907  }
2908  else if (proute != NULL && resultRelInfo->ri_TrigDesc != NULL &&
2909  resultRelInfo->ri_TrigDesc->trig_insert_new_table)
2910  {
2911  /*
2912  * For partitioned tables we can't support multi-inserts when there
2913  * are any statement level insert triggers. It might be possible to
2914  * allow partitioned tables with such triggers in the future, but for
2915  * now, CopyMultiInsertInfoFlush expects that any before row insert
2916  * and statement level insert triggers are on the same relation.
2917  */
2918  insertMethod = CIM_SINGLE;
2919  }
2920  else if (resultRelInfo->ri_FdwRoutine != NULL ||
2921  cstate->volatile_defexprs)
2922  {
2923  /*
2924  * Can't support multi-inserts to foreign tables or if there are any
2925  * volatile default expressions in the table. Similarly to the
2926  * trigger case above, such expressions may query the table we're
2927  * inserting into.
2928  *
2929  * Note: It does not matter if any partitions have any volatile
2930  * default expressions as we use the defaults from the target of the
2931  * COPY command.
2932  */
2933  insertMethod = CIM_SINGLE;
2934  }
2935  else if (contain_volatile_functions(cstate->whereClause))
2936  {
2937  /*
2938  * Can't support multi-inserts if there are any volatile function
2939  * expressions in WHERE clause. Similarly to the trigger case above,
2940  * such expressions may query the table we're inserting into.
2941  */
2942  insertMethod = CIM_SINGLE;
2943  }
2944  else
2945  {
2946  /*
2947  * For partitioned tables, we may still be able to perform bulk
2948  * inserts. However, the possibility of this depends on which types
2949  * of triggers exist on the partition. We must disable bulk inserts
2950  * if the partition is a foreign table or it has any before row insert
2951  * or insert instead triggers (same as we checked above for the parent
2952  * table). Since the partition's resultRelInfos are initialized only
2953  * when we actually need to insert the first tuple into them, we must
2954  * have the intermediate insert method of CIM_MULTI_CONDITIONAL to
2955  * flag that we must later determine if we can use bulk-inserts for
2956  * the partition being inserted into.
2957  */
2958  if (proute)
2959  insertMethod = CIM_MULTI_CONDITIONAL;
2960  else
2961  insertMethod = CIM_MULTI;
2962 
2963  CopyMultiInsertInfoInit(&multiInsertInfo, resultRelInfo, cstate,
2964  estate, mycid, ti_options);
2965  }
2966 
2967  /*
2968  * If not using batch mode (which allocates slots as needed) set up a
2969  * tuple slot too. When inserting into a partitioned table, we also need
2970  * one, even if we might batch insert, to read the tuple in the root
2971  * partition's form.
2972  */
2973  if (insertMethod == CIM_SINGLE || insertMethod == CIM_MULTI_CONDITIONAL)
2974  {
2975  singleslot = table_slot_create(resultRelInfo->ri_RelationDesc,
2976  &estate->es_tupleTable);
2977  bistate = GetBulkInsertState();
2978  }
2979 
2980  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
2981  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
2982 
2983  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
2984  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
2985 
2986  /*
2987  * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
2988  * should do this for COPY, since it's not really an "INSERT" statement as
2989  * such. However, executing these triggers maintains consistency with the
2990  * EACH ROW triggers that we already fire on COPY.
2991  */
2992  ExecBSInsertTriggers(estate, resultRelInfo);
2993 
2994  econtext = GetPerTupleExprContext(estate);
2995 
2996  /* Set up callback to identify error line number */
2997  errcallback.callback = CopyFromErrorCallback;
2998  errcallback.arg = (void *) cstate;
2999  errcallback.previous = error_context_stack;
3000  error_context_stack = &errcallback;
3001 
3002  for (;;)
3003  {
3004  TupleTableSlot *myslot;
3005  bool skip_tuple;
3006 
3008 
3009  /*
3010  * Reset the per-tuple exprcontext. We do this after every tuple, to
3011  * clean-up after expression evaluations etc.
3012  */
3013  ResetPerTupleExprContext(estate);
3014 
3015  /* select slot to (initially) load row into */
3016  if (insertMethod == CIM_SINGLE || proute)
3017  {
3018  myslot = singleslot;
3019  Assert(myslot != NULL);
3020  }
3021  else
3022  {
3023  Assert(resultRelInfo == target_resultRelInfo);
3024  Assert(insertMethod == CIM_MULTI);
3025 
3026  myslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
3027  resultRelInfo);
3028  }
3029 
3030  /*
3031  * Switch to per-tuple context before calling NextCopyFrom, which does
3032  * evaluate default expressions etc. and requires per-tuple context.
3033  */
3035 
3036  ExecClearTuple(myslot);
3037 
3038  /* Directly store the values/nulls array in the slot */
3039  if (!NextCopyFrom(cstate, econtext, myslot->tts_values, myslot->tts_isnull))
3040  break;
3041 
3042  ExecStoreVirtualTuple(myslot);
3043 
3044  /*
3045  * Constraints and where clause might reference the tableoid column,
3046  * so (re-)initialize tts_tableOid before evaluating them.
3047  */
3048  myslot->tts_tableOid = RelationGetRelid(target_resultRelInfo->ri_RelationDesc);
3049 
3050  /* Triggers and stuff need to be invoked in query context. */
3051  MemoryContextSwitchTo(oldcontext);
3052 
3053  if (cstate->whereClause)
3054  {
3055  econtext->ecxt_scantuple = myslot;
3056  /* Skip items that don't match COPY's WHERE clause */
3057  if (!ExecQual(cstate->qualexpr, econtext))
3058  continue;
3059  }
3060 
3061  /* Determine the partition to insert the tuple into */
3062  if (proute)
3063  {
3064  TupleConversionMap *map;
3065 
3066  /*
3067  * Attempt to find a partition suitable for this tuple.
3068  * ExecFindPartition() will raise an error if none can be found or
3069  * if the found partition is not suitable for INSERTs.
3070  */
3071  resultRelInfo = ExecFindPartition(mtstate, target_resultRelInfo,
3072  proute, myslot, estate);
3073 
3074  if (prevResultRelInfo != resultRelInfo)
3075  {
3076  /* Determine which triggers exist on this partition */
3077  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
3078  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
3079 
3080  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
3081  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
3082 
3083  /*
3084  * Disable multi-inserts when the partition has BEFORE/INSTEAD
3085  * OF triggers, or if the partition is a foreign partition.
3086  */
3087  leafpart_use_multi_insert = insertMethod == CIM_MULTI_CONDITIONAL &&
3088  !has_before_insert_row_trig &&
3089  !has_instead_insert_row_trig &&
3090  resultRelInfo->ri_FdwRoutine == NULL;
3091 
3092  /* Set the multi-insert buffer to use for this partition. */
3093  if (leafpart_use_multi_insert)
3094  {
3095  if (resultRelInfo->ri_CopyMultiInsertBuffer == NULL)
3096  CopyMultiInsertInfoSetupBuffer(&multiInsertInfo,
3097  resultRelInfo);
3098  }
3099  else if (insertMethod == CIM_MULTI_CONDITIONAL &&
3100  !CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
3101  {
3102  /*
3103  * Flush pending inserts if this partition can't use
3104  * batching, so rows are visible to triggers etc.
3105  */
3106  CopyMultiInsertInfoFlush(&multiInsertInfo, resultRelInfo);
3107  }
3108 
3109  if (bistate != NULL)
3110  ReleaseBulkInsertStatePin(bistate);
3111  prevResultRelInfo = resultRelInfo;
3112  }
3113 
3114  /*
3115  * For ExecInsertIndexTuples() to work on the partition's indexes
3116  */
3117  estate->es_result_relation_info = resultRelInfo;
3118 
3119  /*
3120  * If we're capturing transition tuples, we might need to convert
3121  * from the partition rowtype to root rowtype.
3122  */
3123  if (cstate->transition_capture != NULL)
3124  {
3125  if (has_before_insert_row_trig)
3126  {
3127  /*
3128  * If there are any BEFORE triggers on the partition,
3129  * we'll have to be ready to convert their result back to
3130  * tuplestore format.
3131  */
3133  cstate->transition_capture->tcs_map =
3134  resultRelInfo->ri_PartitionInfo->pi_PartitionToRootMap;
3135  }
3136  else
3137  {
3138  /*
3139  * Otherwise, just remember the original unconverted
3140  * tuple, to avoid a needless round trip conversion.
3141  */
3143  cstate->transition_capture->tcs_map = NULL;
3144  }
3145  }
3146 
3147  /*
3148  * We might need to convert from the root rowtype to the partition
3149  * rowtype.
3150  */
3151  map = resultRelInfo->ri_PartitionInfo->pi_RootToPartitionMap;
3152  if (insertMethod == CIM_SINGLE || !leafpart_use_multi_insert)
3153  {
3154  /* non batch insert */
3155  if (map != NULL)
3156  {
3157  TupleTableSlot *new_slot;
3158 
3159  new_slot = resultRelInfo->ri_PartitionInfo->pi_PartitionTupleSlot;
3160  myslot = execute_attr_map_slot(map->attrMap, myslot, new_slot);
3161  }
3162  }
3163  else
3164  {
3165  /*
3166  * Prepare to queue up tuple for later batch insert into
3167  * current partition.
3168  */
3169  TupleTableSlot *batchslot;
3170 
3171  /* no other path available for partitioned table */
3172  Assert(insertMethod == CIM_MULTI_CONDITIONAL);
3173 
3174  batchslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
3175  resultRelInfo);
3176 
3177  if (map != NULL)
3178  myslot = execute_attr_map_slot(map->attrMap, myslot,
3179  batchslot);
3180  else
3181  {
3182  /*
3183  * This looks more expensive than it is (Believe me, I
3184  * optimized it away. Twice.). The input is in virtual
3185  * form, and we'll materialize the slot below - for most
3186  * slot types the copy performs the work materialization
3187  * would later require anyway.
3188  */
3189  ExecCopySlot(batchslot, myslot);
3190  myslot = batchslot;
3191  }
3192  }
3193 
3194  /* ensure that triggers etc see the right relation */
3195  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
3196  }
3197 
3198  skip_tuple = false;
3199 
3200  /* BEFORE ROW INSERT Triggers */
3201  if (has_before_insert_row_trig)
3202  {
3203  if (!ExecBRInsertTriggers(estate, resultRelInfo, myslot))
3204  skip_tuple = true; /* "do nothing" */
3205  }
3206 
3207  if (!skip_tuple)
3208  {
3209  /*
3210  * If there is an INSTEAD OF INSERT ROW trigger, let it handle the
3211  * tuple. Otherwise, proceed with inserting the tuple into the
3212  * table or foreign table.
3213  */
3214  if (has_instead_insert_row_trig)
3215  {
3216  ExecIRInsertTriggers(estate, resultRelInfo, myslot);
3217  }
3218  else
3219  {
3220  /* Compute stored generated columns */
3221  if (resultRelInfo->ri_RelationDesc->rd_att->constr &&
3223  ExecComputeStoredGenerated(estate, myslot, CMD_INSERT);
3224 
3225  /*
3226  * If the target is a plain table, check the constraints of
3227  * the tuple.
3228  */
3229  if (resultRelInfo->ri_FdwRoutine == NULL &&
3230  resultRelInfo->ri_RelationDesc->rd_att->constr)
3231  ExecConstraints(resultRelInfo, myslot, estate);
3232 
3233  /*
3234  * Also check the tuple against the partition constraint, if
3235  * there is one; except that if we got here via tuple-routing,
3236  * we don't need to if there's no BR trigger defined on the
3237  * partition.
3238  */
3239  if (resultRelInfo->ri_RelationDesc->rd_rel->relispartition &&
3240  (proute == NULL || has_before_insert_row_trig))
3241  ExecPartitionCheck(resultRelInfo, myslot, estate, true);
3242 
3243  /* Store the slot in the multi-insert buffer, when enabled. */
3244  if (insertMethod == CIM_MULTI || leafpart_use_multi_insert)
3245  {
3246  /*
3247  * The slot previously might point into the per-tuple
3248  * context. For batching it needs to be longer lived.
3249  */
3250  ExecMaterializeSlot(myslot);
3251 
3252  /* Add this tuple to the tuple buffer */
3253  CopyMultiInsertInfoStore(&multiInsertInfo,
3254  resultRelInfo, myslot,
3255  cstate->line_buf.len,
3256  cstate->cur_lineno);
3257 
3258  /*
3259  * If enough inserts have queued up, then flush all
3260  * buffers out to their tables.
3261  */
3262  if (CopyMultiInsertInfoIsFull(&multiInsertInfo))
3263  CopyMultiInsertInfoFlush(&multiInsertInfo, resultRelInfo);
3264  }
3265  else
3266  {
3267  List *recheckIndexes = NIL;
3268 
3269  /* OK, store the tuple */
3270  if (resultRelInfo->ri_FdwRoutine != NULL)
3271  {
3272  myslot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
3273  resultRelInfo,
3274  myslot,
3275  NULL);
3276 
3277  if (myslot == NULL) /* "do nothing" */
3278  continue; /* next tuple please */
3279 
3280  /*
3281  * AFTER ROW Triggers might reference the tableoid
3282  * column, so (re-)initialize tts_tableOid before
3283  * evaluating them.
3284  */
3285  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
3286  }
3287  else
3288  {
3289  /* OK, store the tuple and create index entries for it */
3290  table_tuple_insert(resultRelInfo->ri_RelationDesc,
3291  myslot, mycid, ti_options, bistate);
3292 
3293  if (resultRelInfo->ri_NumIndices > 0)
3294  recheckIndexes = ExecInsertIndexTuples(myslot,
3295  estate,
3296  false,
3297  NULL,
3298  NIL);
3299  }
3300 
3301  /* AFTER ROW INSERT Triggers */
3302  ExecARInsertTriggers(estate, resultRelInfo, myslot,
3303  recheckIndexes, cstate->transition_capture);
3304 
3305  list_free(recheckIndexes);
3306  }
3307  }
3308 
3309  /*
3310  * We count only tuples not suppressed by a BEFORE INSERT trigger
3311  * or FDW; this is the same definition used by nodeModifyTable.c
3312  * for counting tuples inserted by an INSERT command.
3313  */
3314  processed++;
3315  }
3316  }
3317 
3318  /* Flush any remaining buffered tuples */
3319  if (insertMethod != CIM_SINGLE)
3320  {
3321  if (!CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
3322  CopyMultiInsertInfoFlush(&multiInsertInfo, NULL);
3323  }
3324 
3325  /* Done, clean up */
3326  error_context_stack = errcallback.previous;
3327 
3328  if (bistate != NULL)
3329  FreeBulkInsertState(bistate);
3330 
3331  MemoryContextSwitchTo(oldcontext);
3332 
3333  /*
3334  * In the old protocol, tell pqcomm that we can process normal protocol
3335  * messages again.
3336  */
3337  if (cstate->copy_dest == COPY_OLD_FE)
3338  pq_endmsgread();
3339 
3340  /* Execute AFTER STATEMENT insertion triggers */
3341  ExecASInsertTriggers(estate, target_resultRelInfo, cstate->transition_capture);
3342 
3343  /* Handle queued AFTER triggers */
3344  AfterTriggerEndQuery(estate);
3345 
3346  ExecResetTupleTable(estate->es_tupleTable, false);
3347 
3348  /* Allow the FDW to shut down */
3349  if (target_resultRelInfo->ri_FdwRoutine != NULL &&
3350  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert != NULL)
3351  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert(estate,
3352  target_resultRelInfo);
3353 
3354  /* Tear down the multi-insert buffer data */
3355  if (insertMethod != CIM_SINGLE)
3356  CopyMultiInsertInfoCleanup(&multiInsertInfo);
3357 
3358  ExecCloseIndices(target_resultRelInfo);
3359 
3360  /* Close all the partitioned tables, leaf partitions, and their indices */
3361  if (proute)
3362  ExecCleanupTupleRouting(mtstate, proute);
3363 
3364  /* Close any trigger target relations */
3365  ExecCleanUpTriggerState(estate);
3366 
3367  FreeExecutorState(estate);
3368 
3369  return processed;
3370 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
int ri_NumIndices
Definition: execnodes.h:416
Node * whereClause
Definition: copy.c:156
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
#define NIL
Definition: pg_list.h:65
Oid tts_tableOid
Definition: tuptable.h:131
uint32 CommandId
Definition: c.h:534
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:765
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1277
Relation ri_RelationDesc
Definition: execnodes.h:413
List * range_table
Definition: copy.c:184
static void CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, TupleTableSlot *slot, int tuplen, uint64 lineno)
Definition: copy.c:2679
int errhint(const char *fmt,...)
Definition: elog.c:1071
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2268
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2284
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define ResetPerTupleExprContext(estate)
Definition: executor.h:516
#define TABLE_INSERT_FROZEN
Definition: tableam.h:134
#define castNode(_type_, nodeptr)
Definition: nodes.h:598
BeginForeignInsert_function BeginForeignInsert
Definition: fdwapi.h:215
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1173
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:211
struct PartitionRoutingInfo * ri_PartitionInfo
Definition: execnodes.h:487
void ExecComputeStoredGenerated(EState *estate, TupleTableSlot *slot, CmdType cmdtype)
static void CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copy.c:2407
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1886
StringInfoData line_buf
Definition: copy.c:215
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool ThereAreNoPriorRegisteredSnapshots(void)
Definition: snapmgr.c:1604
int errcode(int sqlerrcode)
Definition: elog.c:610
CmdType operation
Definition: execnodes.h:1165
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:103
Datum * tts_values
Definition: tuptable.h:126
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:724
EState * state
Definition: execnodes.h:946
Form_pg_class rd_rel
Definition: rel.h:109
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:370
bool volatile_defexprs
Definition: copy.c:183
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
static void CopyMultiInsertInfoInit(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, CopyState cstate, EState *estate, CommandId mycid, int ti_options)
Definition: copy.c:2427
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1178
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:209
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:151
CopyDest copy_dest
Definition: copy.c:117
ErrorContextCallback * error_context_stack
Definition: elog.c:92
uint64 cur_lineno
Definition: copy.c:160
bool trig_insert_instead_row
Definition: reltrigger.h:58
void FreeExecutorState(EState *estate)
Definition: execUtils.c:191
Relation rel
Definition: copy.c:130
#define GetPerTupleExprContext(estate)
Definition: executor.h:507
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1806
bool trig_insert_new_table
Definition: reltrigger.h:75
bool has_generated_stored
Definition: tupdesc.h:45
TupleConversionMap * pi_RootToPartitionMap
Definition: execPartition.h:37
bool ThereAreNoReadyPortals(void)
Definition: portalmem.c:1209
#define ERROR
Definition: elog.h:43
PlanState ps
Definition: execnodes.h:1164
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
bool ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2192
static bool CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
Definition: copy.c:2452
TupleConversionMap * tcs_map
Definition: trigger.h:74
static bool CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
Definition: copy.c:2464
List * ExecInsertIndexTuples(TupleTableSlot *slot, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:273
TriggerDesc * trigdesc
Definition: rel.h:115
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:1076
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2130
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1190
bool * tts_isnull
Definition: tuptable.h:128
static void CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri)
Definition: copy.c:2595
TupleConstr * constr
Definition: tupdesc.h:85
ResultRelInfo * es_result_relations
Definition: execnodes.h:522
#define RelationGetRelationName(relation)
Definition: rel.h:490
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:442
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, ModifyTableState *mtstate, Relation rel)
AttrMap * attrMap
Definition: tupconvert.h:27
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
EState * CreateExecutorState(void)
Definition: execUtils.c:89
SubTransactionId rd_createSubid
Definition: rel.h:102
Definition: copy.c:94
bool trig_insert_before_row
Definition: reltrigger.h:56
SubTransactionId rd_firstRelfilenodeSubid
Definition: rel.h:105
List * es_tupleTable
Definition: execnodes.h:554
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2181
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4310
int es_num_result_relations
Definition: execnodes.h:523
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:133
TupleConversionMap * pi_PartitionToRootMap
Definition: execPartition.h:43
TupleDesc rd_att
Definition: rel.h:110
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
bool freeze
Definition: copy.c:137
Plan * plan
Definition: execnodes.h:944
void pq_endmsgread(void)
Definition: pqcomm.c:1221
#define ereport(elevel,...)
Definition: elog.h:144
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4432
#define makeNode(_type_)
Definition: nodes.h:577
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
#define Assert(condition)
Definition: c.h:745
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1820
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:723
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2283
CopyInsertMethod
Definition: copy.c:91
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls)
Definition: copy.c:3691
static TupleTableSlot * CopyMultiInsertInfoNextFreeSlot(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copy.c:2660
static void CopyMultiInsertInfoCleanup(CopyMultiInsertInfo *miinfo)
Definition: copy.c:2641
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:226
#define InvalidSubTransactionId
Definition: c.h:526
void ReleaseBulkInsertStatePin(BulkInsertState bistate)
Definition: heapam.c:1832
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
void ExecCleanUpTriggerState(EState *estate)
Definition: execMain.c:1435
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4452
int errmsg(const char *fmt,...)
Definition: elog.c:824
void list_free(List *list)
Definition: list.c:1376
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1764
TransitionCaptureState * transition_capture
Definition: copy.c:187
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:456
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:226
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522
EndForeignInsert_function EndForeignInsert
Definition: fdwapi.h:216
TupleTableSlot * pi_PartitionTupleSlot
Definition: execPartition.h:49
TupleTableSlot * tcs_original_insert_tuple
Definition: trigger.h:83
ExprState * qualexpr
Definition: copy.c:185
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:524

◆ CopyFromErrorCallback()

void CopyFromErrorCallback ( void *  arg)

Definition at line 2284 of file copy.c.

References CopyStateData::binary, CopyStateData::cur_attname, CopyStateData::cur_attval, CopyStateData::cur_lineno, CopyStateData::cur_relname, StringInfoData::data, errcontext, limit_printout_length(), CopyStateData::line_buf, CopyStateData::line_buf_converted, CopyStateData::line_buf_valid, CopyStateData::need_transcoding, pfree(), snprintf, and UINT64_FORMAT.

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

2285 {
2286  CopyState cstate = (CopyState) arg;
2287  char curlineno_str[32];
2288 
2289  snprintf(curlineno_str, sizeof(curlineno_str), UINT64_FORMAT,
2290  cstate->cur_lineno);
2291 
2292  if (cstate->binary)
2293  {
2294  /* can't usefully display the data */
2295  if (cstate->cur_attname)
2296  errcontext("COPY %s, line %s, column %s",
2297  cstate->cur_relname, curlineno_str,
2298  cstate->cur_attname);
2299  else
2300  errcontext("COPY %s, line %s",
2301  cstate->cur_relname, curlineno_str);
2302  }
2303  else
2304  {
2305  if (cstate->cur_attname && cstate->cur_attval)
2306  {
2307  /* error is relevant to a particular column */
2308  char *attval;
2309 
2310  attval = limit_printout_length(cstate->cur_attval);
2311  errcontext("COPY %s, line %s, column %s: \"%s\"",
2312  cstate->cur_relname, curlineno_str,
2313  cstate->cur_attname, attval);
2314  pfree(attval);
2315  }
2316  else if (cstate->cur_attname)
2317  {
2318  /* error is relevant to a particular column, value is NULL */
2319  errcontext("COPY %s, line %s, column %s: null input",
2320  cstate->cur_relname, curlineno_str,
2321  cstate->cur_attname);
2322  }
2323  else
2324  {
2325  /*
2326  * Error is relevant to a particular line.
2327  *
2328  * If line_buf still contains the correct line, and it's already
2329  * transcoded, print it. If it's still in a foreign encoding, it's
2330  * quite likely that the error is precisely a failure to do
2331  * encoding conversion (ie, bad data). We dare not try to convert
2332  * it, and at present there's no way to regurgitate it without
2333  * conversion. So we have to punt and just report the line number.
2334  */
2335  if (cstate->line_buf_valid &&
2336  (cstate->line_buf_converted || !cstate->need_transcoding))
2337  {
2338  char *lineval;
2339 
2340  lineval = limit_printout_length(cstate->line_buf.data);
2341  errcontext("COPY %s, line %s: \"%s\"",
2342  cstate->cur_relname, curlineno_str, lineval);
2343  pfree(lineval);
2344  }
2345  else
2346  {
2347  errcontext("COPY %s, line %s",
2348  cstate->cur_relname, curlineno_str);
2349  }
2350  }
2351  }
2352 }
bool binary
Definition: copy.c:136
bool need_transcoding
Definition: copy.c:126
StringInfoData line_buf
Definition: copy.c:215
bool line_buf_valid
Definition: copy.c:217
bool line_buf_converted
Definition: copy.c:216
uint64 cur_lineno
Definition: copy.c:160
const char * cur_attname
Definition: copy.c:161
void pfree(void *pointer)
Definition: mcxt.c:1057
static char * limit_printout_length(const char *str)
Definition: copy.c:2360
const char * cur_relname
Definition: copy.c:159
#define errcontext
Definition: elog.h:185
struct CopyStateData * CopyState
Definition: copy.h:23
void * arg
const char * cur_attval
Definition: copy.c:162
#define snprintf
Definition: port.h:193
#define UINT64_FORMAT
Definition: c.h:417

◆ CopyGetAttnums()

static List * CopyGetAttnums ( TupleDesc  tupDesc,
Relation  rel,
List attnamelist 
)
static

Definition at line 5077 of file copy.c.

References attnum, ereport, errcode(), errdetail(), errmsg(), ERROR, i, InvalidAttrNumber, lappend_int(), lfirst, list_member_int(), name, namestrcmp(), TupleDescData::natts, NIL, RelationGetRelationName, strVal, and TupleDescAttr.

Referenced by BeginCopy(), and DoCopy().

5078 {
5079  List *attnums = NIL;
5080 
5081  if (attnamelist == NIL)
5082  {
5083  /* Generate default column list */
5084  int attr_count = tupDesc->natts;
5085  int i;
5086 
5087  for (i = 0; i < attr_count; i++)
5088  {
5089  if (TupleDescAttr(tupDesc, i)->attisdropped)
5090  continue;
5091  if (TupleDescAttr(tupDesc, i)->attgenerated)
5092  continue;
5093  attnums = lappend_int(attnums, i + 1);
5094  }
5095  }
5096  else
5097  {
5098  /* Validate the user-supplied list and extract attnums */
5099  ListCell *l;
5100 
5101  foreach(l, attnamelist)
5102  {
5103  char *name = strVal(lfirst(l));
5104  int attnum;
5105  int i;
5106 
5107  /* Lookup column name */
5108  attnum = InvalidAttrNumber;
5109  for (i = 0; i < tupDesc->natts; i++)
5110  {
5111  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
5112 
5113  if (att->attisdropped)
5114  continue;
5115  if (namestrcmp(&(att->attname), name) == 0)
5116  {
5117  if (att->attgenerated)
5118  ereport(ERROR,
5119  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
5120  errmsg("column \"%s\" is a generated column",
5121  name),
5122  errdetail("Generated columns cannot be used in COPY.")));
5123  attnum = att->attnum;
5124  break;
5125  }
5126  }
5127  if (attnum == InvalidAttrNumber)
5128  {
5129  if (rel != NULL)
5130  ereport(ERROR,
5131  (errcode(ERRCODE_UNDEFINED_COLUMN),
5132  errmsg("column \"%s\" of relation \"%s\" does not exist",
5133  name, RelationGetRelationName(rel))));
5134  else
5135  ereport(ERROR,
5136  (errcode(ERRCODE_UNDEFINED_COLUMN),
5137  errmsg("column \"%s\" does not exist",
5138  name)));
5139  }
5140  /* Check for duplicates */
5141  if (list_member_int(attnums, attnum))
5142  ereport(ERROR,
5143  (errcode(ERRCODE_DUPLICATE_COLUMN),
5144  errmsg("column \"%s\" specified more than once",
5145  name)));
5146  attnums = lappend_int(attnums, attnum);
5147  }
5148  }
5149 
5150  return attnums;
5151 }
#define NIL
Definition: pg_list.h:65
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:610
int namestrcmp(Name name, const char *str)
Definition: name.c:247
#define ERROR
Definition: elog.h:43
bool list_member_int(const List *list, int datum)
Definition: list.c:654
int errdetail(const char *fmt,...)
Definition: elog.c:957
#define RelationGetRelationName(relation)
Definition: rel.h:490
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
List * lappend_int(List *list, int datum)
Definition: list.c:339
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:144
#define lfirst(lc)
Definition: pg_list.h:190
const char * name
Definition: encode.c:561
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:824
int i
Definition: pg_list.h:50

◆ CopyGetData()

static int CopyGetData ( CopyState  cstate,
void *  databuf,
int  minread,
int  maxread 
)
static

Definition at line 619 of file copy.c.

References COPY_CALLBACK, CopyStateData::copy_dest, COPY_FILE, CopyStateData::copy_file, COPY_NEW_FE, COPY_OLD_FE, StringInfoData::cursor, CopyStateData::data_source_cb, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, CopyStateData::fe_msgbuf, HOLD_CANCEL_INTERRUPTS, StringInfoData::len, pq_copymsgbytes(), pq_getbyte(), pq_getbytes(), pq_getmessage(), pq_getmsgstring(), pq_startmsgread(), CopyStateData::reached_eof, and RESUME_CANCEL_INTERRUPTS.

Referenced by CopyLoadRawBuf().

620 {
621  int bytesread = 0;
622 
623  switch (cstate->copy_dest)
624  {
625  case COPY_FILE:
626  bytesread = fread(databuf, 1, maxread, cstate->copy_file);
627  if (ferror(cstate->copy_file))
628  ereport(ERROR,
630  errmsg("could not read from COPY file: %m")));
631  if (bytesread == 0)
632  cstate->reached_eof = true;
633  break;
634  case COPY_OLD_FE:
635 
636  /*
637  * We cannot read more than minread bytes (which in practice is 1)
638  * because old protocol doesn't have any clear way of separating
639  * the COPY stream from following data. This is slow, but not any
640  * slower than the code path was originally, and we don't care
641  * much anymore about the performance of old protocol.
642  */
643  if (pq_getbytes((char *) databuf, minread))
644  {
645  /* Only a \. terminator is legal EOF in old protocol */
646  ereport(ERROR,
647  (errcode(ERRCODE_CONNECTION_FAILURE),
648  errmsg("unexpected EOF on client connection with an open transaction")));
649  }
650  bytesread = minread;
651  break;
652  case COPY_NEW_FE:
653  while (maxread > 0 && bytesread < minread && !cstate->reached_eof)
654  {
655  int avail;
656 
657  while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
658  {
659  /* Try to receive another message */
660  int mtype;
661 
662  readmessage:
664  pq_startmsgread();
665  mtype = pq_getbyte();
666  if (mtype == EOF)
667  ereport(ERROR,
668  (errcode(ERRCODE_CONNECTION_FAILURE),
669  errmsg("unexpected EOF on client connection with an open transaction")));
670  if (pq_getmessage(cstate->fe_msgbuf, 0))
671  ereport(ERROR,
672  (errcode(ERRCODE_CONNECTION_FAILURE),
673  errmsg("unexpected EOF on client connection with an open transaction")));
675  switch (mtype)
676  {
677  case 'd': /* CopyData */
678  break;
679  case 'c': /* CopyDone */
680  /* COPY IN correctly terminated by frontend */
681  cstate->reached_eof = true;
682  return bytesread;
683  case 'f': /* CopyFail */
684  ereport(ERROR,
685  (errcode(ERRCODE_QUERY_CANCELED),
686  errmsg("COPY from stdin failed: %s",
687  pq_getmsgstring(cstate->fe_msgbuf))));
688  break;
689  case 'H': /* Flush */
690  case 'S': /* Sync */
691 
692  /*
693  * Ignore Flush/Sync for the convenience of client
694  * libraries (such as libpq) that may send those
695  * without noticing that the command they just
696  * sent was COPY.
697  */
698  goto readmessage;
699  default:
700  ereport(ERROR,
701  (errcode(ERRCODE_PROTOCOL_VIOLATION),
702  errmsg("unexpected message type 0x%02X during COPY from stdin",
703  mtype)));
704  break;
705  }
706  }
707  avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
708  if (avail > maxread)
709  avail = maxread;
710  pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
711  databuf = (void *) ((char *) databuf + avail);
712  maxread -= avail;
713  bytesread += avail;
714  }
715  break;
716  case COPY_CALLBACK:
717  bytesread = cstate->data_source_cb(databuf, minread, maxread);
718  break;
719  }
720 
721  return bytesread;
722 }
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:124
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:581
int errcode(int sqlerrcode)
Definition: elog.c:610
CopyDest copy_dest
Definition: copy.c:117
Definition: copy.c:71
copy_data_source_cb data_source_cb
Definition: copy.c:135
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1197
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1081
int errcode_for_file_access(void)
Definition: elog.c:633
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1259
int pq_getbyte(void)
Definition: pqcomm.c:987
#define ereport(elevel,...)
Definition: elog.h:144
StringInfo fe_msgbuf
Definition: copy.c:119
bool reached_eof
Definition: copy.c:122
void pq_copymsgbytes(StringInfo msg, char *buf, int datalen)
Definition: pqformat.c:530
int errmsg(const char *fmt,...)
Definition: elog.c:824
FILE * copy_file
Definition: copy.c:118
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:126

◆ CopyGetInt16()

static bool CopyGetInt16 ( CopyState  cstate,
int16 val 
)
inlinestatic

Definition at line 776 of file copy.c.

References buf, CopyReadBinaryData(), and pg_ntoh16.

Referenced by NextCopyFrom().

777 {
778  uint16 buf;
779 
780  if (CopyReadBinaryData(cstate, (char *) &buf, sizeof(buf)) != sizeof(buf))
781  {
782  *val = 0; /* suppress compiler warning */
783  return false;
784  }
785  *val = (int16) pg_ntoh16(buf);
786  return true;
787 }
signed short int16
Definition: c.h:361
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
unsigned short uint16
Definition: c.h:373
static char * buf
Definition: pg_test_fsync.c:67
static int CopyReadBinaryData(CopyState cstate, char *dest, int nbytes)
Definition: copy.c:827
long val
Definition: informix.c:664

◆ CopyGetInt32()

static bool CopyGetInt32 ( CopyState  cstate,
int32 val 
)
inlinestatic

Definition at line 747 of file copy.c.

References buf, CopyReadBinaryData(), and pg_ntoh32.

Referenced by BeginCopyFrom(), and CopyReadBinaryAttribute().

748 {
749  uint32 buf;
750 
751  if (CopyReadBinaryData(cstate, (char *) &buf, sizeof(buf)) != sizeof(buf))
752  {
753  *val = 0; /* suppress compiler warning */
754  return false;
755  }
756  *val = (int32) pg_ntoh32(buf);
757  return true;
758 }
signed int int32
Definition: c.h:362
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static char * buf
Definition: pg_test_fsync.c:67
unsigned int uint32
Definition: c.h:374
static int CopyReadBinaryData(CopyState cstate, char *dest, int nbytes)
Definition: copy.c:827
long val
Definition: informix.c:664

◆ CopyLoadRawBuf()

static bool CopyLoadRawBuf ( CopyState  cstate)
static

Definition at line 800 of file copy.c.

References CopyGetData(), CopyStateData::raw_buf, RAW_BUF_BYTES, CopyStateData::raw_buf_index, CopyStateData::raw_buf_len, and RAW_BUF_SIZE.

Referenced by CopyReadBinaryData(), CopyReadLine(), and CopyReadLineText().

801 {
802  int nbytes = RAW_BUF_BYTES(cstate);
803  int inbytes;
804 
805  /* Copy down the unprocessed data if any. */
806  if (nbytes > 0)
807  memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
808  nbytes);
809 
810  inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
811  1, RAW_BUF_SIZE - nbytes);
812  nbytes += inbytes;
813  cstate->raw_buf[nbytes] = '\0';
814  cstate->raw_buf_index = 0;
815  cstate->raw_buf_len = nbytes;
816  return (inbytes > 0);
817 }
int raw_buf_index
Definition: copy.c:229
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:619
char * raw_buf
Definition: copy.c:228
int raw_buf_len
Definition: copy.c:230
#define RAW_BUF_SIZE
Definition: copy.c:227
#define RAW_BUF_BYTES(cstate)
Definition: copy.c:232

◆ CopyMultiInsertBufferCleanup()

static void CopyMultiInsertBufferCleanup ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer 
)
inlinestatic

Definition at line 2561 of file copy.c.

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

Referenced by CopyMultiInsertInfoCleanup(), and CopyMultiInsertInfoFlush().

2563 {
2564  int i;
2565 
2566  /* Ensure buffer was flushed */
2567  Assert(buffer->nused == 0);
2568 
2569  /* Remove back-link to ourself */
2570  buffer->resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
2571 
2572  FreeBulkInsertState(buffer->bistate);
2573 
2574  /* Since we only create slots on demand, just drop the non-null ones. */
2575  for (i = 0; i < MAX_BUFFERED_TUPLES && buffer->slots[i] != NULL; i++)
2576  ExecDropSingleTupleTableSlot(buffer->slots[i]);
2577 
2579  miinfo->ti_options);
2580 
2581  pfree(buffer);
2582 }
Relation ri_RelationDesc
Definition: execnodes.h:413
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
#define MAX_BUFFERED_TUPLES
Definition: copy.c:253
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1371
ResultRelInfo * resultRelInfo
Definition: copy.c:268
void pfree(void *pointer)
Definition: mcxt.c:1057
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
BulkInsertState bistate
Definition: copy.c:269
#define Assert(condition)
Definition: c.h:745
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1820
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:267
int i

◆ CopyMultiInsertBufferFlush()

static void CopyMultiInsertBufferFlush ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer 
)
inlinestatic

Definition at line 2473 of file copy.c.

References CopyMultiInsertBuffer::bistate, CopyMultiInsertInfo::cstate, CopyStateData::cur_lineno, EState::es_result_relation_info, CopyMultiInsertInfo::estate, ExecARInsertTriggers(), ExecClearTuple(), ExecInsertIndexTuples(), GetPerTupleMemoryContext, i, CopyStateData::line_buf_valid, CopyMultiInsertBuffer::linenos, list_free(), MemoryContextSwitchTo(), CopyMultiInsertInfo::mycid, NIL, CopyMultiInsertBuffer::nused, CopyMultiInsertBuffer::resultRelInfo, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, CopyMultiInsertBuffer::slots, table_multi_insert(), CopyMultiInsertInfo::ti_options, CopyStateData::transition_capture, TriggerDesc::trig_insert_after_row, and TriggerDesc::trig_insert_new_table.

Referenced by CopyMultiInsertInfoFlush().

2475 {
2476  MemoryContext oldcontext;
2477  int i;
2478  uint64 save_cur_lineno;
2479  CopyState cstate = miinfo->cstate;
2480  EState *estate = miinfo->estate;
2481  CommandId mycid = miinfo->mycid;
2482  int ti_options = miinfo->ti_options;
2483  bool line_buf_valid = cstate->line_buf_valid;
2484  int nused = buffer->nused;
2485  ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
2486  TupleTableSlot **slots = buffer->slots;
2487 
2488  /* Set es_result_relation_info to the ResultRelInfo we're flushing. */
2489  estate->es_result_relation_info = resultRelInfo;
2490 
2491  /*
2492  * Print error context information correctly, if one of the operations
2493  * below fail.
2494  */
2495  cstate->line_buf_valid = false;
2496  save_cur_lineno = cstate->cur_lineno;
2497 
2498  /*
2499  * table_multi_insert may leak memory, so switch to short-lived memory
2500  * context before calling it.
2501  */
2502  oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2503  table_multi_insert(resultRelInfo->ri_RelationDesc,
2504  slots,
2505  nused,
2506  mycid,
2507  ti_options,
2508  buffer->bistate);
2509  MemoryContextSwitchTo(oldcontext);
2510 
2511  for (i = 0; i < nused; i++)
2512  {
2513  /*
2514  * If there are any indexes, update them for all the inserted tuples,
2515  * and run AFTER ROW INSERT triggers.
2516  */
2517  if (resultRelInfo->ri_NumIndices > 0)
2518  {
2519  List *recheckIndexes;
2520 
2521  cstate->cur_lineno = buffer->linenos[i];
2522  recheckIndexes =
2523  ExecInsertIndexTuples(buffer->slots[i], estate, false, NULL,
2524  NIL);
2525  ExecARInsertTriggers(estate, resultRelInfo,
2526  slots[i], recheckIndexes,
2527  cstate->transition_capture);
2528  list_free(recheckIndexes);
2529  }
2530 
2531  /*
2532  * There's no indexes, but see if we need to run AFTER ROW INSERT
2533  * triggers anyway.
2534  */
2535  else if (resultRelInfo->ri_TrigDesc != NULL &&
2536  (resultRelInfo->ri_TrigDesc->trig_insert_after_row ||
2537  resultRelInfo->ri_TrigDesc->trig_insert_new_table))
2538  {
2539  cstate->cur_lineno = buffer->linenos[i];
2540  ExecARInsertTriggers(estate, resultRelInfo,
2541  slots[i], NIL, cstate->transition_capture);
2542  }
2543 
2544  ExecClearTuple(slots[i]);
2545  }
2546 
2547  /* Mark that all slots are free */
2548  buffer->nused = 0;
2549 
2550  /* reset cur_lineno and line_buf_valid to what they were */
2551  cstate->line_buf_valid = line_buf_valid;
2552  cstate->cur_lineno = save_cur_lineno;
2553 }
int ri_NumIndices
Definition: execnodes.h:416
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:534
Relation ri_RelationDesc
Definition: execnodes.h:413
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2268
EState * estate
Definition: copy.c:286
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
CommandId mycid
Definition: copy.c:287
uint64 linenos[MAX_BUFFERED_TUPLES]
Definition: copy.c:271
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool line_buf_valid
Definition: copy.c:217
ResultRelInfo * resultRelInfo
Definition: copy.c:268
uint64 cur_lineno
Definition: copy.c:160
bool trig_insert_new_table
Definition: reltrigger.h:75
List * ExecInsertIndexTuples(TupleTableSlot *slot, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:273
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:1233
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:425
BulkInsertState bistate
Definition: copy.c:269
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:267
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:512
CopyState cstate
Definition: copy.c:285
void list_free(List *list)
Definition: list.c:1376
int i
TransitionCaptureState * transition_capture
Definition: copy.c:187
Definition: pg_list.h:50
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:524

◆ CopyMultiInsertBufferInit()

static CopyMultiInsertBuffer* CopyMultiInsertBufferInit ( ResultRelInfo rri)
static

Definition at line 2390 of file copy.c.

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

Referenced by CopyMultiInsertInfoSetupBuffer().

2391 {
2392  CopyMultiInsertBuffer *buffer;
2393 
2394  buffer = (CopyMultiInsertBuffer *) palloc(sizeof(CopyMultiInsertBuffer));
2395  memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
2396  buffer->resultRelInfo = rri;
2397  buffer->bistate = GetBulkInsertState();
2398  buffer->nused = 0;
2399 
2400  return buffer;
2401 }
#define MAX_BUFFERED_TUPLES
Definition: copy.c:253
ResultRelInfo * resultRelInfo
Definition: copy.c:268
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1806
BulkInsertState bistate
Definition: copy.c:269
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:267
void * palloc(Size size)
Definition: mcxt.c:950

◆ CopyMultiInsertInfoCleanup()

static void CopyMultiInsertInfoCleanup ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2641 of file copy.c.

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

Referenced by CopyFrom().

2642 {
2643  ListCell *lc;
2644 
2645  foreach(lc, miinfo->multiInsertBuffers)
2646  CopyMultiInsertBufferCleanup(miinfo, lfirst(lc));
2647 
2648  list_free(miinfo->multiInsertBuffers);
2649 }
#define lfirst(lc)
Definition: pg_list.h:190
static void CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copy.c:2561
void list_free(List *list)
Definition: list.c:1376
List * multiInsertBuffers
Definition: copy.c:282

◆ CopyMultiInsertInfoFlush()

static void CopyMultiInsertInfoFlush ( CopyMultiInsertInfo miinfo,
ResultRelInfo curr_rri 
)
inlinestatic

Definition at line 2595 of file copy.c.

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

2596 {
2597  ListCell *lc;
2598 
2599  foreach(lc, miinfo->multiInsertBuffers)
2600  {
2602 
2603  CopyMultiInsertBufferFlush(miinfo, buffer);
2604  }
2605 
2606  miinfo->bufferedTuples = 0;
2607  miinfo->bufferedBytes = 0;
2608 
2609  /*
2610  * Trim the list of tracked buffers down if it exceeds the limit. Here we
2611  * remove buffers starting with the ones we created first. It seems more
2612  * likely that these older ones are less likely to be needed than ones
2613  * that were just created.
2614  */
2616  {
2617  CopyMultiInsertBuffer *buffer;
2618 
2619  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
2620 
2621  /*
2622  * We never want to remove the buffer that's currently being used, so
2623  * if we happen to find that then move it to the end of the list.
2624  */
2625  if (buffer->resultRelInfo == curr_rri)
2626  {
2628  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
2629  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
2630  }
2631 
2632  CopyMultiInsertBufferCleanup(miinfo, buffer);
2634  }
2635 }
ResultRelInfo * resultRelInfo
Definition: copy.c:268
#define linitial(l)
Definition: pg_list.h:195
static void CopyMultiInsertBufferFlush(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copy.c:2473
List * lappend(List *list, void *datum)
Definition: list.c:321
int bufferedTuples
Definition: copy.c:283
#define MAX_PARTITION_BUFFERS
Definition: copy.c:262
#define lfirst(lc)
Definition: pg_list.h:190
static int list_length(const List *l)
Definition: pg_list.h:169
static void CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copy.c:2561
List * multiInsertBuffers
Definition: copy.c:282
List * list_delete_first(List *list)
Definition: list.c:860

◆ CopyMultiInsertInfoInit()

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

Definition at line 2427 of file copy.c.

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

2430 {
2431  miinfo->multiInsertBuffers = NIL;
2432  miinfo->bufferedTuples = 0;
2433  miinfo->bufferedBytes = 0;
2434  miinfo->cstate = cstate;
2435  miinfo->estate = estate;
2436  miinfo->mycid = mycid;
2437  miinfo->ti_options = ti_options;
2438 
2439  /*
2440  * Only setup the buffer when not dealing with a partitioned table.
2441  * Buffers for partitioned tables will just be setup when we need to send
2442  * tuples their way for the first time.
2443  */
2444  if (rri->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2445  CopyMultiInsertInfoSetupBuffer(miinfo, rri);
2446 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:413
EState * estate
Definition: copy.c:286
static void CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copy.c:2407
CommandId mycid
Definition: copy.c:287
Form_pg_class rd_rel
Definition: rel.h:109
int bufferedTuples
Definition: copy.c:283
CopyState cstate
Definition: copy.c:285
List * multiInsertBuffers
Definition: copy.c:282

◆ CopyMultiInsertInfoIsEmpty()

static bool CopyMultiInsertInfoIsEmpty ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2464 of file copy.c.

References CopyMultiInsertInfo::bufferedTuples.

Referenced by CopyFrom().

2465 {
2466  return miinfo->bufferedTuples == 0;
2467 }
int bufferedTuples
Definition: copy.c:283

◆ CopyMultiInsertInfoIsFull()

static bool CopyMultiInsertInfoIsFull ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2452 of file copy.c.

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

Referenced by CopyFrom().

2453 {
2454  if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
2455  miinfo->bufferedBytes >= MAX_BUFFERED_BYTES)
2456  return true;
2457  return false;
2458 }
#define MAX_BUFFERED_TUPLES
Definition: copy.c:253
#define MAX_BUFFERED_BYTES
Definition: copy.c:259
int bufferedTuples
Definition: copy.c:283

◆ CopyMultiInsertInfoNextFreeSlot()

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

Definition at line 2660 of file copy.c.

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

Referenced by CopyFrom().

2662 {
2664  int nused = buffer->nused;
2665 
2666  Assert(buffer != NULL);
2667  Assert(nused < MAX_BUFFERED_TUPLES);
2668 
2669  if (buffer->slots[nused] == NULL)
2670  buffer->slots[nused] = table_slot_create(rri->ri_RelationDesc, NULL);
2671  return buffer->slots[nused];
2672 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
Relation ri_RelationDesc
Definition: execnodes.h:413
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
#define MAX_BUFFERED_TUPLES
Definition: copy.c:253
#define Assert(condition)
Definition: c.h:745
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:267

◆ CopyMultiInsertInfoSetupBuffer()

static void CopyMultiInsertInfoSetupBuffer ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri 
)
inlinestatic

Definition at line 2407 of file copy.c.

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

Referenced by CopyFrom(), and CopyMultiInsertInfoInit().

2409 {
2410  CopyMultiInsertBuffer *buffer;
2411 
2412  buffer = CopyMultiInsertBufferInit(rri);
2413 
2414  /* Setup back-link so we can easily find this buffer again */
2415  rri->ri_CopyMultiInsertBuffer = buffer;
2416  /* Record that we're tracking this buffer */
2417  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
2418 }
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
List * lappend(List *list, void *datum)
Definition: list.c:321
static CopyMultiInsertBuffer * CopyMultiInsertBufferInit(ResultRelInfo *rri)
Definition: copy.c:2390
List * multiInsertBuffers
Definition: copy.c:282

◆ CopyMultiInsertInfoStore()

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

Definition at line 2679 of file copy.c.

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

Referenced by CopyFrom().

2681 {
2683 
2684  Assert(buffer != NULL);
2685  Assert(slot == buffer->slots[buffer->nused]);
2686 
2687  /* Store the line number so we can properly report any errors later */
2688  buffer->linenos[buffer->nused] = lineno;
2689 
2690  /* Record this slot as being used */
2691  buffer->nused++;
2692 
2693  /* Update how many tuples are stored and their size */
2694  miinfo->bufferedTuples++;
2695  miinfo->bufferedBytes += tuplen;
2696 }
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:490
uint64 linenos[MAX_BUFFERED_TUPLES]
Definition: copy.c:271
int bufferedTuples
Definition: copy.c:283
#define Assert(condition)
Definition: c.h:745
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:267

◆ CopyOneRowTo()

static void CopyOneRowTo ( CopyState  cstate,
TupleTableSlot slot 
)
static

Definition at line 2206 of file copy.c.

References attnum, CopyStateData::attnumlist, CopyStateData::binary, CopyAttributeOutCSV(), CopyAttributeOutText(), CopySendChar(), CopySendData(), CopySendEndOfRow(), CopySendInt16(), CopySendInt32(), CopySendString(), CopyStateData::csv_mode, cur, CopyStateData::delim, CopyStateData::force_quote_flags, lfirst_int, list_length(), MemoryContextReset(), MemoryContextSwitchTo(), CopyStateData::null_print_client, CopyStateData::out_functions, OutputFunctionCall(), CopyStateData::rowcontext, SendFunctionCall(), slot_getallattrs(), TupleTableSlot::tts_isnull, TupleTableSlot::tts_values, value, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by copy_dest_receive(), and CopyTo().

2207 {
2208  bool need_delim = false;
2209  FmgrInfo *out_functions = cstate->out_functions;
2210  MemoryContext oldcontext;
2211  ListCell *cur;
2212  char *string;
2213 
2214  MemoryContextReset(cstate->rowcontext);
2215  oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
2216 
2217  if (cstate->binary)
2218  {
2219  /* Binary per-tuple header */
2220  CopySendInt16(cstate, list_length(cstate->attnumlist));
2221  }
2222 
2223  /* Make sure the tuple is fully deconstructed */
2224  slot_getallattrs(slot);
2225 
2226  foreach(cur, cstate->attnumlist)
2227  {
2228  int attnum = lfirst_int(cur);
2229  Datum value = slot->tts_values[attnum - 1];
2230  bool isnull = slot->tts_isnull[attnum - 1];
2231 
2232  if (!cstate->binary)
2233  {
2234  if (need_delim)
2235  CopySendChar(cstate, cstate->delim[0]);
2236  need_delim = true;
2237  }
2238 
2239  if (isnull)
2240  {
2241  if (!cstate->binary)
2242  CopySendString(cstate, cstate->null_print_client);
2243  else
2244  CopySendInt32(cstate, -1);
2245  }
2246  else
2247  {
2248  if (!cstate->binary)
2249  {
2250  string = OutputFunctionCall(&out_functions[attnum - 1],
2251  value);
2252  if (cstate->csv_mode)
2253  CopyAttributeOutCSV(cstate, string,
2254  cstate->force_quote_flags[attnum - 1],
2255  list_length(cstate->attnumlist) == 1);
2256  else
2257  CopyAttributeOutText(cstate, string);
2258  }
2259  else
2260  {
2261  bytea *outputbytes;
2262 
2263  outputbytes = SendFunctionCall(&out_functions[attnum - 1],
2264  value);
2265  CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
2266  CopySendData(cstate, VARDATA(outputbytes),
2267  VARSIZE(outputbytes) - VARHDRSZ);
2268  }
2269  }
2270  }
2271 
2272  CopySendEndOfRow(cstate);
2273 
2274  MemoryContextSwitchTo(oldcontext);
2275 }
Definition: fmgr.h:56
bool csv_mode
Definition: copy.c:138
#define VARDATA(PTR)
Definition: postgres.h:302
bool binary
Definition: copy.c:136
List * attnumlist
Definition: copy.c:132
#define VARSIZE(PTR)
Definition: postgres.h:303
#define VARHDRSZ
Definition: c.h:568
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
struct cursor * cur
Definition: ecpg.c:28
static void CopyAttributeOutText(CopyState cstate, char *string)
Definition: copy.c:4828
Datum * tts_values
Definition: tuptable.h:126
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:137
bool * force_quote_flags
Definition: copy.c:148
char * delim
Definition: copy.c:143
MemoryContext rowcontext
Definition: copy.c:173
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:520
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1577
static void CopySendInt16(CopyState cstate, int16 val)
Definition: copy.c:764
#define lfirst_int(lc)
Definition: pg_list.h:191
static void CopyAttributeOutCSV(CopyState cstate, char *string, bool use_quote, bool single_attr)
Definition: copy.c:4981
static void slot_getallattrs(TupleTableSlot *slot)
Definition: tuptable.h:354
bool * tts_isnull
Definition: tuptable.h:128
char string[11]
Definition: preproc-type.c:46
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1638
uintptr_t Datum
Definition: postgres.h:367
int16 attnum
Definition: pg_attribute.h:79
static struct @143 value
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:508
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:514
static int list_length(const List *l)
Definition: pg_list.h:169
static void CopySendInt32(CopyState cstate, int32 val)
Definition: copy.c:733
FmgrInfo * out_functions
Definition: copy.c:172
static void CopySendEndOfRow(CopyState cstate)
Definition: copy.c:526
Definition: c.h:562
char * null_print_client
Definition: copy.c:142

◆ CopyReadAttributesCSV()

static int CopyReadAttributesCSV ( CopyState  cstate)
static

Definition at line 4601 of file copy.c.

References Assert, CopyStateData::attribute_buf, StringInfoData::data, CopyStateData::delim, enlargeStringInfo(), ereport, errcode(), errmsg(), ERROR, CopyStateData::escape, StringInfoData::len, CopyStateData::line_buf, CopyStateData::max_fields, StringInfoData::maxlen, CopyStateData::null_print, CopyStateData::null_print_len, CopyStateData::quote, CopyStateData::raw_fields, repalloc(), and resetStringInfo().

Referenced by NextCopyFromRawFields().

4602 {
4603  char delimc = cstate->delim[0];
4604  char quotec = cstate->quote[0];
4605  char escapec = cstate->escape[0];
4606  int fieldno;
4607  char *output_ptr;
4608  char *cur_ptr;
4609  char *line_end_ptr;
4610 
4611  /*
4612  * We need a special case for zero-column tables: check that the input
4613  * line is empty, and return.
4614  */
4615  if (cstate->max_fields <= 0)
4616  {
4617  if (cstate->line_buf.len != 0)
4618  ereport(ERROR,
4619  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4620  errmsg("extra data after last expected column")));
4621  return 0;
4622  }
4623 
4624  resetStringInfo(&cstate->attribute_buf);
4625 
4626  /*
4627  * The de-escaped attributes will certainly not be longer than the input
4628  * data line, so we can just force attribute_buf to be large enough and
4629  * then transfer data without any checks for enough space. We need to do
4630  * it this way because enlarging attribute_buf mid-stream would invalidate
4631  * pointers already stored into cstate->raw_fields[].
4632  */
4633  if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
4634  enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
4635  output_ptr = cstate->attribute_buf.data;
4636 
4637  /* set pointer variables for loop */
4638  cur_ptr = cstate->line_buf.data;
4639  line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
4640 
4641  /* Outer loop iterates over fields */
4642  fieldno = 0;
4643  for (;;)
4644  {
4645  bool found_delim = false;
4646  bool saw_quote = false;
4647  char *start_ptr;
4648  char *end_ptr;
4649  int input_len;
4650 
4651  /* Make sure there is enough space for the next value */
4652  if (fieldno >= cstate->max_fields)
4653  {
4654  cstate->max_fields *= 2;
4655  cstate->raw_fields =
4656  repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
4657  }
4658 
4659  /* Remember start of field on both input and output sides */
4660  start_ptr = cur_ptr;
4661  cstate->raw_fields[fieldno] = output_ptr;
4662 
4663  /*
4664  * Scan data for field,
4665  *
4666  * The loop starts in "not quote" mode and then toggles between that
4667  * and "in quote" mode. The loop exits normally if it is in "not
4668  * quote" mode and a delimiter or line end is seen.
4669  */
4670  for (;;)
4671  {
4672  char c;
4673 
4674  /* Not in quote */
4675  for (;;)
4676  {
4677  end_ptr = cur_ptr;
4678  if (cur_ptr >= line_end_ptr)
4679  goto endfield;
4680  c = *cur_ptr++;
4681  /* unquoted field delimiter */
4682  if (c == delimc)
4683  {
4684  found_delim = true;
4685  goto endfield;
4686  }
4687  /* start of quoted field (or part of field) */
4688  if (c == quotec)
4689  {
4690  saw_quote = true;
4691  break;
4692  }
4693  /* Add c to output string */
4694  *output_ptr++ = c;
4695  }
4696 
4697  /* In quote */
4698  for (;;)
4699  {
4700  end_ptr = cur_ptr;
4701  if (cur_ptr >= line_end_ptr)
4702  ereport(ERROR,
4703  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4704  errmsg("unterminated CSV quoted field")));
4705 
4706  c = *cur_ptr++;
4707 
4708  /* escape within a quoted field */
4709  if (c == escapec)
4710  {
4711  /*
4712  * peek at the next char if available, and escape it if it
4713  * is an escape char or a quote char
4714  */
4715  if (cur_ptr < line_end_ptr)
4716  {
4717  char nextc = *cur_ptr;
4718 
4719  if (nextc == escapec || nextc == quotec)
4720  {
4721  *output_ptr++ = nextc;
4722  cur_ptr++;
4723  continue;
4724  }
4725  }
4726  }
4727 
4728  /*
4729  * end of quoted field. Must do this test after testing for
4730  * escape in case quote char and escape char are the same
4731  * (which is the common case).
4732  */
4733  if (c == quotec)
4734  break;
4735 
4736  /* Add c to output string */
4737  *output_ptr++ = c;
4738  }
4739  }
4740 endfield:
4741 
4742  /* Terminate attribute value in output area */
4743  *output_ptr++ = '\0';
4744 
4745  /* Check whether raw input matched null marker */
4746  input_len = end_ptr - start_ptr;
4747  if (!saw_quote && input_len == cstate->null_print_len &&
4748  strncmp(start_ptr, cstate->null_print, input_len) == 0)
4749  cstate->raw_fields[fieldno] = NULL;
4750 
4751  fieldno++;
4752  /* Done if we hit EOL instead of a delim */
4753  if (!found_delim)
4754  break;
4755  }
4756 
4757  /* Clean up state of attribute_buf */
4758  output_ptr--;
4759  Assert(*output_ptr == '\0');
4760  cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
4761 
4762  return fieldno;
4763 }
char ** raw_fields
Definition: copy.c:205
StringInfoData line_buf
Definition: copy.c:215
int errcode(int sqlerrcode)
Definition: elog.c:610
char * delim
Definition: copy.c:143
char * null_print
Definition: copy.c:140
#define ERROR
Definition: elog.h:43
char * c
char * quote
Definition: copy.c:144
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
int max_fields
Definition: copy.c:204
char * escape
Definition: copy.c:145
int null_print_len
Definition: copy.c:141
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
int errmsg(const char *fmt,...)
Definition: elog.c:824
StringInfoData attribute_buf
Definition: copy.c:200

◆ CopyReadAttributesText()

static int CopyReadAttributesText ( CopyState  cstate)
static

Definition at line 4373 of file copy.c.

References Assert, CopyStateData::attribute_buf, StringInfoData::data, CopyStateData::delim, enlargeStringInfo(), ereport, errcode(), errmsg(), ERROR, GetDecimalFromHex(), IS_HIGHBIT_SET, ISOCTAL, StringInfoData::len, CopyStateData::line_buf, CopyStateData::max_fields, StringInfoData::maxlen, CopyStateData::null_print, CopyStateData::null_print_len, OCTVALUE, pg_verifymbstr(), CopyStateData::raw_fields, repalloc(), resetStringInfo(), and val.

Referenced by NextCopyFromRawFields().

4374 {
4375  char delimc = cstate->delim[0];
4376  int fieldno;
4377  char *output_ptr;
4378  char *cur_ptr;
4379  char *line_end_ptr;
4380 
4381  /*
4382  * We need a special case for zero-column tables: check that the input
4383  * line is empty, and return.
4384  */
4385  if (cstate->max_fields <= 0)
4386  {
4387  if (cstate->line_buf.len != 0)
4388  ereport(ERROR,
4389  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4390  errmsg("extra data after last expected column")));
4391  return 0;
4392  }
4393 
4394  resetStringInfo(&cstate->attribute_buf);
4395 
4396  /*
4397  * The de-escaped attributes will certainly not be longer than the input
4398  * data line, so we can just force attribute_buf to be large enough and
4399  * then transfer data without any checks for enough space. We need to do
4400  * it this way because enlarging attribute_buf mid-stream would invalidate
4401  * pointers already stored into cstate->raw_fields[].
4402  */
4403  if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
4404  enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
4405  output_ptr = cstate->attribute_buf.data;
4406 
4407  /* set pointer variables for loop */
4408  cur_ptr = cstate->line_buf.data;
4409  line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
4410 
4411  /* Outer loop iterates over fields */
4412  fieldno = 0;
4413  for (;;)
4414  {
4415  bool found_delim = false;
4416  char *start_ptr;
4417  char *end_ptr;
4418  int input_len;
4419  bool saw_non_ascii = false;
4420 
4421  /* Make sure there is enough space for the next value */
4422  if (fieldno >= cstate->max_fields)
4423  {
4424  cstate->max_fields *= 2;
4425  cstate->raw_fields =
4426  repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
4427  }
4428 
4429  /* Remember start of field on both input and output sides */
4430  start_ptr = cur_ptr;
4431  cstate->raw_fields[fieldno] = output_ptr;
4432 
4433  /*
4434  * Scan data for field.
4435  *
4436  * Note that in this loop, we are scanning to locate the end of field
4437  * and also speculatively performing de-escaping. Once we find the
4438  * end-of-field, we can match the raw field contents against the null
4439  * marker string. Only after that comparison fails do we know that
4440  * de-escaping is actually the right thing to do; therefore we *must
4441  * not* throw any syntax errors before we've done the null-marker
4442  * check.
4443  */
4444  for (;;)
4445  {
4446  char c;
4447 
4448  end_ptr = cur_ptr;
4449  if (cur_ptr >= line_end_ptr)
4450  break;
4451  c = *cur_ptr++;
4452  if (c == delimc)
4453  {
4454  found_delim = true;
4455  break;
4456  }
4457  if (c == '\\')
4458  {
4459  if (cur_ptr >= line_end_ptr)
4460  break;
4461  c = *cur_ptr++;
4462  switch (c)
4463  {
4464  case '0':
4465  case '1':
4466  case '2':
4467  case '3':
4468  case '4':
4469  case '5':
4470  case '6':
4471  case '7':
4472  {
4473  /* handle \013 */
4474  int val;
4475 
4476  val = OCTVALUE(c);
4477  if (cur_ptr < line_end_ptr)
4478  {
4479  c = *cur_ptr;
4480  if (ISOCTAL(c))
4481  {
4482  cur_ptr++;
4483  val = (val << 3) + OCTVALUE(c);
4484  if (cur_ptr < line_end_ptr)
4485  {
4486  c = *cur_ptr;
4487  if (ISOCTAL(c))
4488  {
4489  cur_ptr++;
4490  val = (val << 3) + OCTVALUE(c);
4491  }
4492  }
4493  }
4494  }
4495  c = val & 0377;
4496  if (c == '\0' || IS_HIGHBIT_SET(c))
4497  saw_non_ascii = true;
4498  }
4499  break;
4500  case 'x':
4501  /* Handle \x3F */
4502  if (cur_ptr < line_end_ptr)
4503  {
4504  char hexchar = *cur_ptr;
4505 
4506  if (isxdigit((unsigned char) hexchar))
4507  {
4508  int val = GetDecimalFromHex(hexchar);
4509 
4510  cur_ptr++;
4511  if (cur_ptr < line_end_ptr)
4512  {
4513  hexchar = *cur_ptr;
4514  if (isxdigit((unsigned char) hexchar))
4515  {
4516  cur_ptr++;
4517  val = (val << 4) + GetDecimalFromHex(hexchar);
4518  }
4519  }
4520  c = val & 0xff;
4521  if (c == '\0' || IS_HIGHBIT_SET(c))
4522  saw_non_ascii = true;
4523  }
4524  }
4525  break;
4526  case 'b':
4527  c = '\b';
4528  break;
4529  case 'f':
4530  c = '\f';
4531  break;
4532  case 'n':
4533  c = '\n';
4534  break;
4535  case 'r':
4536  c = '\r';
4537  break;
4538  case 't':
4539  c = '\t';
4540  break;
4541  case 'v':
4542  c = '\v';
4543  break;
4544 
4545  /*
4546  * in all other cases, take the char after '\'
4547  * literally
4548  */
4549  }
4550  }
4551 
4552  /* Add c to output string */
4553  *output_ptr++ = c;
4554  }
4555 
4556  /* Check whether raw input matched null marker */
4557  input_len = end_ptr - start_ptr;
4558  if (input_len == cstate->null_print_len &&
4559  strncmp(start_ptr, cstate->null_print, input_len) == 0)
4560  cstate->raw_fields[fieldno] = NULL;
4561  else
4562  {
4563  /*
4564  * At this point we know the field is supposed to contain data.
4565  *
4566  * If we de-escaped any non-7-bit-ASCII chars, make sure the
4567  * resulting string is valid data for the db encoding.
4568  */
4569  if (saw_non_ascii)
4570  {
4571  char *fld = cstate->raw_fields[fieldno];
4572 
4573  pg_verifymbstr(fld, output_ptr - fld, false);
4574  }
4575  }
4576 
4577  /* Terminate attribute value in output area */
4578  *output_ptr++ = '\0';
4579 
4580  fieldno++;
4581  /* Done if we hit EOL instead of a delim */
4582  if (!found_delim)
4583  break;
4584  }
4585 
4586  /* Clean up state of attribute_buf */
4587  output_ptr--;
4588  Assert(*output_ptr == '\0');
4589  cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
4590 
4591  return fieldno;
4592 }
static int GetDecimalFromHex(char hex)
Definition: copy.c:4345
char ** raw_fields
Definition: copy.c:205
#define ISOCTAL(c)
Definition: copy.c:62
#define OCTVALUE(c)
Definition: copy.c:63
StringInfoData line_buf
Definition: copy.c:215
int errcode(int sqlerrcode)
Definition: elog.c:610
char * delim
Definition: copy.c:143
char * null_print
Definition: copy.c:140
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1097
#define ERROR
Definition: elog.h:43
char * c
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
int max_fields
Definition: copy.c:204
int null_print_len
Definition: copy.c:141
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: mbutils.c:1446
#define ereport(elevel,...)
Definition: elog.h:144
#define Assert(condition)
Definition: c.h:745
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1070
int errmsg(const char *fmt,...)
Definition: elog.c:824
StringInfoData attribute_buf
Definition: copy.c:200
long val
Definition: informix.c:664

◆ CopyReadBinaryAttribute()

static Datum CopyReadBinaryAttribute ( CopyState  cstate,
FmgrInfo flinfo,
Oid  typioparam,
int32  typmod,
bool isnull 
)
static

Definition at line 4770 of file copy.c.

References CopyStateData::attribute_buf, CopyGetInt32(), CopyReadBinaryData(), StringInfoData::cursor, StringInfoData::data, enlargeStringInfo(), ereport, errcode(), errmsg(), ERROR, StringInfoData::len, ReceiveFunctionCall(), and resetStringInfo().

Referenced by NextCopyFrom().

4773 {
4774  int32 fld_size;
4775  Datum result;
4776 
4777  if (!CopyGetInt32(cstate, &fld_size))
4778  ereport(ERROR,
4779  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4780  errmsg("unexpected EOF in COPY data")));
4781  if (fld_size == -1)
4782  {
4783  *isnull = true;
4784  return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
4785  }
4786  if (fld_size < 0)
4787  ereport(ERROR,
4788  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4789  errmsg("invalid field size")));
4790 
4791  /* reset attribute_buf to empty, and load raw data in it */
4792  resetStringInfo(&cstate->attribute_buf);
4793 
4794  enlargeStringInfo(&cstate->attribute_buf, fld_size);
4795  if (CopyReadBinaryData(cstate, cstate->attribute_buf.data,
4796  fld_size) != fld_size)
4797  ereport(ERROR,
4798  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4799  errmsg("unexpected EOF in COPY data")));
4800 
4801  cstate->attribute_buf.len = fld_size;
4802  cstate->attribute_buf.data[fld_size] = '\0';
4803 
4804  /* Call the column type's binary input converter */
4805  result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
4806  typioparam, typmod);
4807 
4808  /* Trouble if it didn't eat the whole buffer */
4809  if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
4810  ereport(ERROR,
4811  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
4812  errmsg("incorrect binary data format")));
4813 
4814  *isnull = false;
4815  return result;
4816 }
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:747
int errcode(int sqlerrcode)
Definition: elog.c:610
signed int int32
Definition: c.h:362
#define ERROR
Definition: elog.h:43
Datum ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1591
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
static int CopyReadBinaryData(CopyState cstate, char *dest, int nbytes)
Definition: copy.c:827
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
StringInfoData attribute_buf
Definition: copy.c:200

◆ CopyReadBinaryData()

static int CopyReadBinaryData ( CopyState  cstate,
char *  dest,
int  nbytes 
)
static

Definition at line 827 of file copy.c.

References CopyLoadRawBuf(), Min, CopyStateData::raw_buf, RAW_BUF_BYTES, and CopyStateData::raw_buf_index.

Referenced by BeginCopyFrom(), CopyGetInt16(), CopyGetInt32(), CopyReadBinaryAttribute(), and NextCopyFrom().

828 {
829  int copied_bytes = 0;
830 
831  if (RAW_BUF_BYTES(cstate) >= nbytes)
832  {
833  /* Enough bytes are present in the buffer. */
834  memcpy(dest, cstate->raw_buf + cstate->raw_buf_index, nbytes);
835  cstate->raw_buf_index += nbytes;
836  copied_bytes = nbytes;
837  }
838  else
839  {
840  /*
841  * Not enough bytes in the buffer, so must read from the file. Need
842  * to loop since 'nbytes' could be larger than the buffer size.
843  */
844  do
845  {
846  int copy_bytes;
847 
848  /* Load more data if buffer is empty. */
849  if (RAW_BUF_BYTES(cstate) == 0)
850  {
851  if (!CopyLoadRawBuf(cstate))
852  break; /* EOF */
853  }
854 
855  /* Transfer some bytes. */
856  copy_bytes = Min(nbytes - copied_bytes, RAW_BUF_BYTES(cstate));
857  memcpy(dest, cstate->raw_buf + cstate->raw_buf_index, copy_bytes);
858  cstate->raw_buf_index += copy_bytes;
859  dest += copy_bytes;
860  copied_bytes += copy_bytes;
861  } while (copied_bytes < nbytes);
862  }
863 
864  return copied_bytes;
865 }
#define Min(x, y)
Definition: c.h:927
int raw_buf_index
Definition: copy.c:229
char * raw_buf
Definition: copy.c:228
static bool CopyLoadRawBuf(CopyState cstate)
Definition: copy.c:800
#define RAW_BUF_BYTES(cstate)
Definition: copy.c:232

◆ CopyReadLine()

static bool CopyReadLine ( CopyState  cstate)
static

Definition at line 3892 of file copy.c.

References appendBinaryStringInfo(), Assert, CopyStateData::copy_dest, COPY_NEW_FE, CopyLoadRawBuf(), CopyReadLineText(), StringInfoData::data, EOL_CR, EOL_CRNL, EOL_NL, CopyStateData::eol_type, EOL_UNKNOWN, CopyStateData::file_encoding, StringInfoData::len, CopyStateData::line_buf, CopyStateData::line_buf_converted, CopyStateData::line_buf_valid, CopyStateData::need_transcoding, pfree(), pg_any_to_server(), CopyStateData::raw_buf_index, CopyStateData::raw_buf_len, and resetStringInfo().

Referenced by NextCopyFromRawFields().

3893 {
3894  bool result;
3895 
3896  resetStringInfo(&cstate->line_buf);
3897  cstate->line_buf_valid = true;
3898 
3899  /* Mark that encoding conversion hasn't occurred yet */
3900  cstate->line_buf_converted = false;
3901 
3902  /* Parse data and transfer into line_buf */
3903  result = CopyReadLineText(cstate);
3904 
3905  if (result)
3906  {
3907  /*
3908  * Reached EOF. In protocol version 3, we should ignore anything
3909  * after \. up to the protocol end of copy data. (XXX maybe better
3910  * not to treat \. as special?)
3911  */
3912  if (cstate->copy_dest == COPY_NEW_FE)
3913  {
3914  do
3915  {
3916  cstate->raw_buf_index = cstate->raw_buf_len;
3917  } while (CopyLoadRawBuf(cstate));
3918  }
3919  }
3920  else
3921  {
3922  /*
3923  * If we didn't hit EOF, then we must have transferred the EOL marker
3924  * to line_buf along with the data. Get rid of it.
3925  */
3926  switch (cstate->eol_type)
3927  {
3928  case EOL_NL:
3929  Assert(cstate->line_buf.len >= 1);
3930  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3931  cstate->line_buf.len--;
3932  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3933  break;
3934  case EOL_CR:
3935  Assert(cstate->line_buf.len >= 1);
3936  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\r');
3937  cstate->line_buf.len--;
3938  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3939  break;
3940  case EOL_CRNL:
3941  Assert(cstate->line_buf.len >= 2);
3942  Assert(cstate->line_buf.data[cstate->line_buf.len - 2] == '\r');
3943  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3944  cstate->line_buf.len -= 2;
3945  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3946  break;
3947  case EOL_UNKNOWN:
3948  /* shouldn't get here */
3949  Assert(false);
3950  break;
3951  }
3952  }
3953 
3954  /* Done reading the line. Convert it to server encoding. */
3955  if (cstate->need_transcoding)
3956  {
3957  char *cvt;
3958 
3959  cvt = pg_any_to_server(cstate->line_buf.data,
3960  cstate->line_buf.len,
3961  cstate->file_encoding);
3962  if (cvt != cstate->line_buf.data)
3963  {
3964  /* transfer converted data back to line_buf */
3965  resetStringInfo(&cstate->line_buf);
3966  appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
3967  pfree(cvt);
3968  }
3969  }
3970 
3971  /* Now it's safe to use the buffer in error messages */
3972  cstate->line_buf_converted = true;
3973 
3974  return result;
3975 }
static bool CopyReadLineText(CopyState cstate)
Definition: copy.c:3981
Definition: copy.c:83
bool need_transcoding
Definition: copy.c:126
StringInfoData line_buf
Definition: copy.c:215
int raw_buf_index
Definition: copy.c:229
bool line_buf_valid
Definition: copy.c:217
bool line_buf_converted
Definition: copy.c:216
CopyDest copy_dest
Definition: copy.c:117
void pfree(void *pointer)
Definition: mcxt.c:1057
static bool CopyLoadRawBuf(CopyState cstate)
Definition: copy.c:800
Definition: copy.c:84
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
int raw_buf_len
Definition: copy.c:230
Definition: copy.c:85
int file_encoding
Definition: copy.c:125
EolType eol_type
Definition: copy.c:124
#define Assert(condition)
Definition: c.h:745
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:619
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CopyReadLineText()

static bool CopyReadLineText ( CopyState  cstate)
static

Definition at line 3981 of file copy.c.

References appendBinaryStringInfo(), CopyLoadRawBuf(), CopyStateData::csv_mode, CopyStateData::cur_lineno, CopyStateData::encoding_embeds_ascii, EOL_CR, EOL_CRNL, EOL_NL, CopyStateData::eol_type, EOL_UNKNOWN, ereport, errcode(), errhint(), errmsg(), ERROR, CopyStateData::escape, CopyStateData::file_encoding, IF_NEED_REFILL_AND_EOF_BREAK, IF_NEED_REFILL_AND_NOT_EOF_CONTINUE, IS_HIGHBIT_SET, CopyStateData::line_buf, NO_END_OF_COPY_GOTO, pg_encoding_mblen(), CopyStateData::quote, CopyStateData::raw_buf, CopyStateData::raw_buf_index, CopyStateData::raw_buf_len, and REFILL_LINEBUF.

Referenced by CopyReadLine().

3982 {
3983  char *copy_raw_buf;
3984  int raw_buf_ptr;
3985  int copy_buf_len;
3986  bool need_data = false;
3987  bool hit_eof = false;
3988  bool result = false;
3989  char mblen_str[2];
3990 
3991  /* CSV variables */
3992  bool first_char_in_line = true;
3993  bool in_quote = false,
3994  last_was_esc = false;
3995  char quotec = '\0';
3996  char escapec = '\0';
3997 
3998  if (cstate->csv_mode)
3999  {
4000  quotec = cstate->quote[0];
4001  escapec = cstate->escape[0];
4002  /* ignore special escape processing if it's the same as quotec */
4003  if (quotec == escapec)
4004  escapec = '\0';
4005  }
4006 
4007  mblen_str[1] = '\0';
4008 
4009  /*
4010  * The objective of this loop is to transfer the entire next input line
4011  * into line_buf. Hence, we only care for detecting newlines (\r and/or
4012  * \n) and the end-of-copy marker (\.).
4013  *
4014  * In CSV mode, \r and \n inside a quoted field are just part of the data
4015  * value and are put in line_buf. We keep just enough state to know if we
4016  * are currently in a quoted field or not.
4017  *
4018  * These four characters, and the CSV escape and quote characters, are
4019  * assumed the same in frontend and backend encodings.
4020  *
4021  * For speed, we try to move data from raw_buf to line_buf in chunks
4022  * rather than one character at a time. raw_buf_ptr points to the next
4023  * character to examine; any characters from raw_buf_index to raw_buf_ptr
4024  * have been determined to be part of the line, but not yet transferred to
4025  * line_buf.
4026  *
4027  * For a little extra speed within the loop, we copy raw_buf and
4028  * raw_buf_len into local variables.
4029  */
4030  copy_raw_buf = cstate->raw_buf;
4031  raw_buf_ptr = cstate->raw_buf_index;
4032  copy_buf_len = cstate->raw_buf_len;
4033 
4034  for (;;)
4035  {
4036  int prev_raw_ptr;
4037  char c;
4038 
4039  /*
4040  * Load more data if needed. Ideally we would just force four bytes
4041  * of read-ahead and avoid the many calls to
4042  * IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(), but the COPY_OLD_FE protocol
4043  * does not allow us to read too far ahead or we might read into the
4044  * next data, so we read-ahead only as far we know we can. One
4045  * optimization would be to read-ahead four byte here if
4046  * cstate->copy_dest != COPY_OLD_FE, but it hardly seems worth it,
4047  * considering the size of the buffer.
4048  */
4049  if (raw_buf_ptr >= copy_buf_len || need_data)
4050  {
4052 
4053  /*
4054  * Try to read some more data. This will certainly reset
4055  * raw_buf_index to zero, and raw_buf_ptr must go with it.
4056  */
4057  if (!CopyLoadRawBuf(cstate))
4058  hit_eof = true;
4059  raw_buf_ptr = 0;
4060  copy_buf_len = cstate->raw_buf_len;
4061 
4062  /*
4063  * If we are completely out of data, break out of the loop,
4064  * reporting EOF.
4065  */
4066  if (copy_buf_len <= 0)
4067  {
4068  result = true;
4069  break;
4070  }
4071  need_data = false;
4072  }
4073 
4074  /* OK to fetch a character */
4075  prev_raw_ptr = raw_buf_ptr;
4076  c = copy_raw_buf[raw_buf_ptr++];
4077 
4078  if (cstate->csv_mode)
4079  {
4080  /*
4081  * If character is '\\' or '\r', we may need to look ahead below.
4082  * Force fetch of the next character if we don't already have it.
4083  * We need to do this before changing CSV state, in case one of
4084  * these characters is also the quote or escape character.
4085  *
4086  * Note: old-protocol does not like forced prefetch, but it's OK
4087  * here since we cannot validly be at EOF.
4088  */
4089  if (c == '\\' || c == '\r')
4090  {
4092  }
4093 
4094  /*
4095  * Dealing with quotes and escapes here is mildly tricky. If the
4096  * quote char is also the escape char, there's no problem - we
4097  * just use the char as a toggle. If they are different, we need
4098  * to ensure that we only take account of an escape inside a
4099  * quoted field and immediately preceding a quote char, and not
4100  * the second in an escape-escape sequence.
4101  */
4102  if (in_quote && c == escapec)
4103  last_was_esc = !last_was_esc;
4104  if (c == quotec && !last_was_esc)
4105  in_quote = !in_quote;
4106  if (c != escapec)
4107  last_was_esc = false;
4108 
4109  /*
4110  * Updating the line count for embedded CR and/or LF chars is
4111  * necessarily a little fragile - this test is probably about the
4112  * best we can do. (XXX it's arguable whether we should do this
4113  * at all --- is cur_lineno a physical or logical count?)
4114  */
4115  if (in_quote && c == (cstate->eol_type == EOL_NL ? '\n' : '\r'))
4116  cstate->cur_lineno++;
4117  }
4118 
4119  /* Process \r */
4120  if (c == '\r' && (!cstate->csv_mode || !in_quote))
4121  {
4122  /* Check for \r\n on first line, _and_ handle \r\n. */
4123  if (cstate->eol_type == EOL_UNKNOWN ||
4124  cstate->eol_type == EOL_CRNL)
4125  {
4126  /*
4127  * If need more data, go back to loop top to load it.
4128  *
4129  * Note that if we are at EOF, c will wind up as '\0' because
4130  * of the guaranteed pad of raw_buf.
4131  */
4133 
4134  /* get next char */
4135  c = copy_raw_buf[raw_buf_ptr];
4136 
4137  if (c == '\n')
4138  {
4139  raw_buf_ptr++; /* eat newline */
4140  cstate->eol_type = EOL_CRNL; /* in case not set yet */
4141  }
4142  else
4143  {
4144  /* found \r, but no \n */
4145  if (cstate->eol_type == EOL_CRNL)
4146  ereport(ERROR,
4147  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4148  !cstate->csv_mode ?
4149  errmsg("literal carriage return found in data") :
4150  errmsg("unquoted carriage return found in data"),
4151  !cstate->csv_mode ?
4152  errhint("Use \"\\r\" to represent carriage return.") :
4153  errhint("Use quoted CSV field to represent carriage return.")));
4154 
4155  /*
4156  * if we got here, it is the first line and we didn't find
4157  * \n, so don't consume the peeked character
4158  */
4159  cstate->eol_type = EOL_CR;
4160  }
4161  }
4162  else if (cstate->eol_type == EOL_NL)
4163  ereport(ERROR,
4164  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4165  !cstate->csv_mode ?
4166  errmsg("literal carriage return found in data") :
4167  errmsg("unquoted carriage return found in data"),
4168  !cstate->csv_mode ?
4169  errhint("Use \"\\r\" to represent carriage return.") :
4170  errhint("Use quoted CSV field to represent carriage return.")));
4171  /* If reach here, we have found the line terminator */
4172  break;
4173  }
4174 
4175  /* Process \n */
4176  if (c == '\n' && (!cstate->csv_mode || !in_quote))
4177  {
4178  if (cstate->eol_type == EOL_CR || cstate->eol_type == EOL_CRNL)
4179  ereport(ERROR,
4180  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4181  !cstate->csv_mode ?
4182  errmsg("literal newline found in data") :
4183  errmsg("unquoted newline found in data"),
4184  !cstate->csv_mode ?
4185  errhint("Use \"\\n\" to represent newline.") :
4186  errhint("Use quoted CSV field to represent newline.")));
4187  cstate->eol_type = EOL_NL; /* in case not set yet */
4188  /* If reach here, we have found the line terminator */
4189  break;
4190  }
4191 
4192  /*
4193  * In CSV mode, we only recognize \. alone on a line. This is because
4194  * \. is a valid CSV data value.
4195  */
4196  if (c == '\\' && (!cstate->csv_mode || first_char_in_line))
4197  {
4198  char c2;
4199 
4202 
4203  /* -----
4204  * get next character
4205  * Note: we do not change c so if it isn't \., we can fall
4206  * through and continue processing for file encoding.
4207  * -----
4208  */
4209  c2 = copy_raw_buf[raw_buf_ptr];
4210 
4211  if (c2 == '.')
4212  {
4213  raw_buf_ptr++; /* consume the '.' */
4214 
4215  /*
4216  * Note: if we loop back for more data here, it does not
4217  * matter that the CSV state change checks are re-executed; we
4218  * will come back here with no important state changed.
4219  */
4220  if (cstate->eol_type == EOL_CRNL)
4221  {
4222  /* Get the next character */
4224  /* if hit_eof, c2 will become '\0' */
4225  c2 = copy_raw_buf[raw_buf_ptr++];
4226 
4227  if (c2 == '\n')
4228  {
4229  if (!cstate->csv_mode)
4230  ereport(ERROR,
4231  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4232  errmsg("end-of-copy marker does not match previous newline style")));
4233  else
4235  }
4236  else if (c2 != '\r')
4237  {
4238  if (!cstate->csv_mode)
4239  ereport(ERROR,
4240  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4241  errmsg("end-of-copy marker corrupt")));
4242  else
4244  }
4245  }
4246 
4247  /* Get the next character */
4249  /* if hit_eof, c2 will become '\0' */
4250  c2 = copy_raw_buf[raw_buf_ptr++];
4251 
4252  if (c2 != '\r' && c2 != '\n')
4253  {
4254  if (!cstate->csv_mode)
4255  ereport(ERROR,
4256  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4257  errmsg("end-of-copy marker corrupt")));
4258  else
4260  }
4261 
4262  if ((cstate->eol_type == EOL_NL && c2 != '\n') ||
4263  (cstate->eol_type == EOL_CRNL && c2 != '\n') ||
4264  (cstate->eol_type == EOL_CR && c2 != '\r'))
4265  {
4266  ereport(ERROR,
4267  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4268  errmsg("end-of-copy marker does not match previous newline style")));
4269  }
4270 
4271  /*
4272  * Transfer only the data before the \. into line_buf, then
4273  * discard the data and the \. sequence.
4274  */
4275  if (prev_raw_ptr > cstate->raw_buf_index)
4277  cstate->raw_buf + cstate->raw_buf_index,
4278  prev_raw_ptr - cstate->raw_buf_index);
4279  cstate->raw_buf_index = raw_buf_ptr;
4280  result = true; /* report EOF */
4281  break;
4282  }
4283  else if (!cstate->csv_mode)
4284 
4285  /*
4286  * If we are here, it means we found a backslash followed by
4287  * something other than a period. In non-CSV mode, anything
4288  * after a backslash is special, so we skip over that second
4289  * character too. If we didn't do that \\. would be
4290  * considered an eof-of copy, while in non-CSV mode it is a
4291  * literal backslash followed by a period. In CSV mode,
4292  * backslashes are not special, so we want to process the
4293  * character after the backslash just like a normal character,
4294  * so we don't increment in those cases.
4295  */
4296  raw_buf_ptr++;
4297  }
4298 
4299  /*
4300  * This label is for CSV cases where \. appears at the start of a
4301  * line, but there is more text after it, meaning it was a data value.
4302  * We are more strict for \. in CSV mode because \. could be a data
4303  * value, while in non-CSV mode, \. cannot be a data value.
4304  */
4305 not_end_of_copy:
4306 
4307  /*
4308  * Process all bytes of a multi-byte character as a group.
4309  *
4310  * We only support multi-byte sequences where the first byte has the
4311  * high-bit set, so as an optimization we can avoid this block
4312  * entirely if it is not set.
4313  */
4314  if (cstate->encoding_embeds_ascii && IS_HIGHBIT_SET(c))
4315  {
4316  int mblen;
4317 
4318  /*
4319  * It is enough to look at the first byte in all our encodings, to
4320  * get the length. (GB18030 is a bit special, but still works for
4321  * our purposes; see comment in pg_gb18030_mblen())
4322  */
4323  mblen_str[0] = c;
4324  mblen = pg_encoding_mblen(cstate->file_encoding, mblen_str);
4325 
4327  IF_NEED_REFILL_AND_EOF_BREAK(mblen - 1);
4328  raw_buf_ptr += mblen - 1;
4329  }
4330  first_char_in_line = false;
4331  } /* end of outer loop */
4332 
4333  /*
4334  * Transfer any still-uncopied data to line_buf.
4335  */
4337 
4338  return result;
4339 }
bool csv_mode
Definition: copy.c:138
int errhint(const char *fmt,...)
Definition: elog.c:1071
Definition: copy.c:83
StringInfoData line_buf
Definition: copy.c:215
#define IF_NEED_REFILL_AND_EOF_BREAK(extralen)
Definition: copy.c:320
int raw_buf_index
Definition: copy.c:229
int errcode(int sqlerrcode)
Definition: elog.c:610
#define REFILL_LINEBUF
Definition: copy.c:337
uint64 cur_lineno
Definition: copy.c:160
#define IS_HIGHBIT_SET(ch)
Definition: c.h:1097
#define ERROR
Definition: elog.h:43
bool encoding_embeds_ascii
Definition: copy.c:127
char * c
char * raw_buf
Definition: copy.c:228
static bool CopyLoadRawBuf(CopyState cstate)
Definition: copy.c:800
char * quote
Definition: copy.c:144
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1554
Definition: copy.c:84
int raw_buf_len
Definition: copy.c:230
char * escape
Definition: copy.c:145
Definition: copy.c:85
int file_encoding
Definition: copy.c:125
#define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen)
Definition: copy.c:308
#define ereport(elevel,...)
Definition: elog.h:144
EolType eol_type
Definition: copy.c:124
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define NO_END_OF_COPY_GOTO
Definition: copy.c:350
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CopySendChar()

static void CopySendChar ( CopyState  cstate,
char  c 
)
static

Definition at line 520 of file copy.c.

References appendStringInfoCharMacro, and CopyStateData::fe_msgbuf.

Referenced by CopyAttributeOutCSV(), CopyAttributeOutText(), CopyOneRowTo(), CopySendEndOfRow(), and CopyTo().

521 {
523 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:128
char * c
StringInfo fe_msgbuf
Definition: copy.c:119

◆ CopySendData()

static void CopySendData ( CopyState  cstate,
const void *  databuf,
int  datasize 
)
static

Definition at line 508 of file copy.c.

References appendBinaryStringInfo(), and CopyStateData::fe_msgbuf.

Referenced by CopyOneRowTo(), CopySendInt16(), CopySendInt32(), CopyTo(), and SendCopyEnd().

509 {
510  appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
511 }
StringInfo fe_msgbuf
Definition: copy.c:119
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CopySendEndOfRow()