PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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.

Typedefs

typedef struct CopyStateDataCopyState
 
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, CopyState cstate, bool is_from, List *options)
 
CopyState BeginCopyFrom (ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
 
void EndCopyFrom (CopyState cstate)
 
bool NextCopyFrom (CopyState cstate, ExprContext *econtext, Datum *values, bool *nulls, Oid *tupleOid)
 
bool NextCopyFromRawFields (CopyState cstate, char ***fields, int *nfields)
 
void CopyFromErrorCallback (void *arg)
 
uint64 CopyFrom (CopyState cstate)
 
DestReceiverCreateCopyDestReceiver (void)
 

Typedef Documentation

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

Definition at line 24 of file copy.h.

Definition at line 23 of file copy.h.

Function Documentation

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

Definition at line 2964 of file copy.c.

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

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

2971 {
2972  CopyState cstate;
2973  bool pipe = (filename == NULL);
2974  TupleDesc tupDesc;
2975  AttrNumber num_phys_attrs,
2976  num_defaults;
2977  FmgrInfo *in_functions;
2978  Oid *typioparams;
2979  int attnum;
2980  Oid in_func_oid;
2981  int *defmap;
2982  ExprState **defexprs;
2983  MemoryContext oldcontext;
2984  bool volatile_defexprs;
2985 
2986  cstate = BeginCopy(pstate, true, rel, NULL, InvalidOid, attnamelist, options);
2987  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
2988 
2989  /* Initialize state variables */
2990  cstate->fe_eof = false;
2991  cstate->eol_type = EOL_UNKNOWN;
2992  cstate->cur_relname = RelationGetRelationName(cstate->rel);
2993  cstate->cur_lineno = 0;
2994  cstate->cur_attname = NULL;
2995  cstate->cur_attval = NULL;
2996 
2997  /* Set up variables to avoid per-attribute overhead. */
2998  initStringInfo(&cstate->attribute_buf);
2999  initStringInfo(&cstate->line_buf);
3000  cstate->line_buf_converted = false;
3001  cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
3002  cstate->raw_buf_index = cstate->raw_buf_len = 0;
3003 
3004  /* Assign range table, we'll need it in CopyFrom. */
3005  if (pstate)
3006  cstate->range_table = pstate->p_rtable;
3007 
3008  tupDesc = RelationGetDescr(cstate->rel);
3009  num_phys_attrs = tupDesc->natts;
3010  num_defaults = 0;
3011  volatile_defexprs = false;
3012 
3013  /*
3014  * Pick up the required catalog information for each attribute in the
3015  * relation, including the input function, the element type (to pass to
3016  * the input function), and info about defaults and constraints. (Which
3017  * input function we use depends on text/binary format choice.)
3018  */
3019  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
3020  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
3021  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
3022  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
3023 
3024  for (attnum = 1; attnum <= num_phys_attrs; attnum++)
3025  {
3026  Form_pg_attribute att = TupleDescAttr(tupDesc, attnum - 1);
3027 
3028  /* We don't need info for dropped attributes */
3029  if (att->attisdropped)
3030  continue;
3031 
3032  /* Fetch the input function and typioparam info */
3033  if (cstate->binary)
3034  getTypeBinaryInputInfo(att->atttypid,
3035  &in_func_oid, &typioparams[attnum - 1]);
3036  else
3037  getTypeInputInfo(att->atttypid,
3038  &in_func_oid, &typioparams[attnum - 1]);
3039  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
3040 
3041  /* Get default info if needed */
3042  if (!list_member_int(cstate->attnumlist, attnum))
3043  {
3044  /* attribute is NOT to be copied from input */
3045  /* use default value if one exists */
3046  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
3047  attnum);
3048 
3049  if (defexpr != NULL)
3050  {
3051  /* Run the expression through planner */
3052  defexpr = expression_planner(defexpr);
3053 
3054  /* Initialize executable expression in copycontext */
3055  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
3056  defmap[num_defaults] = attnum - 1;
3057  num_defaults++;
3058 
3059  /*
3060  * If a default expression looks at the table being loaded,
3061  * then it could give the wrong answer when using
3062  * multi-insert. Since database access can be dynamic this is
3063  * hard to test for exactly, so we use the much wider test of
3064  * whether the default expression is volatile. We allow for
3065  * the special case of when the default expression is the
3066  * nextval() of a sequence which in this specific case is
3067  * known to be safe for use with the multi-insert
3068  * optimization. Hence we use this special case function
3069  * checker rather than the standard check for
3070  * contain_volatile_functions().
3071  */
3072  if (!volatile_defexprs)
3073  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
3074  }
3075  }
3076  }
3077 
3078  /* We keep those variables in cstate. */
3079  cstate->in_functions = in_functions;
3080  cstate->typioparams = typioparams;
3081  cstate->defmap = defmap;
3082  cstate->defexprs = defexprs;
3083  cstate->volatile_defexprs = volatile_defexprs;
3084  cstate->num_defaults = num_defaults;
3085  cstate->is_program = is_program;
3086 
3087  if (data_source_cb)
3088  {
3089  cstate->copy_dest = COPY_CALLBACK;
3090  cstate->data_source_cb = data_source_cb;
3091  }
3092  else if (pipe)
3093  {
3094  Assert(!is_program); /* the grammar does not allow this */
3096  ReceiveCopyBegin(cstate);
3097  else
3098  cstate->copy_file = stdin;
3099  }
3100  else
3101  {
3102  cstate->filename = pstrdup(filename);
3103 
3104  if (cstate->is_program)
3105  {
3106  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
3107  if (cstate->copy_file == NULL)
3108  ereport(ERROR,
3110  errmsg("could not execute command \"%s\": %m",
3111  cstate->filename)));
3112  }
3113  else
3114  {
3115  struct stat st;
3116 
3117  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
3118  if (cstate->copy_file == NULL)
3119  {
3120  /* copy errno because ereport subfunctions might change it */
3121  int save_errno = errno;
3122 
3123  ereport(ERROR,
3125  errmsg("could not open file \"%s\" for reading: %m",
3126  cstate->filename),
3127  (save_errno == ENOENT || save_errno == EACCES) ?
3128  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
3129  "You may want a client-side facility such as psql's \\copy.") : 0));
3130  }
3131 
3132  if (fstat(fileno(cstate->copy_file), &st))
3133  ereport(ERROR,
3135  errmsg("could not stat file \"%s\": %m",
3136  cstate->filename)));
3137 
3138  if (S_ISDIR(st.st_mode))
3139  ereport(ERROR,
3140  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3141  errmsg("\"%s\" is a directory", cstate->filename)));
3142  }
3143  }
3144 
3145  if (!cstate->binary)
3146  {
3147  /* must rely on user to tell us... */
3148  cstate->file_has_oids = cstate->oids;
3149  }
3150  else
3151  {
3152  /* Read and verify binary header */
3153  char readSig[11];
3154  int32 tmp;
3155 
3156  /* Signature */
3157  if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
3158  memcmp(readSig, BinarySignature, 11) != 0)
3159  ereport(ERROR,
3160  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3161  errmsg("COPY file signature not recognized")));
3162  /* Flags field */
3163  if (!CopyGetInt32(cstate, &tmp))
3164  ereport(ERROR,
3165  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3166  errmsg("invalid COPY file header (missing flags)")));
3167  cstate->file_has_oids = (tmp & (1 << 16)) != 0;
3168  tmp &= ~(1 << 16);
3169  if ((tmp >> 16) != 0)
3170  ereport(ERROR,
3171  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3172  errmsg("unrecognized critical flags in COPY file header")));
3173  /* Header extension length */
3174  if (!CopyGetInt32(cstate, &tmp) ||
3175  tmp < 0)
3176  ereport(ERROR,
3177  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3178  errmsg("invalid COPY file header (missing length)")));
3179  /* Skip extension header, if present */
3180  while (tmp-- > 0)
3181  {
3182  if (CopyGetData(cstate, readSig, 1, 1) != 1)
3183  ereport(ERROR,
3184  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3185  errmsg("invalid COPY file header (wrong length)")));
3186  }
3187  }
3188 
3189  if (cstate->file_has_oids && cstate->binary)
3190  {
3192  &in_func_oid, &cstate->oid_typioparam);
3193  fmgr_info(in_func_oid, &cstate->oid_in_function);
3194  }
3195 
3196  /* create workspace for CopyReadAttributes results */
3197  if (!cstate->binary)
3198  {
3199  AttrNumber attr_count = list_length(cstate->attnumlist);
3200  int nfields = cstate->file_has_oids ? (attr_count + 1) : attr_count;
3201 
3202  cstate->max_fields = nfields;
3203  cstate->raw_fields = (char **) palloc(nfields * sizeof(char *));
3204  }
3205 
3206  MemoryContextSwitchTo(oldcontext);
3207 
3208  return cstate;
3209 }
Definition: fmgr.h:56
List * range_table
Definition: copy.c:166
static CopyState BeginCopy(ParseState *pstate, bool is_from, Relation rel, RawStmt *raw_query, Oid queryRelId, List *attnamelist, List *options)
Definition: copy.c:1374
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:1007
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:684
int errhint(const char *fmt,...)
Definition: elog.c:987
char ** raw_fields
Definition: copy.c:190
bool binary
Definition: copy.c:115
#define RelationGetDescr(relation)
Definition: rel.h:428
AttrNumber num_defaults
Definition: copy.c:157
FmgrInfo * in_functions
Definition: copy.c:161
List * attnumlist
Definition: copy.c:111
#define OIDOID
Definition: pg_type.h:328
char * filename
Definition: copy.c:112
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
bool file_has_oids
Definition: copy.c:158
char * pstrdup(const char *in)
Definition: mcxt.c:1077
static void ReceiveCopyBegin(CopyState cstate)
Definition: copy.c:382
Expr * expression_planner(Expr *expr)
Definition: planner.c:5939
StringInfoData line_buf
Definition: copy.c:199
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:509
int raw_buf_index
Definition: copy.c:212
int errcode(int sqlerrcode)
Definition: elog.c:575
bool fe_eof
Definition: copy.c:102
unsigned int Oid
Definition: postgres_ext.h:31
bool volatile_defexprs
Definition: copy.c:165
#define PG_BINARY_R
Definition: c.h:1041
int natts
Definition: tupdesc.h:73
bool line_buf_converted
Definition: copy.c:200
signed int int32
Definition: c.h:256
CopyDest copy_dest
Definition: copy.c:98
const char * cur_attname
Definition: copy.c:140
Relation rel
Definition: copy.c:109
MemoryContext copycontext
Definition: copy.c:146
copy_data_source_cb data_source_cb
Definition: copy.c:114
#define ERROR
Definition: elog.h:43
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:558
void fmgr_info(Oid functionId, FmgrInfo *finfo)
Definition: fmgr.c:127
bool list_member_int(const List *list, int datum)
Definition: list.c:485
char * raw_buf
Definition: copy.c:211
ExprState ** defexprs
Definition: copy.c:164
const char * cur_relname
Definition: copy.c:138
int errcode_for_file_access(void)
Definition: elog.c:598
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2094
FmgrInfo oid_in_function
Definition: copy.c:159
#define RelationGetRelationName(relation)
Definition: rel.h:436
static const char BinarySignature[11]
Definition: copy.c:290
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int raw_buf_len
Definition: copy.c:213
int max_fields
Definition: copy.c:189
FILE * OpenPipeStream(const char *command, const char *mode)
Definition: fd.c:2184
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition: lsyscache.c:2665
#define ereport(elevel, rest)
Definition: elog.h:122
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2599
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
Oid * typioparams
Definition: copy.c:162
bool is_program
Definition: copy.c:113
Node * build_column_default(Relation rel, int attrno)
#define RAW_BUF_SIZE
Definition: copy.c:210
#define InvalidOid
Definition: postgres_ext.h:36
EolType eol_type
Definition: copy.c:103
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
static int list_length(const List *l)
Definition: pg_list.h:89
static char * filename
Definition: pg_dumpall.c:90
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
FILE * copy_file
Definition: copy.c:99
int cur_lineno
Definition: copy.c:139
StringInfoData attribute_buf
Definition: copy.c:185
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execExpr.c:113
const char * cur_attval
Definition: copy.c:141
CommandDest whereToSendOutput
Definition: postgres.c:88
Oid oid_typioparam
Definition: copy.c:160
int16 AttrNumber
Definition: attnum.h:21
int * defmap
Definition: copy.c:163
List * p_rtable
Definition: parse_node.h:172
bool oids
Definition: copy.c:116
uint64 CopyFrom ( CopyState  cstate)

Definition at line 2273 of file copy.c.

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

Referenced by copy_table(), and DoCopy().

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

Definition at line 2168 of file copy.c.

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

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

2169 {
2170  CopyState cstate = (CopyState) arg;
2171 
2172  if (cstate->binary)
2173  {
2174  /* can't usefully display the data */
2175  if (cstate->cur_attname)
2176  errcontext("COPY %s, line %d, column %s",
2177  cstate->cur_relname, cstate->cur_lineno,
2178  cstate->cur_attname);
2179  else
2180  errcontext("COPY %s, line %d",
2181  cstate->cur_relname, cstate->cur_lineno);
2182  }
2183  else
2184  {
2185  if (cstate->cur_attname && cstate->cur_attval)
2186  {
2187  /* error is relevant to a particular column */
2188  char *attval;
2189 
2190  attval = limit_printout_length(cstate->cur_attval);
2191  errcontext("COPY %s, line %d, column %s: \"%s\"",
2192  cstate->cur_relname, cstate->cur_lineno,
2193  cstate->cur_attname, attval);
2194  pfree(attval);
2195  }
2196  else if (cstate->cur_attname)
2197  {
2198  /* error is relevant to a particular column, value is NULL */
2199  errcontext("COPY %s, line %d, column %s: null input",
2200  cstate->cur_relname, cstate->cur_lineno,
2201  cstate->cur_attname);
2202  }
2203  else
2204  {
2205  /*
2206  * Error is relevant to a particular line.
2207  *
2208  * If line_buf still contains the correct line, and it's already
2209  * transcoded, print it. If it's still in a foreign encoding, it's
2210  * quite likely that the error is precisely a failure to do
2211  * encoding conversion (ie, bad data). We dare not try to convert
2212  * it, and at present there's no way to regurgitate it without
2213  * conversion. So we have to punt and just report the line number.
2214  */
2215  if (cstate->line_buf_valid &&
2216  (cstate->line_buf_converted || !cstate->need_transcoding))
2217  {
2218  char *lineval;
2219 
2220  lineval = limit_printout_length(cstate->line_buf.data);
2221  errcontext("COPY %s, line %d: \"%s\"",
2222  cstate->cur_relname, cstate->cur_lineno, lineval);
2223  pfree(lineval);
2224  }
2225  else
2226  {
2227  errcontext("COPY %s, line %d",
2228  cstate->cur_relname, cstate->cur_lineno);
2229  }
2230  }
2231  }
2232 }
bool binary
Definition: copy.c:115
bool need_transcoding
Definition: copy.c:105
StringInfoData line_buf
Definition: copy.c:199
bool line_buf_valid
Definition: copy.c:201
bool line_buf_converted
Definition: copy.c:200
const char * cur_attname
Definition: copy.c:140
void pfree(void *pointer)
Definition: mcxt.c:950
static char * limit_printout_length(const char *str)
Definition: copy.c:2244
const char * cur_relname
Definition: copy.c:138
#define errcontext
Definition: elog.h:164
struct CopyStateData * CopyState
Definition: copy.h:23
void * arg
int cur_lineno
Definition: copy.c:139
const char * cur_attval
Definition: copy.c:141
DestReceiver* CreateCopyDestReceiver ( void  )

Definition at line 4827 of file copy.c.

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

Referenced by CreateDestReceiver().

4828 {
4829  DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
4830 
4831  self->pub.receiveSlot = copy_dest_receive;
4832  self->pub.rStartup = copy_dest_startup;
4833  self->pub.rShutdown = copy_dest_shutdown;
4834  self->pub.rDestroy = copy_dest_destroy;
4835  self->pub.mydest = DestCopyOut;
4836 
4837  self->cstate = NULL; /* will be set later */
4838  self->processed = 0;
4839 
4840  return (DestReceiver *) self;
4841 }
Definition: copy.c:217
static void copy_dest_destroy(DestReceiver *self)
Definition: copy.c:4818
static void copy_dest_shutdown(DestReceiver *self)
Definition: copy.c:4809
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copy.c:4781
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copy.c:4790
#define NULL
Definition: c.h:229
void * palloc(Size size)
Definition: mcxt.c:849
void DoCopy ( ParseState state,
const CopyStmt stmt,
int  stmt_location,
int  stmt_len,
uint64 *  processed 
)

Definition at line 783 of file copy.c.

References AccessShareLock, ACL_INSERT, ACL_SELECT, addRangeTableEntryForRelation(), Assert, CopyStmt::attlist, BeginCopyFrom(), BeginCopyTo(), bms_add_member(), check_enable_rls(), CopyFrom(), CopyGetAttnums(), cur, DoCopyTo(), EndCopyFrom(), EndCopyTo(), ereport, errcode(), errhint(), errmsg(), ERROR, ExecCheckRTPerms(), ColumnRef::fields, CopyStmt::filename, FirstLowInvalidHeapAttributeNumber, SelectStmt::fromClause, get_namespace_name(), heap_close, heap_openrv(), ResTarget::indirection, RangeTblEntry::insertedCols, InvalidOid, CopyStmt::is_from, CopyStmt::is_program, lappend(), lfirst, lfirst_int, list_make1, ColumnRef::location, ResTarget::location, makeNode, makeRangeVar(), ResTarget::name, NIL, NoLock, NULL, CopyStmt::options, ParseState::p_rtable, PreventCommandIfParallelMode(), 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, superuser(), SelectStmt::targetList, ResTarget::val, and XactReadOnly.

Referenced by standard_ProcessUtility().

786 {
787  CopyState cstate;
788  bool is_from = stmt->is_from;
789  bool pipe = (stmt->filename == NULL);
790  Relation rel;
791  Oid relid;
792  RawStmt *query = NULL;
793 
794  /* Disallow COPY to/from file or program except to superusers. */
795  if (!pipe && !superuser())
796  {
797  if (stmt->is_program)
798  ereport(ERROR,
799  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
800  errmsg("must be superuser to COPY to or from an external program"),
801  errhint("Anyone can COPY to stdout or from stdin. "
802  "psql's \\copy command also works for anyone.")));
803  else
804  ereport(ERROR,
805  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
806  errmsg("must be superuser to COPY to or from a file"),
807  errhint("Anyone can COPY to stdout or from stdin. "
808  "psql's \\copy command also works for anyone.")));
809  }
810 
811  if (stmt->relation)
812  {
813  TupleDesc tupDesc;
814  List *attnums;
815  ListCell *cur;
816  RangeTblEntry *rte;
817 
818  Assert(!stmt->query);
819 
820  /* Open and lock the relation, using the appropriate lock type. */
821  rel = heap_openrv(stmt->relation,
822  (is_from ? RowExclusiveLock : AccessShareLock));
823 
824  relid = RelationGetRelid(rel);
825 
826  rte = addRangeTableEntryForRelation(pstate, rel, NULL, false, false);
827  rte->requiredPerms = (is_from ? ACL_INSERT : ACL_SELECT);
828 
829  tupDesc = RelationGetDescr(rel);
830  attnums = CopyGetAttnums(tupDesc, rel, stmt->attlist);
831  foreach(cur, attnums)
832  {
833  int attno = lfirst_int(cur) -
835 
836  if (is_from)
837  rte->insertedCols = bms_add_member(rte->insertedCols, attno);
838  else
839  rte->selectedCols = bms_add_member(rte->selectedCols, attno);
840  }
841  ExecCheckRTPerms(pstate->p_rtable, true);
842 
843  /*
844  * Permission check for row security policies.
845  *
846  * check_enable_rls will ereport(ERROR) if the user has requested
847  * something invalid and will otherwise indicate if we should enable
848  * RLS (returns RLS_ENABLED) or not for this COPY statement.
849  *
850  * If the relation has a row security policy and we are to apply it
851  * then perform a "query" copy and allow the normal query processing
852  * to handle the policies.
853  *
854  * If RLS is not enabled for this, then just fall through to the
855  * normal non-filtering relation handling.
856  */
857  if (check_enable_rls(rte->relid, InvalidOid, false) == RLS_ENABLED)
858  {
860  ColumnRef *cr;
861  ResTarget *target;
862  RangeVar *from;
863  List *targetList = NIL;
864 
865  if (is_from)
866  ereport(ERROR,
867  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
868  errmsg("COPY FROM not supported with row-level security"),
869  errhint("Use INSERT statements instead.")));
870 
871  /*
872  * Build target list
873  *
874  * If no columns are specified in the attribute list of the COPY
875  * command, then the target list is 'all' columns. Therefore, '*'
876  * should be used as the target list for the resulting SELECT
877  * statement.
878  *
879  * In the case that columns are specified in the attribute list,
880  * create a ColumnRef and ResTarget for each column and add them
881  * to the target list for the resulting SELECT statement.
882  */
883  if (!stmt->attlist)
884  {
885  cr = makeNode(ColumnRef);
887  cr->location = -1;
888 
889  target = makeNode(ResTarget);
890  target->name = NULL;
891  target->indirection = NIL;
892  target->val = (Node *) cr;
893  target->location = -1;
894 
895  targetList = list_make1(target);
896  }
897  else
898  {
899  ListCell *lc;
900 
901  foreach(lc, stmt->attlist)
902  {
903  /*
904  * Build the ColumnRef for each column. The ColumnRef
905  * 'fields' property is a String 'Value' node (see
906  * nodes/value.h) that corresponds to the column name
907  * respectively.
908  */
909  cr = makeNode(ColumnRef);
910  cr->fields = list_make1(lfirst(lc));
911  cr->location = -1;
912 
913  /* Build the ResTarget and add the ColumnRef to it. */
914  target = makeNode(ResTarget);
915  target->name = NULL;
916  target->indirection = NIL;
917  target->val = (Node *) cr;
918  target->location = -1;
919 
920  /* Add each column to the SELECT statement's target list */
921  targetList = lappend(targetList, target);
922  }
923  }
924 
925  /*
926  * Build RangeVar for from clause, fully qualified based on the
927  * relation which we have opened and locked.
928  */
931  -1);
932 
933  /* Build query */
934  select = makeNode(SelectStmt);
935  select->targetList = targetList;
936  select->fromClause = list_make1(from);
937 
938  query = makeNode(RawStmt);
939  query->stmt = (Node *) select;
940  query->stmt_location = stmt_location;
941  query->stmt_len = stmt_len;
942 
943  /*
944  * Close the relation for now, but keep the lock on it to prevent
945  * changes between now and when we start the query-based COPY.
946  *
947  * We'll reopen it later as part of the query-based COPY.
948  */
949  heap_close(rel, NoLock);
950  rel = NULL;
951  }
952  }
953  else
954  {
955  Assert(stmt->query);
956 
957  query = makeNode(RawStmt);
958  query->stmt = stmt->query;
959  query->stmt_location = stmt_location;
960  query->stmt_len = stmt_len;
961 
962  relid = InvalidOid;
963  rel = NULL;
964  }
965 
966  if (is_from)
967  {
968  Assert(rel);
969 
970  /* check read-only transaction and parallel mode */
971  if (XactReadOnly && !rel->rd_islocaltemp)
972  PreventCommandIfReadOnly("COPY FROM");
973  PreventCommandIfParallelMode("COPY FROM");
974 
975  cstate = BeginCopyFrom(pstate, rel, stmt->filename, stmt->is_program,
976  NULL, stmt->attlist, stmt->options);
977  *processed = CopyFrom(cstate); /* copy from file to database */
978  EndCopyFrom(cstate);
979  }
980  else
981  {
982  cstate = BeginCopyTo(pstate, rel, query, relid,
983  stmt->filename, stmt->is_program,
984  stmt->attlist, stmt->options);
985  *processed = DoCopyTo(cstate); /* copy from database to file */
986  EndCopyTo(cstate);
987  }
988 
989  /*
990  * Close the relation. If reading, we can release the AccessShareLock we
991  * got; if writing, we should hold the lock until end of transaction to
992  * ensure that updates will be committed before lock is released.
993  */
994  if (rel != NULL)
995  heap_close(rel, (is_from ? NoLock : AccessShareLock));
996 }
List * indirection
Definition: parsenodes.h:440
#define NIL
Definition: pg_list.h:69
Node * val
Definition: parsenodes.h:441
int errhint(const char *fmt,...)
Definition: elog.c:987
void PreventCommandIfParallelMode(const char *cmdname)
Definition: utility.c:254
List * attlist
Definition: parsenodes.h:1937
List * fromClause
Definition: parsenodes.h:1509
#define RelationGetDescr(relation)
Definition: rel.h:428
char * name
Definition: parsenodes.h:439
CopyState BeginCopyFrom(ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copy.c:2964
char * pstrdup(const char *in)
Definition: mcxt.c:1077
bool rd_islocaltemp
Definition: rel.h:90
#define AccessShareLock
Definition: lockdefs.h:36
Definition: nodes.h:509
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
bool superuser(void)
Definition: superuser.c:47
uint64 CopyFrom(CopyState cstate)
Definition: copy.c:2273
#define select(n, r, w, e, timeout)
Definition: win32.h:374
#define FirstLowInvalidHeapAttributeNumber
Definition: sysattr.h:28
AclMode requiredPerms
Definition: parsenodes.h:1047
#define heap_close(r, l)
Definition: heapam.h:97
unsigned int Oid
Definition: postgres_ext.h:31
bool is_program
Definition: parsenodes.h:1940
int location
Definition: parsenodes.h:235
int location
Definition: parsenodes.h:442
#define list_make1(x1)
Definition: pg_list.h:139
Bitmapset * selectedCols
Definition: parsenodes.h:1049
static CopyState BeginCopyTo(ParseState *pstate, Relation rel, RawStmt *query, Oid queryRelId, const char *filename, bool is_program, List *attnamelist, List *options)
Definition: copy.c:1739
#define ERROR
Definition: elog.h:43
#define lfirst_int(lc)
Definition: pg_list.h:107
RangeVar * relation
Definition: parsenodes.h:1934
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3033
Node * stmt
Definition: parsenodes.h:1419
#define NoLock
Definition: lockdefs.h:34
List * targetList
Definition: parsenodes.h:1508
static uint64 DoCopyTo(CopyState cstate)
Definition: copy.c:1868
#define RowExclusiveLock
Definition: lockdefs.h:38
List * options
Definition: parsenodes.h:1942
#define RelationGetRelationName(relation)
Definition: rel.h:436
#define ereport(elevel, rest)
Definition: elog.h:122
List * lappend(List *list, void *datum)
Definition: list.c:128
static List * CopyGetAttnums(TupleDesc tupDesc, Relation rel, List *attnamelist)
Definition: copy.c:4708
#define ACL_SELECT
Definition: parsenodes.h:73
int stmt_len
Definition: parsenodes.h:1421
int stmt_location
Definition: parsenodes.h:1420
Relation heap_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1318
#define InvalidOid
Definition: postgres_ext.h:36
bool XactReadOnly
Definition: xact.c:77
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:53
void EndCopyFrom(CopyState cstate)
Definition: copy.c:3516
#define makeNode(_type_)
Definition: nodes.h:557
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
#define lfirst(lc)
Definition: pg_list.h:106
#define ACL_INSERT
Definition: parsenodes.h:72
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, Alias *alias, bool inh, bool inFromCl)
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:698
void PreventCommandIfReadOnly(const char *cmdname)
Definition: utility.c:236
Node * query
Definition: parsenodes.h:1935
bool is_from
Definition: parsenodes.h:1939
int errmsg(const char *fmt,...)
Definition: elog.c:797
Bitmapset * insertedCols
Definition: parsenodes.h:1050
bool ExecCheckRTPerms(List *rangeTable, bool ereport_on_violation)
Definition: execMain.c:570
char * filename
Definition: parsenodes.h:1941
static void EndCopyTo(CopyState cstate)
Definition: copy.c:1903
Definition: pg_list.h:45
#define RelationGetRelid(relation)
Definition: rel.h:416
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:419
List * fields
Definition: parsenodes.h:234
#define RelationGetNamespace(relation)
Definition: rel.h:443
void EndCopyFrom ( CopyState  cstate)

Definition at line 3516 of file copy.c.

References EndCopy().

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

3517 {
3518  /* No COPY FROM related resources except memory. */
3519 
3520  EndCopy(cstate);
3521 }
static void EndCopy(CopyState cstate)
Definition: copy.c:1716
bool NextCopyFrom ( CopyState  cstate,
ExprContext econtext,
Datum values,
bool nulls,
Oid tupleOid 
)

Definition at line 3275 of file copy.c.

References Assert, CopyStateData::attnumlist, CopyStateData::binary, CopyStateData::convert_select_flags, CopyStateData::copy_dest, COPY_OLD_FE, CopyGetData(), CopyGetInt16(), CopyReadBinaryAttribute(), CStringGetDatum, CopyStateData::csv_mode, cur, CopyStateData::cur_attname, CopyStateData::cur_attval, CopyStateData::cur_lineno, CurrentMemoryContext, DatumGetObjectId, CopyStateData::defexprs, CopyStateData::defmap, DirectFunctionCall1, ExprContext::ecxt_per_tuple_memory, ereport, errcode(), errmsg(), ERROR, ExecEvalExpr(), CopyStateData::file_has_oids, CopyStateData::force_notnull_flags, CopyStateData::force_null_flags, i, CopyStateData::in_functions, InputFunctionCall(), InvalidOid, lfirst_int, list_length(), MemSet, NameStr, tupleDesc::natts, NextCopyFromRawFields(), NULL, CopyStateData::null_print, CopyStateData::num_defaults, CopyStateData::oid_in_function, CopyStateData::oid_typioparam, oidin(), CopyStateData::oids, CopyStateData::rel, RelationGetDescr, TupleDescAttr, and CopyStateData::typioparams.

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

3277 {
3278  TupleDesc tupDesc;
3279  AttrNumber num_phys_attrs,
3280  attr_count,
3281  num_defaults = cstate->num_defaults;
3282  FmgrInfo *in_functions = cstate->in_functions;
3283  Oid *typioparams = cstate->typioparams;
3284  int i;
3285  int nfields;
3286  bool isnull;
3287  bool file_has_oids = cstate->file_has_oids;
3288  int *defmap = cstate->defmap;
3289  ExprState **defexprs = cstate->defexprs;
3290 
3291  tupDesc = RelationGetDescr(cstate->rel);
3292  num_phys_attrs = tupDesc->natts;
3293  attr_count = list_length(cstate->attnumlist);
3294  nfields = file_has_oids ? (attr_count + 1) : attr_count;
3295 
3296  /* Initialize all values for row to NULL */
3297  MemSet(values, 0, num_phys_attrs * sizeof(Datum));
3298  MemSet(nulls, true, num_phys_attrs * sizeof(bool));
3299 
3300  if (!cstate->binary)
3301  {
3302  char **field_strings;
3303  ListCell *cur;
3304  int fldct;
3305  int fieldno;
3306  char *string;
3307 
3308  /* read raw fields in the next line */
3309  if (!NextCopyFromRawFields(cstate, &field_strings, &fldct))
3310  return false;
3311 
3312  /* check for overflowing fields */
3313  if (nfields > 0 && fldct > nfields)
3314  ereport(ERROR,
3315  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3316  errmsg("extra data after last expected column")));
3317 
3318  fieldno = 0;
3319 
3320  /* Read the OID field if present */
3321  if (file_has_oids)
3322  {
3323  if (fieldno >= fldct)
3324  ereport(ERROR,
3325  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3326  errmsg("missing data for OID column")));
3327  string = field_strings[fieldno++];
3328 
3329  if (string == NULL)
3330  ereport(ERROR,
3331  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3332  errmsg("null OID in COPY data")));
3333  else if (cstate->oids && tupleOid != NULL)
3334  {
3335  cstate->cur_attname = "oid";
3336  cstate->cur_attval = string;
3338  CStringGetDatum(string)));
3339  if (*tupleOid == InvalidOid)
3340  ereport(ERROR,
3341  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3342  errmsg("invalid OID in COPY data")));
3343  cstate->cur_attname = NULL;
3344  cstate->cur_attval = NULL;
3345  }
3346  }
3347 
3348  /* Loop to read the user attributes on the line. */
3349  foreach(cur, cstate->attnumlist)
3350  {
3351  int attnum = lfirst_int(cur);
3352  int m = attnum - 1;
3353  Form_pg_attribute att = TupleDescAttr(tupDesc, m);
3354 
3355  if (fieldno >= fldct)
3356  ereport(ERROR,
3357  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3358  errmsg("missing data for column \"%s\"",
3359  NameStr(att->attname))));
3360  string = field_strings[fieldno++];
3361 
3362  if (cstate->convert_select_flags &&
3363  !cstate->convert_select_flags[m])
3364  {
3365  /* ignore input field, leaving column as NULL */
3366  continue;
3367  }
3368 
3369  if (cstate->csv_mode)
3370  {
3371  if (string == NULL &&
3372  cstate->force_notnull_flags[m])
3373  {
3374  /*
3375  * FORCE_NOT_NULL option is set and column is NULL -
3376  * convert it to the NULL string.
3377  */
3378  string = cstate->null_print;
3379  }
3380  else if (string != NULL && cstate->force_null_flags[m]
3381  && strcmp(string, cstate->null_print) == 0)
3382  {
3383  /*
3384  * FORCE_NULL option is set and column matches the NULL
3385  * string. It must have been quoted, or otherwise the
3386  * string would already have been set to NULL. Convert it
3387  * to NULL as specified.
3388  */
3389  string = NULL;
3390  }
3391  }
3392 
3393  cstate->cur_attname = NameStr(att->attname);
3394  cstate->cur_attval = string;
3395  values[m] = InputFunctionCall(&in_functions[m],
3396  string,
3397  typioparams[m],
3398  att->atttypmod);
3399  if (string != NULL)
3400  nulls[m] = false;
3401  cstate->cur_attname = NULL;
3402  cstate->cur_attval = NULL;
3403  }
3404 
3405  Assert(fieldno == nfields);
3406  }
3407  else
3408  {
3409  /* binary */
3410  int16 fld_count;
3411  ListCell *cur;
3412 
3413  cstate->cur_lineno++;
3414 
3415  if (!CopyGetInt16(cstate, &fld_count))
3416  {
3417  /* EOF detected (end of file, or protocol-level EOF) */
3418  return false;
3419  }
3420 
3421  if (fld_count == -1)
3422  {
3423  /*
3424  * Received EOF marker. In a V3-protocol copy, wait for the
3425  * protocol-level EOF, and complain if it doesn't come
3426  * immediately. This ensures that we correctly handle CopyFail,
3427  * if client chooses to send that now.
3428  *
3429  * Note that we MUST NOT try to read more data in an old-protocol
3430  * copy, since there is no protocol-level EOF marker then. We
3431  * could go either way for copy from file, but choose to throw
3432  * error if there's data after the EOF marker, for consistency
3433  * with the new-protocol case.
3434  */
3435  char dummy;
3436 
3437  if (cstate->copy_dest != COPY_OLD_FE &&
3438  CopyGetData(cstate, &dummy, 1, 1) > 0)
3439  ereport(ERROR,
3440  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3441  errmsg("received copy data after EOF marker")));
3442  return false;
3443  }
3444 
3445  if (fld_count != attr_count)
3446  ereport(ERROR,
3447  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3448  errmsg("row field count is %d, expected %d",
3449  (int) fld_count, attr_count)));
3450 
3451  if (file_has_oids)
3452  {
3453  Oid loaded_oid;
3454 
3455  cstate->cur_attname = "oid";
3456  loaded_oid =
3458  0,
3459  &cstate->oid_in_function,
3460  cstate->oid_typioparam,
3461  -1,
3462  &isnull));
3463  if (isnull || loaded_oid == InvalidOid)
3464  ereport(ERROR,
3465  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3466  errmsg("invalid OID in COPY data")));
3467  cstate->cur_attname = NULL;
3468  if (cstate->oids && tupleOid != NULL)
3469  *tupleOid = loaded_oid;
3470  }
3471 
3472  i = 0;
3473  foreach(cur, cstate->attnumlist)
3474  {
3475  int attnum = lfirst_int(cur);
3476  int m = attnum - 1;
3477  Form_pg_attribute att = TupleDescAttr(tupDesc, m);
3478 
3479  cstate->cur_attname = NameStr(att->attname);
3480  i++;
3481  values[m] = CopyReadBinaryAttribute(cstate,
3482  i,
3483  &in_functions[m],
3484  typioparams[m],
3485  att->atttypmod,
3486  &nulls[m]);
3487  cstate->cur_attname = NULL;
3488  }
3489  }
3490 
3491  /*
3492  * Now compute and insert any defaults available for the columns not
3493  * provided by the input data. Anything not processed here or above will
3494  * remain NULL.
3495  */
3496  for (i = 0; i < num_defaults; i++)
3497  {
3498  /*
3499  * The caller must supply econtext and have switched into the
3500  * per-tuple memory context in it.
3501  */
3502  Assert(econtext != NULL);
3504 
3505  values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
3506  &nulls[defmap[i]]);
3507  }
3508 
3509  return true;
3510 }
signed short int16
Definition: c.h:255
bool NextCopyFromRawFields(CopyState cstate, char ***fields, int *nfields)
Definition: copy.c:3223
static Datum CopyReadBinaryAttribute(CopyState cstate, int column_no, FmgrInfo *flinfo, Oid typioparam, int32 typmod, bool *isnull)
Definition: copy.c:4405
Definition: fmgr.h:56
bool csv_mode
Definition: copy.c:118
bool binary
Definition: copy.c:115
#define RelationGetDescr(relation)
Definition: rel.h:428
FmgrInfo * in_functions
Definition: copy.c:161
AttrNumber num_defaults
Definition: copy.c:157
List * attnumlist
Definition: copy.c:111
#define TupleDescAttr(tupdesc, i)
Definition: tupdesc.h:84
bool file_has_oids
Definition: copy.c:158
#define DatumGetObjectId(X)
Definition: postgres.h:506
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:203
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:858
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:584
unsigned int Oid
Definition: postgres_ext.h:31
bool * force_null_flags
Definition: copy.c:132
int natts
Definition: tupdesc.h:73
bool * convert_select_flags
Definition: copy.c:135
CopyDest copy_dest
Definition: copy.c:98
char * null_print
Definition: copy.c:120
const char * cur_attname
Definition: copy.c:140
Relation rel
Definition: copy.c:109
#define ERROR
Definition: elog.h:43
static int CopyGetData(CopyState cstate, void *databuf, int minread, int maxread)
Definition: copy.c:558
#define lfirst_int(lc)
Definition: pg_list.h:107
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:285
ExprState ** defexprs
Definition: copy.c:164
#define CStringGetDatum(X)
Definition: postgres.h:584
char string[11]
Definition: preproc-type.c:46
FmgrInfo oid_in_function
Definition: copy.c:159
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
#define ereport(elevel, rest)
Definition: elog.h:122
Oid * typioparams
Definition: copy.c:162
uintptr_t Datum
Definition: postgres.h:372
Datum InputFunctionCall(FmgrInfo *flinfo, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:1623
#define InvalidOid
Definition: postgres_ext.h:36
bool * force_notnull_flags
Definition: copy.c:130
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:676
static int list_length(const List *l)
Definition: pg_list.h:89
static Datum values[MAXATTR]
Definition: bootstrap.c:163
int errmsg(const char *fmt,...)
Definition: elog.c:797
int i
#define NameStr(name)
Definition: c.h:499
static bool CopyGetInt16(CopyState cstate, int16 *val)
Definition: copy.c:713
int cur_lineno
Definition: copy.c:139
Datum oidin(PG_FUNCTION_ARGS)
Definition: oid.c:117
const char * cur_attval
Definition: copy.c:141
Oid oid_typioparam
Definition: copy.c:160
int16 AttrNumber
Definition: attnum.h:21
int * defmap
Definition: copy.c:163
bool oids
Definition: copy.c:116
bool NextCopyFromRawFields ( CopyState  cstate,
char ***  fields,
int *  nfields 
)

Definition at line 3223 of file copy.c.

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

Referenced by NextCopyFrom().

3224 {
3225  int fldct;
3226  bool done;
3227 
3228  /* only available for text or csv input */
3229  Assert(!cstate->binary);
3230 
3231  /* on input just throw the header line away */
3232  if (cstate->cur_lineno == 0 && cstate->header_line)
3233  {
3234  cstate->cur_lineno++;
3235  if (CopyReadLine(cstate))
3236  return false; /* done */
3237  }
3238 
3239  cstate->cur_lineno++;
3240 
3241  /* Actually read the line into memory here */
3242  done = CopyReadLine(cstate);
3243 
3244  /*
3245  * EOF at start of line means we're done. If we see EOF after some
3246  * characters, we act as though it was newline followed by EOF, ie,
3247  * process the line and then exit loop on next iteration.
3248  */
3249  if (done && cstate->line_buf.len == 0)
3250  return false;
3251 
3252  /* Parse the line into de-escaped field values */
3253  if (cstate->csv_mode)
3254  fldct = CopyReadAttributesCSV(cstate);
3255  else
3256  fldct = CopyReadAttributesText(cstate);
3257 
3258  *fields = cstate->raw_fields;
3259  *nfields = fldct;
3260  return true;
3261 }
bool csv_mode
Definition: copy.c:118
char ** raw_fields
Definition: copy.c:190
bool binary
Definition: copy.c:115
StringInfoData line_buf
Definition: copy.c:199
static int CopyReadAttributesCSV(CopyState cstate)
Definition: copy.c:4236
bool header_line
Definition: copy.c:119
#define Assert(condition)
Definition: c.h:676
static bool CopyReadLine(CopyState cstate)
Definition: copy.c:3532
int cur_lineno
Definition: copy.c:139
static int CopyReadAttributesText(CopyState cstate)
Definition: copy.c:4008
void ProcessCopyOptions ( ParseState pstate,
CopyState  cstate,
bool  is_from,
List options 
)

Definition at line 1016 of file copy.c.

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

Referenced by BeginCopy(), and file_fdw_validator().

1020 {
1021  bool format_specified = false;
1022  ListCell *option;
1023 
1024  /* Support external use for option sanity checking */
1025  if (cstate == NULL)
1026  cstate = (CopyStateData *) palloc0(sizeof(CopyStateData));
1027 
1028  cstate->file_encoding = -1;
1029 
1030  /* Extract options from the statement node tree */
1031  foreach(option, options)
1032  {
1033  DefElem *defel = lfirst_node(DefElem, option);
1034 
1035  if (strcmp(defel->defname, "format") == 0)
1036  {
1037  char *fmt = defGetString(defel);
1038 
1039  if (format_specified)
1040  ereport(ERROR,
1041  (errcode(ERRCODE_SYNTAX_ERROR),
1042  errmsg("conflicting or redundant options"),
1043  parser_errposition(pstate, defel->location)));
1044  format_specified = true;
1045  if (strcmp(fmt, "text") == 0)
1046  /* default format */ ;
1047  else if (strcmp(fmt, "csv") == 0)
1048  cstate->csv_mode = true;
1049  else if (strcmp(fmt, "binary") == 0)
1050  cstate->binary = true;
1051  else
1052  ereport(ERROR,
1053  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1054  errmsg("COPY format \"%s\" not recognized", fmt),
1055  parser_errposition(pstate, defel->location)));
1056  }
1057  else if (strcmp(defel->defname, "oids") == 0)
1058  {
1059  if (cstate->oids)
1060  ereport(ERROR,
1061  (errcode(ERRCODE_SYNTAX_ERROR),
1062  errmsg("conflicting or redundant options"),
1063  parser_errposition(pstate, defel->location)));
1064  cstate->oids = defGetBoolean(defel);
1065  }
1066  else if (strcmp(defel->defname, "freeze") == 0)
1067  {
1068  if (cstate->freeze)
1069  ereport(ERROR,
1070  (errcode(ERRCODE_SYNTAX_ERROR),
1071  errmsg("conflicting or redundant options"),
1072  parser_errposition(pstate, defel->location)));
1073  cstate->freeze = defGetBoolean(defel);
1074  }
1075  else if (strcmp(defel->defname, "delimiter") == 0)
1076  {
1077  if (cstate->delim)
1078  ereport(ERROR,
1079  (errcode(ERRCODE_SYNTAX_ERROR),
1080  errmsg("conflicting or redundant options"),
1081  parser_errposition(pstate, defel->location)));
1082  cstate->delim = defGetString(defel);
1083  }
1084  else if (strcmp(defel->defname, "null") == 0)
1085  {
1086  if (cstate->null_print)
1087  ereport(ERROR,
1088  (errcode(ERRCODE_SYNTAX_ERROR),
1089  errmsg("conflicting or redundant options"),
1090  parser_errposition(pstate, defel->location)));
1091  cstate->null_print = defGetString(defel);
1092  }
1093  else if (strcmp(defel->defname, "header") == 0)
1094  {
1095  if (cstate->header_line)
1096  ereport(ERROR,
1097  (errcode(ERRCODE_SYNTAX_ERROR),
1098  errmsg("conflicting or redundant options"),
1099  parser_errposition(pstate, defel->location)));
1100  cstate->header_line = defGetBoolean(defel);
1101  }
1102  else if (strcmp(defel->defname, "quote") == 0)
1103  {
1104  if (cstate->quote)
1105  ereport(ERROR,
1106  (errcode(ERRCODE_SYNTAX_ERROR),
1107  errmsg("conflicting or redundant options"),
1108  parser_errposition(pstate, defel->location)));
1109  cstate->quote = defGetString(defel);
1110  }
1111  else if (strcmp(defel->defname, "escape") == 0)
1112  {
1113  if (cstate->escape)
1114  ereport(ERROR,
1115  (errcode(ERRCODE_SYNTAX_ERROR),
1116  errmsg("conflicting or redundant options"),
1117  parser_errposition(pstate, defel->location)));
1118  cstate->escape = defGetString(defel);
1119  }
1120  else if (strcmp(defel->defname, "force_quote") == 0)
1121  {
1122  if (cstate->force_quote || cstate->force_quote_all)
1123  ereport(ERROR,
1124  (errcode(ERRCODE_SYNTAX_ERROR),
1125  errmsg("conflicting or redundant options"),
1126  parser_errposition(pstate, defel->location)));
1127  if (defel->arg && IsA(defel->arg, A_Star))
1128  cstate->force_quote_all = true;
1129  else if (defel->arg && IsA(defel->arg, List))
1130  cstate->force_quote = castNode(List, defel->arg);
1131  else
1132  ereport(ERROR,
1133  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1134  errmsg("argument to option \"%s\" must be a list of column names",
1135  defel->defname),
1136  parser_errposition(pstate, defel->location)));
1137  }
1138  else if (strcmp(defel->defname, "force_not_null") == 0)
1139  {
1140  if (cstate->force_notnull)
1141  ereport(ERROR,
1142  (errcode(ERRCODE_SYNTAX_ERROR),
1143  errmsg("conflicting or redundant options"),
1144  parser_errposition(pstate, defel->location)));
1145  if (defel->arg && IsA(defel->arg, List))
1146  cstate->force_notnull = castNode(List, defel->arg);
1147  else
1148  ereport(ERROR,
1149  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1150  errmsg("argument to option \"%s\" must be a list of column names",
1151  defel->defname),
1152  parser_errposition(pstate, defel->location)));
1153  }
1154  else if (strcmp(defel->defname, "force_null") == 0)
1155  {
1156  if (cstate->force_null)
1157  ereport(ERROR,
1158  (errcode(ERRCODE_SYNTAX_ERROR),
1159  errmsg("conflicting or redundant options")));
1160  if (defel->arg && IsA(defel->arg, List))
1161  cstate->force_null = castNode(List, defel->arg);
1162  else
1163  ereport(ERROR,
1164  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1165  errmsg("argument to option \"%s\" must be a list of column names",
1166  defel->defname),
1167  parser_errposition(pstate, defel->location)));
1168  }
1169  else if (strcmp(defel->defname, "convert_selectively") == 0)
1170  {
1171  /*
1172  * Undocumented, not-accessible-from-SQL option: convert only the
1173  * named columns to binary form, storing the rest as NULLs. It's
1174  * allowed for the column list to be NIL.
1175  */
1176  if (cstate->convert_selectively)
1177  ereport(ERROR,
1178  (errcode(ERRCODE_SYNTAX_ERROR),
1179  errmsg("conflicting or redundant options"),
1180  parser_errposition(pstate, defel->location)));
1181  cstate->convert_selectively = true;
1182  if (defel->arg == NULL || IsA(defel->arg, List))
1183  cstate->convert_select = castNode(List, defel->arg);
1184  else
1185  ereport(ERROR,
1186  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1187  errmsg("argument to option \"%s\" must be a list of column names",
1188  defel->defname),
1189  parser_errposition(pstate, defel->location)));
1190  }
1191  else if (strcmp(defel->defname, "encoding") == 0)
1192  {
1193  if (cstate->file_encoding >= 0)
1194  ereport(ERROR,
1195  (errcode(ERRCODE_SYNTAX_ERROR),
1196  errmsg("conflicting or redundant options"),
1197  parser_errposition(pstate, defel->location)));
1199  if (cstate->file_encoding < 0)
1200  ereport(ERROR,
1201  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1202  errmsg("argument to option \"%s\" must be a valid encoding name",
1203  defel->defname),
1204  parser_errposition(pstate, defel->location)));
1205  }
1206  else
1207  ereport(ERROR,
1208  (errcode(ERRCODE_SYNTAX_ERROR),
1209  errmsg("option \"%s\" not recognized",
1210  defel->defname),
1211  parser_errposition(pstate, defel->location)));
1212  }
1213 
1214  /*
1215  * Check for incompatible options (must do these two before inserting
1216  * defaults)
1217  */
1218  if (cstate->binary && cstate->delim)
1219  ereport(ERROR,
1220  (errcode(ERRCODE_SYNTAX_ERROR),
1221  errmsg("cannot specify DELIMITER in BINARY mode")));
1222 
1223  if (cstate->binary && cstate->null_print)
1224  ereport(ERROR,
1225  (errcode(ERRCODE_SYNTAX_ERROR),
1226  errmsg("cannot specify NULL in BINARY mode")));
1227 
1228  /* Set defaults for omitted options */
1229  if (!cstate->delim)
1230  cstate->delim = cstate->csv_mode ? "," : "\t";
1231 
1232  if (!cstate->null_print)
1233  cstate->null_print = cstate->csv_mode ? "" : "\\N";
1234  cstate->null_print_len = strlen(cstate->null_print);
1235 
1236  if (cstate->csv_mode)
1237  {
1238  if (!cstate->quote)
1239  cstate->quote = "\"";
1240  if (!cstate->escape)
1241  cstate->escape = cstate->quote;
1242  }
1243 
1244  /* Only single-byte delimiter strings are supported. */
1245  if (strlen(cstate->delim) != 1)
1246  ereport(ERROR,
1247  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1248  errmsg("COPY delimiter must be a single one-byte character")));
1249 
1250  /* Disallow end-of-line characters */
1251  if (strchr(cstate->delim, '\r') != NULL ||
1252  strchr(cstate->delim, '\n') != NULL)
1253  ereport(ERROR,
1254  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1255  errmsg("COPY delimiter cannot be newline or carriage return")));
1256 
1257  if (strchr(cstate->null_print, '\r') != NULL ||
1258  strchr(cstate->null_print, '\n') != NULL)
1259  ereport(ERROR,
1260  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1261  errmsg("COPY null representation cannot use newline or carriage return")));
1262 
1263  /*
1264  * Disallow unsafe delimiter characters in non-CSV mode. We can't allow
1265  * backslash because it would be ambiguous. We can't allow the other
1266  * cases because data characters matching the delimiter must be
1267  * backslashed, and certain backslash combinations are interpreted
1268  * non-literally by COPY IN. Disallowing all lower case ASCII letters is
1269  * more than strictly necessary, but seems best for consistency and
1270  * future-proofing. Likewise we disallow all digits though only octal
1271  * digits are actually dangerous.
1272  */
1273  if (!cstate->csv_mode &&
1274  strchr("\\.abcdefghijklmnopqrstuvwxyz0123456789",
1275  cstate->delim[0]) != NULL)
1276  ereport(ERROR,
1277  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1278  errmsg("COPY delimiter cannot be \"%s\"", cstate->delim)));
1279 
1280  /* Check header */
1281  if (!cstate->csv_mode && cstate->header_line)
1282  ereport(ERROR,
1283  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1284  errmsg("COPY HEADER available only in CSV mode")));
1285 
1286  /* Check quote */
1287  if (!cstate->csv_mode && cstate->quote != NULL)
1288  ereport(ERROR,
1289  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1290  errmsg("COPY quote available only in CSV mode")));
1291 
1292  if (cstate->csv_mode && strlen(cstate->quote) != 1)
1293  ereport(ERROR,
1294  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1295  errmsg("COPY quote must be a single one-byte character")));
1296 
1297  if (cstate->csv_mode && cstate->delim[0] == cstate->quote[0])
1298  ereport(ERROR,
1299  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1300  errmsg("COPY delimiter and quote must be different")));
1301 
1302  /* Check escape */
1303  if (!cstate->csv_mode && cstate->escape != NULL)
1304  ereport(ERROR,
1305  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1306  errmsg("COPY escape available only in CSV mode")));
1307 
1308  if (cstate->csv_mode && strlen(cstate->escape) != 1)
1309  ereport(ERROR,
1310  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1311  errmsg("COPY escape must be a single one-byte character")));
1312 
1313  /* Check force_quote */
1314  if (!cstate->csv_mode && (cstate->force_quote || cstate->force_quote_all))
1315  ereport(ERROR,
1316  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1317  errmsg("COPY force quote available only in CSV mode")));
1318  if ((cstate->force_quote || cstate->force_quote_all) && is_from)
1319  ereport(ERROR,
1320  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1321  errmsg("COPY force quote only available using COPY TO")));
1322 
1323  /* Check force_notnull */
1324  if (!cstate->csv_mode && cstate->force_notnull != NIL)
1325  ereport(ERROR,
1326  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1327  errmsg("COPY force not null available only in CSV mode")));
1328  if (cstate->force_notnull != NIL && !is_from)
1329  ereport(ERROR,
1330  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1331  errmsg("COPY force not null only available using COPY FROM")));
1332 
1333  /* Check force_null */
1334  if (!cstate->csv_mode && cstate->force_null != NIL)
1335  ereport(ERROR,
1336  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1337  errmsg("COPY force null available only in CSV mode")));
1338 
1339  if (cstate->force_null != NIL && !is_from)
1340  ereport(ERROR,
1341  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1342  errmsg("COPY force null only available using COPY FROM")));
1343 
1344  /* Don't allow the delimiter to appear in the null string. */
1345  if (strchr(cstate->null_print, cstate->delim[0]) != NULL)
1346  ereport(ERROR,
1347  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1348  errmsg("COPY delimiter must not appear in the NULL specification")));
1349 
1350  /* Don't allow the CSV quote char to appear in the null string. */
1351  if (cstate->csv_mode &&
1352  strchr(cstate->null_print, cstate->quote[0]) != NULL)
1353  ereport(ERROR,
1354  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1355  errmsg("CSV quote character must not appear in the NULL specification")));
1356 }
#define NIL
Definition: pg_list.h:69
bool csv_mode
Definition: copy.c:118
#define IsA(nodeptr, _type_)
Definition: nodes.h:560
int pg_char_to_encoding(const char *name)
Definition: encnames.c:551
bool binary
Definition: copy.c:115
#define castNode(_type_, nodeptr)
Definition: nodes.h:578
int errcode(int sqlerrcode)
Definition: elog.c:575
char * delim
Definition: copy.c:123
char * null_print
Definition: copy.c:120
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:43
char * defGetString(DefElem *def)
Definition: define.c:49
#define lfirst_node(type, lc)
Definition: pg_list.h:109
char * quote
Definition: copy.c:124
int location
Definition: parsenodes.h:722
char * escape
Definition: copy.c:125
#define ereport(elevel, rest)
Definition: elog.h:122
int null_print_len
Definition: copy.c:121
List * force_null
Definition: copy.c:131
Node * arg
Definition: parsenodes.h:720
int file_encoding
Definition: copy.c:104
void * palloc0(Size size)
Definition: mcxt.c:878
bool header_line
Definition: copy.c:119
bool freeze
Definition: copy.c:117
List * force_notnull
Definition: copy.c:129
#define NULL
Definition: c.h:229
List * convert_select
Definition: copy.c:134
int parser_errposition(ParseState *pstate, int location)
Definition: parse_node.c:111
bool force_quote_all
Definition: copy.c:127
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * defname
Definition: parsenodes.h:719
Definition: pg_list.h:45
List * force_quote
Definition: copy.c:126
bool convert_selectively
Definition: copy.c:133
bool oids
Definition: copy.c:116