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

References AllocateFile(), Assert, CopyStateData::attnumlist, CopyStateData::attribute_buf, tupleDesc::attrs, BeginCopy(), CopyStateData::binary, BinarySignature, build_column_default(), contain_volatile_functions_not_nextval(), 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, CopyStateData::typioparams, CopyStateData::volatile_defexprs, and whereToSendOutput.

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

2902 {
2903  CopyState cstate;
2904  bool pipe = (filename == NULL);
2905  TupleDesc tupDesc;
2906  Form_pg_attribute *attr;
2907  AttrNumber num_phys_attrs,
2908  num_defaults;
2909  FmgrInfo *in_functions;
2910  Oid *typioparams;
2911  int attnum;
2912  Oid in_func_oid;
2913  int *defmap;
2914  ExprState **defexprs;
2915  MemoryContext oldcontext;
2916  bool volatile_defexprs;
2917 
2918  cstate = BeginCopy(pstate, true, rel, NULL, InvalidOid, attnamelist, options);
2919  oldcontext = MemoryContextSwitchTo(cstate->copycontext);
2920 
2921  /* Initialize state variables */
2922  cstate->fe_eof = false;
2923  cstate->eol_type = EOL_UNKNOWN;
2924  cstate->cur_relname = RelationGetRelationName(cstate->rel);
2925  cstate->cur_lineno = 0;
2926  cstate->cur_attname = NULL;
2927  cstate->cur_attval = NULL;
2928 
2929  /* Set up variables to avoid per-attribute overhead. */
2930  initStringInfo(&cstate->attribute_buf);
2931  initStringInfo(&cstate->line_buf);
2932  cstate->line_buf_converted = false;
2933  cstate->raw_buf = (char *) palloc(RAW_BUF_SIZE + 1);
2934  cstate->raw_buf_index = cstate->raw_buf_len = 0;
2935 
2936  /* Assign range table, we'll need it in CopyFrom. */
2937  if (pstate)
2938  cstate->range_table = pstate->p_rtable;
2939 
2940  tupDesc = RelationGetDescr(cstate->rel);
2941  attr = tupDesc->attrs;
2942  num_phys_attrs = tupDesc->natts;
2943  num_defaults = 0;
2944  volatile_defexprs = false;
2945 
2946  /*
2947  * Pick up the required catalog information for each attribute in the
2948  * relation, including the input function, the element type (to pass to
2949  * the input function), and info about defaults and constraints. (Which
2950  * input function we use depends on text/binary format choice.)
2951  */
2952  in_functions = (FmgrInfo *) palloc(num_phys_attrs * sizeof(FmgrInfo));
2953  typioparams = (Oid *) palloc(num_phys_attrs * sizeof(Oid));
2954  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
2955  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
2956 
2957  for (attnum = 1; attnum <= num_phys_attrs; attnum++)
2958  {
2959  /* We don't need info for dropped attributes */
2960  if (attr[attnum - 1]->attisdropped)
2961  continue;
2962 
2963  /* Fetch the input function and typioparam info */
2964  if (cstate->binary)
2965  getTypeBinaryInputInfo(attr[attnum - 1]->atttypid,
2966  &in_func_oid, &typioparams[attnum - 1]);
2967  else
2968  getTypeInputInfo(attr[attnum - 1]->atttypid,
2969  &in_func_oid, &typioparams[attnum - 1]);
2970  fmgr_info(in_func_oid, &in_functions[attnum - 1]);
2971 
2972  /* Get default info if needed */
2973  if (!list_member_int(cstate->attnumlist, attnum))
2974  {
2975  /* attribute is NOT to be copied from input */
2976  /* use default value if one exists */
2977  Expr *defexpr = (Expr *) build_column_default(cstate->rel,
2978  attnum);
2979 
2980  if (defexpr != NULL)
2981  {
2982  /* Run the expression through planner */
2983  defexpr = expression_planner(defexpr);
2984 
2985  /* Initialize executable expression in copycontext */
2986  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
2987  defmap[num_defaults] = attnum - 1;
2988  num_defaults++;
2989 
2990  /*
2991  * If a default expression looks at the table being loaded,
2992  * then it could give the wrong answer when using
2993  * multi-insert. Since database access can be dynamic this is
2994  * hard to test for exactly, so we use the much wider test of
2995  * whether the default expression is volatile. We allow for
2996  * the special case of when the default expression is the
2997  * nextval() of a sequence which in this specific case is
2998  * known to be safe for use with the multi-insert
2999  * optimization. Hence we use this special case function
3000  * checker rather than the standard check for
3001  * contain_volatile_functions().
3002  */
3003  if (!volatile_defexprs)
3004  volatile_defexprs = contain_volatile_functions_not_nextval((Node *) defexpr);
3005  }
3006  }
3007  }
3008 
3009  /* We keep those variables in cstate. */
3010  cstate->in_functions = in_functions;
3011  cstate->typioparams = typioparams;
3012  cstate->defmap = defmap;
3013  cstate->defexprs = defexprs;
3014  cstate->volatile_defexprs = volatile_defexprs;
3015  cstate->num_defaults = num_defaults;
3016  cstate->is_program = is_program;
3017 
3018  if (data_source_cb)
3019  {
3020  cstate->copy_dest = COPY_CALLBACK;
3021  cstate->data_source_cb = data_source_cb;
3022  }
3023  else if (pipe)
3024  {
3025  Assert(!is_program); /* the grammar does not allow this */
3027  ReceiveCopyBegin(cstate);
3028  else
3029  cstate->copy_file = stdin;
3030  }
3031  else
3032  {
3033  cstate->filename = pstrdup(filename);
3034 
3035  if (cstate->is_program)
3036  {
3037  cstate->copy_file = OpenPipeStream(cstate->filename, PG_BINARY_R);
3038  if (cstate->copy_file == NULL)
3039  ereport(ERROR,
3041  errmsg("could not execute command \"%s\": %m",
3042  cstate->filename)));
3043  }
3044  else
3045  {
3046  struct stat st;
3047 
3048  cstate->copy_file = AllocateFile(cstate->filename, PG_BINARY_R);
3049  if (cstate->copy_file == NULL)
3050  {
3051  /* copy errno because ereport subfunctions might change it */
3052  int save_errno = errno;
3053 
3054  ereport(ERROR,
3056  errmsg("could not open file \"%s\" for reading: %m",
3057  cstate->filename),
3058  (save_errno == ENOENT || save_errno == EACCES) ?
3059  errhint("COPY FROM instructs the PostgreSQL server process to read a file. "
3060  "You may want a client-side facility such as psql's \\copy.") : 0));
3061  }
3062 
3063  if (fstat(fileno(cstate->copy_file), &st))
3064  ereport(ERROR,
3066  errmsg("could not stat file \"%s\": %m",
3067  cstate->filename)));
3068 
3069  if (S_ISDIR(st.st_mode))
3070  ereport(ERROR,
3071  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
3072  errmsg("\"%s\" is a directory", cstate->filename)));
3073  }
3074  }
3075 
3076  if (!cstate->binary)
3077  {
3078  /* must rely on user to tell us... */
3079  cstate->file_has_oids = cstate->oids;
3080  }
3081  else
3082  {
3083  /* Read and verify binary header */
3084  char readSig[11];
3085  int32 tmp;
3086 
3087  /* Signature */
3088  if (CopyGetData(cstate, readSig, 11, 11) != 11 ||
3089  memcmp(readSig, BinarySignature, 11) != 0)
3090  ereport(ERROR,
3091  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3092  errmsg("COPY file signature not recognized")));
3093  /* Flags field */
3094  if (!CopyGetInt32(cstate, &tmp))
3095  ereport(ERROR,
3096  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3097  errmsg("invalid COPY file header (missing flags)")));
3098  cstate->file_has_oids = (tmp & (1 << 16)) != 0;
3099  tmp &= ~(1 << 16);
3100  if ((tmp >> 16) != 0)
3101  ereport(ERROR,
3102  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3103  errmsg("unrecognized critical flags in COPY file header")));
3104  /* Header extension length */
3105  if (!CopyGetInt32(cstate, &tmp) ||
3106  tmp < 0)
3107  ereport(ERROR,
3108  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3109  errmsg("invalid COPY file header (missing length)")));
3110  /* Skip extension header, if present */
3111  while (tmp-- > 0)
3112  {
3113  if (CopyGetData(cstate, readSig, 1, 1) != 1)
3114  ereport(ERROR,
3115  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3116  errmsg("invalid COPY file header (wrong length)")));
3117  }
3118  }
3119 
3120  if (cstate->file_has_oids && cstate->binary)
3121  {
3123  &in_func_oid, &cstate->oid_typioparam);
3124  fmgr_info(in_func_oid, &cstate->oid_in_function);
3125  }
3126 
3127  /* create workspace for CopyReadAttributes results */
3128  if (!cstate->binary)
3129  {
3130  AttrNumber attr_count = list_length(cstate->attnumlist);
3131  int nfields = cstate->file_has_oids ? (attr_count + 1) : attr_count;
3132 
3133  cstate->max_fields = nfields;
3134  cstate->raw_fields = (char **) palloc(nfields * sizeof(char *));
3135  }
3136 
3137  MemoryContextSwitchTo(oldcontext);
3138 
3139  return cstate;
3140 }
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:1372
bool contain_volatile_functions_not_nextval(Node *clause)
Definition: clauses.c:995
static bool CopyGetInt32(CopyState cstate, int32 *val)
Definition: copy.c:682
int errhint(const char *fmt,...)
Definition: elog.c:987
char ** raw_fields
Definition: copy.c:188
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
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:380
Expr * expression_planner(Expr *expr)
Definition: planner.c:5931
Form_pg_attribute * attrs
Definition: tupdesc.h:74
StringInfoData line_buf
Definition: copy.c:197
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Definition: nodes.h:509
int raw_buf_index
Definition: copy.c:210
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:1040
int natts
Definition: tupdesc.h:73
bool line_buf_converted
Definition: copy.c:198
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:556
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:209
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:288
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:187
int raw_buf_len
Definition: copy.c:211
int max_fields
Definition: copy.c:187
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:208
#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:675
static int list_length(const List *l)
Definition: pg_list.h:89
static char * filename
Definition: pg_dumpall.c:89
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:183
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 2292 of file copy.c.

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

Referenced by copy_table(), and DoCopy().

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

2188 {
2189  CopyState cstate = (CopyState) arg;
2190 
2191  if (cstate->binary)
2192  {
2193  /* can't usefully display the data */
2194  if (cstate->cur_attname)
2195  errcontext("COPY %s, line %d, column %s",
2196  cstate->cur_relname, cstate->cur_lineno,
2197  cstate->cur_attname);
2198  else
2199  errcontext("COPY %s, line %d",
2200  cstate->cur_relname, cstate->cur_lineno);
2201  }
2202  else
2203  {
2204  if (cstate->cur_attname && cstate->cur_attval)
2205  {
2206  /* error is relevant to a particular column */
2207  char *attval;
2208 
2209  attval = limit_printout_length(cstate->cur_attval);
2210  errcontext("COPY %s, line %d, column %s: \"%s\"",
2211  cstate->cur_relname, cstate->cur_lineno,
2212  cstate->cur_attname, attval);
2213  pfree(attval);
2214  }
2215  else if (cstate->cur_attname)
2216  {
2217  /* error is relevant to a particular column, value is NULL */
2218  errcontext("COPY %s, line %d, column %s: null input",
2219  cstate->cur_relname, cstate->cur_lineno,
2220  cstate->cur_attname);
2221  }
2222  else
2223  {
2224  /*
2225  * Error is relevant to a particular line.
2226  *
2227  * If line_buf still contains the correct line, and it's already
2228  * transcoded, print it. If it's still in a foreign encoding, it's
2229  * quite likely that the error is precisely a failure to do
2230  * encoding conversion (ie, bad data). We dare not try to convert
2231  * it, and at present there's no way to regurgitate it without
2232  * conversion. So we have to punt and just report the line number.
2233  */
2234  if (cstate->line_buf_valid &&
2235  (cstate->line_buf_converted || !cstate->need_transcoding))
2236  {
2237  char *lineval;
2238 
2239  lineval = limit_printout_length(cstate->line_buf.data);
2240  errcontext("COPY %s, line %d: \"%s\"",
2241  cstate->cur_relname, cstate->cur_lineno, lineval);
2242  pfree(lineval);
2243  }
2244  else
2245  {
2246  errcontext("COPY %s, line %d",
2247  cstate->cur_relname, cstate->cur_lineno);
2248  }
2249  }
2250  }
2251 }
bool binary
Definition: copy.c:115
bool need_transcoding
Definition: copy.c:105
StringInfoData line_buf
Definition: copy.c:197
bool line_buf_valid
Definition: copy.c:199
bool line_buf_converted
Definition: copy.c:198
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:2263
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 4757 of file copy.c.

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

Referenced by CreateDestReceiver().

4758 {
4759  DR_copy *self = (DR_copy *) palloc(sizeof(DR_copy));
4760 
4761  self->pub.receiveSlot = copy_dest_receive;
4762  self->pub.rStartup = copy_dest_startup;
4763  self->pub.rShutdown = copy_dest_shutdown;
4764  self->pub.rDestroy = copy_dest_destroy;
4765  self->pub.mydest = DestCopyOut;
4766 
4767  self->cstate = NULL; /* will be set later */
4768  self->processed = 0;
4769 
4770  return (DestReceiver *) self;
4771 }
Definition: copy.c:215
static void copy_dest_destroy(DestReceiver *self)
Definition: copy.c:4748
static void copy_dest_shutdown(DestReceiver *self)
Definition: copy.c:4739
static void copy_dest_startup(DestReceiver *self, int operation, TupleDesc typeinfo)
Definition: copy.c:4711
static bool copy_dest_receive(TupleTableSlot *slot, DestReceiver *self)
Definition: copy.c:4720
#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 781 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().

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

References EndCopy().

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

3448 {
3449  /* No COPY FROM related resources except memory. */
3450 
3451  EndCopy(cstate);
3452 }
static void EndCopy(CopyState cstate)
Definition: copy.c:1734
bool NextCopyFrom ( CopyState  cstate,
ExprContext econtext,
Datum values,
bool nulls,
Oid tupleOid 
)

Definition at line 3206 of file copy.c.

References Assert, CopyStateData::attnumlist, tupleDesc::attrs, 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, and CopyStateData::typioparams.

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

3208 {
3209  TupleDesc tupDesc;
3210  Form_pg_attribute *attr;
3211  AttrNumber num_phys_attrs,
3212  attr_count,
3213  num_defaults = cstate->num_defaults;
3214  FmgrInfo *in_functions = cstate->in_functions;
3215  Oid *typioparams = cstate->typioparams;
3216  int i;
3217  int nfields;
3218  bool isnull;
3219  bool file_has_oids = cstate->file_has_oids;
3220  int *defmap = cstate->defmap;
3221  ExprState **defexprs = cstate->defexprs;
3222 
3223  tupDesc = RelationGetDescr(cstate->rel);
3224  attr = tupDesc->attrs;
3225  num_phys_attrs = tupDesc->natts;
3226  attr_count = list_length(cstate->attnumlist);
3227  nfields = file_has_oids ? (attr_count + 1) : attr_count;
3228 
3229  /* Initialize all values for row to NULL */
3230  MemSet(values, 0, num_phys_attrs * sizeof(Datum));
3231  MemSet(nulls, true, num_phys_attrs * sizeof(bool));
3232 
3233  if (!cstate->binary)
3234  {
3235  char **field_strings;
3236  ListCell *cur;
3237  int fldct;
3238  int fieldno;
3239  char *string;
3240 
3241  /* read raw fields in the next line */
3242  if (!NextCopyFromRawFields(cstate, &field_strings, &fldct))
3243  return false;
3244 
3245  /* check for overflowing fields */
3246  if (nfields > 0 && fldct > nfields)
3247  ereport(ERROR,
3248  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3249  errmsg("extra data after last expected column")));
3250 
3251  fieldno = 0;
3252 
3253  /* Read the OID field if present */
3254  if (file_has_oids)
3255  {
3256  if (fieldno >= fldct)
3257  ereport(ERROR,
3258  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3259  errmsg("missing data for OID column")));
3260  string = field_strings[fieldno++];
3261 
3262  if (string == NULL)
3263  ereport(ERROR,
3264  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3265  errmsg("null OID in COPY data")));
3266  else if (cstate->oids && tupleOid != NULL)
3267  {
3268  cstate->cur_attname = "oid";
3269  cstate->cur_attval = string;
3271  CStringGetDatum(string)));
3272  if (*tupleOid == InvalidOid)
3273  ereport(ERROR,
3274  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3275  errmsg("invalid OID in COPY data")));
3276  cstate->cur_attname = NULL;
3277  cstate->cur_attval = NULL;
3278  }
3279  }
3280 
3281  /* Loop to read the user attributes on the line. */
3282  foreach(cur, cstate->attnumlist)
3283  {
3284  int attnum = lfirst_int(cur);
3285  int m = attnum - 1;
3286 
3287  if (fieldno >= fldct)
3288  ereport(ERROR,
3289  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3290  errmsg("missing data for column \"%s\"",
3291  NameStr(attr[m]->attname))));
3292  string = field_strings[fieldno++];
3293 
3294  if (cstate->convert_select_flags &&
3295  !cstate->convert_select_flags[m])
3296  {
3297  /* ignore input field, leaving column as NULL */
3298  continue;
3299  }
3300 
3301  if (cstate->csv_mode)
3302  {
3303  if (string == NULL &&
3304  cstate->force_notnull_flags[m])
3305  {
3306  /*
3307  * FORCE_NOT_NULL option is set and column is NULL -
3308  * convert it to the NULL string.
3309  */
3310  string = cstate->null_print;
3311  }
3312  else if (string != NULL && cstate->force_null_flags[m]
3313  && strcmp(string, cstate->null_print) == 0)
3314  {
3315  /*
3316  * FORCE_NULL option is set and column matches the NULL
3317  * string. It must have been quoted, or otherwise the
3318  * string would already have been set to NULL. Convert it
3319  * to NULL as specified.
3320  */
3321  string = NULL;
3322  }
3323  }
3324 
3325  cstate->cur_attname = NameStr(attr[m]->attname);
3326  cstate->cur_attval = string;
3327  values[m] = InputFunctionCall(&in_functions[m],
3328  string,
3329  typioparams[m],
3330  attr[m]->atttypmod);
3331  if (string != NULL)
3332  nulls[m] = false;
3333  cstate->cur_attname = NULL;
3334  cstate->cur_attval = NULL;
3335  }
3336 
3337  Assert(fieldno == nfields);
3338  }
3339  else
3340  {
3341  /* binary */
3342  int16 fld_count;
3343  ListCell *cur;
3344 
3345  cstate->cur_lineno++;
3346 
3347  if (!CopyGetInt16(cstate, &fld_count))
3348  {
3349  /* EOF detected (end of file, or protocol-level EOF) */
3350  return false;
3351  }
3352 
3353  if (fld_count == -1)
3354  {
3355  /*
3356  * Received EOF marker. In a V3-protocol copy, wait for the
3357  * protocol-level EOF, and complain if it doesn't come
3358  * immediately. This ensures that we correctly handle CopyFail,
3359  * if client chooses to send that now.
3360  *
3361  * Note that we MUST NOT try to read more data in an old-protocol
3362  * copy, since there is no protocol-level EOF marker then. We
3363  * could go either way for copy from file, but choose to throw
3364  * error if there's data after the EOF marker, for consistency
3365  * with the new-protocol case.
3366  */
3367  char dummy;
3368 
3369  if (cstate->copy_dest != COPY_OLD_FE &&
3370  CopyGetData(cstate, &dummy, 1, 1) > 0)
3371  ereport(ERROR,
3372  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3373  errmsg("received copy data after EOF marker")));
3374  return false;
3375  }
3376 
3377  if (fld_count != attr_count)
3378  ereport(ERROR,
3379  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3380  errmsg("row field count is %d, expected %d",
3381  (int) fld_count, attr_count)));
3382 
3383  if (file_has_oids)
3384  {
3385  Oid loaded_oid;
3386 
3387  cstate->cur_attname = "oid";
3388  loaded_oid =
3390  0,
3391  &cstate->oid_in_function,
3392  cstate->oid_typioparam,
3393  -1,
3394  &isnull));
3395  if (isnull || loaded_oid == InvalidOid)
3396  ereport(ERROR,
3397  (errcode(ERRCODE_BAD_COPY_FILE_FORMAT),
3398  errmsg("invalid OID in COPY data")));
3399  cstate->cur_attname = NULL;
3400  if (cstate->oids && tupleOid != NULL)
3401  *tupleOid = loaded_oid;
3402  }
3403 
3404  i = 0;
3405  foreach(cur, cstate->attnumlist)
3406  {
3407  int attnum = lfirst_int(cur);
3408  int m = attnum - 1;
3409 
3410  cstate->cur_attname = NameStr(attr[m]->attname);
3411  i++;
3412  values[m] = CopyReadBinaryAttribute(cstate,
3413  i,
3414  &in_functions[m],
3415  typioparams[m],
3416  attr[m]->atttypmod,
3417  &nulls[m]);
3418  cstate->cur_attname = NULL;
3419  }
3420  }
3421 
3422  /*
3423  * Now compute and insert any defaults available for the columns not
3424  * provided by the input data. Anything not processed here or above will
3425  * remain NULL.
3426  */
3427  for (i = 0; i < num_defaults; i++)
3428  {
3429  /*
3430  * The caller must supply econtext and have switched into the
3431  * per-tuple memory context in it.
3432  */
3433  Assert(econtext != NULL);
3435 
3436  values[defmap[i]] = ExecEvalExpr(defexprs[i], econtext,
3437  &nulls[defmap[i]]);
3438  }
3439 
3440  return true;
3441 }
signed short int16
Definition: c.h:255
bool NextCopyFromRawFields(CopyState cstate, char ***fields, int *nfields)
Definition: copy.c:3154
static Datum CopyReadBinaryAttribute(CopyState cstate, int column_no, FmgrInfo *flinfo, Oid typioparam, int32 typmod, bool *isnull)
Definition: copy.c:4336
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
bool file_has_oids
Definition: copy.c:158
#define DatumGetObjectId(X)
Definition: postgres.h:506
MemoryContext ecxt_per_tuple_memory
Definition: execnodes.h:203
Form_pg_attribute * attrs
Definition: tupdesc.h:74
struct cursor * cur
Definition: ecpg.c:28
int errcode(int sqlerrcode)
Definition: elog.c:575
#define MemSet(start, val, len)
Definition: c.h:857
#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:556
#define lfirst_int(lc)
Definition: pg_list.h:107
static Datum ExecEvalExpr(ExprState *state, ExprContext *econtext, bool *isNull)
Definition: executor.h:266
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:675
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:711
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 3154 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().

3155 {
3156  int fldct;
3157  bool done;
3158 
3159  /* only available for text or csv input */
3160  Assert(!cstate->binary);
3161 
3162  /* on input just throw the header line away */
3163  if (cstate->cur_lineno == 0 && cstate->header_line)
3164  {
3165  cstate->cur_lineno++;
3166  if (CopyReadLine(cstate))
3167  return false; /* done */
3168  }
3169 
3170  cstate->cur_lineno++;
3171 
3172  /* Actually read the line into memory here */
3173  done = CopyReadLine(cstate);
3174 
3175  /*
3176  * EOF at start of line means we're done. If we see EOF after some
3177  * characters, we act as though it was newline followed by EOF, ie,
3178  * process the line and then exit loop on next iteration.
3179  */
3180  if (done && cstate->line_buf.len == 0)
3181  return false;
3182 
3183  /* Parse the line into de-escaped field values */
3184  if (cstate->csv_mode)
3185  fldct = CopyReadAttributesCSV(cstate);
3186  else
3187  fldct = CopyReadAttributesText(cstate);
3188 
3189  *fields = cstate->raw_fields;
3190  *nfields = fldct;
3191  return true;
3192 }
bool csv_mode
Definition: copy.c:118
char ** raw_fields
Definition: copy.c:188
bool binary
Definition: copy.c:115
StringInfoData line_buf
Definition: copy.c:197
static int CopyReadAttributesCSV(CopyState cstate)
Definition: copy.c:4167
bool header_line
Definition: copy.c:119
#define Assert(condition)
Definition: c.h:675
static bool CopyReadLine(CopyState cstate)
Definition: copy.c:3463
int cur_lineno
Definition: copy.c:139
static int CopyReadAttributesText(CopyState cstate)
Definition: copy.c:3939
void ProcessCopyOptions ( ParseState pstate,
CopyState  cstate,
bool  is_from,
List options 
)

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

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