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/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 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, int column_no, 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)
 
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 4819 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 312 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 300 of file copy.c.

Referenced by CopyReadLineText().

◆ ISOCTAL

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

Definition at line 61 of file copy.c.

Referenced by CopyReadAttributesText().

◆ MAX_BUFFERED_BYTES

#define MAX_BUFFERED_BYTES   65535

Definition at line 251 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 254 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 342 of file copy.c.

Referenced by CopyReadLineText().

◆ OCTVALUE

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

Definition at line 62 of file copy.c.

Referenced by CopyReadAttributesText().

◆ RAW_BUF_SIZE

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

Definition at line 221 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 329 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 68 of file copy.c.

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

◆ CopyInsertMethod

Enumerator
CIM_SINGLE 
CIM_MULTI 
CIM_MULTI_CONDITIONAL 

Definition at line 90 of file copy.c.

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

◆ EolType

enum EolType
Enumerator
EOL_UNKNOWN 
EOL_NL 
EOL_CR 
EOL_CRNL 

Definition at line 79 of file copy.c.

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

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

1467 {
1468  CopyState cstate;
1469  TupleDesc tupDesc;
1470  int num_phys_attrs;
1471  MemoryContext oldcontext;
1472 
1473  /* Allocate workspace and zero all fields */
1474  cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1475 
1476  /*
1477  * We allocate everything used by a cstate in a new memory context. This
1478  * avoids memory leaks during repeated use of COPY in a query.
1479  */
1481  "COPY",
1483 
1484  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1485 
1486  /* Extract options from the statement node tree */
1487  ProcessCopyOptions(pstate, cstate, is_from, options);
1488 
1489  /* Process the source/target relation or query */
1490  if (rel)
1491  {
1492  Assert(!raw_query);
1493 
1494  cstate->rel = rel;
1495 
1496  tupDesc = RelationGetDescr(cstate->rel);
1497  }
1498  else
1499  {
1500  List *rewritten;
1501  Query *query;
1502  PlannedStmt *plan;
1503  DestReceiver *dest;
1504 
1505  Assert(!is_from);
1506  cstate->rel = NULL;
1507 
1508  /*
1509  * Run parse analysis and rewrite. Note this also acquires sufficient
1510  * locks on the source table(s).
1511  *
1512  * Because the parser and planner tend to scribble on their input, we
1513  * make a preliminary copy of the source querytree. This prevents
1514  * problems in the case that the COPY is in a portal or plpgsql
1515  * function and is executed repeatedly. (See also the same hack in
1516  * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
1517  */
1518  rewritten = pg_analyze_and_rewrite(copyObject(raw_query),
1519  pstate->p_sourcetext, NULL, 0,
1520  NULL);
1521 
1522  /* check that we got back something we can work with */
1523  if (rewritten == NIL)
1524  {
1525  ereport(ERROR,
1526  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1527  errmsg("DO INSTEAD NOTHING rules are not supported for COPY")));
1528  }
1529  else if (list_length(rewritten) > 1)
1530  {
1531  ListCell *lc;
1532 
1533  /* examine queries to determine which error message to issue */
1534  foreach(lc, rewritten)
1535  {
1536  Query *q = lfirst_node(Query, lc);
1537 
1539  ereport(ERROR,
1540  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1541  errmsg("conditional DO INSTEAD rules are not supported for COPY")));
1543  ereport(ERROR,
1544  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1545  errmsg("DO ALSO rules are not supported for the COPY")));
1546  }
1547 
1548  ereport(ERROR,
1549  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1550  errmsg("multi-statement DO INSTEAD rules are not supported for COPY")));
1551  }
1552 
1553  query = linitial_node(Query, rewritten);
1554 
1555  /* The grammar allows SELECT INTO, but we don't support that */
1556  if (query->utilityStmt != NULL &&
1558  ereport(ERROR,
1559  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1560  errmsg("COPY (SELECT INTO) is not supported")));
1561 
1562  Assert(query->utilityStmt == NULL);
1563 
1564  /*
1565  * Similarly the grammar doesn't enforce the presence of a RETURNING
1566  * clause, but this is required here.
1567  */
1568  if (query->commandType != CMD_SELECT &&
1569  query->returningList == NIL)
1570  {
1571  Assert(query->commandType == CMD_INSERT ||
1572  query->commandType == CMD_UPDATE ||
1573  query->commandType == CMD_DELETE);
1574 
1575  ereport(ERROR,
1576  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1577  errmsg("COPY query must have a RETURNING clause")));
1578  }
1579 
1580  /* plan the query */
1581  plan = pg_plan_query(query, CURSOR_OPT_PARALLEL_OK, NULL);
1582 
1583  /*
1584  * With row level security and a user using "COPY relation TO", we
1585  * have to convert the "COPY relation TO" to a query-based COPY (eg:
1586  * "COPY (SELECT * FROM relation) TO"), to allow the rewriter to add
1587  * in any RLS clauses.
1588  *
1589  * When this happens, we are passed in the relid of the originally
1590  * found relation (which we have locked). As the planner will look up
1591  * the relation again, we double-check here to make sure it found the
1592  * same one that we have locked.
1593  */
1594  if (queryRelId != InvalidOid)
1595  {
1596  /*
1597  * Note that with RLS involved there may be multiple relations,
1598  * and while the one we need is almost certainly first, we don't
1599  * make any guarantees of that in the planner, so check the whole
1600  * list and make sure we find the original relation.
1601  */
1602  if (!list_member_oid(plan->relationOids, queryRelId))
1603  ereport(ERROR,
1604  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1605  errmsg("relation referenced by COPY statement has changed")));
1606  }
1607 
1608  /*
1609  * Use a snapshot with an updated command ID to ensure this query sees
1610  * results of any previously executed queries.
1611  */
1614 
1615  /* Create dest receiver for COPY OUT */
1617  ((DR_copy *) dest)->cstate = cstate;
1618 
1619  /* Create a QueryDesc requesting no output */
1620  cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
1623  dest, NULL, NULL, 0);
1624 
1625  /*
1626  * Call ExecutorStart to prepare the plan for execution.
1627  *
1628  * ExecutorStart computes a result tupdesc for us
1629  */
1630  ExecutorStart(cstate->queryDesc, 0);
1631 
1632  tupDesc = cstate->queryDesc->tupDesc;
1633  }
1634 
1635  /* Generate or convert list of attributes to process */
1636  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1637 
1638  num_phys_attrs = tupDesc->natts;
1639 
1640  /* Convert FORCE_QUOTE name list to per-column flags, check validity */
1641  cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1642  if (cstate->force_quote_all)
1643  {
1644  int i;
1645 
1646  for (i = 0; i < num_phys_attrs; i++)
1647  cstate->force_quote_flags[i] = true;
1648  }
1649  else if (cstate->force_quote)
1650  {
1651  List *attnums;
1652  ListCell *cur;
1653 
1654  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_quote);
1655 
1656  foreach(cur, attnums)
1657  {
1658  int attnum = lfirst_int(cur);
1659  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1660 
1661  if (!list_member_int(cstate->attnumlist, attnum))
1662  ereport(ERROR,
1663  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1664  errmsg("FORCE_QUOTE column \"%s\" not referenced by COPY",
1665  NameStr(attr->attname))));
1666  cstate->force_quote_flags[attnum - 1] = true;
1667  }
1668  }
1669 
1670  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1671  cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1672  if (cstate->force_notnull)
1673  {
1674  List *attnums;
1675  ListCell *cur;
1676 
1677  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_notnull);
1678 
1679  foreach(cur, attnums)
1680  {
1681  int attnum = lfirst_int(cur);
1682  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1683 
1684  if (!list_member_int(cstate->attnumlist, attnum))
1685  ereport(ERROR,
1686  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1687  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
1688  NameStr(attr->attname))));
1689  cstate->force_notnull_flags[attnum - 1] = true;
1690  }
1691  }
1692 
1693  /* Convert FORCE_NULL name list to per-column flags, check validity */
1694  cstate->force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1695  if (cstate->force_null)
1696  {
1697  List *attnums;
1698  ListCell *cur;
1699 
1700  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_null);
1701 
1702  foreach(cur, attnums)
1703  {
1704  int attnum = lfirst_int(cur);
1705  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1706 
1707  if (!list_member_int(cstate->attnumlist, attnum))
1708  ereport(ERROR,
1709  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1710  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
1711  NameStr(attr->attname))));
1712  cstate->force_null_flags[attnum - 1] = true;
1713  }
1714  }
1715 
1716  /* Convert convert_selectively name list to per-column flags */
1717  if (cstate->convert_selectively)
1718  {
1719  List *attnums;
1720  ListCell *cur;
1721 
1722  cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1723 
1724  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->convert_select);
1725 
1726  foreach(cur, attnums)
1727  {
1728  int attnum = lfirst_int(cur);
1729  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1730 
1731  if (!list_member_int(cstate->attnumlist, attnum))
1732  ereport(ERROR,
1733  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1734  errmsg_internal("selected column \"%s\" not referenced by COPY",
1735  NameStr(attr->attname))));
1736  cstate->convert_select_flags[attnum - 1] = true;
1737  }
1738  }
1739 
1740  /* Use client encoding when ENCODING option is not specified. */
1741  if (cstate->file_encoding < 0)
1743 
1744  /*
1745  * Set up encoding conversion info. Even if the file and server encodings
1746  * are the same, we must apply pg_any_to_server() to validate data in
1747  * multibyte encodings.
1748  */
1749  cstate->need_transcoding =
1750  (cstate->file_encoding != GetDatabaseEncoding() ||
1752  /* See Multibyte encoding comment above */
1754 
1755  cstate->copy_dest = COPY_FILE; /* default */
1756 
1757  MemoryContextSwitchTo(oldcontext);
1758 
1759  return cstate;
1760 }
#define NIL
Definition: pg_list.h:65
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:783
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
#define AllocSetContextCreate
Definition: memutils.h:170
#define RelationGetDescr(relation)
Definition: rel.h:448
bool need_transcoding
Definition: copy.c:125
List * attnumlist
Definition: copy.c:131
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * relationOids
Definition: plannodes.h:86
Definition: copy.c:228
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
void ProcessCopyOptions(ParseState *pstate, CopyState cstate, bool is_from, List *options)
Definition: copy.c:1109
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:841
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:608
bool * force_quote_flags
Definition: copy.c:147
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:675
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial_node(type, l)
Definition: pg_list.h:198
bool * force_null_flags
Definition: copy.c:151
bool * convert_select_flags
Definition: copy.c:154
CopyDest copy_dest
Definition: copy.c:116
Definition: copy.c:70
Relation rel
Definition: copy.c:129
MemoryContext copycontext
Definition: copy.c:166
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:191
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:771
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:130
bool list_member_int(const List *list, int datum)
Definition: list.c:655
bool encoding_embeds_ascii
Definition: copy.c:126
int pg_database_encoding_max_length(void)
Definition: wchar.c:1881
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:200
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:176
List * returningList
Definition: parsenodes.h:146
#define ereport(elevel, rest)
Definition: elog.h:141
List * force_null
Definition: copy.c:150
int file_encoding
Definition: copy.c:124
static List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:5075
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
void * palloc0(Size size)
Definition: mcxt.c:980
int GetDatabaseEncoding(void)
Definition: mbutils.c:1046
int pg_get_client_encoding(void)
Definition: mbutils.c:298
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
bool * force_notnull_flags
Definition: copy.c:149
CmdType commandType
Definition: parsenodes.h:112
List * force_notnull
Definition: copy.c:148
int errmsg_internal(const char *fmt,...)
Definition: elog.c:909
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:675
QuerySource querySource
Definition: parsenodes.h:114
#define Assert(condition)
Definition: c.h:739
List * convert_select
Definition: copy.c:153
static int list_length(const List *l)
Definition: pg_list.h:169
bool force_quote_all
Definition: copy.c:146
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2692
int errmsg(const char *fmt,...)
Definition: elog.c:822
int i
#define NameStr(name)
Definition: c.h:616
#define copyObject(obj)
Definition: nodes.h:641
Definition: pg_list.h:50
List * force_quote
Definition: copy.c:145
bool convert_selectively
Definition: copy.c:152
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:856

◆ 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 3384 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, CopyGetData(), CopyGetInt32(), 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().

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

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

1832 {
1833  CopyState cstate;
1834  bool pipe = (filename == NULL);
1835  MemoryContext oldcontext;
1836 
1837  if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
1838  {
1839  if (rel->rd_rel->relkind == RELKIND_VIEW)
1840  ereport(ERROR,
1841  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1842  errmsg("cannot copy from view \"%s\"",
1844  errhint("Try the COPY (SELECT ...) TO variant.")));
1845  else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
1846  ereport(ERROR,
1847  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1848  errmsg("cannot copy from materialized view \"%s\"",
1850  errhint("Try the COPY (SELECT ...) TO variant.")));
1851  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1852  ereport(ERROR,
1853  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1854  errmsg("cannot copy from foreign table \"%s\"",
1856  errhint("Try the COPY (SELECT ...) TO variant.")));
1857  else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
1858  ereport(ERROR,
1859  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1860  errmsg("cannot copy from sequence \"%s\"",
1861  RelationGetRelationName(rel))));
1862  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1863  ereport(ERROR,
1864  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1865  errmsg("cannot copy from partitioned table \"%s\"",
1867  errhint("Try the COPY (SELECT ...) TO variant.")));
1868  else
1869  ereport(ERROR,
1870  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1871  errmsg("cannot copy from non-table relation \"%s\"",
1872  RelationGetRelationName(rel))));
1873  }
1874 
1875  cstate = BeginCopy(pstate, false, rel, query, queryRelId, attnamelist,
1876  options);
1877  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1878 
1879  if (pipe)
1880  {
1881  Assert(!is_program); /* the grammar does not allow this */
1883  cstate->copy_file = stdout;
1884  }
1885  else
1886  {
1887  cstate->filename = pstrdup(filename);
1888  cstate->is_program = is_program;
1889 
1890  if (is_program)
1891  {
1892  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
1893  if (cstate->copy_file == NULL)
1894  ereport(ERROR,
1896  errmsg("could not execute command \"%s\": %m",
1897  cstate->filename)));
1898  }
1899  else
1900  {
1901  mode_t oumask; /* Pre-existing umask value */
1902  struct stat st;
1903 
1904  /*
1905  * Prevent write to relative path ... too easy to shoot oneself in
1906  * the foot by overwriting a database file ...
1907  */
1908  if (!is_absolute_path(filename))
1909  ereport(ERROR,
1910  (errcode(ERRCODE_INVALID_NAME),
1911  errmsg("relative path not allowed for COPY to file")));
1912 
1913  oumask = umask(S_IWGRP | S_IWOTH);
1914  PG_TRY();
1915  {
1916  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
1917  }
1918  PG_FINALLY();
1919  {
1920  umask(oumask);
1921  }
1922  PG_END_TRY();
1923  if (cstate->copy_file == NULL)
1924  {
1925  /* copy errno because ereport subfunctions might change it */
1926  int save_errno = errno;
1927 
1928  ereport(ERROR,
1930  errmsg("could not open file \"%s\" for writing: %m",
1931  cstate->filename),
1932  (save_errno == ENOENT || save_errno == EACCES) ?
1933  errhint("COPY TO instructs the PostgreSQL server process to write a file. "
1934  "You may want a client-side facility such as psql's \\copy.") : 0));
1935  }
1936 
1937  if (fstat(fileno(cstate->copy_file), &st))
1938  ereport(ERROR,
1940  errmsg("could not stat file \"%s\": %m",
1941  cstate->filename)));
1942 
1943  if (S_ISDIR(st.st_mode))
1944  ereport(ERROR,
1945  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1946  errmsg("\"%s\" is a directory", cstate->filename)));
1947  }
1948  }
1949 
1950  MemoryContextSwitchTo(oldcontext);
1951 
1952  return cstate;
1953 }
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1460
int errhint(const char *fmt,...)
Definition: elog.c:1069
char * filename
Definition: copy.c:132
char * pstrdup(const char *in)
Definition: mcxt.c:1186
#define S_IWOTH
Definition: win32_port.h:287
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:608
#define PG_BINARY_W
Definition: c.h:1225
Form_pg_class rd_rel
Definition: rel.h:83
MemoryContext copycontext
Definition: copy.c:166
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:631
#define is_absolute_path(filename)
Definition: port.h:86
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2242
#define RelationGetRelationName(relation)
Definition: rel.h:456
#define S_IWGRP
Definition: win32_port.h:275
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2345
#define ereport(elevel, rest)
Definition: elog.h:141
#define stat(a, b)
Definition: win32_port.h:255
bool is_program
Definition: copy.c:133
#define PG_FINALLY()
Definition: elog.h:339
#define Assert(condition)
Definition: c.h:739
#define S_ISDIR(m)
Definition: win32_port.h:296
static char * filename
Definition: pg_dumpall.c:90
int errmsg(const char *fmt,...)
Definition: elog.c:822
FILE * copy_file
Definition: copy.c:117
CommandDest whereToSendOutput
Definition: postgres.c:90
#define PG_TRY()
Definition: elog.h:322
#define PG_END_TRY()
Definition: elog.h:347

◆ ClosePipeToProgram()

static void ClosePipeToProgram ( CopyState  cstate)
static

Definition at line 1766 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().

1767 {
1768  int pclose_rc;
1769 
1770  Assert(cstate->is_program);
1771 
1772  pclose_rc = ClosePipeStream(cstate->copy_file);
1773  if (pclose_rc == -1)
1774  ereport(ERROR,
1776  errmsg("could not close pipe to external command: %m")));
1777  else if (pclose_rc != 0)
1778  {
1779  /*
1780  * If we ended a COPY FROM PROGRAM before reaching EOF, then it's
1781  * expectable for the called program to fail with SIGPIPE, and we
1782  * should not report that as an error. Otherwise, SIGPIPE indicates a
1783  * problem.
1784  */
1785  if (cstate->is_copy_from && !cstate->reached_eof &&
1786  wait_result_is_signal(pclose_rc, SIGPIPE))
1787  return;
1788 
1789  ereport(ERROR,
1790  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1791  errmsg("program \"%s\" failed",
1792  cstate->filename),
1793  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1794  }
1795 }
char * filename
Definition: copy.c:132
int errcode(int sqlerrcode)
Definition: elog.c:608
#define SIGPIPE
Definition: win32_port.h:159
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
int ClosePipeStream(FILE *file)
Definition: fd.c:2651
int errdetail_internal(const char *fmt,...)
Definition: elog.c:982
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:631
bool is_copy_from
Definition: copy.c:120
#define ereport(elevel, rest)
Definition: elog.h:141
bool is_program
Definition: copy.c:133
#define Assert(condition)
Definition: c.h:739
bool reached_eof
Definition: copy.c:121
int errmsg(const char *fmt,...)
Definition: elog.c:822
FILE * copy_file
Definition: copy.c:117

◆ copy_dest_destroy()

static void copy_dest_destroy ( DestReceiver self)
static

Definition at line 5190 of file copy.c.

References pfree().

Referenced by CreateCopyDestReceiver().

5191 {
5192  pfree(self);
5193 }
void pfree(void *pointer)
Definition: mcxt.c:1056

◆ copy_dest_receive()

static bool copy_dest_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 5165 of file copy.c.

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

Referenced by CreateCopyDestReceiver().

5166 {
5167  DR_copy *myState = (DR_copy *) self;
5168  CopyState cstate = myState->cstate;
5169 
5170  /* Send the data */
5171  CopyOneRowTo(cstate, slot);
5172  myState->processed++;
5173 
5174  return true;
5175 }
Definition: copy.c:228
CopyState cstate
Definition: copy.c:231
static void CopyOneRowTo(CopyState cstate, TupleTableSlot *slot)
Definition: copy.c:2158
uint64 processed
Definition: copy.c:232

◆ copy_dest_shutdown()

static void copy_dest_shutdown ( DestReceiver self)
static

Definition at line 5181 of file copy.c.

Referenced by CreateCopyDestReceiver().

5182 {
5183  /* no-op */
5184 }

◆ copy_dest_startup()

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

Definition at line 5156 of file copy.c.

Referenced by CreateCopyDestReceiver().

5157 {
5158  /* no-op */
5159 }

◆ CopyAttributeOutCSV()

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

Definition at line 4979 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().

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

◆ CopyAttributeOutText()

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

Definition at line 4826 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().

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

◆ CopyFrom()

uint64 CopyFrom ( CopyState  cstate)

Definition at line 2655 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_newRelfilenodeSubid, RelationData::rd_rel, CopyStateData::rel, RelationGetRelationName, RelationGetRelid, ReleaseBulkInsertStatePin(), ResetPerTupleExprContext, ModifyTableState::resultRelInfo, ResultRelInfo::ri_CopyMultiInsertBuffer, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_PartitionInfo, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, PlanState::state, TABLE_INSERT_FROZEN, TABLE_INSERT_SKIP_FSM, TABLE_INSERT_SKIP_WAL, 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, CopyStateData::whereClause, and XLogIsNeeded.

Referenced by copy_table(), and DoCopy().

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

◆ CopyFromErrorCallback()

void CopyFromErrorCallback ( void *  arg)

Definition at line 2236 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().

2237 {
2238  CopyState cstate = (CopyState) arg;
2239  char curlineno_str[32];
2240 
2241  snprintf(curlineno_str, sizeof(curlineno_str), UINT64_FORMAT,
2242  cstate->cur_lineno);
2243 
2244  if (cstate->binary)
2245  {
2246  /* can't usefully display the data */
2247  if (cstate->cur_attname)
2248  errcontext("COPY %s, line %s, column %s",
2249  cstate->cur_relname, curlineno_str,
2250  cstate->cur_attname);
2251  else
2252  errcontext("COPY %s, line %s",
2253  cstate->cur_relname, curlineno_str);
2254  }
2255  else
2256  {
2257  if (cstate->cur_attname && cstate->cur_attval)
2258  {
2259  /* error is relevant to a particular column */
2260  char *attval;
2261 
2262  attval = limit_printout_length(cstate->cur_attval);
2263  errcontext("COPY %s, line %s, column %s: \"%s\"",
2264  cstate->cur_relname, curlineno_str,
2265  cstate->cur_attname, attval);
2266  pfree(attval);
2267  }
2268  else if (cstate->cur_attname)
2269  {
2270  /* error is relevant to a particular column, value is NULL */
2271  errcontext("COPY %s, line %s, column %s: null input",
2272  cstate->cur_relname, curlineno_str,
2273  cstate->cur_attname);
2274  }
2275  else
2276  {
2277  /*
2278  * Error is relevant to a particular line.
2279  *
2280  * If line_buf still contains the correct line, and it's already
2281  * transcoded, print it. If it's still in a foreign encoding, it's
2282  * quite likely that the error is precisely a failure to do
2283  * encoding conversion (ie, bad data). We dare not try to convert
2284  * it, and at present there's no way to regurgitate it without
2285  * conversion. So we have to punt and just report the line number.
2286  */
2287  if (cstate->line_buf_valid &&
2288  (cstate->line_buf_converted || !cstate->need_transcoding))
2289  {
2290  char *lineval;
2291 
2292  lineval = limit_printout_length(cstate->line_buf.data);
2293  errcontext("COPY %s, line %s: \"%s\"",
2294  cstate->cur_relname, curlineno_str, lineval);
2295  pfree(lineval);
2296  }
2297  else
2298  {
2299  errcontext("COPY %s, line %s",
2300  cstate->cur_relname, curlineno_str);
2301  }
2302  }
2303  }
2304 }
bool binary
Definition: copy.c:135
bool need_transcoding
Definition: copy.c:125
StringInfoData line_buf
Definition: copy.c:210
bool line_buf_valid
Definition: copy.c:212
bool line_buf_converted
Definition: copy.c:211
uint64 cur_lineno
Definition: copy.c:159
const char * cur_attname
Definition: copy.c:160
void pfree(void *pointer)
Definition: mcxt.c:1056
static char * limit_printout_length(const char *str)
Definition: copy.c:2316
const char * cur_relname
Definition: copy.c:158
#define errcontext
Definition: elog.h:183
struct CopyStateData * CopyState
Definition: copy.h:23
void * arg
const char * cur_attval
Definition: copy.c:161
#define snprintf
Definition: port.h:192
#define UINT64_FORMAT
Definition: c.h:402

◆ CopyGetAttnums()

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

Definition at line 5075 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().

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

◆ CopyGetData()

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

Definition at line 610 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 BeginCopyFrom(), CopyGetInt16(), CopyGetInt32(), CopyLoadRawBuf(), CopyReadBinaryAttribute(), and NextCopyFrom().

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

◆ CopyGetInt16()

static bool CopyGetInt16 ( CopyState  cstate,
int16 val 
)
static

Definition at line 767 of file copy.c.

References buf, CopyGetData(), and pg_ntoh16.

Referenced by NextCopyFrom().

768 {
769  uint16 buf;
770 
771  if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
772  {
773  *val = 0; /* suppress compiler warning */
774  return false;
775  }
776  *val = (int16) pg_ntoh16(buf);
777  return true;
778 }
signed short int16
Definition: c.h:346
#define pg_ntoh16(x)
Definition: pg_bswap.h:124
unsigned short uint16
Definition: c.h:358
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:610
static char * buf
Definition: pg_test_fsync.c:67
long val
Definition: informix.c:664

◆ CopyGetInt32()

static bool CopyGetInt32 ( CopyState  cstate,
int32 val 
)
static

Definition at line 738 of file copy.c.

References buf, CopyGetData(), and pg_ntoh32.

Referenced by BeginCopyFrom(), and CopyReadBinaryAttribute().

739 {
740  uint32 buf;
741 
742  if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
743  {
744  *val = 0; /* suppress compiler warning */
745  return false;
746  }
747  *val = (int32) pg_ntoh32(buf);
748  return true;
749 }
signed int int32
Definition: c.h:347
#define pg_ntoh32(x)
Definition: pg_bswap.h:125
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:610
static char * buf
Definition: pg_test_fsync.c:67
unsigned int uint32
Definition: c.h:359
long val
Definition: informix.c:664

◆ CopyLoadRawBuf()

static bool CopyLoadRawBuf ( CopyState  cstate)
static

Definition at line 792 of file copy.c.

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

Referenced by CopyReadLine(), and CopyReadLineText().

793 {
794  int nbytes;
795  int inbytes;
796 
797  if (cstate->raw_buf_index < cstate->raw_buf_len)
798  {
799  /* Copy down the unprocessed data */
800  nbytes = cstate->raw_buf_len - cstate->raw_buf_index;
801  memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
802  nbytes);
803  }
804  else
805  nbytes = 0; /* no data need be saved */
806 
807  inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
808  1, RAW_BUF_SIZE - nbytes);
809  nbytes += inbytes;
810  cstate->raw_buf[nbytes] = '\0';
811  cstate->raw_buf_index = 0;
812  cstate->raw_buf_len = nbytes;
813  return (inbytes > 0);
814 }
int raw_buf_index
Definition: copy.c:223
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:610
char * raw_buf
Definition: copy.c:222
#define memmove(d, s, c)
Definition: c.h:1267
int raw_buf_len
Definition: copy.c:224
#define RAW_BUF_SIZE
Definition: copy.c:221

◆ CopyMultiInsertBufferCleanup()

static void CopyMultiInsertBufferCleanup ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer 
)
inlinestatic

Definition at line 2517 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().

2519 {
2520  int i;
2521 
2522  /* Ensure buffer was flushed */
2523  Assert(buffer->nused == 0);
2524 
2525  /* Remove back-link to ourself */
2526  buffer->resultRelInfo->ri_CopyMultiInsertBuffer = NULL;
2527 
2528  FreeBulkInsertState(buffer->bistate);
2529 
2530  /* Since we only create slots on demand, just drop the non-null ones. */
2531  for (i = 0; i < MAX_BUFFERED_TUPLES && buffer->slots[i] != NULL; i++)
2532  ExecDropSingleTupleTableSlot(buffer->slots[i]);
2533 
2535  miinfo->ti_options);
2536 
2537  pfree(buffer);
2538 }
Relation ri_RelationDesc
Definition: execnodes.h:410
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:487
#define MAX_BUFFERED_TUPLES
Definition: copy.c:245
static void table_finish_bulk_insert(Relation rel, int options)
Definition: tableam.h:1318
ResultRelInfo * resultRelInfo
Definition: copy.c:260
void pfree(void *pointer)
Definition: mcxt.c:1056
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
BulkInsertState bistate
Definition: copy.c:261
#define Assert(condition)
Definition: c.h:739
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1829
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:259
int i

◆ CopyMultiInsertBufferFlush()

static void CopyMultiInsertBufferFlush ( CopyMultiInsertInfo miinfo,
CopyMultiInsertBuffer buffer 
)
inlinestatic

Definition at line 2429 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().

2431 {
2432  MemoryContext oldcontext;
2433  int i;
2434  uint64 save_cur_lineno;
2435  CopyState cstate = miinfo->cstate;
2436  EState *estate = miinfo->estate;
2437  CommandId mycid = miinfo->mycid;
2438  int ti_options = miinfo->ti_options;
2439  bool line_buf_valid = cstate->line_buf_valid;
2440  int nused = buffer->nused;
2441  ResultRelInfo *resultRelInfo = buffer->resultRelInfo;
2442  TupleTableSlot **slots = buffer->slots;
2443 
2444  /* Set es_result_relation_info to the ResultRelInfo we're flushing. */
2445  estate->es_result_relation_info = resultRelInfo;
2446 
2447  /*
2448  * Print error context information correctly, if one of the operations
2449  * below fail.
2450  */
2451  cstate->line_buf_valid = false;
2452  save_cur_lineno = cstate->cur_lineno;
2453 
2454  /*
2455  * table_multi_insert may leak memory, so switch to short-lived memory
2456  * context before calling it.
2457  */
2458  oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2459  table_multi_insert(resultRelInfo->ri_RelationDesc,
2460  slots,
2461  nused,
2462  mycid,
2463  ti_options,
2464  buffer->bistate);
2465  MemoryContextSwitchTo(oldcontext);
2466 
2467  for (i = 0; i < nused; i++)
2468  {
2469  /*
2470  * If there are any indexes, update them for all the inserted tuples,
2471  * and run AFTER ROW INSERT triggers.
2472  */
2473  if (resultRelInfo->ri_NumIndices > 0)
2474  {
2475  List *recheckIndexes;
2476 
2477  cstate->cur_lineno = buffer->linenos[i];
2478  recheckIndexes =
2479  ExecInsertIndexTuples(buffer->slots[i], estate, false, NULL,
2480  NIL);
2481  ExecARInsertTriggers(estate, resultRelInfo,
2482  slots[i], recheckIndexes,
2483  cstate->transition_capture);
2484  list_free(recheckIndexes);
2485  }
2486 
2487  /*
2488  * There's no indexes, but see if we need to run AFTER ROW INSERT
2489  * triggers anyway.
2490  */
2491  else if (resultRelInfo->ri_TrigDesc != NULL &&
2492  (resultRelInfo->ri_TrigDesc->trig_insert_after_row ||
2493  resultRelInfo->ri_TrigDesc->trig_insert_new_table))
2494  {
2495  cstate->cur_lineno = buffer->linenos[i];
2496  ExecARInsertTriggers(estate, resultRelInfo,
2497  slots[i], NIL, cstate->transition_capture);
2498  }
2499 
2500  ExecClearTuple(slots[i]);
2501  }
2502 
2503  /* Mark that all slots are free */
2504  buffer->nused = 0;
2505 
2506  /* reset cur_lineno and line_buf_valid to what they were */
2507  cstate->line_buf_valid = line_buf_valid;
2508  cstate->cur_lineno = save_cur_lineno;
2509 }
int ri_NumIndices
Definition: execnodes.h:413
#define NIL
Definition: pg_list.h:65
uint32 CommandId
Definition: c.h:528
Relation ri_RelationDesc
Definition: execnodes.h:410
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2599
EState * estate
Definition: copy.c:278
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
CommandId mycid
Definition: copy.c:279
uint64 linenos[MAX_BUFFERED_TUPLES]
Definition: copy.c:263
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool line_buf_valid
Definition: copy.c:212
ResultRelInfo * resultRelInfo
Definition: copy.c:260
uint64 cur_lineno
Definition: copy.c:159
bool trig_insert_new_table
Definition: reltrigger.h:74
List * ExecInsertIndexTuples(TupleTableSlot *slot, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:273
bool trig_insert_after_row
Definition: reltrigger.h:56
static void table_multi_insert(Relation rel, TupleTableSlot **slots, int nslots, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1178
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:422
BulkInsertState bistate
Definition: copy.c:261
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:259
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:506
CopyState cstate
Definition: copy.c:277
void list_free(List *list)
Definition: list.c:1377
int i
TransitionCaptureState * transition_capture
Definition: copy.c:186
Definition: pg_list.h:50
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:521

◆ CopyMultiInsertBufferInit()

static CopyMultiInsertBuffer* CopyMultiInsertBufferInit ( ResultRelInfo rri)
static

Definition at line 2346 of file copy.c.

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

Referenced by CopyMultiInsertInfoSetupBuffer().

2347 {
2348  CopyMultiInsertBuffer *buffer;
2349 
2350  buffer = (CopyMultiInsertBuffer *) palloc(sizeof(CopyMultiInsertBuffer));
2351  memset(buffer->slots, 0, sizeof(TupleTableSlot *) * MAX_BUFFERED_TUPLES);
2352  buffer->resultRelInfo = rri;
2353  buffer->bistate = GetBulkInsertState();
2354  buffer->nused = 0;
2355 
2356  return buffer;
2357 }
#define MAX_BUFFERED_TUPLES
Definition: copy.c:245
ResultRelInfo * resultRelInfo
Definition: copy.c:260
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1815
BulkInsertState bistate
Definition: copy.c:261
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:259
void * palloc(Size size)
Definition: mcxt.c:949

◆ CopyMultiInsertInfoCleanup()

static void CopyMultiInsertInfoCleanup ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2597 of file copy.c.

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

Referenced by CopyFrom().

2598 {
2599  ListCell *lc;
2600 
2601  foreach(lc, miinfo->multiInsertBuffers)
2602  CopyMultiInsertBufferCleanup(miinfo, lfirst(lc));
2603 
2604  list_free(miinfo->multiInsertBuffers);
2605 }
#define lfirst(lc)
Definition: pg_list.h:190
static void CopyMultiInsertBufferCleanup(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copy.c:2517
void list_free(List *list)
Definition: list.c:1377
List * multiInsertBuffers
Definition: copy.c:274

◆ CopyMultiInsertInfoFlush()

static void CopyMultiInsertInfoFlush ( CopyMultiInsertInfo miinfo,
ResultRelInfo curr_rri 
)
inlinestatic

Definition at line 2551 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().

2552 {
2553  ListCell *lc;
2554 
2555  foreach(lc, miinfo->multiInsertBuffers)
2556  {
2558 
2559  CopyMultiInsertBufferFlush(miinfo, buffer);
2560  }
2561 
2562  miinfo->bufferedTuples = 0;
2563  miinfo->bufferedBytes = 0;
2564 
2565  /*
2566  * Trim the list of tracked buffers down if it exceeds the limit. Here we
2567  * remove buffers starting with the ones we created first. It seems more
2568  * likely that these older ones are less likely to be needed than ones
2569  * that were just created.
2570  */
2572  {
2573  CopyMultiInsertBuffer *buffer;
2574 
2575  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
2576 
2577  /*
2578  * We never want to remove the buffer that's currently being used, so
2579  * if we happen to find that then move it to the end of the list.
2580  */
2581  if (buffer->resultRelInfo == curr_rri)
2582  {
2584  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
2585  buffer = (CopyMultiInsertBuffer *) linitial(miinfo->multiInsertBuffers);
2586  }
2587 
2588  CopyMultiInsertBufferCleanup(miinfo, buffer);
2590  }
2591 }
ResultRelInfo * resultRelInfo
Definition: copy.c:260
#define linitial(l)
Definition: pg_list.h:195
static void CopyMultiInsertBufferFlush(CopyMultiInsertInfo *miinfo, CopyMultiInsertBuffer *buffer)
Definition: copy.c:2429
List * lappend(List *list, void *datum)
Definition: list.c:322
int bufferedTuples
Definition: copy.c:275
#define MAX_PARTITION_BUFFERS
Definition: copy.c:254
#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:2517
List * multiInsertBuffers
Definition: copy.c:274
List * list_delete_first(List *list)
Definition: list.c:861

◆ CopyMultiInsertInfoInit()

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

Definition at line 2383 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().

2386 {
2387  miinfo->multiInsertBuffers = NIL;
2388  miinfo->bufferedTuples = 0;
2389  miinfo->bufferedBytes = 0;
2390  miinfo->cstate = cstate;
2391  miinfo->estate = estate;
2392  miinfo->mycid = mycid;
2393  miinfo->ti_options = ti_options;
2394 
2395  /*
2396  * Only setup the buffer when not dealing with a partitioned table.
2397  * Buffers for partitioned tables will just be setup when we need to send
2398  * tuples their way for the first time.
2399  */
2400  if (rri->ri_RelationDesc->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
2401  CopyMultiInsertInfoSetupBuffer(miinfo, rri);
2402 }
#define NIL
Definition: pg_list.h:65
Relation ri_RelationDesc
Definition: execnodes.h:410
EState * estate
Definition: copy.c:278
static void CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copy.c:2363
CommandId mycid
Definition: copy.c:279
Form_pg_class rd_rel
Definition: rel.h:83
int bufferedTuples
Definition: copy.c:275
CopyState cstate
Definition: copy.c:277
List * multiInsertBuffers
Definition: copy.c:274

◆ CopyMultiInsertInfoIsEmpty()

static bool CopyMultiInsertInfoIsEmpty ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2420 of file copy.c.

References CopyMultiInsertInfo::bufferedTuples.

Referenced by CopyFrom().

2421 {
2422  return miinfo->bufferedTuples == 0;
2423 }
int bufferedTuples
Definition: copy.c:275

◆ CopyMultiInsertInfoIsFull()

static bool CopyMultiInsertInfoIsFull ( CopyMultiInsertInfo miinfo)
inlinestatic

Definition at line 2408 of file copy.c.

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

Referenced by CopyFrom().

2409 {
2410  if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
2411  miinfo->bufferedBytes >= MAX_BUFFERED_BYTES)
2412  return true;
2413  return false;
2414 }
#define MAX_BUFFERED_TUPLES
Definition: copy.c:245
#define MAX_BUFFERED_BYTES
Definition: copy.c:251
int bufferedTuples
Definition: copy.c:275

◆ CopyMultiInsertInfoNextFreeSlot()

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

Definition at line 2613 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().

2615 {
2617  int nused = buffer->nused;
2618 
2619  Assert(buffer != NULL);
2620  Assert(nused < MAX_BUFFERED_TUPLES);
2621 
2622  if (buffer->slots[nused] == NULL)
2623  buffer->slots[nused] = table_slot_create(rri->ri_RelationDesc, NULL);
2624  return buffer->slots[nused];
2625 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:77
Relation ri_RelationDesc
Definition: execnodes.h:410
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:487
#define MAX_BUFFERED_TUPLES
Definition: copy.c:245
#define Assert(condition)
Definition: c.h:739
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:259

◆ CopyMultiInsertInfoSetupBuffer()

static void CopyMultiInsertInfoSetupBuffer ( CopyMultiInsertInfo miinfo,
ResultRelInfo rri 
)
inlinestatic

Definition at line 2363 of file copy.c.

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

Referenced by CopyFrom(), and CopyMultiInsertInfoInit().

2365 {
2366  CopyMultiInsertBuffer *buffer;
2367 
2368  buffer = CopyMultiInsertBufferInit(rri);
2369 
2370  /* Setup back-link so we can easily find this buffer again */
2371  rri->ri_CopyMultiInsertBuffer = buffer;
2372  /* Record that we're tracking this buffer */
2373  miinfo->multiInsertBuffers = lappend(miinfo->multiInsertBuffers, buffer);
2374 }
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:487
List * lappend(List *list, void *datum)
Definition: list.c:322
static CopyMultiInsertBuffer * CopyMultiInsertBufferInit(ResultRelInfo *rri)
Definition: copy.c:2346
List * multiInsertBuffers
Definition: copy.c:274

◆ CopyMultiInsertInfoStore()

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

Definition at line 2632 of file copy.c.

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

Referenced by CopyFrom().

2634 {
2636 
2637  Assert(buffer != NULL);
2638  Assert(slot == buffer->slots[buffer->nused]);
2639 
2640  /* Store the line number so we can properly report any errors later */
2641  buffer->linenos[buffer->nused] = lineno;
2642 
2643  /* Record this slot as being used */
2644  buffer->nused++;
2645 
2646  /* Update how many tuples are stored and their size */
2647  miinfo->bufferedTuples++;
2648  miinfo->bufferedBytes += tuplen;
2649 }
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:487
uint64 linenos[MAX_BUFFERED_TUPLES]
Definition: copy.c:263
int bufferedTuples
Definition: copy.c:275
#define Assert(condition)
Definition: c.h:739
TupleTableSlot * slots[MAX_BUFFERED_TUPLES]
Definition: copy.c:259

◆ CopyOneRowTo()

static void CopyOneRowTo ( CopyState  cstate,
TupleTableSlot slot 
)
static

Definition at line 2158 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().

2159 {
2160  bool need_delim = false;
2161  FmgrInfo *out_functions = cstate->out_functions;
2162  MemoryContext oldcontext;
2163  ListCell *cur;
2164  char *string;
2165 
2166  MemoryContextReset(cstate->rowcontext);
2167  oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
2168 
2169  if (cstate->binary)
2170  {
2171  /* Binary per-tuple header */
2172  CopySendInt16(cstate, list_length(cstate->attnumlist));
2173  }
2174 
2175  /* Make sure the tuple is fully deconstructed */
2176  slot_getallattrs(slot);
2177 
2178  foreach(cur, cstate->attnumlist)
2179  {
2180  int attnum = lfirst_int(cur);
2181  Datum value = slot->tts_values[attnum - 1];
2182  bool isnull = slot->tts_isnull[attnum - 1];
2183 
2184  if (!cstate->binary)
2185  {
2186  if (need_delim)
2187  CopySendChar(cstate, cstate->delim[0]);
2188  need_delim = true;
2189  }
2190 
2191  if (isnull)
2192  {
2193  if (!cstate->binary)
2194  CopySendString(cstate, cstate->null_print_client);
2195  else
2196  CopySendInt32(cstate, -1);
2197  }
2198  else
2199  {
2200  if (!cstate->binary)
2201  {
2202  string = OutputFunctionCall(&out_functions[attnum - 1],
2203  value);
2204  if (cstate->csv_mode)
2205  CopyAttributeOutCSV(cstate, string,
2206  cstate->force_quote_flags[attnum - 1],
2207  list_length(cstate->attnumlist) == 1);
2208  else
2209  CopyAttributeOutText(cstate, string);
2210  }
2211  else
2212  {
2213  bytea *outputbytes;
2214 
2215  outputbytes = SendFunctionCall(&out_functions[attnum - 1],
2216  value);
2217  CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
2218  CopySendData(cstate, VARDATA(outputbytes),
2219  VARSIZE(outputbytes) - VARHDRSZ);
2220  }
2221  }
2222  }
2223 
2224  CopySendEndOfRow(cstate);
2225 
2226  MemoryContextSwitchTo(oldcontext);
2227 }
Definition: fmgr.h:56
bool csv_mode
Definition: copy.c:137
#define VARDATA(PTR)
Definition: postgres.h:302
bool binary
Definition: copy.c:135
List * attnumlist
Definition: copy.c:131
#define VARSIZE(PTR)
Definition: postgres.h:303
#define VARHDRSZ
Definition: c.h:562
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static struct @145 value
struct cursor * cur
Definition: ecpg.c:28
static void CopyAttributeOutText(CopyState cstate, char *string)
Definition: copy.c:4826
Datum * tts_values
Definition: tuptable.h:126
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:136
bool * force_quote_flags
Definition: copy.c:147
char * delim
Definition: copy.c:142
MemoryContext rowcontext
Definition: copy.c:172
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:511
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1575
static void CopySendInt16(CopyState cstate, int16 val)
Definition: copy.c:755
#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:4979
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:1636
uintptr_t Datum
Definition: postgres.h:367
int16 attnum
Definition: pg_attribute.h:79
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:499
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:505
static int list_length(const List *l)
Definition: pg_list.h:169
static void CopySendInt32(CopyState cstate, int32 val)
Definition: copy.c:724
FmgrInfo * out_functions
Definition: copy.c:171
static void CopySendEndOfRow(CopyState cstate)
Definition: copy.c:517
Definition: c.h:556
char * null_print_client
Definition: copy.c:141

◆ CopyReadAttributesCSV()

static int CopyReadAttributesCSV ( CopyState  cstate)
static

Definition at line 4598 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().

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

◆ CopyReadAttributesText()

static int CopyReadAttributesText ( CopyState  cstate)
static

Definition at line 4370 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().

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

◆ CopyReadBinaryAttribute()

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

Definition at line 4767 of file copy.c.

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

Referenced by NextCopyFrom().

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

◆ CopyReadLine()

static bool CopyReadLine ( CopyState  cstate)
static

Definition at line 3889 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().

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

◆ CopyReadLineText()

static bool CopyReadLineText ( CopyState  cstate)
static

Definition at line 3978 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().

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

References appendStringInfoCharMacro, and CopyStateData::fe_msgbuf.

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

512 {
514 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:128
char * c
StringInfo fe_msgbuf
Definition: copy.c:118

◆ CopySendData()

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

Definition at line 499 of file copy.c.

References appendBinaryStringInfo(), and CopyStateData::fe_msgbuf.

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

500 {
501  appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
502 }
StringInfo fe_msgbuf
Definition: copy.c:118
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:227

◆ CopySendEndOfRow()

static void CopySendEndOfRow ( CopyState  cstate)
static

Definition at line 517 of file copy.c.

References Assert, CopyStateData::binary, ClosePipeToProgram(), COPY_CALLBACK, CopyStateData::copy_dest, COPY_FILE, CopyStateData::copy_file, COPY_NEW_FE, COPY_OLD_FE, CopySendChar(), CopySendString(), StringInfoData::data, ereport, errcode(), errcode_for_file_access(), errmsg(), ERROR, FATAL, CopyStateData::fe_msgbuf, CopyStateData::is_program, StringInfoData::len, pq_putbytes(), pq_putmessage, and resetStringInfo().

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

518 {
519  StringInfo fe_msgbuf = cstate->fe_msgbuf;
520 
521  switch (cstate->copy_dest)
522  {
523  case COPY_FILE:
524  if (!cstate->binary)
525  {
526  /* Default line termination depends on platform */
527 #ifndef WIN32
528  CopySendChar(cstate, '\n');
529 #else
530  CopySendString(cstate, "\r\n");
531 #endif
532  }
533 
534  if (fwrite(fe_msgbuf->data, fe_msgbuf->len, 1,
535  cstate->copy_file) != 1 ||
536  ferror(cstate->copy_file))
537  {
538  if (cstate->