PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
copy.c File Reference
#include "postgres.h"
#include <ctype.h>
#include <unistd.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/sysattr.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "catalog/pg_type.h"
#include "commands/copy.h"
#include "commands/defrem.h"
#include "commands/trigger.h"
#include "executor/executor.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "miscadmin.h"
#include "optimizer/clauses.h"
#include "optimizer/planner.h"
#include "nodes/makefuncs.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/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
 

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 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 MAX_BUFFERED_TUPLES   1000
 
#define DUMPSOFAR()
 

Typedefs

typedef enum CopyDest CopyDest
 
typedef enum EolType EolType
 
typedef struct CopyStateData CopyStateData
 

Enumerations

enum  CopyDest { COPY_FILE, COPY_OLD_FE, COPY_NEW_FE }
 
enum  EolType { EOL_UNKNOWN, EOL_NL, EOL_CR, EOL_CRNL }
 

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, Oid tupleOid, Datum *values, bool *nulls)
 
static uint64 CopyFrom (CopyState cstate)
 
static void CopyFromInsertBatch (CopyState cstate, EState *estate, CommandId mycid, int hi_options, ResultRelInfo *resultRelInfo, TupleTableSlot *myslot, BulkInsertState bistate, int nBufferedTuples, HeapTuple *bufferedTuples, int firstBufferedLineNo)
 
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)
 
CopyState BeginCopyFrom (ParseState *pstate, Relation rel, const char *filename, bool is_program, List *attnamelist, List *options)
 
bool NextCopyFromRawFields (CopyState cstate, char ***fields, int *nfields)
 
bool NextCopyFrom (CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
 
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

#define DUMPSOFAR ( )
Value:
do { \
if (ptr > start) \
CopySendData(cstate, start, ptr - start); \
} while (0)
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:443

Definition at line 4359 of file copy.c.

Referenced by CopyAttributeOutCSV(), and CopyAttributeOutText().

#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 248 of file copy.c.

Referenced by CopyReadLineText().

#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 236 of file copy.c.

Referenced by CopyReadLineText().

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

Definition at line 52 of file copy.c.

Referenced by CopyReadAttributesText().

#define MAX_BUFFERED_TUPLES   1000

Referenced by CopyFrom().

#define MAX_COPY_DATA_DISPLAY   100

Referenced by limit_printout_length().

#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 278 of file copy.c.

Referenced by CopyReadLineText().

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

Definition at line 53 of file copy.c.

Referenced by CopyReadAttributesText().

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

Definition at line 205 of file copy.c.

Referenced by BeginCopyFrom(), and CopyLoadRawBuf().

#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)
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240

Definition at line 265 of file copy.c.

Referenced by CopyReadLineText().

Typedef Documentation

Enumeration Type Documentation

enum CopyDest
Enumerator
COPY_FILE 
COPY_OLD_FE 
COPY_NEW_FE 

Definition at line 59 of file copy.c.

60 {
61  COPY_FILE, /* to/from file (or a piped program) */
62  COPY_OLD_FE, /* to/from frontend (2.0 protocol) */
63  COPY_NEW_FE /* to/from frontend (3.0 protocol) */
64 } CopyDest;
Definition: copy.c:61
CopyDest
Definition: copy.c:59
enum EolType
Enumerator
EOL_UNKNOWN 
EOL_NL 
EOL_CR 
EOL_CRNL 

Definition at line 69 of file copy.c.

70 {
72  EOL_NL,
73  EOL_CR,
74  EOL_CRNL
75 } EolType;
Definition: copy.c:72
EolType
Definition: copy.c:69
Definition: copy.c:73
Definition: copy.c:74

Function Documentation

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

Definition at line 1370 of file copy.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), Assert, CopyStateData::attnumlist, tupleDesc::attrs, castNode, 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, DestCopyOut, CopyStateData::encoding_embeds_ascii, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, ExecSetupPartitionTupleRouting(), 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, lfirst_int, linitial, list_length(), list_member_int(), list_member_oid(), MemoryContextSwitchTo(), NameStr, tupleDesc::natts, CopyStateData::need_transcoding, NIL, NULL, CopyStateData::num_dispatch, CopyStateData::num_partitions, CopyStateData::oids, ParseState::p_sourcetext, palloc0(), CopyStateData::partition_dispatch_info, CopyStateData::partition_tupconv_maps, CopyStateData::partition_tuple_slot, CopyStateData::partitions, 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, RelationData::rd_rel, CopyStateData::rel, RelationGetDescr, RelationGetRelationName, PlannedStmt::relationOids, RELKIND_PARTITIONED_TABLE, Query::returningList, QueryDesc::tupDesc, UpdateActiveSnapshotCommandId(), and Query::utilityStmt.

Referenced by BeginCopyFrom(), and BeginCopyTo().

1377 {
1378  CopyState cstate;
1379  TupleDesc tupDesc;
1380  int num_phys_attrs;
1381  MemoryContext oldcontext;
1382 
1383  /* Allocate workspace and zero all fields */
1384  cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1385 
1386  /*
1387  * We allocate everything used by a cstate in a new memory context. This
1388  * avoids memory leaks during repeated use of COPY in a query.
1389  */
1391  "COPY",
1393 
1394  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1395 
1396  /* Extract options from the statement node tree */
1397  ProcessCopyOptions(pstate, cstate, is_from, options);
1398 
1399  /* Process the source/target relation or query */
1400  if (rel)
1401  {
1402  Assert(!raw_query);
1403 
1404  cstate->rel = rel;
1405 
1406  tupDesc = RelationGetDescr(cstate->rel);
1407 
1408  /* Don't allow COPY w/ OIDs to or from a table without them */
1409  if (cstate->oids && !cstate->rel->rd_rel->relhasoids)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_UNDEFINED_COLUMN),
1412  errmsg("table \"%s\" does not have OIDs",
1413  RelationGetRelationName(cstate->rel))));
1414 
1415  /* Initialize state for CopyFrom tuple routing. */
1416  if (is_from && rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1417  {
1418  PartitionDispatch *partition_dispatch_info;
1419  ResultRelInfo *partitions;
1420  TupleConversionMap **partition_tupconv_maps;
1421  TupleTableSlot *partition_tuple_slot;
1422  int num_parted,
1423  num_partitions;
1424 
1426  &partition_dispatch_info,
1427  &partitions,
1428  &partition_tupconv_maps,
1429  &partition_tuple_slot,
1430  &num_parted, &num_partitions);
1431  cstate->partition_dispatch_info = partition_dispatch_info;
1432  cstate->num_dispatch = num_parted;
1433  cstate->partitions = partitions;
1434  cstate->num_partitions = num_partitions;
1435  cstate->partition_tupconv_maps = partition_tupconv_maps;
1436  cstate->partition_tuple_slot = partition_tuple_slot;
1437  }
1438  }
1439  else
1440  {
1441  List *rewritten;
1442  Query *query;
1443  PlannedStmt *plan;
1444  DestReceiver *dest;
1445 
1446  Assert(!is_from);
1447  cstate->rel = NULL;
1448 
1449  /* Don't allow COPY w/ OIDs from a query */
1450  if (cstate->oids)
1451  ereport(ERROR,
1452  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1453  errmsg("COPY (query) WITH OIDS is not supported")));
1454 
1455  /*
1456  * Run parse analysis and rewrite. Note this also acquires sufficient
1457  * locks on the source table(s).
1458  *
1459  * Because the parser and planner tend to scribble on their input, we
1460  * make a preliminary copy of the source querytree. This prevents
1461  * problems in the case that the COPY is in a portal or plpgsql
1462  * function and is executed repeatedly. (See also the same hack in
1463  * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
1464  */
1465  rewritten = pg_analyze_and_rewrite((RawStmt *) copyObject(raw_query),
1466  pstate->p_sourcetext, NULL, 0);
1467 
1468  /* check that we got back something we can work with */
1469  if (rewritten == NIL)
1470  {
1471  ereport(ERROR,
1472  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1473  errmsg("DO INSTEAD NOTHING rules are not supported for COPY")));
1474  }
1475  else if (list_length(rewritten) > 1)
1476  {
1477  ListCell *lc;
1478 
1479  /* examine queries to determine which error message to issue */
1480  foreach(lc, rewritten)
1481  {
1482  Query *q = castNode(Query, lfirst(lc));
1483 
1485  ereport(ERROR,
1486  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1487  errmsg("conditional DO INSTEAD rules are not supported for COPY")));
1489  ereport(ERROR,
1490  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1491  errmsg("DO ALSO rules are not supported for the COPY")));
1492  }
1493 
1494  ereport(ERROR,
1495  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1496  errmsg("multi-statement DO INSTEAD rules are not supported for COPY")));
1497  }
1498 
1499  query = castNode(Query, linitial(rewritten));
1500 
1501  /* The grammar allows SELECT INTO, but we don't support that */
1502  if (query->utilityStmt != NULL &&
1504  ereport(ERROR,
1505  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1506  errmsg("COPY (SELECT INTO) is not supported")));
1507 
1508  Assert(query->utilityStmt == NULL);
1509 
1510  /*
1511  * Similarly the grammar doesn't enforce the presence of a RETURNING
1512  * clause, but this is required here.
1513  */
1514  if (query->commandType != CMD_SELECT &&
1515  query->returningList == NIL)
1516  {
1517  Assert(query->commandType == CMD_INSERT ||
1518  query->commandType == CMD_UPDATE ||
1519  query->commandType == CMD_DELETE);
1520 
1521  ereport(ERROR,
1522  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1523  errmsg("COPY query must have a RETURNING clause")));
1524  }
1525 
1526  /* plan the query */
1527  plan = pg_plan_query(query, 0, NULL);
1528 
1529  /*
1530  * With row level security and a user using "COPY relation TO", we
1531  * have to convert the "COPY relation TO" to a query-based COPY (eg:
1532  * "COPY (SELECT * FROM relation) TO"), to allow the rewriter to add
1533  * in any RLS clauses.
1534  *
1535  * When this happens, we are passed in the relid of the originally
1536  * found relation (which we have locked). As the planner will look up
1537  * the relation again, we double-check here to make sure it found the
1538  * same one that we have locked.
1539  */
1540  if (queryRelId != InvalidOid)
1541  {
1542  /*
1543  * Note that with RLS involved there may be multiple relations,
1544  * and while the one we need is almost certainly first, we don't
1545  * make any guarantees of that in the planner, so check the whole
1546  * list and make sure we find the original relation.
1547  */
1548  if (!list_member_oid(plan->relationOids, queryRelId))
1549  ereport(ERROR,
1550  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1551  errmsg("relation referenced by COPY statement has changed")));
1552  }
1553 
1554  /*
1555  * Use a snapshot with an updated command ID to ensure this query sees
1556  * results of any previously executed queries.
1557  */
1560 
1561  /* Create dest receiver for COPY OUT */
1563  ((DR_copy *) dest)->cstate = cstate;
1564 
1565  /* Create a QueryDesc requesting no output */
1566  cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
1569  dest, NULL, 0);
1570 
1571  /*
1572  * Call ExecutorStart to prepare the plan for execution.
1573  *
1574  * ExecutorStart computes a result tupdesc for us
1575  */
1576  ExecutorStart(cstate->queryDesc, 0);
1577 
1578  tupDesc = cstate->queryDesc->tupDesc;
1579  }
1580 
1581  /* Generate or convert list of attributes to process */
1582  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1583 
1584  num_phys_attrs = tupDesc->natts;
1585 
1586  /* Convert FORCE_QUOTE name list to per-column flags, check validity */
1587  cstate->force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1588  if (cstate->force_quote_all)
1589  {
1590  int i;
1591 
1592  for (i = 0; i < num_phys_attrs; i++)
1593  cstate->force_quote_flags[i] = true;
1594  }
1595  else if (cstate->force_quote)
1596  {
1597  List *attnums;
1598  ListCell *cur;
1599 
1600  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_quote);
1601 
1602  foreach(cur, attnums)
1603  {
1604  int attnum = lfirst_int(cur);
1605 
1606  if (!list_member_int(cstate->attnumlist, attnum))
1607  ereport(ERROR,
1608  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1609  errmsg("FORCE_QUOTE column \"%s\" not referenced by COPY",
1610  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1611  cstate->force_quote_flags[attnum - 1] = true;
1612  }
1613  }
1614 
1615  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1616  cstate->force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1617  if (cstate->force_notnull)
1618  {
1619  List *attnums;
1620  ListCell *cur;
1621 
1622  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_notnull);
1623 
1624  foreach(cur, attnums)
1625  {
1626  int attnum = lfirst_int(cur);
1627 
1628  if (!list_member_int(cstate->attnumlist, attnum))
1629  ereport(ERROR,
1630  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1631  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
1632  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1633  cstate->force_notnull_flags[attnum - 1] = true;
1634  }
1635  }
1636 
1637  /* Convert FORCE_NULL name list to per-column flags, check validity */
1638  cstate->force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1639  if (cstate->force_null)
1640  {
1641  List *attnums;
1642  ListCell *cur;
1643 
1644  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->force_null);
1645 
1646  foreach(cur, attnums)
1647  {
1648  int attnum = lfirst_int(cur);
1649 
1650  if (!list_member_int(cstate->attnumlist, attnum))
1651  ereport(ERROR,
1652  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1653  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
1654  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1655  cstate->force_null_flags[attnum - 1] = true;
1656  }
1657  }
1658 
1659  /* Convert convert_selectively name list to per-column flags */
1660  if (cstate->convert_selectively)
1661  {
1662  List *attnums;
1663  ListCell *cur;
1664 
1665  cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1666 
1667  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->convert_select);
1668 
1669  foreach(cur, attnums)
1670  {
1671  int attnum = lfirst_int(cur);
1672 
1673  if (!list_member_int(cstate->attnumlist, attnum))
1674  ereport(ERROR,
1675  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1676  errmsg_internal("selected column \"%s\" not referenced by COPY",
1677  NameStr(tupDesc->attrs[attnum - 1]->attname))));
1678  cstate->convert_select_flags[attnum - 1] = true;
1679  }
1680  }
1681 
1682  /* Use client encoding when ENCODING option is not specified. */
1683  if (cstate->file_encoding < 0)
1685 
1686  /*
1687  * Set up encoding conversion info. Even if the file and server encodings
1688  * are the same, we must apply pg_any_to_server() to validate data in
1689  * multibyte encodings.
1690  */
1691  cstate->need_transcoding =
1692  (cstate->file_encoding != GetDatabaseEncoding() ||
1694  /* See Multibyte encoding comment above */
1696 
1697  cstate->copy_dest = COPY_FILE; /* default */
1698 
1699  MemoryContextSwitchTo(oldcontext);
1700 
1701  return cstate;
1702 }
#define NIL
Definition: pg_list.h:69
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:776
#define IsA(nodeptr, _type_)
Definition: nodes.h:559
#define RelationGetDescr(relation)
Definition: rel.h:425
bool need_transcoding
Definition: copy.c:103
ResultRelInfo * partitions
Definition: copy.c:168
#define castNode(_type_, nodeptr)
Definition: nodes.h:577
List * attnumlist
Definition: copy.c:109
List * relationOids
Definition: plannodes.h:74
Definition: copy.c:212
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:138
Form_pg_attribute * attrs
Definition: tupdesc.h:74
void ProcessCopyOptions(ParseState *pstate, CopyState cstate, bool is_from, List *options)
Definition: copy.c:1012
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, int instrument_options)
Definition: pquery.c:64
bool * force_quote_flags
Definition: copy.c:125
Form_pg_class rd_rel
Definition: rel.h:113
Node * utilityStmt
Definition: parsenodes.h:111
bool * force_null_flags
Definition: copy.c:129
int natts
Definition: tupdesc.h:73
bool * convert_select_flags
Definition: copy.c:132
void * copyObject(const void *from)
Definition: copyfuncs.c:4475
CopyDest copy_dest
Definition: copy.c:96
Definition: copy.c:61
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams)
Definition: postgres.c:644
Relation rel
Definition: copy.c:107
MemoryContext copycontext
Definition: copy.c:143
void ExecSetupPartitionTupleRouting(Relation rel, PartitionDispatch **pd, ResultRelInfo **partitions, TupleConversionMap ***tup_conv_maps, TupleTableSlot **partition_tuple_slot, int *num_parted, int *num_partitions)
Definition: execMain.c:3099
#define linitial(l)
Definition: pg_list.h:110
TupleTableSlot * partition_tuple_slot
Definition: copy.c:170
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:764
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
QueryDesc * queryDesc
Definition: copy.c:108
bool list_member_int(const List *list, int datum)
Definition: list.c:485
int num_dispatch
Definition: copy.c:166
bool encoding_embeds_ascii
Definition: copy.c:104
int pg_database_encoding_max_length(void)
Definition: wchar.c:1833
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:109
#define RelationGetRelationName(relation)
Definition: rel.h:433
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
const char * p_sourcetext
Definition: parse_node.h:167
List * returningList
Definition: parsenodes.h:135
#define ereport(elevel, rest)
Definition: elog.h:122
List * force_null
Definition: copy.c:128
int file_encoding
Definition: copy.c:102
static List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:4610
TupleDesc tupDesc
Definition: execdesc.h:46
#define InvalidSnapshot
Definition: snapshot.h:24
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
void * palloc0(Size size)
Definition: mcxt.c:920
int GetDatabaseEncoding(void)
Definition: mbutils.c:1015
int pg_get_client_encoding(void)
Definition: mbutils.c:317
#define InvalidOid
Definition: postgres_ext.h:36
bool * force_notnull_flags
Definition: copy.c:127
CmdType commandType
Definition: parsenodes.h:103
List * force_notnull
Definition: copy.c:126
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:505
#define NULL
Definition: c.h:226
QuerySource querySource
Definition: parsenodes.h:105
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
List * convert_select
Definition: copy.c:131
static int list_length(const List *l)
Definition: pg_list.h:89
bool force_quote_all
Definition: copy.c:124
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:296
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:494
PartitionDispatch * partition_dispatch_info
Definition: copy.c:165
TupleConversionMap ** partition_tupconv_maps
Definition: copy.c:169
Definition: pg_list.h:45
int num_partitions
Definition: copy.c:167
List * force_quote
Definition: copy.c:123
bool convert_selectively
Definition: copy.c:130
bool oids
Definition: copy.c:113
PlannedStmt * pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:781
CopyState BeginCopyFrom ( ParseState pstate,
Relation  rel,
const char *  filename,
bool  is_program,
List attnamelist,
List options 
)

Definition at line 2876 of file copy.c.

References AllocateFile(), Assert, CopyStateData::attnumlist, CopyStateData::attribute_buf, tupleDesc::attrs, BeginCopy(), CopyStateData::binary, BinarySignature, build_column_default(), contain_volatile_functions_not_nextval(), CopyStateData::copy_file, CopyStateData::copycontext, CopyGetData(), CopyGetInt32(), CopyStateData::cur_attname, CopyStateData::cur_attval, CopyStateData::cur_lineno, CopyStateData::cur_relname, CopyStateData::defexprs, CopyStateData::defmap, DestRemote, CopyStateData::eol_type, EOL_UNKNOWN, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, ExecInitExpr(), expression_planner(), CopyStateData::fe_eof, CopyStateData::file_has_oids, CopyStateData::filename, fmgr_info(), getTypeBinaryInputInfo(), getTypeInputInfo(), CopyStateData::in_functions, initLongStringInfo(), InvalidOid, CopyStateData::is_program, CopyStateData::line_buf, CopyStateData::line_buf_converted, list_length(), list_member_int(), CopyStateData::max_fields, MemoryContextSwitchTo(), tupleDesc::natts, NULL, CopyStateData::num_defaults, CopyStateData::oid_in_function, CopyStateData::oid_typioparam, OIDOID, CopyStateData::oids, OpenPipeStream(), palloc(), PG_BINARY_R, pstrdup(), CopyStateData::raw_buf, CopyStateData::raw_buf_index, CopyStateData::raw_buf_len, RAW_BUF_SIZE, CopyStateData::raw_fields, ReceiveCopyBegin(), CopyStateData::rel, RelationGetDescr, RelationGetRelationName, CopyStateData::typioparams, CopyStateData::volatile_defexprs, and whereToSendOutput.

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

2882 {
2883  CopyState cstate;
2884  bool pipe = (filename == NULL);
2885  TupleDesc tupDesc;
2886  Form_pg_attribute *attr;
2887  AttrNumber num_phys_attrs,
2888  num_defaults;
2889  FmgrInfo *in_functions;
2890  Oid *typioparams;
2891  int attnum;
2892  Oid in_func_oid;
2893  int *defmap;
2894  ExprState **defexprs;
2895  MemoryContext oldcontext;
2896  bool volatile_defexprs;
2897 
2898  cstate = BeginCopy(pstate, true, rel, NULL, InvalidOid, attnamelist, options);
2899  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
2900 
2901  /* Initialize state variables */
2902  cstate->fe_eof = false;
2903  cstate->eol_type = EOL_UNKNOWN;
2904  cstate->cur_relname = RelationGetRelationName(cstate->rel);
2905  cstate->cur_lineno = 0;
2906  cstate->cur_attname = NULL;
2907  cstate->cur_attval = NULL;
2908 
2909  /* Set up variables to avoid per-attribute overhead. */
2911  initLongStringInfo(&cstate->line_buf);
2912  cstate->line_buf_converted = false;
2913  cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
2914  cstate->raw_buf_index = cstate->raw_buf_len = 0;
2915 
2916  tupDesc = RelationGetDescr(cstate->rel);
2917  attr = tupDesc->attrs;
2918  num_phys_attrs = tupDesc->natts;
2919  num_defaults = 0;
2920  volatile_defexprs = false;
2921 
2922  /*
2923  * Pick up the required catalog information for each attribute in the
2924  * relation, including the input function, the element type (to pass to
2925  * the input function), and info about defaults and constraints. (Which
2926  * input function we use depends on text/binary format choice.)
2927  */
2928  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2929  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
2930  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
2931  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
2932 
2933  for (attnum = 1; attnum <= num_phys_attrs; attnum++)
2934  {
2935  /* We don't need info for dropped attributes */
2936  if (attr[attnum - 1]->attisdropped)
2937  continue;
2938 
2939  /* Fetch the input function and typioparam info */
2940  if (cstate->binary)
2941  getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
2942  &in_func_oid, &typioparams[attnum - 1]);
2943  else
2944  getTypeInputInfo(attr[attnum - 1]->atttypid,
2945  &in_func_oid, &typioparams[attnum - 1]);
2946  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
2947 
2948  /* Get default info if needed */
2949  if (!list_member_int(cstate->attnumlist, attnum))
2950  {
2951  /* attribute is NOT to be copied from input */
2952  /* use default value if one exists */
2953  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
2954  attnum);
2955 
2956  if (defexpr != NULL)
2957  {
2958  /* Run the expression through planner */
2959  defexpr = expression_planner(defexpr);
2960 
2961  /* Initialize executable expression in copycontext */
2962  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
2963  defmap[num_defaults] = attnum - 1;
2964  num_defaults++;
2965 
2966  /*
2967  * If a default expression looks at the table being loaded,
2968  * then it could give the wrong answer when using
2969  * multi-insert. Since database access can be dynamic this is
2970  * hard to test for exactly, so we use the much wider test of
2971  * whether the default expression is volatile. We allow for
2972  * the special case of when the default expression is the
2973  * nextval() of a sequence which in this specific case is
2974  * known to be safe for use with the multi-insert
2975  * optimisation. Hence we use this special case function
2976  * checker rather than the standard check for
2977  * contain_volatile_functions().
2978  */
2979  if (!volatile_defexprs)
2980  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
2981  }
2982  }
2983  }
2984 
2985  /* We keep those variables in cstate. */
2986  cstate->in_functions = in_functions;
2987  cstate->typioparams = typioparams;
2988  cstate->defmap = defmap;
2989  cstate->defexprs = defexprs;
2990  cstate->volatile_defexprs = volatile_defexprs;
2991  cstate->num_defaults = num_defaults;
2992  cstate->is_program = is_program;
2993 
2994  if (pipe)
2995  {
2996  Assert(!is_program); /* the grammar does not allow this */
2998  ReceiveCopyBegin(cstate);
2999  else
3000  cstate->copy_file = stdin;
3001  }
3002  else
3003  {
3004  cstate->filename = pstrdup(filename);
3005 
3006  if (cstate->is_program)
3007  {
3008  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
3009  if (cstate->copy_file == NULL)
3010  ereport(ERROR,
3012  errmsg("could not execute command \"%s\": %m",
3013  cstate->filename)));
3014  }
3015  else
3016  {
3017  struct stat st;
3018 
3019  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
3020  if (cstate->copy_file == NULL)
3021  {
3022  /* copy errno because ereport subfunctions might change it */
3023  int save_errno = errno;
3024 
3025  ereport(ERROR,
3027  errmsg("could not open file \"%s\" for reading: %m",
3028  cstate->filename),
3029  (save_errno == ENOENT || save_errno == EACCES) ?
3030  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
3031  "You may want a client-side facility such as psql's \\copy.") : 0));
3032  }
3033 
3034  if (fstat(fileno(cstate->copy_file), &st))
3035  ereport(ERROR,
3037  errmsg("could not stat file \"%s\": %m",
3038  cstate->filename)));
3039 
3040  if (S_ISDIR(st.st_mode))
3041  ereport(ERROR,
3042  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3043  errmsg("\"%s\" is a directory", cstate->filename)));
3044  }
3045  }
3046 
3047  if (!cstate->binary)
3048  {
3049  /* must rely on user to tell us... */
3050  cstate->file_has_oids = cstate->oids;
3051  }
3052  else
3053  {
3054  /* Read and verify binary header */
3055  char readSig[11];
3056  int32 tmp;
3057 
3058  /* Signature */
3059  if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
3060  memcmp(readSig, BinarySignature, 11) != 0)
3061  ereport(ERROR,
3062  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3063  errmsg("COPY file signature not recognized")));
3064  /* Flags field */
3065  if (!CopyGetInt32(cstate, &tmp))
3066  ereport(ERROR,
3067  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3068  errmsg("invalid COPY file header (missing flags)")));
3069  cstate->file_has_oids = (tmp & (1 << 16)) != 0;
3070  tmp &= ~(1 << 16);
3071  if ((tmp >> 16) != 0)
3072  ereport(ERROR,
3073  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3074  errmsg("unrecognized critical flags in COPY file header")));
3075  /* Header extension length */
3076  if (!CopyGetInt32(cstate, &tmp) ||
3077  tmp < 0)
3078  ereport(ERROR,
3079  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3080  errmsg("invalid COPY file header (missing length)")));
3081  /* Skip extension header, if present */
3082  while (tmp-- > 0)
3083  {
3084  if (CopyGetData(cstate, readSig, 1, 1) != 1)
3085  ereport(ERROR,
3086  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3087  errmsg("invalid COPY file header (wrong length)")));
3088  }
3089  }
3090 
3091  if (cstate->file_has_oids && cstate->binary)
3092  {
3094  &in_func_oid, &cstate->oid_typioparam);
3095  fmgr_info(in_func_oid, &cstate->oid_in_function);
3096  }
3097 
3098  /* create workspace for CopyReadAttributes results */
3099  if (!cstate->binary)
3100  {
3101  AttrNumber attr_count = list_length(cstate->attnumlist);
3102  int nfields = cstate->file_has_oids ? (attr_count + 1) : attr_count;
3103 
3104  cstate->max_fields = nfields;
3105  cstate->raw_fields = (char **) palloc(nfields * sizeof(char *));
3106  }
3107 
3108  MemoryContextSwitchTo(oldcontext);
3109 
3110  return cstate;
3111 }
Definition: fmgr.h:53
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1370
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:994
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:674
int errhint(const char *fmt,...)
Definition: elog.c:987
char ** raw_fields
Definition: copy.c:185
bool binary
Definition: copy.c:112
#define RelationGetDescr(relation)
Definition: rel.h:425
AttrNumber num_defaults
Definition: copy.c:154
FmgrInfo * in_functions
Definition: copy.c:158
List * attnumlist
Definition: copy.c:109
#define OIDOID
Definition: pg_type.h:328
char * filename
Definition: copy.c:110
bool file_has_oids
Definition: copy.c:155
char * pstrdup(const char *in)
Definition: mcxt.c:1165
static void ReceiveCopyBegin(CopyState cstate)
Definition: copy.c:378
void initLongStringInfo(StringInfo str)
Definition: stringinfo.c:81
Expr * expression_planner(Expr *expr)
Definition: planner.c:5211
Form_pg_attribute * attrs
Definition: tupdesc.h:74
StringInfoData line_buf
Definition: copy.c:194
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:508
int raw_buf_index
Definition: copy.c:207
int errcode(int sqlerrcode)
Definition: elog.c:575
bool fe_eof
Definition: copy.c:100
unsigned int Oid
Definition: postgres_ext.h:31
bool volatile_defexprs
Definition: copy.c:162
#define PG_BINARY_R
Definition: c.h:1039
int natts
Definition: tupdesc.h:73
bool line_buf_converted
Definition: copy.c:195
signed int int32
Definition: c.h:253
const char * cur_attname
Definition: copy.c:137
Relation rel
Definition: copy.c:107
MemoryContext copycontext
Definition: copy.c:143
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execQual.c:4266
#define ERROR
Definition: elog.h:43
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:551
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:159
bool list_member_int(const List *list, int datum)
Definition: list.c:485
char * raw_buf
Definition: copy.c:206
ExprState ** defexprs
Definition: copy.c:161
const char * cur_relname
Definition: copy.c:135
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2043
FmgrInfo oid_in_function
Definition: copy.c:156
#define RelationGetRelationName(relation)
Definition: rel.h:433
static const char BinarySignature[11]
Definition: copy.c:285
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
int raw_buf_len
Definition: copy.c:208
int max_fields
Definition: copy.c:184
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2133
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2633
#define ereport(elevel, rest)
Definition: elog.h:122
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
Oid * typioparams
Definition: copy.c:159
bool is_program
Definition: copy.c:111
Node * build_column_default(Relation rel, int attrno)
#define RAW_BUF_SIZE
Definition: copy.c:205
#define InvalidOid
Definition: postgres_ext.h:36
EolType eol_type
Definition: copy.c:101
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static int list_length(const List *l)
Definition: pg_list.h:89
static char * filename
Definition: pg_dumpall.c:84
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE * copy_file
Definition: copy.c:97
int cur_lineno
Definition: copy.c:136
StringInfoData attribute_buf
Definition: copy.c:180
const char * cur_attval
Definition: copy.c:138
CommandDest whereToSendOutput
Definition: postgres.c:86
Oid oid_typioparam
Definition: copy.c:157
int16 AttrNumber
Definition: attnum.h:21
int * defmap
Definition: copy.c:160
bool oids
Definition: copy.c:113
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 1754 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(), NULL, OpenPipeStream(), PG_BINARY_W, pstrdup(), RelationData::rd_rel, RelationGetRelationName, RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW, S_IWGRP, S_IWOTH, and whereToSendOutput.

Referenced by DoCopy().

1762 {
1763  CopyState cstate;
1764  bool pipe = (filename == NULL);
1765  MemoryContext oldcontext;
1766 
1767  if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
1768  {
1769  if (rel->rd_rel->relkind == RELKIND_VIEW)
1770  ereport(ERROR,
1771  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1772  errmsg("cannot copy from view \"%s\"",
1774  errhint("Try the COPY (SELECT ...) TO variant.")));
1775  else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
1776  ereport(ERROR,
1777  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1778  errmsg("cannot copy from materialized view \"%s\"",
1780  errhint("Try the COPY (SELECT ...) TO variant.")));
1781  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1782  ereport(ERROR,
1783  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1784  errmsg("cannot copy from foreign table \"%s\"",
1786  errhint("Try the COPY (SELECT ...) TO variant.")));
1787  else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
1788  ereport(ERROR,
1789  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1790  errmsg("cannot copy from sequence \"%s\"",
1791  RelationGetRelationName(rel))));
1792  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1793  ereport(ERROR,
1794  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1795  errmsg("cannot copy from partitioned table \"%s\"",
1797  errhint("Try the COPY (SELECT ...) TO variant.")));
1798  else
1799  ereport(ERROR,
1800  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1801  errmsg("cannot copy from non-table relation \"%s\"",
1802  RelationGetRelationName(rel))));
1803  }
1804 
1805  cstate = BeginCopy(pstate, false, rel, query, queryRelId, attnamelist,
1806  options);
1807  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1808 
1809  if (pipe)
1810  {
1811  Assert(!is_program); /* the grammar does not allow this */
1813  cstate->copy_file = stdout;
1814  }
1815  else
1816  {
1817  cstate->filename = pstrdup(filename);
1818  cstate->is_program = is_program;
1819 
1820  if (is_program)
1821  {
1822  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
1823  if (cstate->copy_file == NULL)
1824  ereport(ERROR,
1826  errmsg("could not execute command \"%s\": %m",
1827  cstate->filename)));
1828  }
1829  else
1830  {
1831  mode_t oumask; /* Pre-existing umask value */
1832  struct stat st;
1833 
1834  /*
1835  * Prevent write to relative path ... too easy to shoot oneself in
1836  * the foot by overwriting a database file ...
1837  */
1838  if (!is_absolute_path(filename))
1839  ereport(ERROR,
1840  (errcode(ERRCODE_INVALID_NAME),
1841  errmsg("relative path not allowed for COPY to file")));
1842 
1843  oumask = umask(S_IWGRP | S_IWOTH);
1844  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
1845  umask(oumask);
1846  if (cstate->copy_file == NULL)
1847  {
1848  /* copy errno because ereport subfunctions might change it */
1849  int save_errno = errno;
1850 
1851  ereport(ERROR,
1853  errmsg("could not open file \"%s\" for writing: %m",
1854  cstate->filename),
1855  (save_errno == ENOENT || save_errno == EACCES) ?
1856  errhint("COPY TO instructs the PostgreSQL server process to write a file. "
1857  "You may want a client-side facility such as psql's \\copy.") : 0));
1858  }
1859 
1860  if (fstat(fileno(cstate->copy_file), &st))
1861  ereport(ERROR,
1863  errmsg("could not stat file \"%s\": %m",
1864  cstate->filename)));
1865 
1866  if (S_ISDIR(st.st_mode))
1867  ereport(ERROR,
1868  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1869  errmsg("\"%s\" is a directory", cstate->filename)));
1870  }
1871  }
1872 
1873  MemoryContextSwitchTo(oldcontext);
1874 
1875  return cstate;
1876 }
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1370
int errhint(const char *fmt,...)
Definition: elog.c:987
char * filename
Definition: copy.c:110
char * pstrdup(const char *in)
Definition: mcxt.c:1165
#define RELKIND_MATVIEW
Definition: pg_class.h:167
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:575
#define PG_BINARY_W
Definition: c.h:1040
Form_pg_class rd_rel
Definition: rel.h:113
MemoryContext copycontext
Definition: copy.c:143
#define ERROR
Definition: elog.h:43
#define S_IWGRP
Definition: win32.h:478
int errcode_for_file_access(void)
Definition: elog.c:598
#define is_absolute_path(filename)
Definition: port.h:77
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2043
#define RelationGetRelationName(relation)
Definition: rel.h:433
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2133
#define ereport(elevel, rest)
Definition: elog.h:122
#define S_IWOTH
Definition: win32.h:482
bool is_program
Definition: copy.c:111
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
static char * filename
Definition: pg_dumpall.c:84
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
FILE * copy_file
Definition: copy.c:97
CommandDest whereToSendOutput
Definition: postgres.c:86
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
static void ClosePipeToProgram ( CopyState  cstate)
static

Definition at line 1708 of file copy.c.

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

Referenced by CopySendEndOfRow(), and EndCopy().

1709 {
1710  int pclose_rc;
1711 
1712  Assert(cstate->is_program);
1713 
1714  pclose_rc = ClosePipeStream(cstate->copy_file);
1715  if (pclose_rc == -1)
1716  ereport(ERROR,
1718  errmsg("could not close pipe to external command: %m")));
1719  else if (pclose_rc != 0)
1720  ereport(ERROR,
1721  (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION),
1722  errmsg("program \"%s\" failed",
1723  cstate->filename),
1724  errdetail_internal("%s", wait_result_to_str(pclose_rc))));
1725 }
char * filename
Definition: copy.c:110
int errcode(int sqlerrcode)
Definition: elog.c:575
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:34
int ClosePipeStream(FILE *file)
Definition: fd.c:2419
int errdetail_internal(const char *fmt,...)
Definition: elog.c:900
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_program
Definition: copy.c:111
#define Assert(condition)
Definition: c.h:670
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE * copy_file
Definition: copy.c:97
static void copy_dest_destroy ( DestReceiver self)
static

Definition at line 4719 of file copy.c.

References pfree().

Referenced by CreateCopyDestReceiver().

4720 {
4721  pfree(self);
4722 }
void pfree(void *pointer)
Definition: mcxt.c:992
static bool copy_dest_receive ( TupleTableSlot slot,
DestReceiver self 
)
static

Definition at line 4691 of file copy.c.

References CopyOneRowTo(), DR_copy::cstate, InvalidOid, DR_copy::processed, slot_getallattrs(), TupleTableSlot::tts_isnull, and TupleTableSlot::tts_values.

Referenced by CreateCopyDestReceiver().

4692 {
4693  DR_copy *myState = (DR_copy *) self;
4694  CopyState cstate = myState->cstate;
4695 
4696  /* Make sure the tuple is fully deconstructed */
4697  slot_getallattrs(slot);
4698 
4699  /* And send the data */
4700  CopyOneRowTo(cstate, InvalidOid, slot->tts_values, slot->tts_isnull);
4701  myState->processed++;
4702 
4703  return true;
4704 }
Definition: copy.c:212
CopyState cstate
Definition: copy.c:215
Datum * tts_values
Definition: tuptable.h:125
bool * tts_isnull
Definition: tuptable.h:126
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1239
#define InvalidOid
Definition: postgres_ext.h:36
static void CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
Definition: copy.c:2090
uint64 processed
Definition: copy.c:216
static void copy_dest_shutdown ( DestReceiver self)
static

Definition at line 4710 of file copy.c.

Referenced by CreateCopyDestReceiver().

4711 {
4712  /* no-op */
4713 }
static void copy_dest_startup ( DestReceiver self,
int  operation,
TupleDesc  typeinfo 
)
static

Definition at line 4682 of file copy.c.

Referenced by CreateCopyDestReceiver().

4683 {
4684  /* no-op */
4685 }
static void CopyAttributeOutCSV ( CopyState  cstate,
char *  string,
bool  use_quote,
bool  single_attr 
)
static

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

4521 {
4522  char *ptr;
4523  char *start;
4524  char c;
4525  char delimc = cstate->delim[0];
4526  char quotec = cstate->quote[0];
4527  char escapec = cstate->escape[0];
4528 
4529  /* force quoting if it matches null_print (before conversion!) */
4530  if (!use_quote && strcmp(string, cstate->null_print) == 0)
4531  use_quote = true;
4532 
4533  if (cstate->need_transcoding)
4534  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
4535  else
4536  ptr = string;
4537 
4538  /*
4539  * Make a preliminary pass to discover if it needs quoting
4540  */
4541  if (!use_quote)
4542  {
4543  /*
4544  * Because '\.' can be a data value, quote it if it appears alone on a
4545  * line so it is not interpreted as the end-of-data marker.
4546  */
4547  if (single_attr && strcmp(ptr, "\\.") == 0)
4548  use_quote = true;
4549  else
4550  {
4551  char *tptr = ptr;
4552 
4553  while ((c = *tptr) != '\0')
4554  {
4555  if (c == delimc || c == quotec || c == '\n' || c == '\r')
4556  {
4557  use_quote = true;
4558  break;
4559  }
4560  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
4561  tptr += pg_encoding_mblen(cstate->file_encoding, tptr);
4562  else
4563  tptr++;
4564  }
4565  }
4566  }
4567 
4568  if (use_quote)
4569  {
4570  CopySendChar(cstate, quotec);
4571 
4572  /*
4573  * We adopt the same optimization strategy as in CopyAttributeOutText
4574  */
4575  start = ptr;
4576  while ((c = *ptr) != '\0')
4577  {
4578  if (c == quotec || c == escapec)
4579  {
4580  DUMPSOFAR();
4581  CopySendChar(cstate, escapec);
4582  start = ptr; /* we include char in next run */
4583  }
4584  if (IS_HIGHBIT_SET(c) && cstate->encoding_embeds_ascii)
4585  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
4586  else
4587  ptr++;
4588  }
4589  DUMPSOFAR();
4590 
4591  CopySendChar(cstate, quotec);
4592  }
4593  else
4594  {
4595  /* If it doesn't need quoting, we can just dump it as-is */
4596  CopySendString(cstate, ptr);
4597  }
4598 }
bool need_transcoding
Definition: copy.c:103
char * delim
Definition: copy.c:120
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:645
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:455
char * null_print
Definition: copy.c:117
#define IS_HIGHBIT_SET(ch)
Definition: c.h:968
bool encoding_embeds_ascii
Definition: copy.c:104
char * c
char * quote
Definition: copy.c:121
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
char string[11]
Definition: preproc-type.c:46
char * escape
Definition: copy.c:122
int file_encoding
Definition: copy.c:102
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:449
#define DUMPSOFAR()
Definition: copy.c:4359
static void CopyAttributeOutText ( CopyState  cstate,
char *  string 
)
static

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

4367 {
4368  char *ptr;
4369  char *start;
4370  char c;
4371  char delimc = cstate->delim[0];
4372 
4373  if (cstate->need_transcoding)
4374  ptr = pg_server_to_any(string, strlen(string), cstate->file_encoding);
4375  else
4376  ptr = string;
4377 
4378  /*
4379  * We have to grovel through the string searching for control characters
4380  * and instances of the delimiter character. In most cases, though, these
4381  * are infrequent. To avoid overhead from calling CopySendData once per
4382  * character, we dump out all characters between escaped characters in a
4383  * single call. The loop invariant is that the data from "start" to "ptr"
4384  * can be sent literally, but hasn't yet been.
4385  *
4386  * We can skip pg_encoding_mblen() overhead when encoding is safe, because
4387  * in valid backend encodings, extra bytes of a multibyte character never
4388  * look like ASCII. This loop is sufficiently performance-critical that
4389  * it's worth making two copies of it to get the IS_HIGHBIT_SET() test out
4390  * of the normal safe-encoding path.
4391  */
4392  if (cstate->encoding_embeds_ascii)
4393  {
4394  start = ptr;
4395  while ((c = *ptr) != '\0')
4396  {
4397  if ((unsigned char) c < (unsigned char) 0x20)
4398  {
4399  /*
4400  * \r and \n must be escaped, the others are traditional. We
4401  * prefer to dump these using the C-like notation, rather than
4402  * a backslash and the literal character, because it makes the
4403  * dump file a bit more proof against Microsoftish data
4404  * mangling.
4405  */
4406  switch (c)
4407  {
4408  case '\b':
4409  c = 'b';
4410  break;
4411  case '\f':
4412  c = 'f';
4413  break;
4414  case '\n':
4415  c = 'n';
4416  break;
4417  case '\r':
4418  c = 'r';
4419  break;
4420  case '\t':
4421  c = 't';
4422  break;
4423  case '\v':
4424  c = 'v';
4425  break;
4426  default:
4427  /* If it's the delimiter, must backslash it */
4428  if (c == delimc)
4429  break;
4430  /* All ASCII control chars are length 1 */
4431  ptr++;
4432  continue; /* fall to end of loop */
4433  }
4434  /* if we get here, we need to convert the control char */
4435  DUMPSOFAR();
4436  CopySendChar(cstate, '\\');
4437  CopySendChar(cstate, c);
4438  start = ++ptr; /* do not include char in next run */
4439  }
4440  else if (c == '\\' || c == delimc)
4441  {
4442  DUMPSOFAR();
4443  CopySendChar(cstate, '\\');
4444  start = ptr++; /* we include char in next run */
4445  }
4446  else if (IS_HIGHBIT_SET(c))
4447  ptr += pg_encoding_mblen(cstate->file_encoding, ptr);
4448  else
4449  ptr++;
4450  }
4451  }
4452  else
4453  {
4454  start = ptr;
4455  while ((c = *ptr) != '\0')
4456  {
4457  if ((unsigned char) c < (unsigned char) 0x20)
4458  {
4459  /*
4460  * \r and \n must be escaped, the others are traditional. We
4461  * prefer to dump these using the C-like notation, rather than
4462  * a backslash and the literal character, because it makes the
4463  * dump file a bit more proof against Microsoftish data
4464  * mangling.
4465  */
4466  switch (c)
4467  {
4468  case '\b':
4469  c = 'b';
4470  break;
4471  case '\f':
4472  c = 'f';
4473  break;
4474  case '\n':
4475  c = 'n';
4476  break;
4477  case '\r':
4478  c = 'r';
4479  break;
4480  case '\t':
4481  c = 't';
4482  break;
4483  case '\v':
4484  c = 'v';
4485  break;
4486  default:
4487  /* If it's the delimiter, must backslash it */
4488  if (c == delimc)
4489  break;
4490  /* All ASCII control chars are length 1 */
4491  ptr++;
4492  continue; /* fall to end of loop */
4493  }
4494  /* if we get here, we need to convert the control char */
4495  DUMPSOFAR();
4496  CopySendChar(cstate, '\\');
4497  CopySendChar(cstate, c);
4498  start = ++ptr; /* do not include char in next run */
4499  }
4500  else if (c == '\\' || c == delimc)
4501  {
4502  DUMPSOFAR();
4503  CopySendChar(cstate, '\\');
4504  start = ptr++; /* we include char in next run */
4505  }
4506  else
4507  ptr++;
4508  }
4509  }
4510 
4511  DUMPSOFAR();
4512 }
bool need_transcoding
Definition: copy.c:103
char * delim
Definition: copy.c:120
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:645
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:455
#define IS_HIGHBIT_SET(ch)
Definition: c.h:968
bool encoding_embeds_ascii
Definition: copy.c:104
char * c
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
char string[11]
Definition: preproc-type.c:46
int file_encoding
Definition: copy.c:102
#define DUMPSOFAR()
Definition: copy.c:4359
static uint64 CopyFrom ( CopyState  cstate)
static

Definition at line 2289 of file copy.c.

References AfterTriggerBeginQuery(), AfterTriggerEndQuery(), ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, CHECK_FOR_INTERRUPTS, tupleDesc::constr, CopyStateData::copy_dest, COPY_OLD_FE, CopyFromErrorCallback(), CopyFromInsertBatch(), CreateExecutorState(), CopyStateData::cur_lineno, CurrentMemoryContext, do_convert_tuple(), ereport, errcode(), errhint(), errmsg(), ERROR, error_context_stack, EState::es_num_result_relations, EState::es_range_table, EState::es_result_relation_info, EState::es_result_relations, EState::es_trig_tuple_slot, EState::es_tupleTable, ExecARInsertTriggers(), ExecASInsertTriggers(), ExecBRInsertTriggers(), ExecBSInsertTriggers(), ExecCloseIndices(), ExecConstraints(), ExecDropSingleTupleTableSlot(), ExecFindPartition(), ExecInitExtraTupleSlot(), ExecInsertIndexTuples(), ExecIRInsertTriggers(), ExecMaterializeSlot(), ExecOpenIndices(), ExecResetTupleTable(), ExecSetSlotDescriptor(), ExecStoreTuple(), FreeBulkInsertState(), FreeExecutorState(), CopyStateData::freeze, GetBulkInsertState(), GetCurrentCommandId(), GetCurrentSubTransactionId(), GetPerTupleExprContext, GetPerTupleMemoryContext, heap_close, heap_form_tuple(), heap_insert(), HEAP_INSERT_FROZEN, HEAP_INSERT_SKIP_FSM, HEAP_INSERT_SKIP_WAL, heap_sync(), HeapTupleSetOid, i, InitResultRelInfo(), InvalidBuffer, InvalidOid, InvalidSubTransactionId, list_free(), makeNode, MAX_BUFFERED_TUPLES, MemoryContextSwitchTo(), tupleDesc::natts, NextCopyFrom(), NIL, NoLock, NULL, CopyStateData::num_dispatch, CopyStateData::num_partitions, palloc(), CopyStateData::partition_dispatch_info, CopyStateData::partition_tupconv_maps, CopyStateData::partition_tuple_slot, CopyStateData::partitions, pfree(), pq_endmsgread(), ErrorContextCallback::previous, CopyStateData::range_table, RelationData::rd_att, RelationData::rd_createSubid, RelationData::rd_newRelfilenodeSubid, RelationData::rd_rel, CopyStateData::rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, PartitionDispatchData::reldesc, ReleaseBulkInsertStatePin(), RELKIND_FOREIGN_TABLE, RELKIND_MATVIEW, RELKIND_PARTITIONED_TABLE, RELKIND_RELATION, RELKIND_SEQUENCE, RELKIND_VIEW, ResetPerTupleExprContext, ResultRelInfo::ri_FdwRoutine, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_PartitionCheck, ResultRelInfo::ri_RelationDesc, ResultRelInfo::ri_TrigDesc, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, ThereAreNoPriorRegisteredSnapshots(), ThereAreNoReadyPortals(), TriggerDesc::trig_insert_before_row, TriggerDesc::trig_insert_instead_row, RelationData::trigdesc, PartitionDispatchData::tupslot, values, CopyStateData::volatile_defexprs, and XLogIsNeeded.

Referenced by DoCopy().

2290 {
2291  HeapTuple tuple;
2292  TupleDesc tupDesc;
2293  Datum *values;
2294  bool *nulls;
2295  ResultRelInfo *resultRelInfo;
2296  ResultRelInfo *saved_resultRelInfo = NULL;
2297  EState *estate = CreateExecutorState(); /* for ExecConstraints() */
2298  ExprContext *econtext;
2299  TupleTableSlot *myslot;
2300  MemoryContext oldcontext = CurrentMemoryContext;
2301 
2302  ErrorContextCallback errcallback;
2303  CommandId mycid = GetCurrentCommandId(true);
2304  int hi_options = 0; /* start with default heap_insert options */
2305  BulkInsertState bistate;
2306  uint64 processed = 0;
2307  bool useHeapMultiInsert;
2308  int nBufferedTuples = 0;
2309  int prev_leaf_part_index = -1;
2310 
2311 #define MAX_BUFFERED_TUPLES 1000
2312  HeapTuple *bufferedTuples = NULL; /* initialize to silence warning */
2313  Size bufferedTuplesSize = 0;
2314  int firstBufferedLineNo = 0;
2315 
2316  Assert(cstate->rel);
2317 
2318  /*
2319  * The target must be a plain relation or have an INSTEAD OF INSERT row
2320  * trigger. (Currently, such triggers are only allowed on views, so we
2321  * only hint about them in the view case.)
2322  */
2323  if (cstate->rel->rd_rel->relkind != RELKIND_RELATION &&
2324  cstate->rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
2325  !(cstate->rel->trigdesc &&
2327  {
2328  if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
2329  ereport(ERROR,
2330  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2331  errmsg("cannot copy to view \"%s\"",
2332  RelationGetRelationName(cstate->rel)),
2333  errhint("To enable copying to a view, provide an INSTEAD OF INSERT trigger.")));
2334  else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
2335  ereport(ERROR,
2336  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2337  errmsg("cannot copy to materialized view \"%s\"",
2338  RelationGetRelationName(cstate->rel))));
2339  else if (cstate->rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2340  ereport(ERROR,
2341  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2342  errmsg("cannot copy to foreign table \"%s\"",
2343  RelationGetRelationName(cstate->rel))));
2344  else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
2345  ereport(ERROR,
2346  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2347  errmsg("cannot copy to sequence \"%s\"",
2348  RelationGetRelationName(cstate->rel))));
2349  else
2350  ereport(ERROR,
2351  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
2352  errmsg("cannot copy to non-table relation \"%s\"",
2353  RelationGetRelationName(cstate->rel))));
2354  }
2355 
2356  tupDesc = RelationGetDescr(cstate->rel);
2357 
2358  /*----------
2359  * Check to see if we can avoid writing WAL
2360  *
2361  * If archive logging/streaming is not enabled *and* either
2362  * - table was created in same transaction as this COPY
2363  * - data is being written to relfilenode created in this transaction
2364  * then we can skip writing WAL. It's safe because if the transaction
2365  * doesn't commit, we'll discard the table (or the new relfilenode file).
2366  * If it does commit, we'll have done the heap_sync at the bottom of this
2367  * routine first.
2368  *
2369  * As mentioned in comments in utils/rel.h, the in-same-transaction test
2370  * is not always set correctly, since in rare cases rd_newRelfilenodeSubid
2371  * can be cleared before the end of the transaction. The exact case is
2372  * when a relation sets a new relfilenode twice in same transaction, yet
2373  * the second one fails in an aborted subtransaction, e.g.
2374  *
2375  * BEGIN;
2376  * TRUNCATE t;
2377  * SAVEPOINT save;
2378  * TRUNCATE t;
2379  * ROLLBACK TO save;
2380  * COPY ...
2381  *
2382  * Also, if the target file is new-in-transaction, we assume that checking
2383  * FSM for free space is a waste of time, even if we must use WAL because
2384  * of archiving. This could possibly be wrong, but it's unlikely.
2385  *
2386  * The comments for heap_insert and RelationGetBufferForTuple specify that
2387  * skipping WAL logging is only safe if we ensure that our tuples do not
2388  * go into pages containing tuples from any other transactions --- but this
2389  * must be the case if we have a new table or new relfilenode, so we need
2390  * no additional work to enforce that.
2391  *----------
2392  */
2393  /* createSubid is creation check, newRelfilenodeSubid is truncation check */
2394  if (cstate->rel->rd_createSubid != InvalidSubTransactionId ||
2396  {
2397  hi_options |= HEAP_INSERT_SKIP_FSM;
2398  if (!XLogIsNeeded())
2399  hi_options |= HEAP_INSERT_SKIP_WAL;
2400  }
2401 
2402  /*
2403  * Optimize if new relfilenode was created in this subxact or one of its
2404  * committed children and we won't see those rows later as part of an
2405  * earlier scan or command. This ensures that if this subtransaction
2406  * aborts then the frozen rows won't be visible after xact cleanup. Note
2407  * that the stronger test of exactly which subtransaction created it is
2408  * crucial for correctness of this optimisation.
2409  */
2410  if (cstate->freeze)
2411  {
2413  ereport(ERROR,
2414  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
2415  errmsg("cannot perform FREEZE because of prior transaction activity")));
2416 
2417  if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
2419  ereport(ERROR,
2420  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2421  errmsg("cannot perform FREEZE because the table was not created or truncated in the current subtransaction")));
2422 
2423  hi_options |= HEAP_INSERT_FROZEN;
2424  }
2425 
2426  /*
2427  * We need a ResultRelInfo so we can use the regular executor's
2428  * index-entry-making machinery. (There used to be a huge amount of code
2429  * here that basically duplicated execUtils.c ...)
2430  */
2431  resultRelInfo = makeNode(ResultRelInfo);
2432  InitResultRelInfo(resultRelInfo,
2433  cstate->rel,
2434  1, /* dummy rangetable index */
2435  NULL,
2436  0);
2437 
2438  ExecOpenIndices(resultRelInfo, false);
2439 
2440  estate->es_result_relations = resultRelInfo;
2441  estate->es_num_result_relations = 1;
2442  estate->es_result_relation_info = resultRelInfo;
2443  estate->es_range_table = cstate->range_table;
2444 
2445  /* Set up a tuple slot too */
2446  myslot = ExecInitExtraTupleSlot(estate);
2447  ExecSetSlotDescriptor(myslot, tupDesc);
2448  /* Triggers might need a slot as well */
2449  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
2450 
2451  /*
2452  * It's more efficient to prepare a bunch of tuples for insertion, and
2453  * insert them in one heap_multi_insert() call, than call heap_insert()
2454  * separately for every tuple. However, we can't do that if there are
2455  * BEFORE/INSTEAD OF triggers, or we need to evaluate volatile default
2456  * expressions. Such triggers or expressions might query the table we're
2457  * inserting to, and act differently if the tuples that have already been
2458  * processed and prepared for insertion are not there. We also can't do
2459  * it if the table is partitioned.
2460  */
2461  if ((resultRelInfo->ri_TrigDesc != NULL &&
2462  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
2463  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)) ||
2464  cstate->partition_dispatch_info != NULL ||
2465  cstate->volatile_defexprs)
2466  {
2467  useHeapMultiInsert = false;
2468  }
2469  else
2470  {
2471  useHeapMultiInsert = true;
2472  bufferedTuples = palloc(MAX_BUFFERED_TUPLES * sizeof(HeapTuple));
2473  }
2474 
2475  /* Prepare to catch AFTER triggers. */
2477 
2478  /*
2479  * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
2480  * should do this for COPY, since it's not really an "INSERT" statement as
2481  * such. However, executing these triggers maintains consistency with the
2482  * EACH ROW triggers that we already fire on COPY.
2483  */
2484  ExecBSInsertTriggers(estate, resultRelInfo);
2485 
2486  values = (Datum *) palloc(tupDesc->natts * sizeof(Datum));
2487  nulls = (bool *) palloc(tupDesc->natts * sizeof(bool));
2488 
2489  bistate = GetBulkInsertState();
2490  econtext = GetPerTupleExprContext(estate);
2491 
2492  /* Set up callback to identify error line number */
2493  errcallback.callback = CopyFromErrorCallback;
2494  errcallback.arg = (void *) cstate;
2495  errcallback.previous = error_context_stack;
2496  error_context_stack = &errcallback;
2497 
2498  for (;;)
2499  {
2500  TupleTableSlot *slot,
2501  *oldslot;
2502  bool skip_tuple;
2503  Oid loaded_oid = InvalidOid;
2504 
2506 
2507  if (nBufferedTuples == 0)
2508  {
2509  /*
2510  * Reset the per-tuple exprcontext. We can only do this if the
2511  * tuple buffer is empty. (Calling the context the per-tuple
2512  * memory context is a bit of a misnomer now.)
2513  */
2514  ResetPerTupleExprContext(estate);
2515  }
2516 
2517  /* Switch into its memory context */
2519 
2520  if (!NextCopyFrom(cstate, econtext, values, nulls, &loaded_oid))
2521  break;
2522 
2523  /* And now we can form the input tuple. */
2524  tuple = heap_form_tuple(tupDesc, values, nulls);
2525 
2526  if (loaded_oid != InvalidOid)
2527  HeapTupleSetOid(tuple, loaded_oid);
2528 
2529  /*
2530  * Constraints might reference the tableoid column, so initialize
2531  * t_tableOid before evaluating them.
2532  */
2533  tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
2534 
2535  /* Triggers and stuff need to be invoked in query context. */
2536  MemoryContextSwitchTo(oldcontext);
2537 
2538  /* Place tuple in tuple slot --- but slot shouldn't free it */
2539  slot = myslot;
2540  ExecStoreTuple(tuple, slot, InvalidBuffer, false);
2541 
2542  /* Determine the partition to heap_insert the tuple into */
2543  oldslot = slot;
2544  if (cstate->partition_dispatch_info)
2545  {
2546  int leaf_part_index;
2547  TupleConversionMap *map;
2548 
2549  /*
2550  * Away we go ... If we end up not finding a partition after all,
2551  * ExecFindPartition() does not return and errors out instead.
2552  * Otherwise, the returned value is to be used as an index into
2553  * arrays mt_partitions[] and mt_partition_tupconv_maps[] that
2554  * will get us the ResultRelInfo and TupleConversionMap for the
2555  * partition, respectively.
2556  */
2557  leaf_part_index = ExecFindPartition(resultRelInfo,
2558  cstate->partition_dispatch_info,
2559  slot,
2560  estate);
2561  Assert(leaf_part_index >= 0 &&
2562  leaf_part_index < cstate->num_partitions);
2563 
2564  /*
2565  * If this tuple is mapped to a partition that is not same as the
2566  * previous one, we'd better make the bulk insert mechanism gets a
2567  * new buffer.
2568  */
2569  if (prev_leaf_part_index != leaf_part_index)
2570  {
2571  ReleaseBulkInsertStatePin(bistate);
2572  prev_leaf_part_index = leaf_part_index;
2573  }
2574 
2575  /*
2576  * Save the old ResultRelInfo and switch to the one corresponding
2577  * to the selected partition.
2578  */
2579  saved_resultRelInfo = resultRelInfo;
2580  resultRelInfo = cstate->partitions + leaf_part_index;
2581 
2582  /* We do not yet have a way to insert into a foreign partition */
2583  if (resultRelInfo->ri_FdwRoutine)
2584  ereport(ERROR,
2585  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2586  errmsg("cannot route inserted tuples to a foreign table")));
2587 
2588  /*
2589  * For ExecInsertIndexTuples() to work on the partition's indexes
2590  */
2591  estate->es_result_relation_info = resultRelInfo;
2592 
2593  /*
2594  * We might need to convert from the parent rowtype to the
2595  * partition rowtype.
2596  */
2597  map = cstate->partition_tupconv_maps[leaf_part_index];
2598  if (map)
2599  {
2600  Relation partrel = resultRelInfo->ri_RelationDesc;
2601 
2602  tuple = do_convert_tuple(tuple, map);
2603 
2604  /*
2605  * We must use the partition's tuple descriptor from this
2606  * point on. Use a dedicated slot from this point on until
2607  * we're finished dealing with the partition.
2608  */
2609  slot = cstate->partition_tuple_slot;
2610  Assert(slot != NULL);
2611  ExecSetSlotDescriptor(slot, RelationGetDescr(partrel));
2612  ExecStoreTuple(tuple, slot, InvalidBuffer, true);
2613  }
2614 
2615  tuple->t_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
2616  }
2617 
2618  skip_tuple = false;
2619 
2620  /* BEFORE ROW INSERT Triggers */
2621  if (resultRelInfo->ri_TrigDesc &&
2622  resultRelInfo->ri_TrigDesc->trig_insert_before_row)
2623  {
2624  slot = ExecBRInsertTriggers(estate, resultRelInfo, slot);
2625 
2626  if (slot == NULL) /* "do nothing" */
2627  skip_tuple = true;
2628  else /* trigger might have changed tuple */
2629  tuple = ExecMaterializeSlot(slot);
2630  }
2631 
2632  if (!skip_tuple)
2633  {
2634  if (resultRelInfo->ri_TrigDesc &&
2635  resultRelInfo->ri_TrigDesc->trig_insert_instead_row)
2636  {
2637  /* Pass the data to the INSTEAD ROW INSERT trigger */
2638  ExecIRInsertTriggers(estate, resultRelInfo, slot);
2639  }
2640  else
2641  {
2642  /* Check the constraints of the tuple */
2643  if (cstate->rel->rd_att->constr ||
2644  resultRelInfo->ri_PartitionCheck)
2645  ExecConstraints(resultRelInfo, slot, oldslot, estate);
2646 
2647  if (useHeapMultiInsert)
2648  {
2649  /* Add this tuple to the tuple buffer */
2650  if (nBufferedTuples == 0)
2651  firstBufferedLineNo = cstate->cur_lineno;
2652  bufferedTuples[nBufferedTuples++] = tuple;
2653  bufferedTuplesSize += tuple->t_len;
2654 
2655  /*
2656  * If the buffer filled up, flush it. Also flush if the
2657  * total size of all the tuples in the buffer becomes
2658  * large, to avoid using large amounts of memory for the
2659  * buffer when the tuples are exceptionally wide.
2660  */
2661  if (nBufferedTuples == MAX_BUFFERED_TUPLES ||
2662  bufferedTuplesSize > 65535)
2663  {
2664  CopyFromInsertBatch(cstate, estate, mycid, hi_options,
2665  resultRelInfo, myslot, bistate,
2666  nBufferedTuples, bufferedTuples,
2667  firstBufferedLineNo);
2668  nBufferedTuples = 0;
2669  bufferedTuplesSize = 0;
2670  }
2671  }
2672  else
2673  {
2674  List *recheckIndexes = NIL;
2675 
2676  /* OK, store the tuple and create index entries for it */
2677  heap_insert(resultRelInfo->ri_RelationDesc, tuple, mycid,
2678  hi_options, bistate);
2679 
2680  if (resultRelInfo->ri_NumIndices > 0)
2681  recheckIndexes = ExecInsertIndexTuples(slot,
2682  &(tuple->t_self),
2683  estate,
2684  false,
2685  NULL,
2686  NIL);
2687 
2688  /* AFTER ROW INSERT Triggers */
2689  ExecARInsertTriggers(estate, resultRelInfo, tuple,
2690  recheckIndexes);
2691 
2692  list_free(recheckIndexes);
2693  }
2694  }
2695 
2696  /*
2697  * We count only tuples not suppressed by a BEFORE INSERT trigger;
2698  * this is the same definition used by execMain.c for counting
2699  * tuples inserted by an INSERT command.
2700  */
2701  processed++;
2702 
2703  if (saved_resultRelInfo)
2704  {
2705  resultRelInfo = saved_resultRelInfo;
2706  estate->es_result_relation_info = resultRelInfo;
2707  }
2708  }
2709  }
2710 
2711  /* Flush any remaining buffered tuples */
2712  if (nBufferedTuples > 0)
2713  CopyFromInsertBatch(cstate, estate, mycid, hi_options,
2714  resultRelInfo, myslot, bistate,
2715  nBufferedTuples, bufferedTuples,
2716  firstBufferedLineNo);
2717 
2718  /* Done, clean up */
2719  error_context_stack = errcallback.previous;
2720 
2721  FreeBulkInsertState(bistate);
2722 
2723  MemoryContextSwitchTo(oldcontext);
2724 
2725  /*
2726  * In the old protocol, tell pqcomm that we can process normal protocol
2727  * messages again.
2728  */
2729  if (cstate->copy_dest == COPY_OLD_FE)
2730  pq_endmsgread();
2731 
2732  /* Execute AFTER STATEMENT insertion triggers */
2733  ExecASInsertTriggers(estate, resultRelInfo);
2734 
2735  /* Handle queued AFTER triggers */
2736  AfterTriggerEndQuery(estate);
2737 
2738  pfree(values);
2739  pfree(nulls);
2740 
2741  ExecResetTupleTable(estate->es_tupleTable, false);
2742 
2743  ExecCloseIndices(resultRelInfo);
2744 
2745  /* Close all the partitioned tables, leaf partitions, and their indices */
2746  if (cstate->partition_dispatch_info)
2747  {
2748  int i;
2749 
2750  /*
2751  * Remember cstate->partition_dispatch_info[0] corresponds to the root
2752  * partitioned table, which we must not try to close, because it is
2753  * the main target table of COPY that will be closed eventually by
2754  * DoCopy(). Also, tupslot is NULL for the root partitioned table.
2755  */
2756  for (i = 1; i < cstate->num_dispatch; i++)
2757  {
2759 
2760  heap_close(pd->reldesc, NoLock);
2762  }
2763  for (i = 0; i < cstate->num_partitions; i++)
2764  {
2765  ResultRelInfo *resultRelInfo = cstate->partitions + i;
2766 
2767  ExecCloseIndices(resultRelInfo);
2768  heap_close(resultRelInfo->ri_RelationDesc, NoLock);
2769  }
2770 
2771  /* Release the standalone partition tuple descriptor */
2773  }
2774 
2775  FreeExecutorState(estate);
2776 
2777  /*
2778  * If we skipped writing WAL, then we need to sync the heap (but not
2779  * indexes since those use WAL anyway)
2780  */
2781  if (hi_options & HEAP_INSERT_SKIP_WAL)
2782  heap_sync(cstate->rel);
2783 
2784  return processed;
2785 }
int ri_NumIndices
Definition: execnodes.h:336
#define NIL
Definition: pg_list.h:69
uint32 CommandId
Definition: c.h:407
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1221
Relation ri_RelationDesc
Definition: execnodes.h:335
List * range_table
Definition: copy.c:163
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
int errhint(const char *fmt,...)
Definition: elog.c:987
void CopyFromErrorCallback(void *arg)
Definition: copy.c:2184
List * ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:271
#define ResetPerTupleExprContext(estate)
Definition: executor.h:347
#define RelationGetDescr(relation)
Definition: rel.h:425
#define HEAP_INSERT_FROZEN
Definition: heapam.h:30
ResultRelInfo * partitions
Definition: copy.c:168
#define XLogIsNeeded()
Definition: xlog.h:145
#define MAX_BUFFERED_TUPLES
TupleTableSlot * ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2251
#define RELKIND_MATVIEW
Definition: pg_class.h:167
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
bool ThereAreNoPriorRegisteredSnapshots(void)
Definition: snapmgr.c:1603
int errcode(int sqlerrcode)
Definition: elog.c:575
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:110
void heap_sync(Relation rel)
Definition: heapam.c:9122
#define HEAP_INSERT_SKIP_WAL
Definition: heapam.h:28
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:692
#define heap_close(r, l)
Definition: heapam.h:97
List * es_range_table
Definition: execnodes.h:372
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool volatile_defexprs
Definition: copy.c:162
struct ErrorContextCallback * previous
Definition: elog.h:238
int natts
Definition: tupdesc.h:73
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
CopyDest copy_dest
Definition: copy.c:96
#define HeapTupleSetOid(tuple, oid)
Definition: htup_details.h:698
ErrorContextCallback * error_context_stack
Definition: elog.c:88
bool trig_insert_instead_row
Definition: reltrigger.h:57
void FreeExecutorState(EState *estate)
Definition: execUtils.c:168
Relation rel
Definition: copy.c:107
#define GetPerTupleExprContext(estate)
Definition: executor.h:338
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:2306
void pfree(void *pointer)
Definition: mcxt.c:992
bool ThereAreNoReadyPortals(void)
Definition: portalmem.c:1127
TupleTableSlot * partition_tuple_slot
Definition: copy.c:170
#define ERROR
Definition: elog.h:43
static void CopyFromInsertBatch(CopyState cstate, EState *estate, CommandId mycid, int hi_options, ResultRelInfo *resultRelInfo, TupleTableSlot *myslot, BulkInsertState bistate, int nBufferedTuples, HeapTuple *bufferedTuples, int firstBufferedLineNo)
Definition: copy.c:2793
ItemPointerData t_self
Definition: htup.h:65
TriggerDesc * trigdesc
Definition: rel.h:119
int num_dispatch
Definition: copy.c:166
uint32 t_len
Definition: htup.h:64
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2111
#define NoLock
Definition: lockdefs.h:34
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:216
ResultRelInfo * es_result_relations
Definition: execnodes.h:382
#define RelationGetRelationName(relation)
Definition: rel.h:433
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:343
Oid t_tableOid
Definition: htup.h:66
#define RELKIND_FOREIGN_TABLE
Definition: pg_class.h:166
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:388
#define ereport(elevel, rest)
Definition: elog.h:122
Oid heap_insert(Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2383
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:339
EState * CreateExecutorState(void)
Definition: execUtils.c:72
SubTransactionId rd_createSubid
Definition: rel.h:109
#define RELKIND_PARTITIONED_TABLE
Definition: pg_class.h:168
bool trig_insert_before_row
Definition: reltrigger.h:55
List * es_tupleTable
Definition: execnodes.h:399
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
uintptr_t Datum
Definition: postgres.h:374
TupleTableSlot * tupslot
Definition: partition.h:66
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2163
int ExecFindPartition(ResultRelInfo *resultRelInfo, PartitionDispatch *pd, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:3188
int es_num_result_relations
Definition: execnodes.h:383
List * ri_PartitionCheck
Definition: execnodes.h:353
TupleDesc rd_att
Definition: rel.h:114
bool freeze
Definition: copy.c:114
void pq_endmsgread(void)
Definition: pqcomm.c:1181
#define InvalidOid
Definition: postgres_ext.h:36
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, TupleTableSlot *orig_slot, EState *estate)
Definition: execMain.c:1789
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4150
#define makeNode(_type_)
Definition: nodes.h:556
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:2320
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:648
TupleConstr * constr
Definition: tupdesc.h:76
size_t Size
Definition: c.h:352
#define InvalidSubTransactionId
Definition: c.h:399
HeapTuple ExecMaterializeSlot(TupleTableSlot *slot)
Definition: execTuples.c:725
void ReleaseBulkInsertStatePin(BulkInsertState bistate)
Definition: heapam.c:2332
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes)
Definition: trigger.c:2239
HeapTuple do_convert_tuple(HeapTuple tuple, TupleConversionMap *map)
Definition: tupconvert.c:341
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:343
#define HEAP_INSERT_SKIP_FSM
Definition: heapam.h:29
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4170
void(* callback)(void *arg)
Definition: elog.h:239
void * palloc(Size size)
Definition: mcxt.c:891
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_VIEW
Definition: pg_class.h:164
void list_free(List *list)
Definition: list.c:1133
bool NextCopyFrom(CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
Definition: copy.c:3177
int i
int cur_lineno
Definition: copy.c:136
PartitionDispatch * partition_dispatch_info
Definition: copy.c:165
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
TupleTableSlot * ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2173
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:686
TupleConversionMap ** partition_tupconv_maps
Definition: copy.c:169
#define RELKIND_RELATION
Definition: pg_class.h:160
#define RELKIND_SEQUENCE
Definition: pg_class.h:162
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:413
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
int num_partitions
Definition: copy.c:167
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:384
void CopyFromErrorCallback ( void *  arg)

Definition at line 2184 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, and pfree().

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

2185 {
2186  CopyState cstate = (CopyState) arg;
2187 
2188  if (cstate->binary)
2189  {
2190  /* can't usefully display the data */
2191  if (cstate->cur_attname)
2192  errcontext("COPY %s, line %d, column %s",
2193  cstate->cur_relname, cstate->cur_lineno,
2194  cstate->cur_attname);
2195  else
2196  errcontext("COPY %s, line %d",
2197  cstate->cur_relname, cstate->cur_lineno);
2198  }
2199  else
2200  {
2201  if (cstate->cur_attname && cstate->cur_attval)
2202  {
2203  /* error is relevant to a particular column */
2204  char *attval;
2205 
2206  attval = limit_printout_length(cstate->cur_attval);
2207  errcontext("COPY %s, line %d, column %s: \"%s\"",
2208  cstate->cur_relname, cstate->cur_lineno,
2209  cstate->cur_attname, attval);
2210  pfree(attval);
2211  }
2212  else if (cstate->cur_attname)
2213  {
2214  /* error is relevant to a particular column, value is NULL */
2215  errcontext("COPY %s, line %d, column %s: null input",
2216  cstate->cur_relname, cstate->cur_lineno,
2217  cstate->cur_attname);
2218  }
2219  else
2220  {
2221  /*
2222  * Error is relevant to a particular line.
2223  *
2224  * If line_buf still contains the correct line, and it's already
2225  * transcoded, print it. If it's still in a foreign encoding, it's
2226  * quite likely that the error is precisely a failure to do
2227  * encoding conversion (ie, bad data). We dare not try to convert
2228  * it, and at present there's no way to regurgitate it without
2229  * conversion. So we have to punt and just report the line number.
2230  */
2231  if (cstate->line_buf_valid &&
2232  (cstate->line_buf_converted || !cstate->need_transcoding))
2233  {
2234  char *lineval;
2235 
2236  lineval = limit_printout_length(cstate->line_buf.data);
2237  errcontext("COPY %s, line %d: \"%s\"",
2238  cstate->cur_relname, cstate->cur_lineno, lineval);
2239  pfree(lineval);
2240  }
2241  else
2242  {
2243  errcontext("COPY %s, line %d",
2244  cstate->cur_relname, cstate->cur_lineno);
2245  }
2246  }
2247  }
2248 }
bool binary
Definition: copy.c:112
bool need_transcoding
Definition: copy.c:103
StringInfoData line_buf
Definition: copy.c:194
bool line_buf_valid
Definition: copy.c:196
bool line_buf_converted
Definition: copy.c:195
const char * cur_attname
Definition: copy.c:137
void pfree(void *pointer)
Definition: mcxt.c:992
static char * limit_printout_length(const char *str)
Definition: copy.c:2260
const char * cur_relname
Definition: copy.c:135
#define errcontext
Definition: elog.h:164
struct CopyStateData * CopyState
Definition: copy.h:23
void * arg
int cur_lineno
Definition: copy.c:136
const char * cur_attval
Definition: copy.c:138
static void CopyFromInsertBatch ( CopyState  cstate,
EState estate,
CommandId  mycid,
int  hi_options,
ResultRelInfo resultRelInfo,
TupleTableSlot myslot,
BulkInsertState  bistate,
int  nBufferedTuples,
HeapTuple bufferedTuples,
int  firstBufferedLineNo 
)
static

Definition at line 2793 of file copy.c.

References CopyStateData::cur_lineno, ExecARInsertTriggers(), ExecInsertIndexTuples(), ExecStoreTuple(), GetPerTupleMemoryContext, heap_multi_insert(), i, InvalidBuffer, CopyStateData::line_buf_valid, list_free(), MemoryContextSwitchTo(), NIL, NULL, CopyStateData::rel, ResultRelInfo::ri_NumIndices, ResultRelInfo::ri_TrigDesc, and TriggerDesc::trig_insert_after_row.

Referenced by CopyFrom().

2798 {
2799  MemoryContext oldcontext;
2800  int i;
2801  int save_cur_lineno;
2802 
2803  /*
2804  * Print error context information correctly, if one of the operations
2805  * below fail.
2806  */
2807  cstate->line_buf_valid = false;
2808  save_cur_lineno = cstate->cur_lineno;
2809 
2810  /*
2811  * heap_multi_insert leaks memory, so switch to short-lived memory context
2812  * before calling it.
2813  */
2814  oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2815  heap_multi_insert(cstate->rel,
2816  bufferedTuples,
2817  nBufferedTuples,
2818  mycid,
2819  hi_options,
2820  bistate);
2821  MemoryContextSwitchTo(oldcontext);
2822 
2823  /*
2824  * If there are any indexes, update them for all the inserted tuples, and
2825  * run AFTER ROW INSERT triggers.
2826  */
2827  if (resultRelInfo->ri_NumIndices > 0)
2828  {
2829  for (i = 0; i < nBufferedTuples; i++)
2830  {
2831  List *recheckIndexes;
2832 
2833  cstate->cur_lineno = firstBufferedLineNo + i;
2834  ExecStoreTuple(bufferedTuples[i], myslot, InvalidBuffer, false);
2835  recheckIndexes =
2836  ExecInsertIndexTuples(myslot, &(bufferedTuples[i]->t_self),
2837  estate, false, NULL, NIL);
2838  ExecARInsertTriggers(estate, resultRelInfo,
2839  bufferedTuples[i],
2840  recheckIndexes);
2841  list_free(recheckIndexes);
2842  }
2843  }
2844 
2845  /*
2846  * There's no indexes, but see if we need to run AFTER ROW INSERT triggers
2847  * anyway.
2848  */
2849  else if (resultRelInfo->ri_TrigDesc != NULL &&
2850  resultRelInfo->ri_TrigDesc->trig_insert_after_row)
2851  {
2852  for (i = 0; i < nBufferedTuples; i++)
2853  {
2854  cstate->cur_lineno = firstBufferedLineNo + i;
2855  ExecARInsertTriggers(estate, resultRelInfo,
2856  bufferedTuples[i],
2857  NIL);
2858  }
2859  }
2860 
2861  /* reset cur_lineno to where we were */
2862  cstate->cur_lineno = save_cur_lineno;
2863 }
int ri_NumIndices
Definition: execnodes.h:336
#define NIL
Definition: pg_list.h:69
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
List * ExecInsertIndexTuples(TupleTableSlot *slot, ItemPointer tupleid, EState *estate, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:271
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define InvalidBuffer
Definition: buf.h:25
bool line_buf_valid
Definition: copy.c:196
Relation rel
Definition: copy.c:107
bool trig_insert_after_row
Definition: reltrigger.h:56
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:339
#define NULL
Definition: c.h:226
void heap_multi_insert(Relation relation, HeapTuple *tuples, int ntuples, CommandId cid, int options, BulkInsertState bistate)
Definition: heapam.c:2645
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, HeapTuple trigtuple, List *recheckIndexes)
Definition: trigger.c:2239
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:343
void list_free(List *list)
Definition: list.c:1133
int i
int cur_lineno
Definition: copy.c:136
Definition: pg_list.h:45
static List * CopyGetAttnums ( TupleDesc  tupDesc,
Relation  rel,
List attnamelist 
)
static

Definition at line 4610 of file copy.c.

References tupleDesc::attrs, ereport, errcode(), errmsg(), ERROR, i, InvalidAttrNumber, lappend_int(), lfirst, list_member_int(), name, namestrcmp(), tupleDesc::natts, NIL, NULL, RelationGetRelationName, and strVal.

Referenced by BeginCopy(), and DoCopy().

4611 {
4612  List *attnums = NIL;
4613 
4614  if (attnamelist == NIL)
4615  {
4616  /* Generate default column list */
4617  Form_pg_attribute *attr = tupDesc->attrs;
4618  int attr_count = tupDesc->natts;
4619  int i;
4620 
4621  for (i = 0; i < attr_count; i++)
4622  {
4623  if (attr[i]->attisdropped)
4624  continue;
4625  attnums = lappend_int(attnums, i + 1);
4626  }
4627  }
4628  else
4629  {
4630  /* Validate the user-supplied list and extract attnums */
4631  ListCell *l;
4632 
4633  foreach(l, attnamelist)
4634  {
4635  char *name = strVal(lfirst(l));
4636  int attnum;
4637  int i;
4638 
4639  /* Lookup column name */
4640  attnum = InvalidAttrNumber;
4641  for (i = 0; i < tupDesc->natts; i++)
4642  {
4643  if (tupDesc->attrs[i]->attisdropped)
4644  continue;
4645  if (namestrcmp(&(tupDesc->attrs[i]->attname), name) == 0)
4646  {
4647  attnum = tupDesc->attrs[i]->attnum;
4648  break;
4649  }
4650  }
4651  if (attnum == InvalidAttrNumber)
4652  {
4653  if (rel != NULL)
4654  ereport(ERROR,
4655  (errcode(ERRCODE_UNDEFINED_COLUMN),
4656  errmsg("column \"%s\" of relation \"%s\" does not exist",
4657  name, RelationGetRelationName(rel))));
4658  else
4659  ereport(ERROR,
4660  (errcode(ERRCODE_UNDEFINED_COLUMN),
4661  errmsg("column \"%s\" does not exist",
4662  name)));
4663  }
4664  /* Check for duplicates */
4665  if (list_member_int(attnums, attnum))
4666  ereport(ERROR,
4667  (errcode(ERRCODE_DUPLICATE_COLUMN),
4668  errmsg("column \"%s\" specified more than once",
4669  name)));
4670  attnums = lappend_int(attnums, attnum);
4671  }
4672  }
4673 
4674  return attnums;
4675 }
#define NIL
Definition: pg_list.h:69
Form_pg_attribute * attrs
Definition: tupdesc.h:74
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:575
int namestrcmp(Name name, const char *str)
Definition: name.c:248
int natts
Definition: tupdesc.h:73
#define ERROR
Definition: elog.h:43
bool list_member_int(const List *list, int datum)
Definition: list.c:485
#define RelationGetRelationName(relation)
Definition: rel.h:433
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend_int(List *list, int datum)
Definition: list.c:146
#define NULL
Definition: c.h:226
#define lfirst(lc)
Definition: pg_list.h:106
const char * name
Definition: encode.c:521
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
Definition: pg_list.h:45
static int CopyGetData ( CopyState  cstate,
void *  databuf,
int  minread,
int  maxread 
)
static

Definition at line 551 of file copy.c.

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

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

552 {
553  int bytesread = 0;
554 
555  switch (cstate->copy_dest)
556  {
557  case COPY_FILE:
558  bytesread = fread(databuf, 1, maxread, cstate->copy_file);
559  if (ferror(cstate->copy_file))
560  ereport(ERROR,
562  errmsg("could not read from COPY file: %m")));
563  break;
564  case COPY_OLD_FE:
565 
566  /*
567  * We cannot read more than minread bytes (which in practice is 1)
568  * because old protocol doesn't have any clear way of separating
569  * the COPY stream from following data. This is slow, but not any
570  * slower than the code path was originally, and we don't care
571  * much anymore about the performance of old protocol.
572  */
573  if (pq_getbytes((char *) databuf, minread))
574  {
575  /* Only a \. terminator is legal EOF in old protocol */
576  ereport(ERROR,
577  (errcode(ERRCODE_CONNECTION_FAILURE),
578  errmsg("unexpected EOF on client connection with an open transaction")));
579  }
580  bytesread = minread;
581  break;
582  case COPY_NEW_FE:
583  while (maxread > 0 && bytesread < minread && !cstate->fe_eof)
584  {
585  int avail;
586 
587  while (cstate->fe_msgbuf->cursor >= cstate->fe_msgbuf->len)
588  {
589  /* Try to receive another message */
590  int mtype;
591 
592  readmessage:
594  pq_startmsgread();
595  mtype = pq_getbyte();
596  if (mtype == EOF)
597  ereport(ERROR,
598  (errcode(ERRCODE_CONNECTION_FAILURE),
599  errmsg("unexpected EOF on client connection with an open transaction")));
600  if (pq_getmessage(cstate->fe_msgbuf, 0))
601  ereport(ERROR,
602  (errcode(ERRCODE_CONNECTION_FAILURE),
603  errmsg("unexpected EOF on client connection with an open transaction")));
605  switch (mtype)
606  {
607  case 'd': /* CopyData */
608  break;
609  case 'c': /* CopyDone */
610  /* COPY IN correctly terminated by frontend */
611  cstate->fe_eof = true;
612  return bytesread;
613  case 'f': /* CopyFail */
614  ereport(ERROR,
615  (errcode(ERRCODE_QUERY_CANCELED),
616  errmsg("COPY from stdin failed: %s",
617  pq_getmsgstring(cstate->fe_msgbuf))));
618  break;
619  case 'H': /* Flush */
620  case 'S': /* Sync */
621 
622  /*
623  * Ignore Flush/Sync for the convenience of client
624  * libraries (such as libpq) that may send those
625  * without noticing that the command they just
626  * sent was COPY.
627  */
628  goto readmessage;
629  default:
630  ereport(ERROR,
631  (errcode(ERRCODE_PROTOCOL_VIOLATION),
632  errmsg("unexpected message type 0x%02X during COPY from stdin",
633  mtype)));
634  break;
635  }
636  }
637  avail = cstate->fe_msgbuf->len - cstate->fe_msgbuf->cursor;
638  if (avail > maxread)
639  avail = maxread;
640  pq_copymsgbytes(cstate->fe_msgbuf, databuf, avail);
641  databuf = (void *) ((char *) databuf + avail);
642  maxread -= avail;
643  bytesread += avail;
644  }
645  break;
646  }
647 
648  return bytesread;
649 }
#define HOLD_CANCEL_INTERRUPTS()
Definition: miscadmin.h:122
const char * pq_getmsgstring(StringInfo msg)
Definition: pqformat.c:621
int errcode(int sqlerrcode)
Definition: elog.c:575
bool fe_eof
Definition: copy.c:100
CopyDest copy_dest
Definition: copy.c:96
Definition: copy.c:61
#define ERROR
Definition: elog.h:43
void pq_startmsgread(void)
Definition: pqcomm.c:1157
int pq_getbytes(char *s, size_t len)
Definition: pqcomm.c:1041
int errcode_for_file_access(void)
Definition: elog.c:598
#define ereport(elevel, rest)
Definition: elog.h:122
int pq_getmessage(StringInfo s, int maxlen)
Definition: pqcomm.c:1219
int pq_getbyte(void)
Definition: pqcomm.c:947
StringInfo fe_msgbuf
Definition: copy.c:98
void pq_copymsgbytes(StringInfo msg, char *buf, int datalen)
Definition: pqformat.c:570
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE * copy_file
Definition: copy.c:97
#define RESUME_CANCEL_INTERRUPTS()
Definition: miscadmin.h:124
static bool CopyGetInt16 ( CopyState  cstate,
int16 val 
)
static

Definition at line 703 of file copy.c.

References buf, and CopyGetData().

Referenced by NextCopyFrom().

704 {
705  uint16 buf;
706 
707  if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
708  {
709  *val = 0; /* suppress compiler warning */
710  return false;
711  }
712  *val = (int16) ntohs(buf);
713  return true;
714 }
signed short int16
Definition: c.h:252
unsigned short uint16
Definition: c.h:264
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:551
static char * buf
Definition: pg_test_fsync.c:65
long val
Definition: informix.c:689
static bool CopyGetInt32 ( CopyState  cstate,
int32 val 
)
static

Definition at line 674 of file copy.c.

References buf, and CopyGetData().

Referenced by BeginCopyFrom(), and CopyReadBinaryAttribute().

675 {
676  uint32 buf;
677 
678  if (CopyGetData(cstate, &buf, sizeof(buf), sizeof(buf)) != sizeof(buf))
679  {
680  *val = 0; /* suppress compiler warning */
681  return false;
682  }
683  *val = (int32) ntohl(buf);
684  return true;
685 }
signed int int32
Definition: c.h:253
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:551
static char * buf
Definition: pg_test_fsync.c:65
unsigned int uint32
Definition: c.h:265
long val
Definition: informix.c:689
static bool CopyLoadRawBuf ( CopyState  cstate)
static

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

729 {
730  int nbytes;
731  int inbytes;
732 
733  if (cstate->raw_buf_index < cstate->raw_buf_len)
734  {
735  /* Copy down the unprocessed data */
736  nbytes = cstate->raw_buf_len - cstate->raw_buf_index;
737  memmove(cstate->raw_buf, cstate->raw_buf + cstate->raw_buf_index,
738  nbytes);
739  }
740  else
741  nbytes = 0; /* no data need be saved */
742 
743  inbytes = CopyGetData(cstate, cstate->raw_buf + nbytes,
744  1, RAW_BUF_SIZE - nbytes);
745  nbytes += inbytes;
746  cstate->raw_buf[nbytes] = '\0';
747  cstate->raw_buf_index = 0;
748  cstate->raw_buf_len = nbytes;
749  return (inbytes > 0);
750 }
int raw_buf_index
Definition: copy.c:207
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:551
char * raw_buf
Definition: copy.c:206
#define memmove(d, s, c)
Definition: c.h:1057
int raw_buf_len
Definition: copy.c:208
#define RAW_BUF_SIZE
Definition: copy.c:205
static void CopyOneRowTo ( CopyState  cstate,
Oid  tupleOid,
Datum values,
bool nulls 
)
static

Definition at line 2090 of file copy.c.

References CopyStateData::attnumlist, CopyStateData::binary, CopyAttributeOutCSV(), CopyAttributeOutText(), CopySendChar(), CopySendData(), CopySendEndOfRow(), CopySendInt16(), CopySendInt32(), CopySendString(), CopyStateData::csv_mode, cur, DatumGetCString, CopyStateData::delim, DirectFunctionCall1, CopyStateData::force_quote_flags, lfirst_int, list_length(), MemoryContextReset(), MemoryContextSwitchTo(), CopyStateData::null_print_client, ObjectIdGetDatum, oidout(), CopyStateData::oids, CopyStateData::out_functions, OutputFunctionCall(), CopyStateData::rowcontext, SendFunctionCall(), value, VARDATA, VARHDRSZ, and VARSIZE.

Referenced by copy_dest_receive(), and CopyTo().

2091 {
2092  bool need_delim = false;
2093  FmgrInfo *out_functions = cstate->out_functions;
2094  MemoryContext oldcontext;
2095  ListCell *cur;
2096  char *string;
2097 
2098  MemoryContextReset(cstate->rowcontext);
2099  oldcontext = MemoryContextSwitchTo(cstate->rowcontext);
2100 
2101  if (cstate->binary)
2102  {
2103  /* Binary per-tuple header */
2104  CopySendInt16(cstate, list_length(cstate->attnumlist));
2105  /* Send OID if wanted --- note attnumlist doesn't include it */
2106  if (cstate->oids)
2107  {
2108  /* Hack --- assume Oid is same size as int32 */
2109  CopySendInt32(cstate, sizeof(int32));
2110  CopySendInt32(cstate, tupleOid);
2111  }
2112  }
2113  else
2114  {
2115  /* Text format has no per-tuple header, but send OID if wanted */
2116  /* Assume digits don't need any quoting or encoding conversion */
2117  if (cstate->oids)
2118  {
2120  ObjectIdGetDatum(tupleOid)));
2121  CopySendString(cstate, string);
2122  need_delim = true;
2123  }
2124  }
2125 
2126  foreach(cur, cstate->attnumlist)
2127  {
2128  int attnum = lfirst_int(cur);
2129  Datum value = values[attnum - 1];
2130  bool isnull = nulls[attnum - 1];
2131 
2132  if (!cstate->binary)
2133  {
2134  if (need_delim)
2135  CopySendChar(cstate, cstate->delim[0]);
2136  need_delim = true;
2137  }
2138 
2139  if (isnull)
2140  {
2141  if (!cstate->binary)
2142  CopySendString(cstate, cstate->null_print_client);
2143  else
2144  CopySendInt32(cstate, -1);
2145  }
2146  else
2147  {
2148  if (!cstate->binary)
2149  {
2150  string = OutputFunctionCall(&out_functions[attnum - 1],
2151  value);
2152  if (cstate->csv_mode)
2153  CopyAttributeOutCSV(cstate, string,
2154  cstate->force_quote_flags[attnum - 1],
2155  list_length(cstate->attnumlist) == 1);
2156  else
2157  CopyAttributeOutText(cstate, string);
2158  }
2159  else
2160  {
2161  bytea *outputbytes;
2162 
2163  outputbytes = SendFunctionCall(&out_functions[attnum - 1],
2164  value);
2165  CopySendInt32(cstate, VARSIZE(outputbytes) - VARHDRSZ);
2166  CopySendData(cstate, VARDATA(outputbytes),
2167  VARSIZE(outputbytes) - VARHDRSZ);
2168  }
2169  }
2170  }
2171 
2172  CopySendEndOfRow(cstate);
2173 
2174  MemoryContextSwitchTo(oldcontext);
2175 }
Definition: fmgr.h:53
bool csv_mode
Definition: copy.c:115
static struct @76 value
#define VARDATA(PTR)
Definition: postgres.h:305
bool binary
Definition: copy.c:112
List * attnumlist
Definition: copy.c:109
#define VARSIZE(PTR)
Definition: postgres.h:306
#define VARHDRSZ
Definition: c.h:440
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
struct cursor * cur
Definition: ecpg.c:28
static void CopyAttributeOutText(CopyState cstate, char *string)
Definition: copy.c:4366
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:135
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:555
bool * force_quote_flags
Definition: copy.c:125
char * delim
Definition: copy.c:120
Datum oidout(PG_FUNCTION_ARGS)
Definition: oid.c:127
MemoryContext rowcontext
Definition: copy.c:149
signed int int32
Definition: c.h:253
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:455
char * OutputFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1926
static void CopySendInt16(CopyState cstate, int16 val)
Definition: copy.c:691
#define ObjectIdGetDatum(X)
Definition: postgres.h:515
#define DatumGetCString(X)
Definition: postgres.h:574
#define lfirst_int(lc)
Definition: pg_list.h:107
static void CopyAttributeOutCSV(CopyState cstate, char *string, bool use_quote, bool single_attr)
Definition: copy.c:4519
char string[11]
Definition: preproc-type.c:46
bytea * SendFunctionCall(FmgrInfo *flinfo, Datum val)
Definition: fmgr.c:1987
uintptr_t Datum
Definition: postgres.h:374
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:443
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:449
static int list_length(const List *l)
Definition: pg_list.h:89
static void CopySendInt32(CopyState cstate, int32 val)
Definition: copy.c:660
static Datum values[MAXATTR]
Definition: bootstrap.c:162
FmgrInfo * out_functions
Definition: copy.c:148
static void CopySendEndOfRow(CopyState cstate)
Definition: copy.c:461
Definition: c.h:434
char * null_print_client
Definition: copy.c:119
bool oids
Definition: copy.c:113
static int CopyReadAttributesCSV ( CopyState  cstate)
static

Definition at line 4138 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, NULL, CopyStateData::null_print, CopyStateData::null_print_len, CopyStateData::quote, CopyStateData::raw_fields, repalloc(), and resetStringInfo().

Referenced by NextCopyFromRawFields().

4139 {
4140  char delimc = cstate->delim[0];
4141  char quotec = cstate->quote[0];
4142  char escapec = cstate->escape[0];
4143  int fieldno;
4144  char *output_ptr;
4145  char *cur_ptr;
4146  char *line_end_ptr;
4147 
4148  /*
4149  * We need a special case for zero-column tables: check that the input
4150  * line is empty, and return.
4151  */
4152  if (cstate->max_fields <= 0)
4153  {
4154  if (cstate->line_buf.len != 0)
4155  ereport(ERROR,
4156  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4157  errmsg("extra data after last expected column")));
4158  return 0;
4159  }
4160 
4161  resetStringInfo(&cstate->attribute_buf);
4162 
4163  /*
4164  * The de-escaped attributes will certainly not be longer than the input
4165  * data line, so we can just force attribute_buf to be large enough and
4166  * then transfer data without any checks for enough space. We need to do
4167  * it this way because enlarging attribute_buf mid-stream would invalidate
4168  * pointers already stored into cstate->raw_fields[].
4169  */
4170  if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
4171  enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
4172  output_ptr = cstate->attribute_buf.data;
4173 
4174  /* set pointer variables for loop */
4175  cur_ptr = cstate->line_buf.data;
4176  line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
4177 
4178  /* Outer loop iterates over fields */
4179  fieldno = 0;
4180  for (;;)
4181  {
4182  bool found_delim = false;
4183  bool saw_quote = false;
4184  char *start_ptr;
4185  char *end_ptr;
4186  int input_len;
4187 
4188  /* Make sure there is enough space for the next value */
4189  if (fieldno >= cstate->max_fields)
4190  {
4191  cstate->max_fields *= 2;
4192  cstate->raw_fields =
4193  repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
4194  }
4195 
4196  /* Remember start of field on both input and output sides */
4197  start_ptr = cur_ptr;
4198  cstate->raw_fields[fieldno] = output_ptr;
4199 
4200  /*
4201  * Scan data for field,
4202  *
4203  * The loop starts in "not quote" mode and then toggles between that
4204  * and "in quote" mode. The loop exits normally if it is in "not
4205  * quote" mode and a delimiter or line end is seen.
4206  */
4207  for (;;)
4208  {
4209  char c;
4210 
4211  /* Not in quote */
4212  for (;;)
4213  {
4214  end_ptr = cur_ptr;
4215  if (cur_ptr >= line_end_ptr)
4216  goto endfield;
4217  c = *cur_ptr++;
4218  /* unquoted field delimiter */
4219  if (c == delimc)
4220  {
4221  found_delim = true;
4222  goto endfield;
4223  }
4224  /* start of quoted field (or part of field) */
4225  if (c == quotec)
4226  {
4227  saw_quote = true;
4228  break;
4229  }
4230  /* Add c to output string */
4231  *output_ptr++ = c;
4232  }
4233 
4234  /* In quote */
4235  for (;;)
4236  {
4237  end_ptr = cur_ptr;
4238  if (cur_ptr >= line_end_ptr)
4239  ereport(ERROR,
4240  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4241  errmsg("unterminated CSV quoted field")));
4242 
4243  c = *cur_ptr++;
4244 
4245  /* escape within a quoted field */
4246  if (c == escapec)
4247  {
4248  /*
4249  * peek at the next char if available, and escape it if it
4250  * is an escape char or a quote char
4251  */
4252  if (cur_ptr < line_end_ptr)
4253  {
4254  char nextc = *cur_ptr;
4255 
4256  if (nextc == escapec || nextc == quotec)
4257  {
4258  *output_ptr++ = nextc;
4259  cur_ptr++;
4260  continue;
4261  }
4262  }
4263  }
4264 
4265  /*
4266  * end of quoted field. Must do this test after testing for
4267  * escape in case quote char and escape char are the same
4268  * (which is the common case).
4269  */
4270  if (c == quotec)
4271  break;
4272 
4273  /* Add c to output string */
4274  *output_ptr++ = c;
4275  }
4276  }
4277 endfield:
4278 
4279  /* Terminate attribute value in output area */
4280  *output_ptr++ = '\0';
4281 
4282  /* Check whether raw input matched null marker */
4283  input_len = end_ptr - start_ptr;
4284  if (!saw_quote && input_len == cstate->null_print_len &&
4285  strncmp(start_ptr, cstate->null_print, input_len) == 0)
4286  cstate->raw_fields[fieldno] = NULL;
4287 
4288  fieldno++;
4289  /* Done if we hit EOL instead of a delim */
4290  if (!found_delim)
4291  break;
4292  }
4293 
4294  /* Clean up state of attribute_buf */
4295  output_ptr--;
4296  Assert(*output_ptr == '\0');
4297  cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
4298 
4299  return fieldno;
4300 }
char ** raw_fields
Definition: copy.c:185
StringInfoData line_buf
Definition: copy.c:194
int errcode(int sqlerrcode)
Definition: elog.c:575
char * delim
Definition: copy.c:120
char * null_print
Definition: copy.c:117
#define ERROR
Definition: elog.h:43
char * c
char * quote
Definition: copy.c:121
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:277
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
int max_fields
Definition: copy.c:184
char * escape
Definition: copy.c:122
#define ereport(elevel, rest)
Definition: elog.h:122
int null_print_len
Definition: copy.c:118
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1021
int errmsg(const char *fmt,...)
Definition: elog.c:797
StringInfoData attribute_buf
Definition: copy.c:180
static int CopyReadAttributesText ( CopyState  cstate)
static

Definition at line 3910 of file copy.c.

References 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, NULL, CopyStateData::null_print, CopyStateData::null_print_len, OCTVALUE, pg_verifymbstr(), CopyStateData::raw_fields, repalloc(), resetStringInfo(), and val.

Referenced by NextCopyFromRawFields().

3911 {
3912  char delimc = cstate->delim[0];
3913  int fieldno;
3914  char *output_ptr;
3915  char *cur_ptr;
3916  char *line_end_ptr;
3917 
3918  /*
3919  * We need a special case for zero-column tables: check that the input
3920  * line is empty, and return.
3921  */
3922  if (cstate->max_fields <= 0)
3923  {
3924  if (cstate->line_buf.len != 0)
3925  ereport(ERROR,
3926  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3927  errmsg("extra data after last expected column")));
3928  return 0;
3929  }
3930 
3931  resetStringInfo(&cstate->attribute_buf);
3932 
3933  /*
3934  * The de-escaped attributes will certainly not be longer than the input
3935  * data line, so we can just force attribute_buf to be large enough and
3936  * then transfer data without any checks for enough space. We need to do
3937  * it this way because enlarging attribute_buf mid-stream would invalidate
3938  * pointers already stored into cstate->raw_fields[].
3939  */
3940  if (cstate->attribute_buf.maxlen <= cstate->line_buf.len)
3941  enlargeStringInfo(&cstate->attribute_buf, cstate->line_buf.len);
3942  output_ptr = cstate->attribute_buf.data;
3943 
3944  /* set pointer variables for loop */
3945  cur_ptr = cstate->line_buf.data;
3946  line_end_ptr = cstate->line_buf.data + cstate->line_buf.len;
3947 
3948  /* Outer loop iterates over fields */
3949  fieldno = 0;
3950  for (;;)
3951  {
3952  bool found_delim = false;
3953  char *start_ptr;
3954  char *end_ptr;
3955  int input_len;
3956  bool saw_non_ascii = false;
3957 
3958  /* Make sure there is enough space for the next value */
3959  if (fieldno >= cstate->max_fields)
3960  {
3961  cstate->max_fields *= 2;
3962  cstate->raw_fields =
3963  repalloc(cstate->raw_fields, cstate->max_fields * sizeof(char *));
3964  }
3965 
3966  /* Remember start of field on both input and output sides */
3967  start_ptr = cur_ptr;
3968  cstate->raw_fields[fieldno] = output_ptr;
3969 
3970  /*
3971  * Scan data for field.
3972  *
3973  * Note that in this loop, we are scanning to locate the end of field
3974  * and also speculatively performing de-escaping. Once we find the
3975  * end-of-field, we can match the raw field contents against the null
3976  * marker string. Only after that comparison fails do we know that
3977  * de-escaping is actually the right thing to do; therefore we *must
3978  * not* throw any syntax errors before we've done the null-marker
3979  * check.
3980  */
3981  for (;;)
3982  {
3983  char c;
3984 
3985  end_ptr = cur_ptr;
3986  if (cur_ptr >= line_end_ptr)
3987  break;
3988  c = *cur_ptr++;
3989  if (c == delimc)
3990  {
3991  found_delim = true;
3992  break;
3993  }
3994  if (c == '\\')
3995  {
3996  if (cur_ptr >= line_end_ptr)
3997  break;
3998  c = *cur_ptr++;
3999  switch (c)
4000  {
4001  case '0':
4002  case '1':
4003  case '2':
4004  case '3':
4005  case '4':
4006  case '5':
4007  case '6':
4008  case '7':
4009  {
4010  /* handle \013 */
4011  int val;
4012 
4013  val = OCTVALUE(c);
4014  if (cur_ptr < line_end_ptr)
4015  {
4016  c = *cur_ptr;
4017  if (ISOCTAL(c))
4018  {
4019  cur_ptr++;
4020  val = (val << 3) + OCTVALUE(c);
4021  if (cur_ptr < line_end_ptr)
4022  {
4023  c = *cur_ptr;
4024  if (ISOCTAL(c))
4025  {
4026  cur_ptr++;
4027  val = (val << 3) + OCTVALUE(c);
4028  }
4029  }
4030  }
4031  }
4032  c = val & 0377;
4033  if (c == '\0' || IS_HIGHBIT_SET(c))
4034  saw_non_ascii = true;
4035  }
4036  break;
4037  case 'x':
4038  /* Handle \x3F */
4039  if (cur_ptr < line_end_ptr)
4040  {
4041  char hexchar = *cur_ptr;
4042 
4043  if (isxdigit((unsigned char) hexchar))
4044  {
4045  int val = GetDecimalFromHex(hexchar);
4046 
4047  cur_ptr++;
4048  if (cur_ptr < line_end_ptr)
4049  {
4050  hexchar = *cur_ptr;
4051  if (isxdigit((unsigned char) hexchar))
4052  {
4053  cur_ptr++;
4054  val = (val << 4) + GetDecimalFromHex(hexchar);
4055  }
4056  }
4057  c = val & 0xff;
4058  if (c == '\0' || IS_HIGHBIT_SET(c))
4059  saw_non_ascii = true;
4060  }
4061  }
4062  break;
4063  case 'b':
4064  c = '\b';
4065  break;
4066  case 'f':
4067  c = '\f';
4068  break;
4069  case 'n':
4070  c = '\n';
4071  break;
4072  case 'r':
4073  c = '\r';
4074  break;
4075  case 't':
4076  c = '\t';
4077  break;
4078  case 'v':
4079  c = '\v';
4080  break;
4081 
4082  /*
4083  * in all other cases, take the char after '\'
4084  * literally
4085  */
4086  }
4087  }
4088 
4089  /* Add c to output string */
4090  *output_ptr++ = c;
4091  }
4092 
4093  /* Check whether raw input matched null marker */
4094  input_len = end_ptr - start_ptr;
4095  if (input_len == cstate->null_print_len &&
4096  strncmp(start_ptr, cstate->null_print, input_len) == 0)
4097  cstate->raw_fields[fieldno] = NULL;
4098  else
4099  {
4100  /*
4101  * At this point we know the field is supposed to contain data.
4102  *
4103  * If we de-escaped any non-7-bit-ASCII chars, make sure the
4104  * resulting string is valid data for the db encoding.
4105  */
4106  if (saw_non_ascii)
4107  {
4108  char *fld = cstate->raw_fields[fieldno];
4109 
4110  pg_verifymbstr(fld, output_ptr - fld, false);
4111  }
4112  }
4113 
4114  /* Terminate attribute value in output area */
4115  *output_ptr++ = '\0';
4116 
4117  fieldno++;
4118  /* Done if we hit EOL instead of a delim */
4119  if (!found_delim)
4120  break;
4121  }
4122 
4123  /* Clean up state of attribute_buf */
4124  output_ptr--;
4125  Assert(*output_ptr == '\0');
4126  cstate->attribute_buf.len = (output_ptr - cstate->attribute_buf.data);
4127 
4128  return fieldno;
4129 }
static int GetDecimalFromHex(char hex)
Definition: copy.c:3882
char ** raw_fields
Definition: copy.c:185
#define ISOCTAL(c)
Definition: copy.c:52
#define OCTVALUE(c)
Definition: copy.c:53
StringInfoData line_buf
Definition: copy.c:194
int errcode(int sqlerrcode)
Definition: elog.c:575
char * delim
Definition: copy.c:120
char * null_print
Definition: copy.c:117
#define IS_HIGHBIT_SET(ch)
Definition: c.h:968
#define ERROR
Definition: elog.h:43
char * c
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:277
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
int max_fields
Definition: copy.c:184
#define ereport(elevel, rest)
Definition: elog.h:122
int null_print_len
Definition: copy.c:118
#define NULL
Definition: c.h:226
#define Assert(condition)
Definition: c.h:670
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1021
int errmsg(const char *fmt,...)
Definition: elog.c:797
bool pg_verifymbstr(const char *mbstr, int len, bool noError)
Definition: wchar.c:1866
StringInfoData attribute_buf
Definition: copy.c:180
long val
Definition: informix.c:689
static Datum CopyReadBinaryAttribute ( CopyState  cstate,
int  column_no,
FmgrInfo flinfo,
Oid  typioparam,
int32  typmod,
bool isnull 
)
static

Definition at line 4307 of file copy.c.

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

Referenced by NextCopyFrom().

4311 {
4312  int32 fld_size;
4313  Datum result;
4314 
4315  if (!CopyGetInt32(cstate, &fld_size))
4316  ereport(ERROR,
4317  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4318  errmsg("unexpected EOF in COPY data")));
4319  if (fld_size == -1)
4320  {
4321  *isnull = true;
4322  return ReceiveFunctionCall(flinfo, NULL, typioparam, typmod);
4323  }
4324  if (fld_size < 0)
4325  ereport(ERROR,
4326  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4327  errmsg("invalid field size")));
4328 
4329  /* reset attribute_buf to empty, and load raw data in it */
4330  resetStringInfo(&cstate->attribute_buf);
4331 
4332  enlargeStringInfo(&cstate->attribute_buf, fld_size);
4333  if (CopyGetData(cstate, cstate->attribute_buf.data,
4334  fld_size, fld_size) != fld_size)
4335  ereport(ERROR,
4336  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
4337  errmsg("unexpected EOF in COPY data")));
4338 
4339  cstate->attribute_buf.len = fld_size;
4340  cstate->attribute_buf.data[fld_size] = '\0';
4341 
4342  /* Call the column type's binary input converter */
4343  result = ReceiveFunctionCall(flinfo, &cstate->attribute_buf,
4344  typioparam, typmod);
4345 
4346  /* Trouble if it didn't eat the whole buffer */
4347  if (cstate->attribute_buf.cursor != cstate->attribute_buf.len)
4348  ereport(ERROR,
4349  (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
4350  errmsg("incorrect binary data format")));
4351 
4352  *isnull = false;
4353  return result;
4354 }
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:674
int errcode(int sqlerrcode)
Definition: elog.c:575
signed int int32
Definition: c.h:253
#define ERROR
Definition: elog.h:43
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:551
Datum ReceiveFunctionCall(FmgrInfo *flinfo, StringInfo buf, Oid typioparam, int32 typmod)
Definition: fmgr.c:1940
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:277
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
#define ereport(elevel, rest)
Definition: elog.h:122
uintptr_t Datum
Definition: postgres.h:374
#define NULL
Definition: c.h:226
int errmsg(const char *fmt,...)
Definition: elog.c:797
StringInfoData attribute_buf
Definition: copy.c:180
static bool CopyReadLine ( CopyState  cstate)
static

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

3435 {
3436  bool result;
3437 
3438  resetStringInfo(&cstate->line_buf);
3439  cstate->line_buf_valid = true;
3440 
3441  /* Mark that encoding conversion hasn't occurred yet */
3442  cstate->line_buf_converted = false;
3443 
3444  /* Parse data and transfer into line_buf */
3445  result = CopyReadLineText(cstate);
3446 
3447  if (result)
3448  {
3449  /*
3450  * Reached EOF. In protocol version 3, we should ignore anything
3451  * after \. up to the protocol end of copy data. (XXX maybe better
3452  * not to treat \. as special?)
3453  */
3454  if (cstate->copy_dest == COPY_NEW_FE)
3455  {
3456  do
3457  {
3458  cstate->raw_buf_index = cstate->raw_buf_len;
3459  } while (CopyLoadRawBuf(cstate));
3460  }
3461  }
3462  else
3463  {
3464  /*
3465  * If we didn't hit EOF, then we must have transferred the EOL marker
3466  * to line_buf along with the data. Get rid of it.
3467  */
3468  switch (cstate->eol_type)
3469  {
3470  case EOL_NL:
3471  Assert(cstate->line_buf.len >= 1);
3472  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3473  cstate->line_buf.len--;
3474  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3475  break;
3476  case EOL_CR:
3477  Assert(cstate->line_buf.len >= 1);
3478  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\r');
3479  cstate->line_buf.len--;
3480  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3481  break;
3482  case EOL_CRNL:
3483  Assert(cstate->line_buf.len >= 2);
3484  Assert(cstate->line_buf.data[cstate->line_buf.len - 2] == '\r');
3485  Assert(cstate->line_buf.data[cstate->line_buf.len - 1] == '\n');
3486  cstate->line_buf.len -= 2;
3487  cstate->line_buf.data[cstate->line_buf.len] = '\0';
3488  break;
3489  case EOL_UNKNOWN:
3490  /* shouldn't get here */
3491  Assert(false);
3492  break;
3493  }
3494  }
3495 
3496  /* Done reading the line. Convert it to server encoding. */
3497  if (cstate->need_transcoding)
3498  {
3499  char *cvt;
3500 
3501  cvt = pg_any_to_server(cstate->line_buf.data,
3502  cstate->line_buf.len,
3503  cstate->file_encoding);
3504  if (cvt != cstate->line_buf.data)
3505  {
3506  /* transfer converted data back to line_buf */
3507  resetStringInfo(&cstate->line_buf);
3508  appendBinaryStringInfo(&cstate->line_buf, cvt, strlen(cvt));
3509  pfree(cvt);
3510  }
3511  }
3512 
3513  /* Now it's safe to use the buffer in error messages */
3514  cstate->line_buf_converted = true;
3515 
3516  return result;
3517 }
static bool CopyReadLineText(CopyState cstate)
Definition: copy.c:3523
Definition: copy.c:72
bool need_transcoding
Definition: copy.c:103
StringInfoData line_buf
Definition: copy.c:194
int raw_buf_index
Definition: copy.c:207
bool line_buf_valid
Definition: copy.c:196
bool line_buf_converted
Definition: copy.c:195
CopyDest copy_dest
Definition: copy.c:96
void pfree(void *pointer)
Definition: mcxt.c:992
static bool CopyLoadRawBuf(CopyState cstate)
Definition: copy.c:728
Definition: copy.c:73
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
int raw_buf_len
Definition: copy.c:208
Definition: copy.c:74
int file_encoding
Definition: copy.c:102
EolType eol_type
Definition: copy.c:101
#define Assert(condition)
Definition: c.h:670
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:572
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
static bool CopyReadLineText ( CopyState  cstate)
static

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

3524 {
3525  char *copy_raw_buf;
3526  int raw_buf_ptr;
3527  int copy_buf_len;
3528  bool need_data = false;
3529  bool hit_eof = false;
3530  bool result = false;
3531  char mblen_str[2];
3532 
3533  /* CSV variables */
3534  bool first_char_in_line = true;
3535  bool in_quote = false,
3536  last_was_esc = false;
3537  char quotec = '\0';
3538  char escapec = '\0';
3539 
3540  if (cstate->csv_mode)
3541  {
3542  quotec = cstate->quote[0];
3543  escapec = cstate->escape[0];
3544  /* ignore special escape processing if it's the same as quotec */
3545  if (quotec == escapec)
3546  escapec = '\0';
3547  }
3548 
3549  mblen_str[1] = '\0';
3550 
3551  /*
3552  * The objective of this loop is to transfer the entire next input line
3553  * into line_buf. Hence, we only care for detecting newlines (\r and/or
3554  * \n) and the end-of-copy marker (\.).
3555  *
3556  * In CSV mode, \r and \n inside a quoted field are just part of the data
3557  * value and are put in line_buf. We keep just enough state to know if we
3558  * are currently in a quoted field or not.
3559  *
3560  * These four characters, and the CSV escape and quote characters, are
3561  * assumed the same in frontend and backend encodings.
3562  *
3563  * For speed, we try to move data from raw_buf to line_buf in chunks
3564  * rather than one character at a time. raw_buf_ptr points to the next
3565  * character to examine; any characters from raw_buf_index to raw_buf_ptr
3566  * have been determined to be part of the line, but not yet transferred to
3567  * line_buf.
3568  *
3569  * For a little extra speed within the loop, we copy raw_buf and
3570  * raw_buf_len into local variables.
3571  */
3572  copy_raw_buf = cstate->raw_buf;
3573  raw_buf_ptr = cstate->raw_buf_index;
3574  copy_buf_len = cstate->raw_buf_len;
3575 
3576  for (;;)
3577  {
3578  int prev_raw_ptr;
3579  char c;
3580 
3581  /*
3582  * Load more data if needed. Ideally we would just force four bytes
3583  * of read-ahead and avoid the many calls to
3584  * IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(), but the COPY_OLD_FE protocol
3585  * does not allow us to read too far ahead or we might read into the
3586  * next data, so we read-ahead only as far we know we can. One
3587  * optimization would be to read-ahead four byte here if
3588  * cstate->copy_dest != COPY_OLD_FE, but it hardly seems worth it,
3589  * considering the size of the buffer.
3590  */
3591  if (raw_buf_ptr >= copy_buf_len || need_data)
3592  {
3594 
3595  /*
3596  * Try to read some more data. This will certainly reset
3597  * raw_buf_index to zero, and raw_buf_ptr must go with it.
3598  */
3599  if (!CopyLoadRawBuf(cstate))
3600  hit_eof = true;
3601  raw_buf_ptr = 0;
3602  copy_buf_len = cstate->raw_buf_len;
3603 
3604  /*
3605  * If we are completely out of data, break out of the loop,
3606  * reporting EOF.
3607  */
3608  if (copy_buf_len <= 0)
3609  {
3610  result = true;
3611  break;
3612  }
3613  need_data = false;
3614  }
3615 
3616  /* OK to fetch a character */
3617  prev_raw_ptr = raw_buf_ptr;
3618  c = copy_raw_buf[raw_buf_ptr++];
3619 
3620  if (cstate->csv_mode)
3621  {
3622  /*
3623  * If character is '\\' or '\r', we may need to look ahead below.
3624  * Force fetch of the next character if we don't already have it.
3625  * We need to do this before changing CSV state, in case one of
3626  * these characters is also the quote or escape character.
3627  *
3628  * Note: old-protocol does not like forced prefetch, but it's OK
3629  * here since we cannot validly be at EOF.
3630  */
3631  if (c == '\\' || c == '\r')
3632  {
3634  }
3635 
3636  /*
3637  * Dealing with quotes and escapes here is mildly tricky. If the
3638  * quote char is also the escape char, there's no problem - we
3639  * just use the char as a toggle. If they are different, we need
3640  * to ensure that we only take account of an escape inside a
3641  * quoted field and immediately preceding a quote char, and not
3642  * the second in an escape-escape sequence.
3643  */
3644  if (in_quote && c == escapec)
3645  last_was_esc = !last_was_esc;
3646  if (c == quotec && !last_was_esc)
3647  in_quote = !in_quote;
3648  if (c != escapec)
3649  last_was_esc = false;
3650 
3651  /*
3652  * Updating the line count for embedded CR and/or LF chars is
3653  * necessarily a little fragile - this test is probably about the
3654  * best we can do. (XXX it's arguable whether we should do this
3655  * at all --- is cur_lineno a physical or logical count?)
3656  */
3657  if (in_quote && c == (cstate->eol_type == EOL_NL ? '\n' : '\r'))
3658  cstate->cur_lineno++;
3659  }
3660 
3661  /* Process \r */
3662  if (c == '\r' && (!cstate->csv_mode || !in_quote))
3663  {
3664  /* Check for \r\n on first line, _and_ handle \r\n. */
3665  if (cstate->eol_type == EOL_UNKNOWN ||
3666  cstate->eol_type == EOL_CRNL)
3667  {
3668  /*
3669  * If need more data, go back to loop top to load it.
3670  *
3671  * Note that if we are at EOF, c will wind up as '\0' because
3672  * of the guaranteed pad of raw_buf.
3673  */
3675 
3676  /* get next char */
3677  c = copy_raw_buf[raw_buf_ptr];
3678 
3679  if (c == '\n')
3680  {
3681  raw_buf_ptr++; /* eat newline */
3682  cstate->eol_type = EOL_CRNL; /* in case not set yet */
3683  }
3684  else
3685  {
3686  /* found \r, but no \n */
3687  if (cstate->eol_type == EOL_CRNL)
3688  ereport(ERROR,
3689  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3690  !cstate->csv_mode ?
3691  errmsg("literal carriage return found in data") :
3692  errmsg("unquoted carriage return found in data"),
3693  !cstate->csv_mode ?
3694  errhint("Use \"\\r\" to represent carriage return.") :
3695  errhint("Use quoted CSV field to represent carriage return.")));
3696 
3697  /*
3698  * if we got here, it is the first line and we didn't find
3699  * \n, so don't consume the peeked character
3700  */
3701  cstate->eol_type = EOL_CR;
3702  }
3703  }
3704  else if (cstate->eol_type == EOL_NL)
3705  ereport(ERROR,
3706  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3707  !cstate->csv_mode ?
3708  errmsg("literal carriage return found in data") :
3709  errmsg("unquoted carriage return found in data"),
3710  !cstate->csv_mode ?
3711  errhint("Use \"\\r\" to represent carriage return.") :
3712  errhint("Use quoted CSV field to represent carriage return.")));
3713  /* If reach here, we have found the line terminator */
3714  break;
3715  }
3716 
3717  /* Process \n */
3718  if (c == '\n' && (!cstate->csv_mode || !in_quote))
3719  {
3720  if (cstate->eol_type == EOL_CR || cstate->eol_type == EOL_CRNL)
3721  ereport(ERROR,
3722  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3723  !cstate->csv_mode ?
3724  errmsg("literal newline found in data") :
3725  errmsg("unquoted newline found in data"),
3726  !cstate->csv_mode ?
3727  errhint("Use \"\\n\" to represent newline.") :
3728  errhint("Use quoted CSV field to represent newline.")));
3729  cstate->eol_type = EOL_NL; /* in case not set yet */
3730  /* If reach here, we have found the line terminator */
3731  break;
3732  }
3733 
3734  /*
3735  * In CSV mode, we only recognize \. alone on a line. This is because
3736  * \. is a valid CSV data value.
3737  */
3738  if (c == '\\' && (!cstate->csv_mode || first_char_in_line))
3739  {
3740  char c2;
3741 
3744 
3745  /* -----
3746  * get next character
3747  * Note: we do not change c so if it isn't \., we can fall
3748  * through and continue processing for file encoding.
3749  * -----
3750  */
3751  c2 = copy_raw_buf[raw_buf_ptr];
3752 
3753  if (c2 == '.')
3754  {
3755  raw_buf_ptr++; /* consume the '.' */
3756 
3757  /*
3758  * Note: if we loop back for more data here, it does not
3759  * matter that the CSV state change checks are re-executed; we
3760  * will come back here with no important state changed.
3761  */
3762  if (cstate->eol_type == EOL_CRNL)
3763  {
3764  /* Get the next character */
3766  /* if hit_eof, c2 will become '\0' */
3767  c2 = copy_raw_buf[raw_buf_ptr++];
3768 
3769  if (c2 == '\n')
3770  {
3771  if (!cstate->csv_mode)
3772  ereport(ERROR,
3773  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3774  errmsg("end-of-copy marker does not match previous newline style")));
3775  else
3777  }
3778  else if (c2 != '\r')
3779  {
3780  if (!cstate->csv_mode)
3781  ereport(ERROR,
3782  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3783  errmsg("end-of-copy marker corrupt")));
3784  else
3786  }
3787  }
3788 
3789  /* Get the next character */
3791  /* if hit_eof, c2 will become '\0' */
3792  c2 = copy_raw_buf[raw_buf_ptr++];
3793 
3794  if (c2 != '\r' && c2 != '\n')
3795  {
3796  if (!cstate->csv_mode)
3797  ereport(ERROR,
3798  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3799  errmsg("end-of-copy marker corrupt")));
3800  else
3802  }
3803 
3804  if ((cstate->eol_type == EOL_NL && c2 != '\n') ||
3805  (cstate->eol_type == EOL_CRNL && c2 != '\n') ||
3806  (cstate->eol_type == EOL_CR && c2 != '\r'))
3807  {
3808  ereport(ERROR,
3809  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3810  errmsg("end-of-copy marker does not match previous newline style")));
3811  }
3812 
3813  /*
3814  * Transfer only the data before the \. into line_buf, then
3815  * discard the data and the \. sequence.
3816  */
3817  if (prev_raw_ptr > cstate->raw_buf_index)
3819  cstate->raw_buf + cstate->raw_buf_index,
3820  prev_raw_ptr - cstate->raw_buf_index);
3821  cstate->raw_buf_index = raw_buf_ptr;
3822  result = true; /* report EOF */
3823  break;
3824  }
3825  else if (!cstate->csv_mode)
3826 
3827  /*
3828  * If we are here, it means we found a backslash followed by
3829  * something other than a period. In non-CSV mode, anything
3830  * after a backslash is special, so we skip over that second
3831  * character too. If we didn't do that \\. would be
3832  * considered an eof-of copy, while in non-CSV mode it is a
3833  * literal backslash followed by a period. In CSV mode,
3834  * backslashes are not special, so we want to process the
3835  * character after the backslash just like a normal character,
3836  * so we don't increment in those cases.
3837  */
3838  raw_buf_ptr++;
3839  }
3840 
3841  /*
3842  * This label is for CSV cases where \. appears at the start of a
3843  * line, but there is more text after it, meaning it was a data value.
3844  * We are more strict for \. in CSV mode because \. could be a data
3845  * value, while in non-CSV mode, \. cannot be a data value.
3846  */
3847 not_end_of_copy:
3848 
3849  /*
3850  * Process all bytes of a multi-byte character as a group.
3851  *
3852  * We only support multi-byte sequences where the first byte has the
3853  * high-bit set, so as an optimization we can avoid this block
3854  * entirely if it is not set.
3855  */
3856  if (cstate->encoding_embeds_ascii && IS_HIGHBIT_SET(c))
3857  {
3858  int mblen;
3859 
3860  mblen_str[0] = c;
3861  /* All our encodings only read the first byte to get the length */
3862  mblen = pg_encoding_mblen(cstate->file_encoding, mblen_str);
3864  IF_NEED_REFILL_AND_EOF_BREAK(mblen - 1);
3865  raw_buf_ptr += mblen - 1;
3866  }
3867  first_char_in_line = false;
3868  } /* end of outer loop */
3869 
3870  /*
3871  * Transfer any still-uncopied data to line_buf.
3872  */
3874 
3875  return result;
3876 }
bool csv_mode
Definition: copy.c:115
int errhint(const char *fmt,...)
Definition: elog.c:987
Definition: copy.c:72
StringInfoData line_buf
Definition: copy.c:194
#define IF_NEED_REFILL_AND_EOF_BREAK(extralen)
Definition: copy.c:248
int raw_buf_index
Definition: copy.c:207
int errcode(int sqlerrcode)
Definition: elog.c:575
#define REFILL_LINEBUF
Definition: copy.c:265
#define IS_HIGHBIT_SET(ch)
Definition: c.h:968
#define ERROR
Definition: elog.h:43
bool encoding_embeds_ascii
Definition: copy.c:104
char * c
char * raw_buf
Definition: copy.c:206
static bool CopyLoadRawBuf(CopyState cstate)
Definition: copy.c:728
char * quote
Definition: copy.c:121
int pg_encoding_mblen(int encoding, const char *mbstr)
Definition: wchar.c:1785
Definition: copy.c:73
int raw_buf_len
Definition: copy.c:208
char * escape
Definition: copy.c:122
#define ereport(elevel, rest)
Definition: elog.h:122
Definition: copy.c:74
int file_encoding
Definition: copy.c:102
#define IF_NEED_REFILL_AND_NOT_EOF_CONTINUE(extralen)
Definition: copy.c:236
EolType eol_type
Definition: copy.c:101
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define NO_END_OF_COPY_GOTO
Definition: copy.c:278
int cur_lineno
Definition: copy.c:136
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
static void CopySendChar ( CopyState  cstate,
char  c 
)
static

Definition at line 455 of file copy.c.

References appendStringInfoCharMacro, and CopyStateData::fe_msgbuf.

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

456 {
458 }
#define appendStringInfoCharMacro(str, ch)
Definition: stringinfo.h:135
char * c
StringInfo fe_msgbuf
Definition: copy.c:98
static void CopySendData ( CopyState  cstate,
const void *  databuf,
int  datasize 
)
static

Definition at line 443 of file copy.c.

References appendBinaryStringInfo(), and CopyStateData::fe_msgbuf.

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

444 {
445  appendBinaryStringInfo(cstate->fe_msgbuf, databuf, datasize);
446 }
StringInfo fe_msgbuf
Definition: copy.c:98
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
static void CopySendEndOfRow ( CopyState  cstate)
static

Definition at line 461 of file copy.c.

References CopyStateData::binary, ClosePipeToProgram(), 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().

462 {
463  StringInfo fe_msgbuf = cstate->fe_msgbuf;
464 
465  switch (cstate->copy_dest)
466  {
467  case COPY_FILE:
468  if (!cstate->binary)
469  {
470  /* Default line termination depends on platform */
471 #ifndef WIN32
472  CopySendChar(cstate, '\n');
473 #else
474  CopySendString(cstate, "\r\n");
475 #endif
476  }
477 
478  if (fwrite(fe_msgbuf->data, fe_msgbuf->len, 1,
479  cstate->copy_file) != 1 ||
480  ferror(cstate->copy_file))
481  {
482  if (cstate->is_program)
483  {
484  if (errno == EPIPE)
485  {
486  /*
487  * The pipe will be closed automatically on error at
488  * the end of transaction, but we might get a better
489  * error message from the subprocess' exit code than
490  * just "Broken Pipe"
491  */
492  ClosePipeToProgram(cstate);
493 
494  /*
495  * If ClosePipeToProgram() didn't throw an error, the
496  * program terminated normally, but closed the pipe
497  * first. Restore errno, and throw an error.
498  */
499  errno = EPIPE;
500  }
501  ereport(ERROR,
503  errmsg("could not write to COPY program: %m")));
504  }
505  else
506  ereport(ERROR,
508  errmsg("could not write to COPY file: %m")));
509  }
510  break;
511  case COPY_OLD_FE:
512  /* The FE/BE protocol uses \n as newline for all platforms */
513  if (!cstate->binary)
514  CopySendChar(cstate, '\n');
515 
516  if (pq_putbytes(fe_msgbuf->data, fe_msgbuf->len))
517  {
518  /* no hope of recovering connection sync, so FATAL */
519  ereport(FATAL,
520  (errcode(ERRCODE_CONNECTION_FAILURE),
521  errmsg("connection lost during COPY to stdout")));
522  }
523  break;
524  case COPY_NEW_FE:
525  /* The FE/BE protocol uses \n as newline for all platforms */
526  if (!cstate->binary)
527  CopySendChar(cstate, '\n');
528 
529  /* Dump the accumulated row as one CopyData message */
530  (void) pq_putmessage('d', fe_msgbuf->data, fe_msgbuf->len);
531  break;
532  }
533 
534  resetStringInfo(fe_msgbuf);
535 }
bool binary
Definition: copy.c:112
int errcode(int sqlerrcode)
Definition: elog.c:575
static void ClosePipeToProgram(CopyState cstate)
Definition: copy.c:1708
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:455
CopyDest copy_dest
Definition: copy.c:96
Definition: copy.c:61
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
int errcode_for_file_access(void)
Definition: elog.c:598
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
#define ereport(elevel, rest)
Definition: elog.h:122
bool is_program
Definition: copy.c:111
StringInfo fe_msgbuf
Definition: copy.c:98
static void CopySendString(CopyState cstate, const char *str)
Definition: copy.c:449
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE * copy_file
Definition: copy.c:97
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:43
int pq_putbytes(const char *s, size_t len)
Definition: pqcomm.c:1300
static void CopySendInt16 ( CopyState  cstate,
int16  val 
)
static

Definition at line 691 of file copy.c.

References buf, and CopySendData().

Referenced by CopyOneRowTo(), and CopyTo().

692 {
693  uint16 buf;
694 
695  buf = htons((uint16) val);
696  CopySendData(cstate, &buf, sizeof(buf));
697 }
unsigned short uint16
Definition: c.h:264
static char * buf
Definition: pg_test_fsync.c:65
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:443
long val
Definition: informix.c:689
static void CopySendInt32 ( CopyState  cstate,
int32  val 
)
static

Definition at line 660 of file copy.c.

References buf, and CopySendData().

Referenced by CopyOneRowTo(), and CopyTo().

661 {
662  uint32 buf;
663 
664  buf = htonl((uint32) val);
665  CopySendData(cstate, &buf, sizeof(buf));
666 }
static char * buf
Definition: pg_test_fsync.c:65
unsigned int uint32
Definition: c.h:265
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:443
long val
Definition: informix.c:689
static void CopySendString ( CopyState  cstate,
const char *  str 
)
static

Definition at line 449 of file copy.c.

References appendBinaryStringInfo(), and CopyStateData::fe_msgbuf.

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

450 {
451  appendBinaryStringInfo(cstate->fe_msgbuf, str, strlen(str));
452 }
StringInfo fe_msgbuf
Definition: copy.c:98
void appendBinaryStringInfo(StringInfo str, const char *data, int datalen)
Definition: stringinfo.c:240
static uint64 CopyTo ( CopyState  cstate)
static

Definition at line 1937 of file copy.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate(), CopyStateData::attnumlist, tupleDesc::attrs, CopyStateData::binary, BinarySignature, CHECK_FOR_INTERRUPTS, CopyAttributeOutCSV(), CopyOneRowTo(), CopySendChar(), CopySendData(), CopySendEndOfRow(), CopySendInt16(), CopySendInt32(), cur, CurrentMemoryContext, CopyStateData::delim, QueryDesc::dest, ExecutorRun(), CopyStateData::fe_msgbuf, CopyStateData::file_encoding, fmgr_info(), ForwardScanDirection, GetActiveSnapshot(), getTypeBinaryOutputInfo(), getTypeOutputInfo(), CopyStateData::header_line, heap_beginscan(), heap_deform_tuple(), heap_endscan(), heap_getnext(), HeapTupleGetOid, lfirst_int, list_length(), makeLongStringInfo(), MemoryContextDelete(), NameStr, tupleDesc::natts, CopyStateData::need_transcoding, NULL, CopyStateData::null_print, CopyStateData::null_print_client, CopyStateData::null_print_len, CopyStateData::oids, CopyStateData::out_functions, palloc(), pfree(), pg_server_to_any(), CopyStateData::queryDesc, CopyStateData::rel, RelationGetDescr, CopyStateData::rowcontext, QueryDesc::tupDesc, and values.

Referenced by DoCopyTo().

1938 {
1939  TupleDesc tupDesc;
1940  int num_phys_attrs;
1941  Form_pg_attribute *attr;
1942  ListCell *cur;
1943  uint64 processed;
1944 
1945  if (cstate->rel)
1946  tupDesc = RelationGetDescr(cstate->rel);
1947  else
1948  tupDesc = cstate->queryDesc->tupDesc;
1949  attr = tupDesc->attrs;
1950  num_phys_attrs = tupDesc->natts;
1951  cstate->null_print_client = cstate->null_print; /* default */
1952 
1953  /* We use fe_msgbuf as a per-row buffer regardless of copy_dest */
1954  cstate->fe_msgbuf = makeLongStringInfo();
1955 
1956  /* Get info about the columns we need to process. */
1957  cstate->out_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1958  foreach(cur, cstate->attnumlist)
1959  {
1960  int attnum = lfirst_int(cur);
1961  Oid out_func_oid;
1962  bool isvarlena;
1963 
1964  if (cstate->binary)
1965  getTypeBinaryOutputInfo(attr[attnum - 1]->atttypid,
1966  &out_func_oid,
1967  &isvarlena);
1968  else
1969  getTypeOutputInfo(attr[attnum - 1]->atttypid,
1970  &out_func_oid,
1971  &isvarlena);
1972  fmgr_info(out_func_oid, &cstate->out_functions[attnum - 1]);
1973  }
1974 
1975  /*
1976  * Create a temporary memory context that we can reset once per row to
1977  * recover palloc'd memory. This avoids any problems with leaks inside
1978  * datatype output routines, and should be faster than retail pfree's
1979  * anyway. (We don't need a whole econtext as CopyFrom does.)
1980  */
1982  "COPY TO",
1984 
1985  if (cstate->binary)
1986  {
1987  /* Generate header for a binary copy */
1988  int32 tmp;
1989 
1990  /* Signature */
1991  CopySendData(cstate, BinarySignature, 11);
1992  /* Flags field */
1993  tmp = 0;
1994  if (cstate->oids)
1995  tmp |= (1 << 16);
1996  CopySendInt32(cstate, tmp);
1997  /* No header extension */
1998  tmp = 0;
1999  CopySendInt32(cstate, tmp);
2000  }
2001  else
2002  {
2003  /*
2004  * For non-binary copy, we need to convert null_print to file
2005  * encoding, because it will be sent directly with CopySendString.
2006  */
2007  if (cstate->need_transcoding)
2008  cstate->null_print_client = pg_server_to_any(cstate->null_print,
2009  cstate->null_print_len,
2010  cstate->file_encoding);
2011 
2012  /* if a header has been requested send the line */
2013  if (cstate->header_line)
2014  {
2015  bool hdr_delim = false;
2016 
2017  foreach(cur, cstate->attnumlist)
2018  {
2019  int attnum = lfirst_int(cur);
2020  char *colname;
2021 
2022  if (hdr_delim)
2023  CopySendChar(cstate, cstate->delim[0]);
2024  hdr_delim = true;
2025 
2026  colname = NameStr(attr[attnum - 1]->attname);
2027 
2028  CopyAttributeOutCSV(cstate, colname, false,
2029  list_length(cstate->attnumlist) == 1);
2030  }
2031 
2032  CopySendEndOfRow(cstate);
2033  }
2034  }
2035 
2036  if (cstate->rel)
2037  {
2038  Datum *values;
2039  bool *nulls;
2040  HeapScanDesc scandesc;
2041  HeapTuple tuple;
2042 
2043  values = (Datum *) palloc(num_phys_attrs * sizeof(Datum));
2044  nulls = (bool *) palloc(num_phys_attrs * sizeof(bool));
2045 
2046  scandesc = heap_beginscan(cstate->rel, GetActiveSnapshot(), 0, NULL);
2047 
2048  processed = 0;
2049  while ((tuple = heap_getnext(scandesc, ForwardScanDirection)) != NULL)
2050  {
2052 
2053  /* Deconstruct the tuple ... faster than repeated heap_getattr */
2054  heap_deform_tuple(tuple, tupDesc, values, nulls);
2055 
2056  /* Format and send the data */
2057  CopyOneRowTo(cstate, HeapTupleGetOid(tuple), values, nulls);
2058  processed++;
2059  }
2060 
2061  heap_endscan(scandesc);
2062 
2063  pfree(values);
2064  pfree(nulls);
2065  }
2066  else
2067  {
2068  /* run the plan --- the dest receiver will send tuples */
2070  processed = ((DR_copy *) cstate->queryDesc->dest)->processed;
2071  }
2072 
2073  if (cstate->binary)
2074  {
2075  /* Generate trailer for a binary copy */
2076  CopySendInt16(cstate, -1);
2077  /* Need to flush out the trailer */
2078  CopySendEndOfRow(cstate);
2079  }
2080 
2082 
2083  return processed;
2084 }
Definition: fmgr.h:53
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
void getTypeOutputInfo(Oid type, Oid *typOutput, bool *typIsVarlena)
Definition: lsyscache.c:2600
bool binary
Definition: copy.c:112
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1581
#define RelationGetDescr(relation)
Definition: rel.h:425
bool need_transcoding
Definition: copy.c:103
List * attnumlist
Definition: copy.c:109
Definition: copy.c:212
Form_pg_attribute * attrs
Definition: tupdesc.h:74
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:834
void ExecutorRun(QueryDesc *queryDesc, ScanDirection direction, uint64 count)
Definition: execMain.c:285
struct cursor * cur
Definition: ecpg.c:28
unsigned int Oid
Definition: postgres_ext.h:31
char * delim
Definition: copy.c:120
MemoryContext rowcontext
Definition: copy.c:149
int natts
Definition: tupdesc.h:73
char * pg_server_to_any(const char *s, int len, int encoding)
Definition: mbutils.c:645
signed int int32
Definition: c.h:253
static void CopySendChar(CopyState cstate, char c)
Definition: copy.c:455
char * null_print
Definition: copy.c:117
Relation rel
Definition: copy.c:107
void pfree(void *pointer)
Definition: mcxt.c:992
static void CopySendInt16(CopyState cstate, int16 val)
Definition: copy.c:691
#define lfirst_int(lc)
Definition: pg_list.h:107
static void CopyAttributeOutCSV(CopyState cstate, char *string, bool use_quote, bool single_attr)
Definition: copy.c:4519
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:159
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:145
QueryDesc * queryDesc
Definition: copy.c:108
static const char BinarySignature[11]
Definition: copy.c:285
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
int null_print_len
Definition: copy.c:118
int file_encoding
Definition: copy.c:102
TupleDesc tupDesc
Definition: execdesc.h:46
void getTypeBinaryOutputInfo(Oid type, Oid *typSend, bool *typIsVarlena)
Definition: lsyscache.c:2666
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:440
bool header_line
Definition: copy.c:116
uintptr_t Datum
Definition: postgres.h:374
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1781
#define NULL
Definition: c.h:226
static void CopySendData(CopyState cstate, const void *databuf, int datasize)
Definition: copy.c:443
StringInfo fe_msgbuf
Definition: copy.c:98
static int list_length(const List *l)
Definition: pg_list.h:89
static void CopySendInt32(CopyState cstate, int32 val)
Definition: copy.c:660
void heap_deform_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *values, bool *isnull)
Definition: heaptuple.c:935
static Datum values[MAXATTR]
Definition: bootstrap.c:162
DestReceiver * dest
Definition: execdesc.h:41
FmgrInfo * out_functions
Definition: copy.c:148
void * palloc(Size size)
Definition: mcxt.c:891
static void CopySendEndOfRow(CopyState cstate)
Definition: copy.c:461
#define NameStr(name)
Definition: c.h:494
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
char * null_print_client
Definition: copy.c:119
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
HeapScanDesc heap_beginscan(Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
Definition: heapam.c:1394
StringInfo makeLongStringInfo(void)
Definition: stringinfo.c:46
static void CopyOneRowTo(CopyState cstate, Oid tupleOid, Datum *values, bool *nulls)
Definition: copy.c:2090
bool oids
Definition: copy.c:113
DestReceiver* CreateCopyDestReceiver ( void  )

Definition at line 4728 of file copy.c.

References copy_dest_destroy(), copy_dest_receive(), copy_dest_shutdown(), copy_dest_startup(), DestCopyOut, NULL, and palloc().

Referenced by CreateDestReceiver().

4729 {
4730  DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
4731 
4732  self->pub.receiveSlot = copy_dest_receive;
4733  self->pub.rStartup = copy_dest_startup;
4734  self->pub.rShutdown = copy_dest_shutdown;
4735  self->pub.rDestroy = copy_dest_destroy;
4736  self->pub.mydest = DestCopyOut;
4737 
4738  self->cstate = NULL; /* will be set later */
4739  self->processed = 0;
4740 
4741  return (DestReceiver *) self;
4742 }
Definition: copy.c:212
static void copy_dest_destroy(DestReceiver *self)
Definition: copy.c:4719
static void copy_dest_shutdown(DestReceiver *self)
Definition: copy.c:4710
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copy.c:4682
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copy.c:4691
#define NULL
Definition: c.h:226
void * palloc(Size size)
Definition: mcxt.c:891
void DoCopy ( ParseState pstate,
const CopyStmt stmt,
int  stmt_location,
int  stmt_len,
uint64 *  processed 
)

Definition at line 773 of file copy.c.

References AccessShareLock, ACL_INSERT, ACL_SELECT, Assert, CopyStmt::attlist, BeginCopyFrom(), BeginCopyTo(), bms_add_member(), check_enable_rls(), CopyFrom(), CopyGetAttnums(), cur, DoCopyTo(), EndCopyFrom(), EndCopyTo(), ereport, errcode(), errhint(), errmsg(), ERROR, ExecCheckRTPerms(), ColumnRef::fields, CopyStmt::filename, FirstLowInvalidHeapAttributeNumber, SelectStmt::fromClause, get_namespace_name(), heap_close, heap_openrv(), ResTarget::indirection, RangeTblEntry::insertedCols, InvalidOid, CopyStmt::is_from, CopyStmt::is_program, lappend(), lfirst, lfirst_int, list_make1, ColumnRef::location, ResTarget::location, makeNode, makeRangeVar(), ResTarget::name, NIL, NoLock, NULL, CopyStmt::options, PreventCommandIfParallelMode(), PreventCommandIfReadOnly(), CopyStmt::query, CopyStateData::range_table, RelationData::rd_islocaltemp, RelationData::rd_rel, CopyStmt::relation, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::relkind, RangeTblEntry::requiredPerms, RLS_ENABLED, RowExclusiveLock, RTE_RELATION, RangeTblEntry::rtekind, select, RangeTblEntry::selectedCols, RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, superuser(), SelectStmt::targetList, ResTarget::val, and XactReadOnly.

Referenced by standard_ProcessUtility().

776 {
777  CopyState cstate;
778  bool is_from = stmt->is_from;
779  bool pipe = (stmt->filename == NULL);
780  Relation rel;
781  Oid relid;
782  RawStmt *query = NULL;
783  List *range_table = NIL;
784 
785  /* Disallow COPY to/from file or program except to superusers. */
786  if (!pipe && !superuser())
787  {
788  if (stmt->is_program)
789  ereport(ERROR,
790  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
791  errmsg("must be superuser to COPY to or from an external program"),
792  errhint("Anyone can COPY to stdout or from stdin. "
793  "psql's \\copy command also works for anyone.")));
794  else
795  ereport(ERROR,
796  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
797  errmsg("must be superuser to COPY to or from a file"),
798  errhint("Anyone can COPY to stdout or from stdin. "
799  "psql's \\copy command also works for anyone.")));
800  }
801 
802  if (stmt->relation)
803  {
804  TupleDesc tupDesc;
805  AclMode required_access = (is_from ? ACL_INSERT : ACL_SELECT);
806  List *attnums;
807  ListCell *cur;
808  RangeTblEntry *rte;
809 
810  Assert(!stmt->query);
811 
812  /* Open and lock the relation, using the appropriate lock type. */
813  rel = heap_openrv(stmt->relation,
814  (is_from ? RowExclusiveLock : AccessShareLock));
815 
816  relid = RelationGetRelid(rel);
817 
818  rte = makeNode(RangeTblEntry);
819  rte->rtekind = RTE_RELATION;
820  rte->relid = RelationGetRelid(rel);
821  rte->relkind = rel->rd_rel->relkind;
822  rte->requiredPerms = required_access;
823  range_table = list_make1(rte);
824 
825  tupDesc = RelationGetDescr(rel);
826  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
827  foreach(cur, attnums)
828  {
829  int attno = lfirst_int(cur) -
831 
832  if (is_from)
833  rte->insertedCols = bms_add_member(rte->insertedCols, attno);
834  else
835  rte->selectedCols = bms_add_member(rte->selectedCols, attno);
836  }
837  ExecCheckRTPerms(range_table, true);
838 
839  /*
840  * Permission check for row security policies.
841  *
842  * check_enable_rls will ereport(ERROR) if the user has requested
843  * something invalid and will otherwise indicate if we should enable
844  * RLS (returns RLS_ENABLED) or not for this COPY statement.
845  *
846  * If the relation has a row security policy and we are to apply it
847  * then perform a "query" copy and allow the normal query processing
848  * to handle the policies.
849  *
850  * If RLS is not enabled for this, then just fall through to the
851  * normal non-filtering relation handling.
852  */
853  if (check_enable_rls(rte->relid, InvalidOid, false) == RLS_ENABLED)
854  {
856  ColumnRef *cr;
857  ResTarget *target;
858  RangeVar *from;
859  List *targetList = NIL;
860 
861  if (is_from)
862  ereport(ERROR,
863  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
864  errmsg("COPY FROM not supported with row-level security"),
865  errhint("Use INSERT statements instead.")));
866 
867  /*
868  * Build target list
869  *
870  * If no columns are specified in the attribute list of the COPY
871  * command, then the target list is 'all' columns. Therefore, '*'
872  * should be used as the target list for the resulting SELECT
873  * statement.
874  *
875  * In the case that columns are specified in the attribute list,
876  * create a ColumnRef and ResTarget for each column and add them
877  * to the target list for the resulting SELECT statement.
878  */
879  if (!stmt->attlist)
880  {
881  cr = makeNode(ColumnRef);
883  cr->location = -1;
884 
885  target = makeNode(ResTarget);
886  target->name = NULL;
887  target->indirection = NIL;
888  target->val = (Node *) cr;
889  target->location = -1;
890 
891  targetList = list_make1(target);
892  }
893  else
894  {
895  ListCell *lc;
896 
897  foreach(lc, stmt->attlist)
898  {
899  /*
900  * Build the ColumnRef for each column. The ColumnRef
901  * 'fields' property is a String 'Value' node (see
902  * nodes/value.h) that corresponds to the column name
903  * respectively.
904  */
905  cr = makeNode(ColumnRef);
906  cr->fields = list_make1(lfirst(lc));
907  cr->location = -1;
908 
909  /* Build the ResTarget and add the ColumnRef to it. */
910  target = makeNode(ResTarget);
911  target->name = NULL;
912  target->indirection = NIL;
913  target->val = (Node *) cr;
914  target->location = -1;
915 
916  /* Add each column to the SELECT statement's target list */
917  targetList = lappend(targetList, target);
918  }
919  }
920 
921  /*
922  * Build RangeVar for from clause, fully qualified based on the
923  * relation which we have opened and locked.
924  */
926  RelationGetRelationName(rel), -1);
927 
928  /* Build query */
929  select = makeNode(SelectStmt);
930  select->targetList = targetList;
931  select->fromClause = list_make1(from);
932 
933  query = makeNode(RawStmt);
934  query->stmt = (Node *) select;
935  query->stmt_location = stmt_location;
936  query->stmt_len = stmt_len;
937 
938  /*
939  * Close the relation for now, but keep the lock on it to prevent
940  * changes between now and when we start the query-based COPY.
941  *
942  * We'll reopen it later as part of the query-based COPY.
943  */
944  heap_close(rel, NoLock);
945  rel = NULL;
946  }
947  }
948  else
949  {
950  Assert(stmt->query);
951 
952  query = makeNode(RawStmt);
953  query->stmt = stmt->query;
954  query->stmt_location = stmt_location;
955  query->stmt_len = stmt_len;
956 
957  relid = InvalidOid;
958  rel = NULL;
959  }
960 
961  if (is_from)
962  {
963  Assert(rel);
964 
965  /* check read-only transaction and parallel mode */
966  if (XactReadOnly && !rel->rd_islocaltemp)
967  PreventCommandIfReadOnly("COPY FROM");
968  PreventCommandIfParallelMode("COPY FROM");
969 
970  cstate = BeginCopyFrom(pstate, rel, stmt->filename, stmt->is_program,
971  stmt->attlist, stmt->options);
972  cstate->range_table = range_table;
973  *processed = CopyFrom(cstate); /* copy from file to database */
974  EndCopyFrom(cstate);
975  }
976  else
977  {
978  cstate = BeginCopyTo(pstate, rel, query, relid,
979  stmt->filename, stmt->is_program,
980  stmt->attlist, stmt->options);
981  *processed = DoCopyTo(cstate); /* copy from database to file */
982  EndCopyTo(cstate);
983  }
984 
985  /*
986  * Close the relation. If reading, we can release the AccessShareLock we
987  * got; if writing, we should hold the lock until end of transaction to
988  * ensure that updates will be committed before lock is released.
989  */
990  if (rel != NULL)
991  heap_close(rel, (is_from ? NoLock : AccessShareLock));
992 }
List * indirection
Definition: parsenodes.h:432
#define NIL
Definition: pg_list.h:69
List * range_table
Definition: copy.c:163
Node * val
Definition: parsenodes.h:433
int errhint(const char *fmt,...)
Definition: elog.c:987
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:253
List * attlist
Definition: parsenodes.h:1836
List * fromClause
Definition: parsenodes.h:1426
#define RelationGetDescr(relation)
Definition: rel.h:425
char * name
Definition: parsenodes.h:431
bool rd_islocaltemp
Definition: rel.h:90
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:508
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
#define select(n, r, w, e, timeout)
Definition: win32.h:384
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
AclMode requiredPerms
Definition: parsenodes.h:965
#define heap_close(r, l)
Definition: heapam.h:97
Form_pg_class rd_rel
Definition: rel.h:113
unsigned int Oid
Definition: postgres_ext.h:31
bool is_program
Definition: parsenodes.h:1839
int location
Definition: parsenodes.h:227
int location
Definition: parsenodes.h:434
#define list_make1(x1)
Definition: pg_list.h:133
uint32 AclMode
Definition: parsenodes.h:63
Bitmapset * selectedCols
Definition: