PostgreSQL Source Code  git master
copy.h File Reference
#include "nodes/execnodes.h"
#include "nodes/parsenodes.h"
#include "parser/parse_node.h"
#include "tcop/dest.h"
Include dependency graph for copy.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  CopyFormatOptions
 

Typedefs

typedef struct CopyFormatOptions CopyFormatOptions
 
typedef struct CopyFromStateDataCopyFromState
 
typedef struct CopyToStateDataCopyToState
 
typedef int(* copy_data_source_cb) (void *outbuf, int minread, int maxread)
 

Functions

void DoCopy (ParseState *state, const CopyStmt *stmt, int stmt_location, int stmt_len, uint64 *processed)
 
void ProcessCopyOptions (ParseState *pstate, CopyFormatOptions *ops_out, bool is_from, List *options)
 
CopyFromState BeginCopyFrom (ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
 
void EndCopyFrom (CopyFromState cstate)
 
bool NextCopyFrom (CopyFromState cstate, ExprContext *econtext, Datum *values, bool *nulls)
 
bool NextCopyFromRawFields (CopyFromState cstate, char ***fields, int *nfields)
 
void CopyFromErrorCallback (void *arg)
 
uint64 CopyFrom (CopyFromState cstate)
 
DestReceiverCreateCopyDestReceiver (void)
 
CopyToState BeginCopyTo (ParseState *pstate, Relation rel, RawStmt *query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
 
void EndCopyTo (CopyToState cstate)
 
uint64 DoCopyTo (CopyToState cstate)
 
ListCopyGetAttnums (TupleDesc tupDesc, Relation rel, List *attnamelist)
 

Typedef Documentation

◆ copy_data_source_cb

typedef int(* copy_data_source_cb) (void *outbuf, int minread, int maxread)

Definition at line 57 of file copy.h.

◆ CopyFormatOptions

◆ CopyFromState

Definition at line 54 of file copy.h.

◆ CopyToState

typedef struct CopyToStateData* CopyToState

Definition at line 55 of file copy.h.

Function Documentation

◆ BeginCopyFrom()

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

Definition at line 1180 of file copyfrom.c.

References AllocateFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, attnum, CopyFromStateData::attnumlist, CopyFromStateData::attribute_buf, CopyFormatOptions::binary, build_column_default(), CopyFromStateData::bytes_processed, contain_volatile_functions_not_nextval(), CopyFormatOptions::convert_select, CopyFromStateData::convert_select_flags, CopyFormatOptions::convert_selectively, COPY_CALLBACK, COPY_FILE, CopyFromStateData::copy_file, CopyFromStateData::copy_src, CopyFromStateData::copycontext, CopyGetAttnums(), cur, CopyFromStateData::cur_attname, CopyFromStateData::cur_attval, CopyFromStateData::cur_lineno, CopyFromStateData::cur_relname, CurrentMemoryContext, CopyFromStateData::data_source_cb, CopyFromStateData::defexprs, CopyFromStateData::defmap, DestRemote, CopyFromStateData::encoding_embeds_ascii, CopyFromStateData::eol_type, EOL_UNKNOWN, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), errmsg_internal(), ERROR, ExecInitExpr(), expression_planner(), CopyFormatOptions::file_encoding, CopyFromStateData::file_encoding, CopyFromStateData::filename, fmgr_info(), CopyFormatOptions::force_notnull, CopyFormatOptions::force_notnull_flags, CopyFormatOptions::force_null, CopyFormatOptions::force_null_flags, fstat, GetDatabaseEncoding(), getTypeBinaryInputInfo(), getTypeInputInfo(), CopyFromStateData::in_functions, initStringInfo(), InvalidOid, CopyFromStateData::is_program, lfirst_int, CopyFromStateData::line_buf, CopyFromStateData::line_buf_converted, list_length(), list_member_int(), CopyFromStateData::max_fields, MemoryContextSwitchTo(), NameStr, TupleDescData::natts, CopyFromStateData::need_transcoding, CopyFromStateData::num_defaults, OpenPipeStream(), CopyFromStateData::opts, ParseState::p_rtable, palloc(), palloc0(), PG_BINARY_R, pg_database_encoding_max_length(), PG_ENCODING_IS_CLIENT_ONLY, pg_get_client_encoding(), pgstat_progress_start_command(), pgstat_progress_update_param(), ProcessCopyOptions(), PROGRESS_COMMAND_COPY, PROGRESS_COPY_BYTES_TOTAL, pstrdup(), CopyFromStateData::range_table, CopyFromStateData::raw_buf, CopyFromStateData::raw_buf_index, CopyFromStateData::raw_buf_len, RAW_BUF_SIZE, CopyFromStateData::raw_fields, CopyFromStateData::reached_eof, ReceiveCopyBegin(), ReceiveCopyBinaryHeader(), CopyFromStateData::rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, S_ISDIR, stat::st_mode, stat::st_size, TupleDescAttr, CopyFromStateData::typioparams, CopyFromStateData::volatile_defexprs, CopyFromStateData::whereClause, and whereToSendOutput.

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

1188 {
1189  CopyFromState cstate;
1190  bool pipe = (filename == NULL);
1191  TupleDesc tupDesc;
1192  AttrNumber num_phys_attrs,
1193  num_defaults;
1194  FmgrInfo *in_functions;
1195  Oid *typioparams;
1196  int attnum;
1197  Oid in_func_oid;
1198  int *defmap;
1199  ExprState **defexprs;
1200  MemoryContext oldcontext;
1201  bool volatile_defexprs;
1202 
1203  /* Allocate workspace and zero all fields */
1204  cstate = (CopyFromStateData *) palloc0(sizeof(CopyFromStateData));
1205 
1206  /*
1207  * We allocate everything used by a cstate in a new memory context. This
1208  * avoids memory leaks during repeated use of COPY in a query.
1209  */
1211  "COPY",
1213 
1214  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1215 
1216  /* Extract options from the statement node tree */
1217  ProcessCopyOptions(pstate, &cstate->opts, true /* is_from */, options);
1218 
1219  /* Process the target relation */
1220  cstate->rel = rel;
1221 
1222  tupDesc = RelationGetDescr(cstate->rel);
1223 
1224  /* process commmon options or initialization */
1225 
1226  /* Generate or convert list of attributes to process */
1227  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
1228 
1229  num_phys_attrs = tupDesc->natts;
1230 
1231  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
1232  cstate->opts.force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1233  if (cstate->opts.force_notnull)
1234  {
1235  List *attnums;
1236  ListCell *cur;
1237 
1238  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_notnull);
1239 
1240  foreach(cur, attnums)
1241  {
1242  int attnum = lfirst_int(cur);
1243  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1244 
1245  if (!list_member_int(cstate->attnumlist, attnum))
1246  ereport(ERROR,
1247  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1248  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
1249  NameStr(attr->attname))));
1250  cstate->opts.force_notnull_flags[attnum - 1] = true;
1251  }
1252  }
1253 
1254  /* Convert FORCE_NULL name list to per-column flags, check validity */
1255  cstate->opts.force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1256  if (cstate->opts.force_null)
1257  {
1258  List *attnums;
1259  ListCell *cur;
1260 
1261  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_null);
1262 
1263  foreach(cur, attnums)
1264  {
1265  int attnum = lfirst_int(cur);
1266  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1267 
1268  if (!list_member_int(cstate->attnumlist, attnum))
1269  ereport(ERROR,
1270  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1271  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
1272  NameStr(attr->attname))));
1273  cstate->opts.force_null_flags[attnum - 1] = true;
1274  }
1275  }
1276 
1277  /* Convert convert_selectively name list to per-column flags */
1278  if (cstate->opts.convert_selectively)
1279  {
1280  List *attnums;
1281  ListCell *cur;
1282 
1283  cstate->convert_select_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
1284 
1285  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.convert_select);
1286 
1287  foreach(cur, attnums)
1288  {
1289  int attnum = lfirst_int(cur);
1290  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
1291 
1292  if (!list_member_int(cstate->attnumlist, attnum))
1293  ereport(ERROR,
1294  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
1295  errmsg_internal("selected column \"%s\" not referenced by COPY",
1296  NameStr(attr->attname))));
1297  cstate->convert_select_flags[attnum - 1] = true;
1298  }
1299  }
1300 
1301  /* Use client encoding when ENCODING option is not specified. */
1302  if (cstate->opts.file_encoding < 0)
1304  else
1305  cstate->file_encoding = cstate->opts.file_encoding;
1306 
1307  /*
1308  * Set up encoding conversion info. Even if the file and server encodings
1309  * are the same, we must apply pg_any_to_server() to validate data in
1310  * multibyte encodings.
1311  */
1312  cstate->need_transcoding =
1313  (cstate->file_encoding != GetDatabaseEncoding() ||
1315  /* See Multibyte encoding comment above */
1317 
1318  cstate->copy_src = COPY_FILE; /* default */
1319 
1320  cstate->whereClause = whereClause;
1321 
1322  MemoryContextSwitchTo(oldcontext);
1323 
1324  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
1325 
1326  /* Initialize state variables */
1327  cstate->reached_eof = false;
1328  cstate->eol_type = EOL_UNKNOWN;
1329  cstate->cur_relname = RelationGetRelationName(cstate->rel);
1330  cstate->cur_lineno = 0;
1331  cstate->cur_attname = NULL;
1332  cstate->cur_attval = NULL;
1333 
1334  /*
1335  * Set up variables to avoid per-attribute overhead. attribute_buf and
1336  * raw_buf are used in both text and binary modes, but we use line_buf
1337  * only in text mode.
1338  */
1339  initStringInfo(&cstate->attribute_buf);
1340  cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
1341  cstate->raw_buf_index = cstate->raw_buf_len = 0;
1342  if (!cstate->opts.binary)
1343  {
1344  initStringInfo(&cstate->line_buf);
1345  cstate->line_buf_converted = false;
1346  }
1347 
1348  /* Assign range table, we'll need it in CopyFrom. */
1349  if (pstate)
1350  cstate->range_table = pstate->p_rtable;
1351 
1352  tupDesc = RelationGetDescr(cstate->rel);
1353  num_phys_attrs = tupDesc->natts;
1354  num_defaults = 0;
1355  volatile_defexprs = false;
1356 
1357  /*
1358  * Pick up the required catalog information for each attribute in the
1359  * relation, including the input function, the element type (to pass to
1360  * the input function), and info about defaults and constraints. (Which
1361  * input function we use depends on text/binary format choice.)
1362  */
1363  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
1364  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
1365  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
1366  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
1367 
1368  for (attnum = 1; attnum <= num_phys_attrs; attnum++)
1369  {
1370  Form_pg_attribute att = TupleDescAttr(tupDesc, attnum - 1);
1371 
1372  /* We don't need info for dropped attributes */
1373  if (att->attisdropped)
1374  continue;
1375 
1376  /* Fetch the input function and typioparam info */
1377  if (cstate->opts.binary)
1378  getTypeBinaryInputInfo(att->atttypid,
1379  &in_func_oid, &typioparams[attnum - 1]);
1380  else
1381  getTypeInputInfo(att->atttypid,
1382  &in_func_oid, &typioparams[attnum - 1]);
1383  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
1384 
1385  /* Get default info if needed */
1386  if (!list_member_int(cstate->attnumlist, attnum) && !att->attgenerated)
1387  {
1388  /* attribute is NOT to be copied from input */
1389  /* use default value if one exists */
1390  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
1391  attnum);
1392 
1393  if (defexpr != NULL)
1394  {
1395  /* Run the expression through planner */
1396  defexpr = expression_planner(defexpr);
1397 
1398  /* Initialize executable expression in copycontext */
1399  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
1400  defmap[num_defaults] = attnum - 1;
1401  num_defaults++;
1402 
1403  /*
1404  * If a default expression looks at the table being loaded,
1405  * then it could give the wrong answer when using
1406  * multi-insert. Since database access can be dynamic this is
1407  * hard to test for exactly, so we use the much wider test of
1408  * whether the default expression is volatile. We allow for
1409  * the special case of when the default expression is the
1410  * nextval() of a sequence which in this specific case is
1411  * known to be safe for use with the multi-insert
1412  * optimization. Hence we use this special case function
1413  * checker rather than the standard check for
1414  * contain_volatile_functions().
1415  */
1416  if (!volatile_defexprs)
1417  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
1418  }
1419  }
1420  }
1421 
1422 
1423  /* initialize progress */
1425  cstate->rel ? RelationGetRelid(cstate->rel) : InvalidOid);
1426  cstate->bytes_processed = 0;
1427 
1428  /* We keep those variables in cstate. */
1429  cstate->in_functions = in_functions;
1430  cstate->typioparams = typioparams;
1431  cstate->defmap = defmap;
1432  cstate->defexprs = defexprs;
1433  cstate->volatile_defexprs = volatile_defexprs;
1434  cstate->num_defaults = num_defaults;
1435  cstate->is_program = is_program;
1436 
1437  if (data_source_cb)
1438  {
1439  cstate->copy_src = COPY_CALLBACK;
1440  cstate->data_source_cb = data_source_cb;
1441  }
1442  else if (pipe)
1443  {
1444  Assert(!is_program); /* the grammar does not allow this */
1446  ReceiveCopyBegin(cstate);
1447  else
1448  cstate->copy_file = stdin;
1449  }
1450  else
1451  {
1452  cstate->filename = pstrdup(filename);
1453 
1454  if (cstate->is_program)
1455  {
1456  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
1457  if (cstate->copy_file == NULL)
1458  ereport(ERROR,
1460  errmsg("could not execute command \"%s\": %m",
1461  cstate->filename)));
1462  }
1463  else
1464  {
1465  struct stat st;
1466 
1467  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
1468  if (cstate->copy_file == NULL)
1469  {
1470  /* copy errno because ereport subfunctions might change it */
1471  int save_errno = errno;
1472 
1473  ereport(ERROR,
1475  errmsg("could not open file \"%s\" for reading: %m",
1476  cstate->filename),
1477  (save_errno == ENOENT || save_errno == EACCES) ?
1478  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
1479  "You may want a client-side facility such as psql's \\copy.") : 0));
1480  }
1481 
1482  if (fstat(fileno(cstate->copy_file), &st))
1483  ereport(ERROR,
1485  errmsg("could not stat file \"%s\": %m",
1486  cstate->filename)));
1487 
1488  if (S_ISDIR(st.st_mode))
1489  ereport(ERROR,
1490  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1491  errmsg("\"%s\" is a directory", cstate->filename)));
1492 
1494  }
1495  }
1496 
1497  if (cstate->opts.binary)
1498  {
1499  /* Read and verify binary header */
1500  ReceiveCopyBinaryHeader(cstate);
1501  }
1502 
1503  /* create workspace for CopyReadAttributes results */
1504  if (!cstate->opts.binary)
1505  {
1506  AttrNumber attr_count = list_length(cstate->attnumlist);
1507 
1508  cstate->max_fields = attr_count;
1509  cstate->raw_fields = (char **) palloc(attr_count * sizeof(char *));
1510  }
1511 
1512  MemoryContextSwitchTo(oldcontext);
1513 
1514  return cstate;
1515 }
copy_data_source_cb data_source_cb
void ReceiveCopyBegin(CopyFromState cstate)
Definition: fmgr.h:56
#define AllocSetContextCreate
Definition: memutils.h:170
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:487
const char * cur_attname
int errhint(const char *fmt,...)
Definition: elog.c:1162
StringInfoData attribute_buf
#define RelationGetDescr(relation)
Definition: rel.h:483
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3457
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
char * pstrdup(const char *in)
Definition: mcxt.c:1187
Expr * expression_planner(Expr *expr)
Definition: planner.c:6166
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
StringInfoData line_buf
Definition: nodes.h:528
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:704
List * force_notnull
Definition: copy.h:45
const char * cur_attval
unsigned int Oid
Definition: postgres_ext.h:31
#define PG_BINARY_R
Definition: c.h:1261
MemoryContext copycontext
#define RAW_BUF_SIZE
#define fstat
Definition: win32_port.h:274
#define ERROR
Definition: elog.h:45
#define lfirst_int(lc)
Definition: pg_list.h:170
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:126
bool binary
Definition: copy.h:32
List * force_null
Definition: copy.h:47
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
bool list_member_int(const List *list, int datum)
Definition: list.c:669
#define PROGRESS_COPY_BYTES_TOTAL
Definition: progress.h:138
int errcode_for_file_access(void)
Definition: elog.c:727
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2354
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
int file_encoding
Definition: copy.h:30
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2457
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2860
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2794
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Node * build_column_default(Relation rel, int attrno)
void * palloc0(Size size)
Definition: mcxt.c:981
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
int pg_get_client_encoding(void)
Definition: mbutils.c:336
const char * cur_relname
List * convert_select
Definition: copy.h:50
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
bool convert_selectively
Definition: copy.h:49
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1002
#define Assert(condition)
Definition: c.h:792
bool * force_null_flags
Definition: copy.h:48
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:686
static int list_length(const List *l)
Definition: pg_list.h:149
void ReceiveCopyBinaryHeader(CopyFromState cstate)
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1436
#define S_ISDIR(m)
Definition: win32_port.h:316
CopyFormatOptions opts
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
static char * filename
Definition: pg_dumpall.c:91
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:915
#define NameStr(name)
Definition: c.h:669
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:123
CommandDest whereToSendOutput
Definition: postgres.c:92
Definition: pg_list.h:50
int16 AttrNumber
Definition: attnum.h:21
#define RelationGetRelid(relation)
Definition: rel.h:457
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:334
List * p_rtable
Definition: parse_node.h:180
bool * force_notnull_flags
Definition: copy.h:46

◆ BeginCopyTo()

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

Definition at line 383 of file copyto.c.

References AllocateFile(), ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, attnum, CopyToStateData::attnumlist, CopyToStateData::bytes_processed, CMD_DELETE, CMD_INSERT, CMD_SELECT, CMD_UPDATE, Query::commandType, CopyToStateData::copy_dest, COPY_FILE, CopyToStateData::copy_file, CopyToStateData::copycontext, CopyGetAttnums(), copyObject, CreateDestReceiver(), CreateQueryDesc(), cur, CurrentMemoryContext, CURSOR_OPT_PARALLEL_OK, generate_unaccent_rules::dest, DestCopyOut, DestRemote, CopyToStateData::encoding_embeds_ascii, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg(), ERROR, ExecutorStart(), CopyFormatOptions::file_encoding, CopyToStateData::file_encoding, CopyToStateData::filename, CopyFormatOptions::force_notnull, CopyFormatOptions::force_notnull_flags, CopyFormatOptions::force_null, CopyFormatOptions::force_null_flags, CopyFormatOptions::force_quote, CopyFormatOptions::force_quote_all, CopyFormatOptions::force_quote_flags, fstat, GetActiveSnapshot(), GetDatabaseEncoding(), i, InvalidOid, InvalidSnapshot, is_absolute_path, CopyToStateData::is_program, IsA, lfirst_int, lfirst_node, linitial_node, list_length(), list_member_int(), list_member_oid(), MemoryContextSwitchTo(), NameStr, TupleDescData::natts, CopyToStateData::need_transcoding, NIL, OpenPipeStream(), CopyToStateData::opts, ParseState::p_sourcetext, palloc0(), pg_analyze_and_rewrite(), PG_BINARY_W, pg_database_encoding_max_length(), PG_ENCODING_IS_CLIENT_ONLY, PG_END_TRY, PG_FINALLY, pg_get_client_encoding(), pg_plan_query(), PG_TRY, pgstat_progress_start_command(), ProcessCopyOptions(), PROGRESS_COMMAND_COPY, pstrdup(), PushCopiedSnapshot(), QSRC_NON_INSTEAD_RULE, QSRC_QUAL_INSTEAD_RULE, CopyToStateData::queryDesc, Query::querySource, RelationData::rd_rel, CopyToStateData::rel, RelationGetDescr, RelationGetRelationName, RelationGetRelid, PlannedStmt::relationOids, Query::returningList, S_ISDIR, S_IWGRP, S_IWOTH, stat::st_mode, generate_unaccent_rules::stdout, QueryDesc::tupDesc, TupleDescAttr, UpdateActiveSnapshotCommandId(), Query::utilityStmt, and whereToSendOutput.

Referenced by DoCopy().

391 {
392  CopyToState cstate;
393  bool pipe = (filename == NULL);
394  TupleDesc tupDesc;
395  int num_phys_attrs;
396  MemoryContext oldcontext;
397 
398  if (rel != NULL && rel->rd_rel->relkind != RELKIND_RELATION)
399  {
400  if (rel->rd_rel->relkind == RELKIND_VIEW)
401  ereport(ERROR,
402  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
403  errmsg("cannot copy from view \"%s\"",
405  errhint("Try the COPY (SELECT ...) TO variant.")));
406  else if (rel->rd_rel->relkind == RELKIND_MATVIEW)
407  ereport(ERROR,
408  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
409  errmsg("cannot copy from materialized view \"%s\"",
411  errhint("Try the COPY (SELECT ...) TO variant.")));
412  else if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
413  ereport(ERROR,
414  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
415  errmsg("cannot copy from foreign table \"%s\"",
417  errhint("Try the COPY (SELECT ...) TO variant.")));
418  else if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
419  ereport(ERROR,
420  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
421  errmsg("cannot copy from sequence \"%s\"",
422  RelationGetRelationName(rel))));
423  else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
424  ereport(ERROR,
425  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
426  errmsg("cannot copy from partitioned table \"%s\"",
428  errhint("Try the COPY (SELECT ...) TO variant.")));
429  else
430  ereport(ERROR,
431  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
432  errmsg("cannot copy from non-table relation \"%s\"",
433  RelationGetRelationName(rel))));
434  }
435 
436 
437  /* Allocate workspace and zero all fields */
438  cstate = (CopyToStateData *) palloc0(sizeof(CopyToStateData));
439 
440  /*
441  * We allocate everything used by a cstate in a new memory context. This
442  * avoids memory leaks during repeated use of COPY in a query.
443  */
445  "COPY",
447 
448  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
449 
450  /* Extract options from the statement node tree */
451  ProcessCopyOptions(pstate, &cstate->opts, false /* is_from */, options);
452 
453  /* Process the source/target relation or query */
454  if (rel)
455  {
456  Assert(!raw_query);
457 
458  cstate->rel = rel;
459 
460  tupDesc = RelationGetDescr(cstate->rel);
461  }
462  else
463  {
464  List *rewritten;
465  Query *query;
466  PlannedStmt *plan;
468 
469  cstate->rel = NULL;
470 
471  /*
472  * Run parse analysis and rewrite. Note this also acquires sufficient
473  * locks on the source table(s).
474  *
475  * Because the parser and planner tend to scribble on their input, we
476  * make a preliminary copy of the source querytree. This prevents
477  * problems in the case that the COPY is in a portal or plpgsql
478  * function and is executed repeatedly. (See also the same hack in
479  * DECLARE CURSOR and PREPARE.) XXX FIXME someday.
480  */
481  rewritten = pg_analyze_and_rewrite(copyObject(raw_query),
482  pstate->p_sourcetext, NULL, 0,
483  NULL);
484 
485  /* check that we got back something we can work with */
486  if (rewritten == NIL)
487  {
488  ereport(ERROR,
489  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
490  errmsg("DO INSTEAD NOTHING rules are not supported for COPY")));
491  }
492  else if (list_length(rewritten) > 1)
493  {
494  ListCell *lc;
495 
496  /* examine queries to determine which error message to issue */
497  foreach(lc, rewritten)
498  {
499  Query *q = lfirst_node(Query, lc);
500 
502  ereport(ERROR,
503  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
504  errmsg("conditional DO INSTEAD rules are not supported for COPY")));
506  ereport(ERROR,
507  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
508  errmsg("DO ALSO rules are not supported for the COPY")));
509  }
510 
511  ereport(ERROR,
512  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
513  errmsg("multi-statement DO INSTEAD rules are not supported for COPY")));
514  }
515 
516  query = linitial_node(Query, rewritten);
517 
518  /* The grammar allows SELECT INTO, but we don't support that */
519  if (query->utilityStmt != NULL &&
521  ereport(ERROR,
522  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
523  errmsg("COPY (SELECT INTO) is not supported")));
524 
525  Assert(query->utilityStmt == NULL);
526 
527  /*
528  * Similarly the grammar doesn't enforce the presence of a RETURNING
529  * clause, but this is required here.
530  */
531  if (query->commandType != CMD_SELECT &&
532  query->returningList == NIL)
533  {
534  Assert(query->commandType == CMD_INSERT ||
535  query->commandType == CMD_UPDATE ||
536  query->commandType == CMD_DELETE);
537 
538  ereport(ERROR,
539  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
540  errmsg("COPY query must have a RETURNING clause")));
541  }
542 
543  /* plan the query */
544  plan = pg_plan_query(query, pstate->p_sourcetext,
545  CURSOR_OPT_PARALLEL_OK, NULL);
546 
547  /*
548  * With row level security and a user using "COPY relation TO", we
549  * have to convert the "COPY relation TO" to a query-based COPY (eg:
550  * "COPY (SELECT * FROM relation) TO"), to allow the rewriter to add
551  * in any RLS clauses.
552  *
553  * When this happens, we are passed in the relid of the originally
554  * found relation (which we have locked). As the planner will look up
555  * the relation again, we double-check here to make sure it found the
556  * same one that we have locked.
557  */
558  if (queryRelId != InvalidOid)
559  {
560  /*
561  * Note that with RLS involved there may be multiple relations,
562  * and while the one we need is almost certainly first, we don't
563  * make any guarantees of that in the planner, so check the whole
564  * list and make sure we find the original relation.
565  */
566  if (!list_member_oid(plan->relationOids, queryRelId))
567  ereport(ERROR,
568  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
569  errmsg("relation referenced by COPY statement has changed")));
570  }
571 
572  /*
573  * Use a snapshot with an updated command ID to ensure this query sees
574  * results of any previously executed queries.
575  */
578 
579  /* Create dest receiver for COPY OUT */
581  ((DR_copy *) dest)->cstate = cstate;
582 
583  /* Create a QueryDesc requesting no output */
584  cstate->queryDesc = CreateQueryDesc(plan, pstate->p_sourcetext,
587  dest, NULL, NULL, 0);
588 
589  /*
590  * Call ExecutorStart to prepare the plan for execution.
591  *
592  * ExecutorStart computes a result tupdesc for us
593  */
594  ExecutorStart(cstate->queryDesc, 0);
595 
596  tupDesc = cstate->queryDesc->tupDesc;
597  }
598 
599  /* Generate or convert list of attributes to process */
600  cstate->attnumlist = CopyGetAttnums(tupDesc, cstate->rel, attnamelist);
601 
602  num_phys_attrs = tupDesc->natts;
603 
604  /* Convert FORCE_QUOTE name list to per-column flags, check validity */
605  cstate->opts.force_quote_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
606  if (cstate->opts.force_quote_all)
607  {
608  int i;
609 
610  for (i = 0; i < num_phys_attrs; i++)
611  cstate->opts.force_quote_flags[i] = true;
612  }
613  else if (cstate->opts.force_quote)
614  {
615  List *attnums;
616  ListCell *cur;
617 
618  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_quote);
619 
620  foreach(cur, attnums)
621  {
622  int attnum = lfirst_int(cur);
623  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
624 
625  if (!list_member_int(cstate->attnumlist, attnum))
626  ereport(ERROR,
627  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
628  errmsg("FORCE_QUOTE column \"%s\" not referenced by COPY",
629  NameStr(attr->attname))));
630  cstate->opts.force_quote_flags[attnum - 1] = true;
631  }
632  }
633 
634  /* Convert FORCE_NOT_NULL name list to per-column flags, check validity */
635  cstate->opts.force_notnull_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
636  if (cstate->opts.force_notnull)
637  {
638  List *attnums;
639  ListCell *cur;
640 
641  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_notnull);
642 
643  foreach(cur, attnums)
644  {
645  int attnum = lfirst_int(cur);
646  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
647 
648  if (!list_member_int(cstate->attnumlist, attnum))
649  ereport(ERROR,
650  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
651  errmsg("FORCE_NOT_NULL column \"%s\" not referenced by COPY",
652  NameStr(attr->attname))));
653  cstate->opts.force_notnull_flags[attnum - 1] = true;
654  }
655  }
656 
657  /* Convert FORCE_NULL name list to per-column flags, check validity */
658  cstate->opts.force_null_flags = (bool *) palloc0(num_phys_attrs * sizeof(bool));
659  if (cstate->opts.force_null)
660  {
661  List *attnums;
662  ListCell *cur;
663 
664  attnums = CopyGetAttnums(tupDesc, cstate->rel, cstate->opts.force_null);
665 
666  foreach(cur, attnums)
667  {
668  int attnum = lfirst_int(cur);
669  Form_pg_attribute attr = TupleDescAttr(tupDesc, attnum - 1);
670 
671  if (!list_member_int(cstate->attnumlist, attnum))
672  ereport(ERROR,
673  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
674  errmsg("FORCE_NULL column \"%s\" not referenced by COPY",
675  NameStr(attr->attname))));
676  cstate->opts.force_null_flags[attnum - 1] = true;
677  }
678  }
679 
680  /* Use client encoding when ENCODING option is not specified. */
681  if (cstate->opts.file_encoding < 0)
683  else
684  cstate->file_encoding = cstate->opts.file_encoding;
685 
686  /*
687  * Set up encoding conversion info. Even if the file and server encodings
688  * are the same, we must apply pg_any_to_server() to validate data in
689  * multibyte encodings.
690  */
691  cstate->need_transcoding =
692  (cstate->file_encoding != GetDatabaseEncoding() ||
694  /* See Multibyte encoding comment above */
696 
697  cstate->copy_dest = COPY_FILE; /* default */
698 
699  MemoryContextSwitchTo(oldcontext);
700 
701  if (pipe)
702  {
703  Assert(!is_program); /* the grammar does not allow this */
705  cstate->copy_file = stdout;
706  }
707  else
708  {
709  cstate->filename = pstrdup(filename);
710  cstate->is_program = is_program;
711 
712  if (is_program)
713  {
714  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_W);
715  if (cstate->copy_file == NULL)
716  ereport(ERROR,
718  errmsg("could not execute command \"%s\": %m",
719  cstate->filename)));
720  }
721  else
722  {
723  mode_t oumask; /* Pre-existing umask value */
724  struct stat st;
725 
726  /*
727  * Prevent write to relative path ... too easy to shoot oneself in
728  * the foot by overwriting a database file ...
729  */
731  ereport(ERROR,
732  (errcode(ERRCODE_INVALID_NAME),
733  errmsg("relative path not allowed for COPY to file")));
734 
735  oumask = umask(S_IWGRP | S_IWOTH);
736  PG_TRY();
737  {
738  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_W);
739  }
740  PG_FINALLY();
741  {
742  umask(oumask);
743  }
744  PG_END_TRY();
745  if (cstate->copy_file == NULL)
746  {
747  /* copy errno because ereport subfunctions might change it */
748  int save_errno = errno;
749 
750  ereport(ERROR,
752  errmsg("could not open file \"%s\" for writing: %m",
753  cstate->filename),
754  (save_errno == ENOENT || save_errno == EACCES) ?
755  errhint("COPY TO instructs the PostgreSQL server process to write a file. "
756  "You may want a client-side facility such as psql's \\copy.") : 0));
757  }
758 
759  if (fstat(fileno(cstate->copy_file), &st))
760  ereport(ERROR,
762  errmsg("could not stat file \"%s\": %m",
763  cstate->filename)));
764 
765  if (S_ISDIR(st.st_mode))
766  ereport(ERROR,
767  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
768  errmsg("\"%s\" is a directory", cstate->filename)));
769  }
770  }
771 
772  /* initialize progress */
774  cstate->rel ? RelationGetRelid(cstate->rel) : InvalidOid);
775  cstate->bytes_processed = 0;
776 
777  MemoryContextSwitchTo(oldcontext);
778 
779  return cstate;
780 }
int file_encoding
Definition: copyto.c:79
#define NIL
Definition: pg_list.h:65
void UpdateActiveSnapshotCommandId(void)
Definition: snapmgr.c:728
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define AllocSetContextCreate
Definition: memutils.h:170
int errhint(const char *fmt,...)
Definition: elog.c:1162
Relation rel
Definition: copyto.c:84
bool need_transcoding
Definition: copyto.c:80
FILE * copy_file
Definition: copyto.c:76
#define RelationGetDescr(relation)
Definition: rel.h:483
void pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
Definition: pgstat.c:3457
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
List * relationOids
Definition: plannodes.h:80
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool * force_quote_flags
Definition: copy.h:44
#define S_IWOTH
Definition: win32_port.h:307
void ExecutorStart(QueryDesc *queryDesc, int eflags)
Definition: execMain.c:143
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Snapshot GetActiveSnapshot(void)
Definition: snapmgr.c:786
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:704
#define PG_BINARY_W
Definition: c.h:1262
uint64 bytes_processed
Definition: copyto.c:100
List * force_notnull
Definition: copy.h:45
bool force_quote_all
Definition: copy.h:43
Form_pg_class rd_rel
Definition: rel.h:110
List * pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string, Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition: postgres.c:677
Node * utilityStmt
Definition: parsenodes.h:120
#define linitial_node(type, l)
Definition: pg_list.h:177
bool is_program
Definition: copyto.c:88
QueryDesc * queryDesc
Definition: copyto.c:85
#define fstat
Definition: win32_port.h:274
List * attnumlist
Definition: copyto.c:86
#define ERROR
Definition: elog.h:45
#define lfirst_int(lc)
Definition: pg_list.h:170
MemoryContext copycontext
Definition: copyto.c:96
void PushCopiedSnapshot(Snapshot snapshot)
Definition: snapmgr.c:716
QueryDesc * CreateQueryDesc(PlannedStmt *plannedstmt, const char *sourceText, Snapshot snapshot, Snapshot crosscheck_snapshot, DestReceiver *dest, ParamListInfo params, QueryEnvironment *queryEnv, int instrument_options)
Definition: pquery.c:67
List * force_null
Definition: copy.h:47
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
#define lfirst_node(type, lc)
Definition: pg_list.h:172
bool list_member_int(const List *list, int datum)
Definition: list.c:669
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition: dest.c:113
int errcode_for_file_access(void)
Definition: elog.c:727
#define is_absolute_path(filename)
Definition: port.h:86
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2354
#define RelationGetRelationName(relation)
Definition: rel.h:491
#define S_IWGRP
Definition: win32_port.h:295
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
const char * p_sourcetext
Definition: parse_node.h:179
int file_encoding
Definition: copy.h:30
List * returningList
Definition: parsenodes.h:146
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2457
CopyDest copy_dest
Definition: copyto.c:75
TupleDesc tupDesc
Definition: execdesc.h:47
#define InvalidSnapshot
Definition: snapshot.h:123
#define PG_FINALLY()
Definition: elog.h:326
void * palloc0(Size size)
Definition: mcxt.c:981
List * force_quote
Definition: copy.h:42
int GetDatabaseEncoding(void)
Definition: mbutils.c:1151
int pg_get_client_encoding(void)
Definition: mbutils.c:336
#define InvalidOid
Definition: postgres_ext.h:36
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
CmdType commandType
Definition: parsenodes.h:112
bool list_member_oid(const List *list, Oid datum)
Definition: list.c:689
QuerySource querySource
Definition: parsenodes.h:114
#define Assert(condition)
Definition: c.h:792
bool * force_null_flags
Definition: copy.h:48
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:686
static int list_length(const List *l)
Definition: pg_list.h:149
int pg_database_encoding_max_length(void)
Definition: mbutils.c:1436
CopyFormatOptions opts
Definition: copyto.c:90
#define S_ISDIR(m)
Definition: win32_port.h:316
#define PG_ENCODING_IS_CLIENT_ONLY(_enc)
Definition: pg_wchar.h:298
static char * filename
Definition: pg_dumpall.c:91
#define CURSOR_OPT_PARALLEL_OK
Definition: parsenodes.h:2732
int errmsg(const char *fmt,...)
Definition: elog.c:915
int i
#define NameStr(name)
Definition: c.h:669
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition: postgres.c:858
bool encoding_embeds_ascii
Definition: copyto.c:81
#define copyObject(obj)
Definition: nodes.h:644
CommandDest whereToSendOutput
Definition: postgres.c:92
char * filename
Definition: copyto.c:87
#define PG_TRY()
Definition: elog.h:309
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:457
#define PG_END_TRY()
Definition: elog.h:334
void ProcessCopyOptions(ParseState *pstate, CopyFormatOptions *opts_out, bool is_from, List *options)
Definition: copy.c:334
bool * force_notnull_flags
Definition: copy.h:46

◆ CopyFrom()

uint64 CopyFrom ( CopyFromState  cstate)

Definition at line 524 of file copyfrom.c.

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

Referenced by copy_table(), and DoCopy().

525 {
526  ResultRelInfo *resultRelInfo;
527  ResultRelInfo *target_resultRelInfo;
528  ResultRelInfo *prevResultRelInfo = NULL;
529  EState *estate = CreateExecutorState(); /* for ExecConstraints() */
530  ModifyTableState *mtstate;
531  ExprContext *econtext;
532  TupleTableSlot *singleslot = NULL;
533  MemoryContext oldcontext = CurrentMemoryContext;
534 
535  PartitionTupleRouting *proute = NULL;
536  ErrorContextCallback errcallback;
537  CommandId mycid = GetCurrentCommandId(true);
538  int ti_options = 0; /* start with default options for insert */
539  BulkInsertState bistate = NULL;
540  CopyInsertMethod insertMethod;
541  CopyMultiInsertInfo multiInsertInfo = {0}; /* pacify compiler */
542  uint64 processed = 0;
543  bool has_before_insert_row_trig;
544  bool has_instead_insert_row_trig;
545  bool leafpart_use_multi_insert = false;
546 
547  Assert(cstate->rel);
548  Assert(list_length(cstate->range_table) == 1);
549 
550  /*
551  * The target must be a plain, foreign, or partitioned relation, or have
552  * an INSTEAD OF INSERT row trigger. (Currently, such triggers are only
553  * allowed on views, so we only hint about them in the view case.)
554  */
555  if (cstate->rel->rd_rel->relkind != RELKIND_RELATION &&
556  cstate->rel->rd_rel->relkind != RELKIND_FOREIGN_TABLE &&
557  cstate->rel->rd_rel->relkind != RELKIND_PARTITIONED_TABLE &&
558  !(cstate->rel->trigdesc &&
560  {
561  if (cstate->rel->rd_rel->relkind == RELKIND_VIEW)
562  ereport(ERROR,
563  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
564  errmsg("cannot copy to view \"%s\"",
565  RelationGetRelationName(cstate->rel)),
566  errhint("To enable copying to a view, provide an INSTEAD OF INSERT trigger.")));
567  else if (cstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
568  ereport(ERROR,
569  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
570  errmsg("cannot copy to materialized view \"%s\"",
571  RelationGetRelationName(cstate->rel))));
572  else if (cstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
573  ereport(ERROR,
574  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
575  errmsg("cannot copy to sequence \"%s\"",
576  RelationGetRelationName(cstate->rel))));
577  else
578  ereport(ERROR,
579  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
580  errmsg("cannot copy to non-table relation \"%s\"",
581  RelationGetRelationName(cstate->rel))));
582  }
583 
584  /*
585  * If the target file is new-in-transaction, we assume that checking FSM
586  * for free space is a waste of time. This could possibly be wrong, but
587  * it's unlikely.
588  */
589  if (RELKIND_HAS_STORAGE(cstate->rel->rd_rel->relkind) &&
592  ti_options |= TABLE_INSERT_SKIP_FSM;
593 
594  /*
595  * Optimize if new relfilenode was created in this subxact or one of its
596  * committed children and we won't see those rows later as part of an
597  * earlier scan or command. The subxact test ensures that if this subxact
598  * aborts then the frozen rows won't be visible after xact cleanup. Note
599  * that the stronger test of exactly which subtransaction created it is
600  * crucial for correctness of this optimization. The test for an earlier
601  * scan or command tolerates false negatives. FREEZE causes other sessions
602  * to see rows they would not see under MVCC, and a false negative merely
603  * spreads that anomaly to the current session.
604  */
605  if (cstate->opts.freeze)
606  {
607  /*
608  * We currently disallow COPY FREEZE on partitioned tables. The
609  * reason for this is that we've simply not yet opened the partitions
610  * to determine if the optimization can be applied to them. We could
611  * go and open them all here, but doing so may be quite a costly
612  * overhead for small copies. In any case, we may just end up routing
613  * tuples to a small number of partitions. It seems better just to
614  * raise an ERROR for partitioned tables.
615  */
616  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
617  {
618  ereport(ERROR,
619  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
620  errmsg("cannot perform COPY FREEZE on a partitioned table")));
621  }
622 
623  /*
624  * Tolerate one registration for the benefit of FirstXactSnapshot.
625  * Scan-bearing queries generally create at least two registrations,
626  * though relying on that is fragile, as is ignoring ActiveSnapshot.
627  * Clear CatalogSnapshot to avoid counting its registration. We'll
628  * still detect ongoing catalog scans, each of which separately
629  * registers the snapshot it uses.
630  */
633  ereport(ERROR,
634  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
635  errmsg("cannot perform COPY FREEZE because of prior transaction activity")));
636 
637  if (cstate->rel->rd_createSubid != GetCurrentSubTransactionId() &&
639  ereport(ERROR,
640  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
641  errmsg("cannot perform COPY FREEZE because the table was not created or truncated in the current subtransaction")));
642 
643  ti_options |= TABLE_INSERT_FROZEN;
644  }
645 
646  /*
647  * We need a ResultRelInfo so we can use the regular executor's
648  * index-entry-making machinery. (There used to be a huge amount of code
649  * here that basically duplicated execUtils.c ...)
650  */
651  ExecInitRangeTable(estate, cstate->range_table);
652  resultRelInfo = target_resultRelInfo = makeNode(ResultRelInfo);
653  ExecInitResultRelation(estate, resultRelInfo, 1);
654 
655  /* Verify the named relation is a valid target for INSERT */
656  CheckValidResultRel(resultRelInfo, CMD_INSERT);
657 
658  ExecOpenIndices(resultRelInfo, false);
659 
660  /*
661  * Set up a ModifyTableState so we can let FDW(s) init themselves for
662  * foreign-table result relation(s).
663  */
664  mtstate = makeNode(ModifyTableState);
665  mtstate->ps.plan = NULL;
666  mtstate->ps.state = estate;
667  mtstate->operation = CMD_INSERT;
668  mtstate->resultRelInfo = resultRelInfo;
669 
670  if (resultRelInfo->ri_FdwRoutine != NULL &&
671  resultRelInfo->ri_FdwRoutine->BeginForeignInsert != NULL)
672  resultRelInfo->ri_FdwRoutine->BeginForeignInsert(mtstate,
673  resultRelInfo);
674 
675  /* Prepare to catch AFTER triggers. */
677 
678  /*
679  * If there are any triggers with transition tables on the named relation,
680  * we need to be prepared to capture transition tuples.
681  *
682  * Because partition tuple routing would like to know about whether
683  * transition capture is active, we also set it in mtstate, which is
684  * passed to ExecFindPartition() below.
685  */
686  cstate->transition_capture = mtstate->mt_transition_capture =
688  RelationGetRelid(cstate->rel),
689  CMD_INSERT);
690 
691  /*
692  * If the named relation is a partitioned table, initialize state for
693  * CopyFrom tuple routing.
694  */
695  if (cstate->rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
696  proute = ExecSetupPartitionTupleRouting(estate, NULL, cstate->rel);
697 
698  if (cstate->whereClause)
699  cstate->qualexpr = ExecInitQual(castNode(List, cstate->whereClause),
700  &mtstate->ps);
701 
702  /*
703  * It's generally more efficient to prepare a bunch of tuples for
704  * insertion, and insert them in one table_multi_insert() call, than call
705  * table_tuple_insert() separately for every tuple. However, there are a
706  * number of reasons why we might not be able to do this. These are
707  * explained below.
708  */
709  if (resultRelInfo->ri_TrigDesc != NULL &&
710  (resultRelInfo->ri_TrigDesc->trig_insert_before_row ||
711  resultRelInfo->ri_TrigDesc->trig_insert_instead_row))
712  {
713  /*
714  * Can't support multi-inserts when there are any BEFORE/INSTEAD OF
715  * triggers on the table. Such triggers might query the table we're
716  * inserting into and act differently if the tuples that have already
717  * been processed and prepared for insertion are not there.
718  */
719  insertMethod = CIM_SINGLE;
720  }
721  else if (proute != NULL && resultRelInfo->ri_TrigDesc != NULL &&
722  resultRelInfo->ri_TrigDesc->trig_insert_new_table)
723  {
724  /*
725  * For partitioned tables we can't support multi-inserts when there
726  * are any statement level insert triggers. It might be possible to
727  * allow partitioned tables with such triggers in the future, but for
728  * now, CopyMultiInsertInfoFlush expects that any before row insert
729  * and statement level insert triggers are on the same relation.
730  */
731  insertMethod = CIM_SINGLE;
732  }
733  else if (resultRelInfo->ri_FdwRoutine != NULL ||
734  cstate->volatile_defexprs)
735  {
736  /*
737  * Can't support multi-inserts to foreign tables or if there are any
738  * volatile default expressions in the table. Similarly to the
739  * trigger case above, such expressions may query the table we're
740  * inserting into.
741  *
742  * Note: It does not matter if any partitions have any volatile
743  * default expressions as we use the defaults from the target of the
744  * COPY command.
745  */
746  insertMethod = CIM_SINGLE;
747  }
748  else if (contain_volatile_functions(cstate->whereClause))
749  {
750  /*
751  * Can't support multi-inserts if there are any volatile function
752  * expressions in WHERE clause. Similarly to the trigger case above,
753  * such expressions may query the table we're inserting into.
754  */
755  insertMethod = CIM_SINGLE;
756  }
757  else
758  {
759  /*
760  * For partitioned tables, we may still be able to perform bulk
761  * inserts. However, the possibility of this depends on which types
762  * of triggers exist on the partition. We must disable bulk inserts
763  * if the partition is a foreign table or it has any before row insert
764  * or insert instead triggers (same as we checked above for the parent
765  * table). Since the partition's resultRelInfos are initialized only
766  * when we actually need to insert the first tuple into them, we must
767  * have the intermediate insert method of CIM_MULTI_CONDITIONAL to
768  * flag that we must later determine if we can use bulk-inserts for
769  * the partition being inserted into.
770  */
771  if (proute)
772  insertMethod = CIM_MULTI_CONDITIONAL;
773  else
774  insertMethod = CIM_MULTI;
775 
776  CopyMultiInsertInfoInit(&multiInsertInfo, resultRelInfo, cstate,
777  estate, mycid, ti_options);
778  }
779 
780  /*
781  * If not using batch mode (which allocates slots as needed) set up a
782  * tuple slot too. When inserting into a partitioned table, we also need
783  * one, even if we might batch insert, to read the tuple in the root
784  * partition's form.
785  */
786  if (insertMethod == CIM_SINGLE || insertMethod == CIM_MULTI_CONDITIONAL)
787  {
788  singleslot = table_slot_create(resultRelInfo->ri_RelationDesc,
789  &estate->es_tupleTable);
790  bistate = GetBulkInsertState();
791  }
792 
793  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
794  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
795 
796  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
797  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
798 
799  /*
800  * Check BEFORE STATEMENT insertion triggers. It's debatable whether we
801  * should do this for COPY, since it's not really an "INSERT" statement as
802  * such. However, executing these triggers maintains consistency with the
803  * EACH ROW triggers that we already fire on COPY.
804  */
805  ExecBSInsertTriggers(estate, resultRelInfo);
806 
807  econtext = GetPerTupleExprContext(estate);
808 
809  /* Set up callback to identify error line number */
810  errcallback.callback = CopyFromErrorCallback;
811  errcallback.arg = (void *) cstate;
812  errcallback.previous = error_context_stack;
813  error_context_stack = &errcallback;
814 
815  for (;;)
816  {
817  TupleTableSlot *myslot;
818  bool skip_tuple;
819 
821 
822  /*
823  * Reset the per-tuple exprcontext. We do this after every tuple, to
824  * clean-up after expression evaluations etc.
825  */
826  ResetPerTupleExprContext(estate);
827 
828  /* select slot to (initially) load row into */
829  if (insertMethod == CIM_SINGLE || proute)
830  {
831  myslot = singleslot;
832  Assert(myslot != NULL);
833  }
834  else
835  {
836  Assert(resultRelInfo == target_resultRelInfo);
837  Assert(insertMethod == CIM_MULTI);
838 
839  myslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
840  resultRelInfo);
841  }
842 
843  /*
844  * Switch to per-tuple context before calling NextCopyFrom, which does
845  * evaluate default expressions etc. and requires per-tuple context.
846  */
848 
849  ExecClearTuple(myslot);
850 
851  /* Directly store the values/nulls array in the slot */
852  if (!NextCopyFrom(cstate, econtext, myslot->tts_values, myslot->tts_isnull))
853  break;
854 
855  ExecStoreVirtualTuple(myslot);
856 
857  /*
858  * Constraints and where clause might reference the tableoid column,
859  * so (re-)initialize tts_tableOid before evaluating them.
860  */
861  myslot->tts_tableOid = RelationGetRelid(target_resultRelInfo->ri_RelationDesc);
862 
863  /* Triggers and stuff need to be invoked in query context. */
864  MemoryContextSwitchTo(oldcontext);
865 
866  if (cstate->whereClause)
867  {
868  econtext->ecxt_scantuple = myslot;
869  /* Skip items that don't match COPY's WHERE clause */
870  if (!ExecQual(cstate->qualexpr, econtext))
871  continue;
872  }
873 
874  /* Determine the partition to insert the tuple into */
875  if (proute)
876  {
877  TupleConversionMap *map;
878 
879  /*
880  * Attempt to find a partition suitable for this tuple.
881  * ExecFindPartition() will raise an error if none can be found or
882  * if the found partition is not suitable for INSERTs.
883  */
884  resultRelInfo = ExecFindPartition(mtstate, target_resultRelInfo,
885  proute, myslot, estate);
886 
887  if (prevResultRelInfo != resultRelInfo)
888  {
889  /* Determine which triggers exist on this partition */
890  has_before_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
891  resultRelInfo->ri_TrigDesc->trig_insert_before_row);
892 
893  has_instead_insert_row_trig = (resultRelInfo->ri_TrigDesc &&
894  resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
895 
896  /*
897  * Disable multi-inserts when the partition has BEFORE/INSTEAD
898  * OF triggers, or if the partition is a foreign partition.
899  */
900  leafpart_use_multi_insert = insertMethod == CIM_MULTI_CONDITIONAL &&
901  !has_before_insert_row_trig &&
902  !has_instead_insert_row_trig &&
903  resultRelInfo->ri_FdwRoutine == NULL;
904 
905  /* Set the multi-insert buffer to use for this partition. */
906  if (leafpart_use_multi_insert)
907  {
908  if (resultRelInfo->ri_CopyMultiInsertBuffer == NULL)
909  CopyMultiInsertInfoSetupBuffer(&multiInsertInfo,
910  resultRelInfo);
911  }
912  else if (insertMethod == CIM_MULTI_CONDITIONAL &&
913  !CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
914  {
915  /*
916  * Flush pending inserts if this partition can't use
917  * batching, so rows are visible to triggers etc.
918  */
919  CopyMultiInsertInfoFlush(&multiInsertInfo, resultRelInfo);
920  }
921 
922  if (bistate != NULL)
923  ReleaseBulkInsertStatePin(bistate);
924  prevResultRelInfo = resultRelInfo;
925  }
926 
927  /*
928  * If we're capturing transition tuples, we might need to convert
929  * from the partition rowtype to root rowtype. But if there are no
930  * BEFORE triggers on the partition that could change the tuple,
931  * we can just remember the original unconverted tuple to avoid a
932  * needless round trip conversion.
933  */
934  if (cstate->transition_capture != NULL)
936  !has_before_insert_row_trig ? myslot : NULL;
937 
938  /*
939  * We might need to convert from the root rowtype to the partition
940  * rowtype.
941  */
942  map = resultRelInfo->ri_RootToPartitionMap;
943  if (insertMethod == CIM_SINGLE || !leafpart_use_multi_insert)
944  {
945  /* non batch insert */
946  if (map != NULL)
947  {
948  TupleTableSlot *new_slot;
949 
950  new_slot = resultRelInfo->ri_PartitionTupleSlot;
951  myslot = execute_attr_map_slot(map->attrMap, myslot, new_slot);
952  }
953  }
954  else
955  {
956  /*
957  * Prepare to queue up tuple for later batch insert into
958  * current partition.
959  */
960  TupleTableSlot *batchslot;
961 
962  /* no other path available for partitioned table */
963  Assert(insertMethod == CIM_MULTI_CONDITIONAL);
964 
965  batchslot = CopyMultiInsertInfoNextFreeSlot(&multiInsertInfo,
966  resultRelInfo);
967 
968  if (map != NULL)
969  myslot = execute_attr_map_slot(map->attrMap, myslot,
970  batchslot);
971  else
972  {
973  /*
974  * This looks more expensive than it is (Believe me, I
975  * optimized it away. Twice.). The input is in virtual
976  * form, and we'll materialize the slot below - for most
977  * slot types the copy performs the work materialization
978  * would later require anyway.
979  */
980  ExecCopySlot(batchslot, myslot);
981  myslot = batchslot;
982  }
983  }
984 
985  /* ensure that triggers etc see the right relation */
986  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
987  }
988 
989  skip_tuple = false;
990 
991  /* BEFORE ROW INSERT Triggers */
992  if (has_before_insert_row_trig)
993  {
994  if (!ExecBRInsertTriggers(estate, resultRelInfo, myslot))
995  skip_tuple = true; /* "do nothing" */
996  }
997 
998  if (!skip_tuple)
999  {
1000  /*
1001  * If there is an INSTEAD OF INSERT ROW trigger, let it handle the
1002  * tuple. Otherwise, proceed with inserting the tuple into the
1003  * table or foreign table.
1004  */
1005  if (has_instead_insert_row_trig)
1006  {
1007  ExecIRInsertTriggers(estate, resultRelInfo, myslot);
1008  }
1009  else
1010  {
1011  /* Compute stored generated columns */
1012  if (resultRelInfo->ri_RelationDesc->rd_att->constr &&
1014  ExecComputeStoredGenerated(resultRelInfo, estate, myslot,
1015  CMD_INSERT);
1016 
1017  /*
1018  * If the target is a plain table, check the constraints of
1019  * the tuple.
1020  */
1021  if (resultRelInfo->ri_FdwRoutine == NULL &&
1022  resultRelInfo->ri_RelationDesc->rd_att->constr)
1023  ExecConstraints(resultRelInfo, myslot, estate);
1024 
1025  /*
1026  * Also check the tuple against the partition constraint, if
1027  * there is one; except that if we got here via tuple-routing,
1028  * we don't need to if there's no BR trigger defined on the
1029  * partition.
1030  */
1031  if (resultRelInfo->ri_RelationDesc->rd_rel->relispartition &&
1032  (proute == NULL || has_before_insert_row_trig))
1033  ExecPartitionCheck(resultRelInfo, myslot, estate, true);
1034 
1035  /* Store the slot in the multi-insert buffer, when enabled. */
1036  if (insertMethod == CIM_MULTI || leafpart_use_multi_insert)
1037  {
1038  /*
1039  * The slot previously might point into the per-tuple
1040  * context. For batching it needs to be longer lived.
1041  */
1042  ExecMaterializeSlot(myslot);
1043 
1044  /* Add this tuple to the tuple buffer */
1045  CopyMultiInsertInfoStore(&multiInsertInfo,
1046  resultRelInfo, myslot,
1047  cstate->line_buf.len,
1048  cstate->cur_lineno);
1049 
1050  /*
1051  * If enough inserts have queued up, then flush all
1052  * buffers out to their tables.
1053  */
1054  if (CopyMultiInsertInfoIsFull(&multiInsertInfo))
1055  CopyMultiInsertInfoFlush(&multiInsertInfo, resultRelInfo);
1056  }
1057  else
1058  {
1059  List *recheckIndexes = NIL;
1060 
1061  /* OK, store the tuple */
1062  if (resultRelInfo->ri_FdwRoutine != NULL)
1063  {
1064  myslot = resultRelInfo->ri_FdwRoutine->ExecForeignInsert(estate,
1065  resultRelInfo,
1066  myslot,
1067  NULL);
1068 
1069  if (myslot == NULL) /* "do nothing" */
1070  continue; /* next tuple please */
1071 
1072  /*
1073  * AFTER ROW Triggers might reference the tableoid
1074  * column, so (re-)initialize tts_tableOid before
1075  * evaluating them.
1076  */
1077  myslot->tts_tableOid = RelationGetRelid(resultRelInfo->ri_RelationDesc);
1078  }
1079  else
1080  {
1081  /* OK, store the tuple and create index entries for it */
1082  table_tuple_insert(resultRelInfo->ri_RelationDesc,
1083  myslot, mycid, ti_options, bistate);
1084 
1085  if (resultRelInfo->ri_NumIndices > 0)
1086  recheckIndexes = ExecInsertIndexTuples(resultRelInfo,
1087  myslot,
1088  estate,
1089  false,
1090  false,
1091  NULL,
1092  NIL);
1093  }
1094 
1095  /* AFTER ROW INSERT Triggers */
1096  ExecARInsertTriggers(estate, resultRelInfo, myslot,
1097  recheckIndexes, cstate->transition_capture);
1098 
1099  list_free(recheckIndexes);
1100  }
1101  }
1102 
1103  /*
1104  * We count only tuples not suppressed by a BEFORE INSERT trigger
1105  * or FDW; this is the same definition used by nodeModifyTable.c
1106  * for counting tuples inserted by an INSERT command. Update
1107  * progress of the COPY command as well.
1108  */
1110  }
1111  }
1112 
1113  /* Flush any remaining buffered tuples */
1114  if (insertMethod != CIM_SINGLE)
1115  {
1116  if (!CopyMultiInsertInfoIsEmpty(&multiInsertInfo))
1117  CopyMultiInsertInfoFlush(&multiInsertInfo, NULL);
1118  }
1119 
1120  /* Done, clean up */
1121  error_context_stack = errcallback.previous;
1122 
1123  if (bistate != NULL)
1124  FreeBulkInsertState(bistate);
1125 
1126  MemoryContextSwitchTo(oldcontext);
1127 
1128  /*
1129  * In the old protocol, tell pqcomm that we can process normal protocol
1130  * messages again.
1131  */
1132  if (cstate->copy_src == COPY_OLD_FE)
1133  pq_endmsgread();
1134 
1135  /* Execute AFTER STATEMENT insertion triggers */
1136  ExecASInsertTriggers(estate, target_resultRelInfo, cstate->transition_capture);
1137 
1138  /* Handle queued AFTER triggers */
1139  AfterTriggerEndQuery(estate);
1140 
1141  ExecResetTupleTable(estate->es_tupleTable, false);
1142 
1143  /* Allow the FDW to shut down */
1144  if (target_resultRelInfo->ri_FdwRoutine != NULL &&
1145  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert != NULL)
1146  target_resultRelInfo->ri_FdwRoutine->EndForeignInsert(estate,
1147  target_resultRelInfo);
1148 
1149  /* Tear down the multi-insert buffer data */
1150  if (insertMethod != CIM_SINGLE)
1151  CopyMultiInsertInfoCleanup(&multiInsertInfo);
1152 
1153  /* Close all the partitioned tables, leaf partitions, and their indices */
1154  if (proute)
1155  ExecCleanupTupleRouting(mtstate, proute);
1156 
1157  /* Close the result relations, including any trigger target relations */
1158  ExecCloseResultRelations(estate);
1160 
1161  FreeExecutorState(estate);
1162 
1163  return processed;
1164 }
TupleTableSlot * table_slot_create(Relation relation, List **reglist)
Definition: tableam.c:91
int ri_NumIndices
Definition: execnodes.h:415
static TupleTableSlot * ExecCopySlot(TupleTableSlot *dstslot, TupleTableSlot *srcslot)
Definition: tuptable.h:475
#define NIL
Definition: pg_list.h:65
Oid tts_tableOid
Definition: tuptable.h:131
uint32 CommandId
Definition: c.h:589
void ExecInitRangeTable(EState *estate, List *rangeTable)
Definition: execUtils.c:750
Relation ri_RelationDesc
Definition: execnodes.h:412
static TupleTableSlot * CopyMultiInsertInfoNextFreeSlot(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copyfrom.c:482
static void CopyMultiInsertInfoCleanup(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:463
bool NextCopyFrom(CopyFromState cstate, ExprContext *econtext, Datum *values, bool *nulls)
int errhint(const char *fmt,...)
Definition: elog.c:1162
void ExecARInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot, List *recheckIndexes, TransitionCaptureState *transition_capture)
Definition: trigger.c:2320
struct CopyMultiInsertBuffer * ri_CopyMultiInsertBuffer
Definition: execnodes.h:508
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define ResetPerTupleExprContext(estate)
Definition: executor.h:518
#define TABLE_INSERT_FROZEN
Definition: tableam.h:234
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
void ExecInitResultRelation(EState *estate, ResultRelInfo *resultRelInfo, Index rti)
Definition: execUtils.c:833
BeginForeignInsert_function BeginForeignInsert
Definition: fdwapi.h:225
ResultRelInfo * resultRelInfo
Definition: execnodes.h:1163
void ExecCloseResultRelations(EState *estate)
Definition: execMain.c:1430
ExecForeignInsert_function ExecForeignInsert
Definition: fdwapi.h:219
void pgstat_progress_update_param(int index, int64 val)
Definition: pgstat.c:3478
void ExecConstraints(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate)
Definition: execMain.c:1801
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
StringInfoData line_buf
bool ThereAreNoPriorRegisteredSnapshots(void)
Definition: snapmgr.c:1604
int errcode(int sqlerrcode)
Definition: elog.c:704
static bool CopyMultiInsertInfoIsEmpty(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:288
void ExecComputeStoredGenerated(ResultRelInfo *resultRelInfo, EState *estate, TupleTableSlot *slot, CmdType cmdtype)
CmdType operation
Definition: execnodes.h:1155
SubTransactionId rd_newRelfilenodeSubid
Definition: rel.h:104
Datum * tts_values
Definition: tuptable.h:126
bool contain_volatile_functions(Node *clause)
Definition: clauses.c:437
EState * state
Definition: execnodes.h:936
Form_pg_class rd_rel
Definition: rel.h:110
static bool ExecQual(ExprState *state, ExprContext *econtext)
Definition: executor.h:372
void(* callback)(void *arg)
Definition: elog.h:243
List * ExecInsertIndexTuples(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool update, bool noDupErr, bool *specConflict, List *arbiterIndexes)
Definition: execIndexing.c:293
struct ErrorContextCallback * previous
Definition: elog.h:242
static void CopyMultiInsertInfoFlush(CopyMultiInsertInfo *miinfo, ResultRelInfo *curr_rri)
Definition: copyfrom.c:417
static void table_tuple_insert(Relation rel, TupleTableSlot *slot, CommandId cid, int options, struct BulkInsertStateData *bistate)
Definition: tableam.h:1284
ExprState * ExecInitQual(List *qual, PlanState *parent)
Definition: execExpr.c:209
void ExecCloseRangeTableRelations(EState *estate)
Definition: execMain.c:1473
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:165
static void CopyMultiInsertInfoSetupBuffer(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri)
Definition: copyfrom.c:231
static void CopyMultiInsertInfoInit(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, CopyFromState cstate, EState *estate, CommandId mycid, int ti_options)
Definition: copyfrom.c:251
ErrorContextCallback * error_context_stack
Definition: elog.c:93
bool trig_insert_instead_row
Definition: reltrigger.h:58
void FreeExecutorState(EState *estate)
Definition: execUtils.c:185
#define GetPerTupleExprContext(estate)
Definition: executor.h:509
BulkInsertState GetBulkInsertState(void)
Definition: heapam.c:1824
bool trig_insert_new_table
Definition: reltrigger.h:75
bool has_generated_stored
Definition: tupdesc.h:45
void CopyFromErrorCallback(void *arg)
Definition: copyfrom.c:108
bool ThereAreNoReadyPortals(void)
Definition: portalmem.c:1209
#define ERROR
Definition: elog.h:45
PlanState ps
Definition: execnodes.h:1154
void ExecCleanupTupleRouting(ModifyTableState *mtstate, PartitionTupleRouting *proute)
bool ExecBRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2244
TupleTableSlot * ri_PartitionTupleSlot
Definition: execnodes.h:498
TriggerDesc * trigdesc
Definition: rel.h:116
void CheckValidResultRel(ResultRelInfo *resultRelInfo, CmdType operation)
Definition: execMain.c:995
void ExecBSInsertTriggers(EState *estate, ResultRelInfo *relinfo)
Definition: trigger.c:2182
struct TransitionCaptureState * mt_transition_capture
Definition: execnodes.h:1185
bool * tts_isnull
Definition: tuptable.h:128
TupleConstr * constr
Definition: tupdesc.h:85
#define RelationGetRelationName(relation)
Definition: rel.h:491
struct FdwRoutine * ri_FdwRoutine
Definition: execnodes.h:441
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
PartitionTupleRouting * ExecSetupPartitionTupleRouting(EState *estate, ModifyTableState *mtstate, Relation rel)
AttrMap * attrMap
Definition: tupconvert.h:27
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:424
EState * CreateExecutorState(void)
Definition: execUtils.c:89
TransitionCaptureState * transition_capture
SubTransactionId rd_createSubid
Definition: rel.h:103
bool trig_insert_before_row
Definition: reltrigger.h:56
SubTransactionId rd_firstRelfilenodeSubid
Definition: rel.h:106
List * es_tupleTable
Definition: execnodes.h:567
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:1161
void ExecASInsertTriggers(EState *estate, ResultRelInfo *relinfo, TransitionCaptureState *transition_capture)
Definition: trigger.c:2233
TransitionCaptureState * MakeTransitionCaptureState(TriggerDesc *trigdesc, Oid relid, CmdType cmdType)
Definition: trigger.c:4378
#define TABLE_INSERT_SKIP_FSM
Definition: tableam.h:233
TupleDesc rd_att
Definition: rel.h:111
static void ExecMaterializeSlot(TupleTableSlot *slot)
Definition: tuptable.h:443
Plan * plan
Definition: execnodes.h:934
void pq_endmsgread(void)
Definition: pqcomm.c:1233
#define ereport(elevel,...)
Definition: elog.h:155
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4500
#define makeNode(_type_)
Definition: nodes.h:576
TupleTableSlot * execute_attr_map_slot(AttrMap *attrMap, TupleTableSlot *in_slot, TupleTableSlot *out_slot)
Definition: tupconvert.c:177
CopyInsertMethod
#define Assert(condition)
Definition: c.h:792
void FreeBulkInsertState(BulkInsertState bistate)
Definition: heapam.c:1838
SubTransactionId GetCurrentSubTransactionId(void)
Definition: xact.c:723
bool ExecIRInsertTriggers(EState *estate, ResultRelInfo *relinfo, TupleTableSlot *slot)
Definition: trigger.c:2335
static int list_length(const List *l)
Definition: pg_list.h:149
TupleTableSlot * ecxt_scantuple
Definition: execnodes.h:225
#define InvalidSubTransactionId
Definition: c.h:581
void ReleaseBulkInsertStatePin(BulkInsertState bistate)
Definition: heapam.c:1850
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:514
CopyFormatOptions opts
bool freeze
Definition: copy.h:33
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4520
TupleConversionMap * ri_RootToPartitionMap
Definition: execnodes.h:497
int errmsg(const char *fmt,...)
Definition: elog.c:915
void list_free(List *list)
Definition: list.c:1391
static bool CopyMultiInsertInfoIsFull(CopyMultiInsertInfo *miinfo)
Definition: copyfrom.c:276
bool ExecPartitionCheck(ResultRelInfo *resultRelInfo, TupleTableSlot *slot, EState *estate, bool emitError)
Definition: execMain.c:1679
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
static void CopyMultiInsertInfoStore(CopyMultiInsertInfo *miinfo, ResultRelInfo *rri, TupleTableSlot *slot, int tuplen, uint64 lineno)
Definition: copyfrom.c:501
CommandId GetCurrentCommandId(bool used)
Definition: xact.c:761
ResultRelInfo * ExecFindPartition(ModifyTableState *mtstate, ResultRelInfo *rootResultRelInfo, PartitionTupleRouting *proute, TupleTableSlot *slot, EState *estate)
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:457
#define PROGRESS_COPY_LINES_PROCESSED
Definition: progress.h:139
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:1522
EndForeignInsert_function EndForeignInsert
Definition: fdwapi.h:226
TupleTableSlot * tcs_original_insert_tuple
Definition: trigger.h:75

◆ CopyFromErrorCallback()

void CopyFromErrorCallback ( void *  arg)

Definition at line 108 of file copyfrom.c.

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

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

109 {
110  CopyFromState cstate = (CopyFromState) arg;
111  char curlineno_str[32];
112 
113  snprintf(curlineno_str, sizeof(curlineno_str), UINT64_FORMAT,
114  cstate->cur_lineno);
115 
116  if (cstate->opts.binary)
117  {
118  /* can't usefully display the data */
119  if (cstate->cur_attname)
120  errcontext("COPY %s, line %s, column %s",
121  cstate->cur_relname, curlineno_str,
122  cstate->cur_attname);
123  else
124  errcontext("COPY %s, line %s",
125  cstate->cur_relname, curlineno_str);
126  }
127  else
128  {
129  if (cstate->cur_attname && cstate->cur_attval)
130  {
131  /* error is relevant to a particular column */
132  char *attval;
133 
134  attval = limit_printout_length(cstate->cur_attval);
135  errcontext("COPY %s, line %s, column %s: \"%s\"",
136  cstate->cur_relname, curlineno_str,
137  cstate->cur_attname, attval);
138  pfree(attval);
139  }
140  else if (cstate->cur_attname)
141  {
142  /* error is relevant to a particular column, value is NULL */
143  errcontext("COPY %s, line %s, column %s: null input",
144  cstate->cur_relname, curlineno_str,
145  cstate->cur_attname);
146  }
147  else
148  {
149  /*
150  * Error is relevant to a particular line.
151  *
152  * If line_buf still contains the correct line, and it's already
153  * transcoded, print it. If it's still in a foreign encoding, it's
154  * quite likely that the error is precisely a failure to do
155  * encoding conversion (ie, bad data). We dare not try to convert
156  * it, and at present there's no way to regurgitate it without
157  * conversion. So we have to punt and just report the line number.
158  */
159  if (cstate->line_buf_valid &&
160  (cstate->line_buf_converted || !cstate->need_transcoding))
161  {
162  char *lineval;
163 
164  lineval = limit_printout_length(cstate->line_buf.data);
165  errcontext("COPY %s, line %s: \"%s\"",
166  cstate->cur_relname, curlineno_str, lineval);
167  pfree(lineval);
168  }
169  else
170  {
171  errcontext("COPY %s, line %s",
172  cstate->cur_relname, curlineno_str);
173  }
174  }
175  }
176 }
const char * cur_attname
StringInfoData line_buf
const char * cur_attval
static char * limit_printout_length(const char *str)
Definition: copyfrom.c:184
void pfree(void *pointer)
Definition: mcxt.c:1057
bool binary
Definition: copy.h:32
const char * cur_relname
struct CopyFromStateData * CopyFromState
Definition: copy.h:54
CopyFormatOptions opts
#define errcontext
Definition: elog.h:199
void * arg
#define snprintf
Definition: port.h:215
#define UINT64_FORMAT
Definition: c.h:472

◆ CopyGetAttnums()

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

Definition at line 686 of file copy.c.

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

Referenced by BeginCopyFrom(), BeginCopyTo(), and DoCopy().

687 {
688  List *attnums = NIL;
689 
690  if (attnamelist == NIL)
691  {
692  /* Generate default column list */
693  int attr_count = tupDesc->natts;
694  int i;
695 
696  for (i = 0; i < attr_count; i++)
697  {
698  if (TupleDescAttr(tupDesc, i)->attisdropped)
699  continue;
700  if (TupleDescAttr(tupDesc, i)->attgenerated)
701  continue;
702  attnums = lappend_int(attnums, i + 1);
703  }
704  }
705  else
706  {
707  /* Validate the user-supplied list and extract attnums */
708  ListCell *l;
709 
710  foreach(l, attnamelist)
711  {
712  char *name = strVal(lfirst(l));
713  int attnum;
714  int i;
715 
716  /* Lookup column name */
717  attnum = InvalidAttrNumber;
718  for (i = 0; i < tupDesc->natts; i++)
719  {
720  Form_pg_attribute att = TupleDescAttr(tupDesc, i);
721 
722  if (att->attisdropped)
723  continue;
724  if (namestrcmp(&(att->attname), name) == 0)
725  {
726  if (att->attgenerated)
727  ereport(ERROR,
728  (errcode(ERRCODE_INVALID_COLUMN_REFERENCE),
729  errmsg("column \"%s\" is a generated column",
730  name),
731  errdetail("Generated columns cannot be used in COPY.")));
732  attnum = att->attnum;
733  break;
734  }
735  }
736  if (attnum == InvalidAttrNumber)
737  {
738  if (rel != NULL)
739  ereport(ERROR,
740  (errcode(ERRCODE_UNDEFINED_COLUMN),
741  errmsg("column \"%s\" of relation \"%s\" does not exist",
742  name, RelationGetRelationName(rel))));
743  else
744  ereport(ERROR,
745  (errcode(ERRCODE_UNDEFINED_COLUMN),
746  errmsg("column \"%s\" does not exist",
747  name)));
748  }
749  /* Check for duplicates */
750  if (list_member_int(attnums, attnum))
751  ereport(ERROR,
752  (errcode(ERRCODE_DUPLICATE_COLUMN),
753  errmsg("column \"%s\" specified more than once",
754  name)));
755  attnums = lappend_int(attnums, attnum);
756  }
757  }
758 
759  return attnums;
760 }
#define NIL
Definition: pg_list.h:65
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:704
int namestrcmp(Name name, const char *str)
Definition: name.c:247
#define ERROR
Definition: elog.h:45
bool list_member_int(const List *list, int datum)
Definition: list.c:669
int errdetail(const char *fmt,...)
Definition: elog.c:1048
#define RelationGetRelationName(relation)
Definition: rel.h:491
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
List * lappend_int(List *list, int datum)
Definition: list.c:354
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
#define InvalidAttrNumber
Definition: attnum.h:23
int errmsg(const char *fmt,...)
Definition: elog.c:915
int i
Definition: pg_list.h:50

◆ CreateCopyDestReceiver()

DestReceiver* CreateCopyDestReceiver ( void  )

Definition at line 1351 of file copyto.c.

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

Referenced by CreateDestReceiver().

1352 {
1353  DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
1354 
1355  self->pub.receiveSlot = copy_dest_receive;
1356  self->pub.rStartup = copy_dest_startup;
1357  self->pub.rShutdown = copy_dest_shutdown;
1358  self->pub.rDestroy = copy_dest_destroy;
1359  self->pub.mydest = DestCopyOut;
1360 
1361  self->cstate = NULL; /* will be set later */
1362  self->processed = 0;
1363 
1364  return (DestReceiver *) self;
1365 }
static void copy_dest_destroy(DestReceiver *self)
Definition: copyto.c:1342
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copyto.c:1315
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copyto.c:1306
void * palloc(Size size)
Definition: mcxt.c:950
static void copy_dest_shutdown(DestReceiver *self)
Definition: copyto.c:1333

◆ DoCopy()

void DoCopy ( ParseState state,
const CopyStmt stmt,
int  stmt_location,
int  stmt_len,
uint64 *  processed 
)

Definition at line 64 of file copy.c.

References AccessShareLock, ACL_INSERT, ACL_SELECT, addNSItemToQuery(), addRangeTableEntryForRelation(), Assert, assign_expr_collations(), CopyStmt::attlist, BeginCopyFrom(), BeginCopyTo(), bms_add_member(), canonicalize_qual(), check_enable_rls(), coerce_to_boolean(), CopyFrom(), CopyGetAttnums(), cur, DoCopyTo(), EndCopyFrom(), EndCopyTo(), ereport, errcode(), errhint(), errmsg(), ERROR, eval_const_expressions(), ExecCheckRTPerms(), EXPR_KIND_COPY_WHERE, ColumnRef::fields, CopyStmt::filename, FirstLowInvalidHeapAttributeNumber, SelectStmt::fromClause, get_namespace_name(), GetUserId(), ResTarget::indirection, RangeTblEntry::insertedCols, InvalidOid, CopyStmt::is_from, is_member_of_role(), CopyStmt::is_program, lappend(), lfirst, lfirst_int, list_make1, ColumnRef::location, ResTarget::location, make_ands_implicit(), makeNode, makeRangeVar(), ResTarget::name, NIL, NoLock, CopyStmt::options, ParseState::p_rtable, ParseNamespaceItem::p_rte, PreventCommandIfReadOnly(), pstrdup(), CopyStmt::query, RelationData::rd_islocaltemp, CopyStmt::relation, RelationGetDescr, RelationGetNamespace, RelationGetRelationName, RelationGetRelid, RangeTblEntry::relid, RangeTblEntry::requiredPerms, RLS_ENABLED, RowExclusiveLock, select, RangeTblEntry::selectedCols, RawStmt::stmt, RawStmt::stmt_len, RawStmt::stmt_location, table_close(), table_openrv(), SelectStmt::targetList, transformExpr(), ResTarget::val, CopyStmt::whereClause, and XactReadOnly.

Referenced by standard_ProcessUtility().

67 {
68  bool is_from = stmt->is_from;
69  bool pipe = (stmt->filename == NULL);
70  Relation rel;
71  Oid relid;
72  RawStmt *query = NULL;
73  Node *whereClause = NULL;
74 
75  /*
76  * Disallow COPY to/from file or program except to users with the
77  * appropriate role.
78  */
79  if (!pipe)
80  {
81  if (stmt->is_program)
82  {
83  if (!is_member_of_role(GetUserId(), DEFAULT_ROLE_EXECUTE_SERVER_PROGRAM))
84  ereport(ERROR,
85  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
86  errmsg("must be superuser or a member of the pg_execute_server_program role to COPY to or from an external program"),
87  errhint("Anyone can COPY to stdout or from stdin. "
88  "psql's \\copy command also works for anyone.")));
89  }
90  else
91  {
92  if (is_from && !is_member_of_role(GetUserId(), DEFAULT_ROLE_READ_SERVER_FILES))
93  ereport(ERROR,
94  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
95  errmsg("must be superuser or a member of the pg_read_server_files role to COPY from a file"),
96  errhint("Anyone can COPY to stdout or from stdin. "
97  "psql's \\copy command also works for anyone.")));
98 
99  if (!is_from && !is_member_of_role(GetUserId(), DEFAULT_ROLE_WRITE_SERVER_FILES))
100  ereport(ERROR,
101  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
102  errmsg("must be superuser or a member of the pg_write_server_files role to COPY to a file"),
103  errhint("Anyone can COPY to stdout or from stdin. "
104  "psql's \\copy command also works for anyone.")));
105  }
106  }
107 
108  if (stmt->relation)
109  {
110  LOCKMODE lockmode = is_from ? RowExclusiveLock : AccessShareLock;
111  ParseNamespaceItem *nsitem;
112  RangeTblEntry *rte;
113  TupleDesc tupDesc;
114  List *attnums;
115  ListCell *cur;
116 
117  Assert(!stmt->query);
118 
119  /* Open and lock the relation, using the appropriate lock type. */
120  rel = table_openrv(stmt->relation, lockmode);
121 
122  relid = RelationGetRelid(rel);
123 
124  nsitem = addRangeTableEntryForRelation(pstate, rel, lockmode,
125  NULL, false, false);
126  rte = nsitem->p_rte;
127  rte->requiredPerms = (is_from ? ACL_INSERT : ACL_SELECT);
128 
129  if (stmt->whereClause)
130  {
131  /* add nsitem to query namespace */
132  addNSItemToQuery(pstate, nsitem, false, true, true);
133 
134  /* Transform the raw expression tree */
135  whereClause = transformExpr(pstate, stmt->whereClause, EXPR_KIND_COPY_WHERE);
136 
137  /* Make sure it yields a boolean result. */
138  whereClause = coerce_to_boolean(pstate, whereClause, "WHERE");
139 
140  /* we have to fix its collations too */
141  assign_expr_collations(pstate, whereClause);
142 
143  whereClause = eval_const_expressions(NULL, whereClause);
144 
145  whereClause = (Node *) canonicalize_qual((Expr *) whereClause, false);
146  whereClause = (Node *) make_ands_implicit((Expr *) whereClause);
147  }
148 
149  tupDesc = RelationGetDescr(rel);
150  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
151  foreach(cur, attnums)
152  {
153  int attno = lfirst_int(cur) -
155 
156  if (is_from)
157  rte->insertedCols = bms_add_member(rte->insertedCols, attno);
158  else
159  rte->selectedCols = bms_add_member(rte->selectedCols, attno);
160  }
161  ExecCheckRTPerms(pstate->p_rtable, true);
162 
163  /*
164  * Permission check for row security policies.
165  *
166  * check_enable_rls will ereport(ERROR) if the user has requested
167  * something invalid and will otherwise indicate if we should enable
168  * RLS (returns RLS_ENABLED) or not for this COPY statement.
169  *
170  * If the relation has a row security policy and we are to apply it
171  * then perform a "query" copy and allow the normal query processing
172  * to handle the policies.
173  *
174  * If RLS is not enabled for this, then just fall through to the
175  * normal non-filtering relation handling.
176  */
177  if (check_enable_rls(rte->relid, InvalidOid, false) == RLS_ENABLED)
178  {
180  ColumnRef *cr;
181  ResTarget *target;
182  RangeVar *from;
183  List *targetList = NIL;
184 
185  if (is_from)
186  ereport(ERROR,
187  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
188  errmsg("COPY FROM not supported with row-level security"),
189  errhint("Use INSERT statements instead.")));
190 
191  /*
192  * Build target list
193  *
194  * If no columns are specified in the attribute list of the COPY
195  * command, then the target list is 'all' columns. Therefore, '*'
196  * should be used as the target list for the resulting SELECT
197  * statement.
198  *
199  * In the case that columns are specified in the attribute list,
200  * create a ColumnRef and ResTarget for each column and add them
201  * to the target list for the resulting SELECT statement.
202  */
203  if (!stmt->attlist)
204  {
205  cr = makeNode(ColumnRef);
207  cr->location = -1;
208 
209  target = makeNode(ResTarget);
210  target->name = NULL;
211  target->indirection = NIL;
212  target->val = (Node *) cr;
213  target->location = -1;
214 
215  targetList = list_make1(target);
216  }
217  else
218  {
219  ListCell *lc;
220 
221  foreach(lc, stmt->attlist)
222  {
223  /*
224  * Build the ColumnRef for each column. The ColumnRef
225  * 'fields' property is a String 'Value' node (see
226  * nodes/value.h) that corresponds to the column name
227  * respectively.
228  */
229  cr = makeNode(ColumnRef);
230  cr->fields = list_make1(lfirst(lc));
231  cr->location = -1;
232 
233  /* Build the ResTarget and add the ColumnRef to it. */
234  target = makeNode(ResTarget);
235  target->name = NULL;
236  target->indirection = NIL;
237  target->val = (Node *) cr;
238  target->location = -1;
239 
240  /* Add each column to the SELECT statement's target list */
241  targetList = lappend(targetList, target);
242  }
243  }
244 
245  /*
246  * Build RangeVar for from clause, fully qualified based on the
247  * relation which we have opened and locked.
248  */
251  -1);
252 
253  /* Build query */
254  select = makeNode(SelectStmt);
255  select->targetList = targetList;
256  select->fromClause = list_make1(from);
257 
258  query = makeNode(RawStmt);
259  query->stmt = (Node *) select;
260  query->stmt_location = stmt_location;
261  query->stmt_len = stmt_len;
262 
263  /*
264  * Close the relation for now, but keep the lock on it to prevent
265  * changes between now and when we start the query-based COPY.
266  *
267  * We'll reopen it later as part of the query-based COPY.
268  */
269  table_close(rel, NoLock);
270  rel = NULL;
271  }
272  }
273  else
274  {
275  Assert(stmt->query);
276 
277  query = makeNode(RawStmt);
278  query->stmt = stmt->query;
279  query->stmt_location = stmt_location;
280  query->stmt_len = stmt_len;
281 
282  relid = InvalidOid;
283  rel = NULL;
284  }
285 
286  if (is_from)
287  {
288  CopyFromState cstate;
289 
290  Assert(rel);
291 
292  /* check read-only transaction and parallel mode */
293  if (XactReadOnly && !rel->rd_islocaltemp)
294  PreventCommandIfReadOnly("COPY FROM");
295 
296  cstate = BeginCopyFrom(pstate, rel, whereClause,
297  stmt->filename, stmt->is_program,
298  NULL, stmt->attlist, stmt->options);
299  *processed = CopyFrom(cstate); /* copy from file to database */
300  EndCopyFrom(cstate);
301  }
302  else
303  {
304  CopyToState cstate;
305 
306  cstate = BeginCopyTo(pstate, rel, query, relid,
307  stmt->filename, stmt->is_program,
308  stmt->attlist, stmt->options);
309  *processed = DoCopyTo(cstate); /* copy from database to file */
310  EndCopyTo(cstate);
311  }
312 
313  if (rel != NULL)
314  table_close(rel, NoLock);
315 }
List * indirection
Definition: parsenodes.h:442
#define NIL
Definition: pg_list.h:65
Node * whereClause
Definition: parsenodes.h:2035
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Node * val
Definition: parsenodes.h:443
int errhint(const char *fmt,...)
Definition: elog.c:1162
List * attlist
Definition: parsenodes.h:2029
List * fromClause
Definition: parsenodes.h:1603
#define RelationGetDescr(relation)
Definition: rel.h:483
int LOCKMODE
Definition: lockdefs.h:26
char * name
Definition: parsenodes.h:441
Oid GetUserId(void)
Definition: miscinit.c:476
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:524
char * pstrdup(const char *in)
Definition: mcxt.c:1187
bool rd_islocaltemp
Definition: rel.h:60
Node * transformExpr(ParseState *pstate, Node *expr, ParseExprKind exprKind)
Definition: parse_expr.c:94
#define AccessShareLock
Definition: lockdefs.h:36
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
Definition: nodes.h:528
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:704
Node * eval_const_expressions(PlannerInfo *root, Node *node)
Definition: clauses.c:2022
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:27
AclMode requiredPerms
Definition: parsenodes.h:1124
unsigned int Oid
Definition: postgres_ext.h:31
bool is_program
Definition: parsenodes.h:2032
void EndCopyTo(CopyToState cstate)
Definition: copyto.c:822
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
int location
Definition: parsenodes.h:237
int location
Definition: parsenodes.h:444
#define list_make1(x1)
Definition: pg_list.h:206
void assign_expr_collations(ParseState *pstate, Node *expr)
RangeTblEntry * p_rte
Definition: parse_node.h:257
Bitmapset * selectedCols
Definition: parsenodes.h:1126
#define ERROR
Definition: elog.h:45
#define lfirst_int(lc)
Definition: pg_list.h:170
RangeVar * relation
Definition: parsenodes.h:2026
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3289
Node * stmt
Definition: parsenodes.h:1513
#define NoLock
Definition: lockdefs.h:34
List * targetList
Definition: parsenodes.h:1602
#define RowExclusiveLock
Definition: lockdefs.h:38
Expr * canonicalize_qual(Expr *qual, bool is_check)
Definition: prepqual.c:292
List * options
Definition: parsenodes.h:2034
#define select(n, r, w, e, timeout)
Definition: win32_port.h:464
#define RelationGetRelationName(relation)
Definition: rel.h:491
List * lappend(List *list, void *datum)
Definition: list.c:336
#define ACL_SELECT
Definition: parsenodes.h:75
List * make_ands_implicit(Expr *clause)
Definition: makefuncs.c:719
int stmt_len
Definition: parsenodes.h:1515
int stmt_location
Definition: parsenodes.h:1514
Relation table_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: table.c:102
#define InvalidOid
Definition: postgres_ext.h:36
CopyToState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *raw_query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
Definition: copyto.c:383
#define ereport(elevel,...)
Definition: elog.h:155
bool XactReadOnly
Definition: xact.c:78
bool is_member_of_role(Oid member, Oid role)
Definition: acl.c:4919
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
#define makeNode(_type_)
Definition: nodes.h:576
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1180
#define Assert(condition)
Definition: c.h:792
#define lfirst(lc)
Definition: pg_list.h:169
#define ACL_INSERT
Definition: parsenodes.h:74
List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:686
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:408
void EndCopyFrom(CopyFromState cstate)
Definition: copyfrom.c:1521
Node * query
Definition: parsenodes.h:2027
bool is_from
Definition: parsenodes.h:2031
int errmsg(const char *fmt,...)
Definition: elog.c:915
Bitmapset * insertedCols
Definition: parsenodes.h:1127
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:571
char * filename
Definition: parsenodes.h:2033
uint64 DoCopyTo(CopyToState cstate)
Definition: copyto.c:787
Definition: pg_list.h:50
#define RelationGetRelid(relation)
Definition: rel.h:457
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
List * fields
Definition: parsenodes.h:236
#define RelationGetNamespace(relation)
Definition: rel.h:498
Node * coerce_to_boolean(ParseState *pstate, Node *node, const char *constructName)

◆ DoCopyTo()

uint64 DoCopyTo ( CopyToState  cstate)

Definition at line 787 of file copyto.c.

References CopyTo(), DestRemote, CopyToStateData::filename, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, pq_endcopyout, SendCopyBegin(), SendCopyEnd(), and whereToSendOutput.

Referenced by DoCopy().

788 {
789  bool pipe = (cstate->filename == NULL);
790  bool fe_copy = (pipe && whereToSendOutput == DestRemote);
791  uint64 processed;
792 
793  PG_TRY();
794  {
795  if (fe_copy)
796  SendCopyBegin(cstate);
797 
798  processed = CopyTo(cstate);
799 
800  if (fe_copy)
801  SendCopyEnd(cstate);
802  }
803  PG_CATCH();
804  {
805  /*
806  * Make sure we turn off old-style COPY OUT mode upon error. It is
807  * okay to do this in all cases, since it does nothing if the mode is
808  * not on.
809  */
810  pq_endcopyout(true);
811  PG_RE_THROW();
812  }
813  PG_END_TRY();
814 
815  return processed;
816 }
static void SendCopyEnd(CopyToState cstate)
Definition: copyto.c:174
static void SendCopyBegin(CopyToState cstate)
Definition: copyto.c:141
#define PG_CATCH()
Definition: elog.h:319
#define pq_endcopyout(errorAbort)
Definition: libpq.h:47
#define PG_RE_THROW()
Definition: elog.h:350
CommandDest whereToSendOutput
Definition: postgres.c:92
char * filename
Definition: copyto.c:87
#define PG_TRY()
Definition: elog.h:309
static uint64 CopyTo(CopyToState cstate)
Definition: copyto.c:841
#define PG_END_TRY()
Definition: elog.h:334

◆ EndCopyFrom()

void EndCopyFrom ( CopyFromState  cstate)

Definition at line 1521 of file copyfrom.c.

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

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

1522 {
1523  /* No COPY FROM related resources except memory. */
1524  if (cstate->is_program)
1525  {
1526  ClosePipeFromProgram(cstate);
1527  }
1528  else
1529  {
1530  if (cstate->filename != NULL && FreeFile(cstate->copy_file))
1531  ereport(ERROR,
1533  errmsg("could not close file \"%s\": %m",
1534  cstate->filename)));
1535  }
1536 
1538 
1540  pfree(cstate);
1541 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:212
MemoryContext copycontext
void pfree(void *pointer)
Definition: mcxt.c:1057
#define ERROR
Definition: elog.h:45
static void ClosePipeFromProgram(CopyFromState cstate)
Definition: copyfrom.c:1547
int errcode_for_file_access(void)
Definition: elog.c:727
void pgstat_progress_end_command(void)
Definition: pgstat.c:3529
#define ereport(elevel,...)
Definition: elog.h:155
int FreeFile(FILE *file)
Definition: fd.c:2553
int errmsg(const char *fmt,...)
Definition: elog.c:915

◆ EndCopyTo()

void EndCopyTo ( CopyToState  cstate)

Definition at line 822 of file copyto.c.

References EndCopy(), ExecutorEnd(), ExecutorFinish(), FreeQueryDesc(), PopActiveSnapshot(), and CopyToStateData::queryDesc.

Referenced by DoCopy().

823 {
824  if (cstate->queryDesc != NULL)
825  {
826  /* Close down the query and free resources. */
827  ExecutorFinish(cstate->queryDesc);
828  ExecutorEnd(cstate->queryDesc);
829  FreeQueryDesc(cstate->queryDesc);
831  }
832 
833  /* Clean up storage */
834  EndCopy(cstate);
835 }
void FreeQueryDesc(QueryDesc *qdesc)
Definition: pquery.c:105
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
static void EndCopy(CopyToState cstate)
Definition: copyto.c:358
QueryDesc * queryDesc
Definition: copyto.c:85
void ExecutorEnd(QueryDesc *queryDesc)
Definition: execMain.c:462
void ExecutorFinish(QueryDesc *queryDesc)
Definition: execMain.c:402

◆ NextCopyFrom()

bool NextCopyFrom ( CopyFromState  cstate,
ExprContext econtext,
Datum values,
bool nulls 
)

Definition at line 505 of file copyfromparse.c.

References Assert, attnum, CopyFromStateData::attnumlist, CopyFormatOptions::binary, CopyFromStateData::convert_select_flags, COPY_OLD_FE, CopyFromStateData::copy_src, CopyGetInt16(), CopyReadBinaryAttribute(), CopyReadBinaryData(), CopyFormatOptions::csv_mode, cur, CopyFromStateData::cur_attname, CopyFromStateData::cur_attval, CopyFromStateData::cur_lineno, CurrentMemoryContext, CopyFromStateData::defexprs, CopyFromStateData::defmap, ExprContext::ecxt_per_tuple_memory, ereport, errcode(), errmsg(), ERROR, ExecEvalExpr(), CopyFormatOptions::force_notnull_flags, CopyFormatOptions::force_null_flags, i, CopyFromStateData::in_functions, InputFunctionCall(), lfirst_int, list_length(), MemSet, NameStr, TupleDescData::natts, NextCopyFromRawFields(), CopyFormatOptions::null_print, CopyFromStateData::num_defaults, CopyFromStateData::opts, CopyFromStateData::rel, RelationGetDescr, TupleDescAttr, and CopyFromStateData::typioparams.

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

507 {
508  TupleDesc tupDesc;
509  AttrNumber num_phys_attrs,
510  attr_count,
511  num_defaults = cstate->num_defaults;
512  FmgrInfo *in_functions = cstate->in_functions;
513  Oid *typioparams = cstate->typioparams;
514  int i;
515  int *defmap = cstate->defmap;
516  ExprState **defexprs = cstate->defexprs;
517 
518  tupDesc = RelationGetDescr(cstate->rel);
519  num_phys_attrs = tupDesc->natts;
520  attr_count = list_length(cstate->attnumlist);
521 
522  /* Initialize all values for row to NULL */
523  MemSet(values, 0, num_phys_attrs * sizeof(Datum));
524  MemSet(nulls, true, num_phys_attrs * sizeof(bool));
525 
526  if (!cstate->opts.binary)
527  {
528  char **field_strings;
529  ListCell *cur;
530  int fldct;
531  int fieldno;
532  char *string;
533 
534  /* read raw fields in the next line */
535  if (!NextCopyFromRawFields(cstate, &field_strings, &fldct))
536  return false;
537 
538  /* check for overflowing fields */
539  if (attr_count > 0 && fldct > attr_count)
540  ereport(ERROR,
541  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
542  errmsg("extra data after last expected column")));
543 
544  fieldno = 0;
545 
546  /* Loop to read the user attributes on the line. */
547  foreach(cur, cstate->attnumlist)
548  {
549  int attnum = lfirst_int(cur);
550  int m = attnum - 1;
551  Form_pg_attribute att = TupleDescAttr(tupDesc, m);
552 
553  if (fieldno >= fldct)
554  ereport(ERROR,
555  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
556  errmsg("missing data for column \"%s\"",
557  NameStr(att->attname))));
558  string = field_strings[fieldno++];
559 
560  if (cstate->convert_select_flags &&
561  !cstate->convert_select_flags[m])
562  {
563  /* ignore input field, leaving column as NULL */
564  continue;
565  }
566 
567  if (cstate->opts.csv_mode)
568  {
569  if (string == NULL &&
570  cstate->opts.force_notnull_flags[m])
571  {
572  /*
573  * FORCE_NOT_NULL option is set and column is NULL -
574  * convert it to the NULL string.
575  */
576  string = cstate->opts.null_print;
577  }
578  else if (string != NULL && cstate->opts.force_null_flags[m]
579  && strcmp(string, cstate->opts.null_print) == 0)
580  {
581  /*
582  * FORCE_NULL option is set and column matches the NULL
583  * string. It must have been quoted, or otherwise the
584  * string would already have been set to NULL. Convert it
585  * to NULL as specified.
586  */
587  string = NULL;
588  }
589  }
590 
591  cstate->cur_attname = NameStr(att->attname);
592  cstate->cur_attval = string;
593  values[m] = InputFunctionCall(&in_functions[m],
594  string,
595  typioparams[m],
596  att->atttypmod);
597  if (string != NULL)
598  nulls[m] = false;
599  cstate->cur_attname = NULL;
600  cstate->cur_attval = NULL;
601  }
602 
603  Assert(fieldno == attr_count);
604  }
605  else
606  {
607  /* binary */
608  int16 fld_count;
609  ListCell *cur;
610 
611  cstate->cur_lineno++;
612 
613  if (!CopyGetInt16(cstate, &fld_count))
614  {
615  /* EOF detected (end of file, or protocol-level EOF) */
616  return false;
617  }
618 
619  if (fld_count == -1)
620  {
621  /*
622  * Received EOF marker. In a V3-protocol copy, wait for the
623  * protocol-level EOF, and complain if it doesn't come
624  * immediately. This ensures that we correctly handle CopyFail,
625  * if client chooses to send that now.
626  *
627  * Note that we MUST NOT try to read more data in an old-protocol
628  * copy, since there is no protocol-level EOF marker then. We
629  * could go either way for copy from file, but choose to throw
630  * error if there's data after the EOF marker, for consistency
631  * with the new-protocol case.
632  */
633  char dummy;
634 
635  if (cstate->copy_src != COPY_OLD_FE &&
636  CopyReadBinaryData(cstate, &dummy, 1) > 0)
637  ereport(ERROR,
638  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
639  errmsg("received copy data after EOF marker")));
640  return false;
641  }
642 
643  if (fld_count != attr_count)
644  ereport(ERROR,
645  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
646  errmsg("row field count is %d, expected %d",
647  (int) fld_count, attr_count)));
648 
649  foreach(cur, cstate->attnumlist)
650  {
651  int attnum = lfirst_int(cur);
652  int m = attnum - 1;
653  Form_pg_attribute att = TupleDescAttr(tupDesc, m);
654 
655  cstate->cur_attname = NameStr(att->attname);
656  values[m] = CopyReadBinaryAttribute(cstate,
657  &in_functions[m],
658  typioparams[m],
659  att->atttypmod,
660  &nulls[m]);
661  cstate->cur_attname = NULL;
662  }
663  }
664 
665  /*
666  * Now compute and insert any defaults available for the columns not
667  * provided by the input data. Anything not processed here or above will
668  * remain NULL.
669  */
670  for (i = 0; i < num_defaults; i++)
671  {
672  /*
673  * The caller must supply econtext and have switched into the
674  * per-tuple memory context in it.
675  */
676  Assert(econtext != NULL);
678 
679  values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
680  &nulls[defmap[i]]);
681  }
682 
683  return true;
684 }
signed short int16
Definition: c.h:416
Definition: fmgr.h:56
bool NextCopyFromRawFields(CopyFromState cstate, char ***fields, int *nfields)
const char * cur_attname
#define RelationGetDescr(relation)
Definition: rel.h:483
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:92
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:233
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:704
static bool CopyGetInt16(CopyFromState cstate, int16 *val)
#define MemSet(start, val, len)
Definition: c.h:996
const char * cur_attval
unsigned int Oid
Definition: postgres_ext.h:31
char * null_print
Definition: copy.h:36
static int CopyReadBinaryData(CopyFromState cstate, char *dest, int nbytes)
#define ERROR
Definition: elog.h:45
#define lfirst_int(lc)
Definition: pg_list.h:170
bool binary
Definition: copy.h:32
bool csv_mode
Definition: copy.h:34
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:292
char string[11]
Definition: preproc-type.c:46
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:193
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
uintptr_t Datum
Definition: postgres.h:367
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1532
int16 attnum
Definition: pg_attribute.h:79
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:792
bool * force_null_flags
Definition: copy.h:48
static int list_length(const List *l)
Definition: pg_list.h:149
CopyFormatOptions opts
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:915
int i
#define NameStr(name)
Definition: c.h:669
static Datum CopyReadBinaryAttribute(CopyFromState cstate, FmgrInfo *flinfo, Oid typioparam, int32 typmod, bool *isnull)
int16 AttrNumber
Definition: attnum.h:21
bool * force_notnull_flags
Definition: copy.h:46

◆ NextCopyFromRawFields()

bool NextCopyFromRawFields ( CopyFromState  cstate,
char ***  fields,
int *  nfields 
)

Definition at line 454 of file copyfromparse.c.

References Assert, CopyFormatOptions::binary, CopyReadAttributesCSV(), CopyReadAttributesText(), CopyReadLine(), CopyFormatOptions::csv_mode, CopyFromStateData::cur_lineno, CopyFormatOptions::header_line, StringInfoData::len, CopyFromStateData::line_buf, CopyFromStateData::opts, and CopyFromStateData::raw_fields.

Referenced by NextCopyFrom().

455 {
456  int fldct;
457  bool done;
458 
459  /* only available for text or csv input */
460  Assert(!cstate->opts.binary);
461 
462  /* on input just throw the header line away */
463  if (cstate->cur_lineno == 0 && cstate->opts.header_line)
464  {
465  cstate->cur_lineno++;
466  if (CopyReadLine(cstate))
467  return false; /* done */
468  }
469 
470  cstate->cur_lineno++;
471 
472  /* Actually read the line into memory here */
473  done = CopyReadLine(cstate);
474 
475  /*
476  * EOF at start of line means we're done. If we see EOF after some
477  * characters, we act as though it was newline followed by EOF, ie,
478  * process the line and then exit loop on next iteration.
479  */
480  if (done && cstate->line_buf.len == 0)
481  return false;
482 
483  /* Parse the line into de-escaped field values */
484  if (cstate->opts.csv_mode)
485  fldct = CopyReadAttributesCSV(cstate);
486  else
487  fldct = CopyReadAttributesText(cstate);
488 
489  *fields = cstate->raw_fields;
490  *nfields = fldct;
491  return true;
492 }
StringInfoData line_buf
static bool CopyReadLine(CopyFromState cstate)
bool binary
Definition: copy.h:32
bool csv_mode
Definition: copy.h:34
bool header_line
Definition: copy.h:35
static int CopyReadAttributesText(CopyFromState cstate)
#define Assert(condition)
Definition: c.h:792
CopyFormatOptions opts
static int CopyReadAttributesCSV(CopyFromState cstate)

◆ ProcessCopyOptions()

void ProcessCopyOptions ( ParseState pstate,
CopyFormatOptions ops_out,
bool  is_from,
List options 
)

Definition at line 334 of file copy.c.

References DefElem::arg, CopyFormatOptions::binary, castNode, CopyFormatOptions::convert_select, CopyFormatOptions::convert_selectively, CopyFormatOptions::csv_mode, defGetBoolean(), defGetString(), DefElem::defname, CopyFormatOptions::delim, ereport, errcode(), errmsg(), ERROR, CopyFormatOptions::escape, CopyFormatOptions::file_encoding, CopyFormatOptions::force_notnull, CopyFormatOptions::force_null, CopyFormatOptions::force_quote, CopyFormatOptions::force_quote_all, CopyFormatOptions::freeze, CopyFormatOptions::header_line, IsA, lfirst_node, DefElem::location, NIL, CopyFormatOptions::null_print, CopyFormatOptions::null_print_len, palloc0(), parser_errposition(), pg_char_to_encoding(), and CopyFormatOptions::quote.

Referenced by BeginCopyFrom(), BeginCopyTo(), and file_fdw_validator().

338 {
339  bool format_specified = false;
340  bool freeze_specified = false;
341  bool header_specified = false;
342  ListCell *option;
343 
344  /* Support external use for option sanity checking */
345  if (opts_out == NULL)
346  opts_out = (CopyFormatOptions *) palloc0(sizeof(CopyFormatOptions));
347 
348  opts_out->file_encoding = -1;
349 
350  /* Extract options from the statement node tree */
351  foreach(option, options)
352  {
353  DefElem *defel = lfirst_node(DefElem, option);
354 
355  if (strcmp(defel->defname, "format") == 0)
356  {
357  char *fmt = defGetString(defel);
358 
359  if (format_specified)
360  ereport(ERROR,
361  (errcode(ERRCODE_SYNTAX_ERROR),
362  errmsg("conflicting or redundant options"),
363  parser_errposition(pstate, defel->location)));
364  format_specified = true;
365  if (strcmp(fmt, "text") == 0)
366  /* default format */ ;
367  else if (strcmp(fmt, "csv") == 0)
368  opts_out->csv_mode = true;
369  else if (strcmp(fmt, "binary") == 0)
370  opts_out->binary = true;
371  else
372  ereport(ERROR,
373  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
374  errmsg("COPY format \"%s\" not recognized", fmt),
375  parser_errposition(pstate, defel->location)));
376  }
377  else if (strcmp(defel->defname, "freeze") == 0)
378  {
379  if (freeze_specified)
380  ereport(ERROR,
381  (errcode(ERRCODE_SYNTAX_ERROR),
382  errmsg("conflicting or redundant options"),
383  parser_errposition(pstate, defel->location)));
384  freeze_specified = true;
385  opts_out->freeze = defGetBoolean(defel);
386  }
387  else if (strcmp(defel->defname, "delimiter") == 0)
388  {
389  if (opts_out->delim)
390  ereport(ERROR,
391  (errcode(ERRCODE_SYNTAX_ERROR),
392  errmsg("conflicting or redundant options"),
393  parser_errposition(pstate, defel->location)));
394  opts_out->delim = defGetString(defel);
395  }
396  else if (strcmp(defel->defname, "null") == 0)
397  {
398  if (opts_out->null_print)
399  ereport(ERROR,
400  (errcode(ERRCODE_SYNTAX_ERROR),
401  errmsg("conflicting or redundant options"),
402  parser_errposition(pstate, defel->location)));
403  opts_out->null_print = defGetString(defel);
404  }
405  else if (strcmp(defel->defname, "header") == 0)
406  {
407  if (header_specified)
408  ereport(ERROR,
409  (errcode(ERRCODE_SYNTAX_ERROR),
410  errmsg("conflicting or redundant options"),
411  parser_errposition(pstate, defel->location)));
412  header_specified = true;
413  opts_out->header_line = defGetBoolean(defel);
414  }
415  else if (strcmp(defel->defname, "quote") == 0)
416  {
417  if (opts_out->quote)
418  ereport(ERROR,
419  (errcode(ERRCODE_SYNTAX_ERROR),
420  errmsg("conflicting or redundant options"),
421  parser_errposition(pstate, defel->location)));
422  opts_out->quote = defGetString(defel);
423  }
424  else if (strcmp(defel->defname, "escape") == 0)
425  {
426  if (opts_out->escape)
427  ereport(ERROR,
428  (errcode(ERRCODE_SYNTAX_ERROR),
429  errmsg("conflicting or redundant options"),
430  parser_errposition(pstate, defel->location)));
431  opts_out->escape = defGetString(defel);
432  }
433  else if (strcmp(defel->defname, "force_quote") == 0)
434  {
435  if (opts_out->force_quote || opts_out->force_quote_all)
436  ereport(ERROR,
437  (errcode(ERRCODE_SYNTAX_ERROR),
438  errmsg("conflicting or redundant options"),
439  parser_errposition(pstate, defel->location)));
440  if (defel->arg && IsA(defel->arg, A_Star))
441  opts_out->force_quote_all = true;
442  else if (defel->arg && IsA(defel->arg, List))
443  opts_out->force_quote = castNode(List, defel->arg);
444  else
445  ereport(ERROR,
446  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
447  errmsg("argument to option \"%s\" must be a list of column names",
448  defel->defname),
449  parser_errposition(pstate, defel->location)));
450  }
451  else if (strcmp(defel->defname, "force_not_null") == 0)
452  {
453  if (opts_out->force_notnull)
454  ereport(ERROR,
455  (errcode(ERRCODE_SYNTAX_ERROR),
456  errmsg("conflicting or redundant options"),
457  parser_errposition(pstate, defel->location)));
458  if (defel->arg && IsA(defel->arg, List))
459  opts_out->force_notnull = castNode(List, defel->arg);
460  else
461  ereport(ERROR,
462  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
463  errmsg("argument to option \"%s\" must be a list of column names",
464  defel->defname),
465  parser_errposition(pstate, defel->location)));
466  }
467  else if (strcmp(defel->defname, "force_null") == 0)
468  {
469  if (opts_out->force_null)
470  ereport(ERROR,
471  (errcode(ERRCODE_SYNTAX_ERROR),
472  errmsg("conflicting or redundant options")));
473  if (defel->arg && IsA(defel->arg, List))
474  opts_out->force_null = castNode(List, defel->arg);
475  else
476  ereport(ERROR,
477  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
478  errmsg("argument to option \"%s\" must be a list of column names",
479  defel->defname),
480  parser_errposition(pstate, defel->location)));
481  }
482  else if (strcmp(defel->defname, "convert_selectively") == 0)
483  {
484  /*
485  * Undocumented, not-accessible-from-SQL option: convert only the
486  * named columns to binary form, storing the rest as NULLs. It's
487  * allowed for the column list to be NIL.
488  */
489  if (opts_out->convert_selectively)
490  ereport(ERROR,
491  (errcode(ERRCODE_SYNTAX_ERROR),
492  errmsg("conflicting or redundant options"),
493  parser_errposition(pstate, defel->location)));
494  opts_out->convert_selectively = true;
495  if (defel->arg == NULL || IsA(defel->arg, List))
496  opts_out->convert_select = castNode(List, defel->arg);
497  else
498  ereport(ERROR,
499  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
500  errmsg("argument to option \"%s\" must be a list of column names",
501  defel->defname),
502  parser_errposition(pstate, defel->location)));
503  }
504  else if (strcmp(defel->defname, "encoding") == 0)
505  {
506  if (opts_out->file_encoding >= 0)
507  ereport(ERROR,
508  (errcode(ERRCODE_SYNTAX_ERROR),
509  errmsg("conflicting or redundant options"),
510  parser_errposition(pstate, defel->location)));
511  opts_out->file_encoding = pg_char_to_encoding(defGetString(defel));
512  if (opts_out->file_encoding < 0)
513  ereport(ERROR,
514  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
515  errmsg("argument to option \"%s\" must be a valid encoding name",
516  defel->defname),
517  parser_errposition(pstate, defel->location)));
518  }
519  else
520  ereport(ERROR,
521  (errcode(ERRCODE_SYNTAX_ERROR),
522  errmsg("option \"%s\" not recognized",
523  defel->defname),
524  parser_errposition(pstate, defel->location)));
525  }
526 
527  /*
528  * Check for incompatible options (must do these two before inserting
529  * defaults)
530  */
531  if (opts_out->binary && opts_out->delim)
532  ereport(ERROR,
533  (errcode(ERRCODE_SYNTAX_ERROR),
534  errmsg("cannot specify DELIMITER in BINARY mode")));
535 
536  if (opts_out->binary && opts_out->null_print)
537  ereport(ERROR,
538  (errcode(ERRCODE_SYNTAX_ERROR),
539  errmsg("cannot specify NULL in BINARY mode")));
540 
541  /* Set defaults for omitted options */
542  if (!opts_out->delim)
543  opts_out->delim = opts_out->csv_mode ? "," : "\t";
544 
545  if (!opts_out->null_print)
546  opts_out->null_print = opts_out->csv_mode ? "" : "\\N";
547  opts_out->null_print_len = strlen(opts_out->null_print);
548 
549  if (opts_out->csv_mode)
550  {
551  if (!opts_out->quote)
552  opts_out->quote = "\"";
553  if (!opts_out->escape)
554  opts_out->escape = opts_out->quote;
555  }
556 
557  /* Only single-byte delimiter strings are supported. */
558  if (strlen(opts_out->delim) != 1)
559  ereport(ERROR,
560  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
561  errmsg("COPY delimiter must be a single one-byte character")));
562 
563  /* Disallow end-of-line characters */
564  if (strchr(opts_out->delim, '\r') != NULL ||
565  strchr(opts_out->delim, '\n') != NULL)
566  ereport(ERROR,
567  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
568  errmsg("COPY delimiter cannot be newline or carriage return")));
569 
570  if (strchr(opts_out->null_print, '\r') != NULL ||
571  strchr(opts_out->null_print, '\n') != NULL)
572  ereport(ERROR,
573  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
574  errmsg("COPY null representation cannot use newline or carriage return")));
575 
576  /*
577  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
578  * backslash because it would be ambiguous. We can't allow the other
579  * cases because data characters matching the delimiter must be
580  * backslashed, and certain backslash combinations are interpreted
581  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
582  * more than strictly necessary, but seems best for consistency and
583  * future-proofing. Likewise we disallow all digits though only octal
584  * digits are actually dangerous.
585  */
586  if (!opts_out->csv_mode &&
587  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
588  opts_out->delim[0]) != NULL)
589  ereport(ERROR,
590  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
591  errmsg("COPY delimiter cannot be \"%s\"", opts_out->delim)));
592 
593  /* Check header */
594  if (!opts_out->csv_mode && opts_out->header_line)
595  ereport(ERROR,
596  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
597  errmsg("COPY HEADER available only in CSV mode")));
598 
599  /* Check quote */
600  if (!opts_out->csv_mode && opts_out->quote != NULL)
601  ereport(ERROR,
602  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
603  errmsg("COPY quote available only in CSV mode")));
604 
605  if (opts_out->csv_mode && strlen(opts_out->quote) != 1)
606  ereport(ERROR,
607  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
608  errmsg("COPY quote must be a single one-byte character")));
609 
610  if (opts_out->csv_mode && opts_out->delim[0] == opts_out->quote[0])
611  ereport(ERROR,
612  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
613  errmsg("COPY delimiter and quote must be different")));
614 
615  /* Check escape */
616  if (!opts_out->csv_mode && opts_out->escape != NULL)
617  ereport(ERROR,
618  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
619  errmsg("COPY escape available only in CSV mode")));
620 
621  if (opts_out->csv_mode && strlen(opts_out->escape) != 1)
622  ereport(ERROR,
623  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
624  errmsg("COPY escape must be a single one-byte character")));
625 
626  /* Check force_quote */
627  if (!opts_out->csv_mode && (opts_out->force_quote || opts_out->force_quote_all))
628  ereport(ERROR,
629  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
630  errmsg("COPY force quote available only in CSV mode")));
631  if ((opts_out->force_quote || opts_out->force_quote_all) && is_from)
632  ereport(ERROR,
633  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
634  errmsg("COPY force quote only available using COPY TO")));
635 
636  /* Check force_notnull */
637  if (!opts_out->csv_mode && opts_out->force_notnull != NIL)
638  ereport(ERROR,
639  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
640  errmsg("COPY force not null available only in CSV mode")));
641  if (opts_out->force_notnull != NIL && !is_from)
642  ereport(ERROR,
643  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
644  errmsg("COPY force not null only available using COPY FROM")));
645 
646  /* Check force_null */
647  if (!opts_out->csv_mode && opts_out->force_null != NIL)
648  ereport(ERROR,
649  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
650  errmsg("COPY force null available only in CSV mode")));
651 
652  if (opts_out->force_null != NIL && !is_from)
653  ereport(ERROR,
654  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
655  errmsg("COPY force null only available using COPY FROM")));
656 
657  /* Don't allow the delimiter to appear in the null string. */
658  if (strchr(opts_out->null_print, opts_out->delim[0]) != NULL)
659  ereport(ERROR,
660  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
661  errmsg("COPY delimiter must not appear in the NULL specification")));
662 
663  /* Don't allow the CSV quote char to appear in the null string. */
664  if (opts_out->csv_mode &&
665  strchr(opts_out->null_print, opts_out->quote[0]) != NULL)
666  ereport(ERROR,
667  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
668  errmsg("CSV quote character must not appear in the NULL specification")));
669 }
#define NIL
Definition: pg_list.h:65
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
int pg_char_to_encoding(const char *name)
Definition: encnames.c:550
#define castNode(_type_, nodeptr)
Definition: nodes.h:597
int errcode(int sqlerrcode)
Definition: elog.c:704
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:45
char * defGetString(DefElem *def)
Definition: define.c:49
#define lfirst_node(type, lc)
Definition: pg_list.h:172
int location
Definition: parsenodes.h:736
Node * arg
Definition: parsenodes.h:734
void * palloc0(Size size)
Definition: mcxt.c:981
#define ereport(elevel,...)
Definition: elog.h:155
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
int errmsg(const char *fmt,...)
Definition: elog.c:915
char * defname
Definition: parsenodes.h:733
Definition: pg_list.h:50