-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcopy.c
More file actions
1694 lines (1478 loc) · 48.6 KB
/
Copy pathcopy.c
File metadata and controls
1694 lines (1478 loc) · 48.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file and its contents are licensed under the Apache License 2.0.
* Please see the included NOTICE for copyright information and
* LICENSE-APACHE for a copy of the license.
*/
/*
* This file contains source code that was copied and/or modified from
* the PostgreSQL database, which is licensed under the open-source
* PostgreSQL License. Please see the NOTICE at the top level
* directory for a copy of the PostgreSQL License.
*
* The code copies data to a hypertable or migrates existing data from
* a table to a hypertable when create_hypertable(..., migrate_data =>
* 'true', ...) is called.
*
* Unfortunately, there aren't any good hooks in the regular COPY code to
* insert our chunk dispatching. So, most of this code is a straight-up
* copy of the regular PostgreSQL source code for the COPY command
* (command/copy.c and command/copyfrom.c), albeit with minor modifications.
*/
#include <postgres.h>
#include <access/heapam.h>
#include <access/hio.h>
#include <access/sysattr.h>
#include <access/xact.h>
#include <catalog/pg_trigger_d.h>
#include <commands/copy.h>
#include <commands/copyfrom_internal.h>
#include <commands/tablecmds.h>
#include <commands/trigger.h>
#include <executor/executor.h>
#include <executor/nodeModifyTable.h>
#include <miscadmin.h>
#include <nodes/makefuncs.h>
#include <optimizer/optimizer.h>
#include <parser/parse_coerce.h>
#include <parser/parse_collate.h>
#include <parser/parse_expr.h>
#include <parser/parse_relation.h>
#include <storage/bufmgr.h>
#include <storage/smgr.h>
#include <utils/builtins.h>
#include <utils/elog.h>
#include <utils/guc.h>
#include <utils/hsearch.h>
#include <utils/lsyscache.h>
#include <utils/rel.h>
#include <utils/rls.h>
#include "compat/compat.h"
#include "chunk_insert_state.h"
#include "copy.h"
#include "cross_module_fn.h"
#include "dimension.h"
#include "guc.h"
#include "hypertable.h"
#include "indexing.h"
#include "subspace_store.h"
/*
* Represents the insert method to be used during COPY FROM.
*/
typedef enum TSCopyInsertMethod
{
TS_CIM_SINGLE, /* use table_tuple_insert or ExecForeignInsert */
TS_CIM_MULTI_CONDITIONAL, /* use table_multi_insert or
* ExecForeignBatchInsert only if valid */
TS_CIM_COMPRESSION, /* use compression for the insert */
} TSCopyInsertMethod;
/*
* No more than this many tuples per TSCopyMultiInsertBuffer
*
* Caution: Don't make this too big, as we could end up with this many
* TSCopyMultiInsertBuffer items stored in TSCopyMultiInsertInfo's
* multiInsertBuffers list. Increasing this can cause quadratic growth in
* memory requirements during copies into partitioned tables with a large
* number of partitions.
*/
#define MAX_BUFFERED_TUPLES 1000
/*
* Flush buffers if there are >= this many bytes, as counted by the input
* size, of tuples stored.
*/
#define MAX_BUFFERED_BYTES 65535
/* Trim the list of buffers back down to this number after flushing */
#define MAX_PARTITION_BUFFERS 32
/* Stores multi-insert data related to a single relation in CopyFrom. */
typedef struct TSCopyMultiInsertBuffer
{
TSCopyInsertMethod method; /* The insert method to use */
/*
* Tuple description for inserted tuple slots. We use a copy of the result
* relation tupdesc to disable reference counting for this tupdesc. It is
* not needed and is wasting a lot of CPU in ResourceOwner.
*/
TupleDesc tupdesc;
TupleTableSlot *slots[MAX_BUFFERED_TUPLES]; /* Array to store tuples */
Point *point; /* The point in space of this buffer */
BulkInsertState bistate; /* BulkInsertState for this buffer */
int nused; /* number of 'slots' containing tuples */
uint64 linenos[MAX_BUFFERED_TUPLES]; /* Line # of tuple in copy
* stream */
bool can_skip_constraints; /* Whether we can skip constraint
* checks for this relation */
RowCompressor *compressor; /* compressor for the chunk */
BulkWriter *bulk_writer; /* BulkWriter for the compressed chunk */
} TSCopyMultiInsertBuffer;
/*
* Stores one or many TSCopyMultiInsertBuffers and details about the size and
* number of tuples which are stored in them. This allows multiple buffers to
* exist at once when COPYing into a partitioned table.
*
* The HTAB is used to store the relationship between a chunk and a
* TSCopyMultiInsertBuffer beyond the lifetime of the ChunkInsertState.
*
* Chunks can be closed (e.g., due to timescaledb.max_open_chunks_per_insert).
* When ts_chunk_dispatch_get_chunk_insert_state is called again for a closed
* chunk, a new ChunkInsertState is returned.
*/
typedef struct TSCopyMultiInsertInfo
{
HTAB *multiInsertBuffers; /* Maps the chunk ids to the buffers (chunkid ->
TSCopyMultiInsertBuffer) */
int bufferedTuples; /* number of tuples buffered over all buffers */
int bufferedBytes; /* number of bytes from all buffered tuples */
CopyChunkState *ccstate; /* Copy chunk state for this TSCopyMultiInsertInfo */
EState *estate; /* Executor state used for COPY */
CommandId mycid; /* Command Id used for COPY */
int ti_options; /* table insert options */
Hypertable *ht; /* The hypertable for the inserts */
bool has_continuous_aggregate;
} TSCopyMultiInsertInfo;
/*
* The entry of the multiInsertBuffers HTAB.
*/
typedef struct MultiInsertBufferEntry
{
int32 key;
TSCopyMultiInsertBuffer *buffer;
} MultiInsertBufferEntry;
static CopyChunkState *
copy_chunk_state_create(Hypertable *ht, Relation rel, CopyFromFunc from_func, CopyFromState cstate,
TableScanDesc scandesc)
{
CopyChunkState *ccstate;
EState *estate = CreateExecutorState();
ccstate = palloc(sizeof(CopyChunkState));
ccstate->rel = rel;
ccstate->estate = estate;
ccstate->cstate = cstate;
ccstate->scandesc = scandesc;
ccstate->next_copy_from = from_func;
ccstate->where_clause = NULL;
return ccstate;
}
/*
* Determine whether we can skip constraints checks for this relation.
* We will skip constraints checks if:
* 1. The relation has CHECK constraints that match the number of dimensions
* 2. The relation has no NOT NULL constraints on non-partitioning columns
*/
static bool
can_skip_constraint_check(Hypertable *ht, TupleDesc tupledesc)
{
/*
* When the number of constraints does not match the number of dimensions then there are
* additional constraints that we need to check during COPY. Partitioning constraints would
* have already been checked by tuple routing.
*/
Assert(tupledesc->constr->num_check >= ht->space->num_dimensions);
if (tupledesc->constr && tupledesc->constr->num_check != ht->space->num_dimensions)
{
return false;
}
for (int i = 0; i < tupledesc->natts; i++)
{
Form_pg_attribute att = TupleDescAttr(tupledesc, i);
if (att->attisdropped)
{
continue;
}
/*
* If we have NOT NULL constraints on non-partitioning columns, we cannot skip
* constraints and have to check them.
*/
if (att->attnotnull)
{
if (ts_is_partitioning_column_name(ht, att->attname))
{
continue;
}
return false;
}
}
return true;
}
/*
* Allocate memory and initialize a new TSCopyMultiInsertBuffer for this
* ResultRelInfo.
*/
static TSCopyMultiInsertBuffer *
TSCopyMultiInsertBufferInit(TSCopyMultiInsertInfo *miinfo, ChunkInsertState *cis, Point *point,
TSCopyInsertMethod method)
{
TSCopyMultiInsertBuffer *buffer;
buffer = (TSCopyMultiInsertBuffer *) palloc0(sizeof(TSCopyMultiInsertBuffer));
buffer->method = method;
buffer->point = palloc(POINT_SIZE(point->num_coords));
memcpy(buffer->point, point, POINT_SIZE(point->num_coords));
buffer->can_skip_constraints = can_skip_constraint_check(miinfo->ht, cis->rel->rd_att);
/*
* Downgrade the insert method when triggers are present.
*/
if (method != TS_CIM_SINGLE && cis->result_relation_info->ri_TrigDesc)
{
/* If there are BEFORE INSERT row triggers, we cannot use
* multi-insert, as the tuples may be inserted in an out-of-order manner,
* which might violate the semantics of the triggers.
*
* For compressed inserts we fall back to TS_CIM_SINGLE when any triggers are present.
* This is a safety measure. We might actually safely allow some of these in the future.
*/
if (method == TS_CIM_MULTI_CONDITIONAL &&
(cis->result_relation_info->ri_TrigDesc->trig_insert_before_row ||
cis->result_relation_info->ri_TrigDesc->trig_insert_instead_row))
{
buffer->method = TS_CIM_SINGLE;
}
else if (method == TS_CIM_COMPRESSION)
{
buffer->method = TS_CIM_SINGLE;
}
}
switch (buffer->method)
{
case TS_CIM_SINGLE:
break;
case TS_CIM_MULTI_CONDITIONAL:
buffer->bistate = GetBulkInsertState();
/*
* Make a non-refcounted copy of tupdesc to avoid spending CPU in
* ResourceOwner when creating a big number of table slots. This happens
* because each new slot pins its tuple descriptor using PinTupleDesc, and
* for reference-counting tuples this involves adding a new reference to
* ResourceOwner, which is not very efficient for a large number of
* references.
*/
buffer->tupdesc = CreateTupleDescCopyConstr(cis->rel->rd_att);
Assert(buffer->tupdesc->tdrefcount == -1);
break;
case TS_CIM_COMPRESSION:
{
bool sort = ts_guc_enable_direct_compress_copy_sort_batches &&
!ts_guc_enable_direct_compress_copy_client_sorted;
buffer->compressor =
ts_cm_functions->compressor_init(cis->rel,
&buffer->bulk_writer,
sort,
ts_guc_direct_compress_copy_tuple_sort_limit,
cis->created_compressed_chunk);
if (miinfo->has_continuous_aggregate && !ts_guc_skip_cagg_invalidation)
{
ts_cm_functions->compressor_set_invalidation(buffer->compressor,
miinfo->ht,
RelationGetRelid(cis->rel));
}
/*
* The sorting done in the compressor is only a local sort for the
* currently ingested batch and will produce overlapping batches for
* multiple independent insert streams. Therefore we still need to
* mark the chunk as unordered until we adjust the rest of the code to
* be able to deal with overlapping batches.
*/
if (!ts_guc_enable_direct_compress_copy_client_sorted)
{
Chunk *chunk = ts_chunk_get_by_id(cis->chunk_id, true);
if (!ts_chunk_is_unordered(chunk))
{
ts_chunk_set_unordered(chunk);
}
}
cis->columnstore_insert = true;
break;
}
}
return buffer;
}
/*
* Get the existing TSCopyMultiInsertBuffer for the chunk or create a new one.
*/
static inline TSCopyMultiInsertBuffer *
TSCopyMultiInsertInfoGetOrSetupBuffer(TSCopyMultiInsertInfo *miinfo, ChunkInsertState *cis,
Point *point, TSCopyInsertMethod method)
{
bool found;
int32 chunk_id;
Assert(miinfo != NULL);
Assert(cis != NULL);
Assert(point != NULL);
chunk_id = cis->chunk_id;
MultiInsertBufferEntry *entry =
hash_search(miinfo->multiInsertBuffers, &chunk_id, HASH_ENTER, &found);
/* No insert buffer for this chunk exists, create a new one */
if (!found)
{
entry->buffer = TSCopyMultiInsertBufferInit(miinfo, cis, point, method);
}
return entry->buffer;
}
/*
* Create a new HTAB that maps from the chunk_id to the multi-insert buffers.
*/
static HTAB *
TSCopyCreateNewInsertBufferHashMap()
{
struct HASHCTL hctl = {
.keysize = sizeof(int32),
.entrysize = sizeof(MultiInsertBufferEntry),
.hcxt = CurrentMemoryContext,
};
return hash_create("COPY insert buffer", 20, &hctl, HASH_ELEM | HASH_CONTEXT | HASH_BLOBS);
}
/*
* Initialize an already allocated TSCopyMultiInsertInfo.
*/
static void
TSCopyMultiInsertInfoInit(TSCopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
CopyChunkState *ccstate, EState *estate, CommandId mycid, int ti_options,
Hypertable *ht)
{
miinfo->multiInsertBuffers = TSCopyCreateNewInsertBufferHashMap();
miinfo->bufferedTuples = 0;
miinfo->bufferedBytes = 0;
miinfo->ccstate = ccstate;
miinfo->estate = estate;
miinfo->mycid = mycid;
miinfo->ti_options = ti_options;
miinfo->ht = ht;
miinfo->has_continuous_aggregate = ts_hypertable_has_continuous_aggregates(ht->fd.id);
}
/*
* Returns true if the buffers are full.
*/
static inline bool
TSCopyMultiInsertInfoIsFull(TSCopyMultiInsertInfo *miinfo)
{
if (miinfo->bufferedTuples >= MAX_BUFFERED_TUPLES ||
miinfo->bufferedBytes >= MAX_BUFFERED_BYTES)
{
return true;
}
return false;
}
/*
* Write the tuples stored in 'buffer' out to the table.
*/
static inline int
TSCopyMultiInsertBufferFlush(TSCopyMultiInsertInfo *miinfo, TSCopyMultiInsertBuffer *buffer)
{
MemoryContext oldcontext;
int i;
Assert(miinfo != NULL);
Assert(buffer != NULL);
EState *estate = miinfo->estate;
CommandId mycid = miinfo->mycid;
int ti_options = miinfo->ti_options;
int nused = buffer->nused;
TupleTableSlot **slots = buffer->slots;
if (buffer->method == TS_CIM_COMPRESSION)
{
ts_cm_functions->compressor_flush(buffer->compressor, buffer->bulk_writer);
}
/*
* table_multi_insert and reinitialization of the chunk insert state may
* leak memory, so switch to short-lived memory context before calling it.
*/
oldcontext = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
/*
* A chunk can be closed while buffering the tuples. Even when the chunk
* insert state is moved to the copy memory context, the underlying
* table is closed and pointers (e.g., result_relation_info point) to invalid
* addresses. Re-reading the chunk insert state ensures that the table is
* open and the pointers are valid.
*
* No callback on changed chunk is needed, the bulk insert state buffer is
* freed in TSCopyMultiInsertBufferCleanup().
*/
ChunkInsertState *cis = ts_chunk_tuple_routing_find_chunk(miinfo->ccstate->ctr, buffer->point);
ResultRelInfo *resultRelInfo = cis->result_relation_info;
/*
* Add context information to the copy state, which is used to display
* error messages with additional details.
*/
uint64 save_cur_lineno = 0;
bool line_buf_valid = false;
CopyFromState cstate = miinfo->ccstate->cstate;
/* cstate can be NULL in calls that are invoked from timescaledb_move_from_table_to_chunks. */
if (cstate != NULL)
{
line_buf_valid = cstate->line_buf_valid;
save_cur_lineno = cstate->cur_lineno;
cstate->line_buf_valid = false;
}
table_multi_insert(resultRelInfo->ri_RelationDesc,
slots,
nused,
mycid,
ti_options,
buffer->bistate);
MemoryContextSwitchTo(oldcontext);
for (i = 0; i < nused; i++)
{
if (cstate != NULL)
{
cstate->cur_lineno = buffer->linenos[i];
}
/*
* If there are any indexes, update them for all the inserted tuples,
* and run AFTER ROW INSERT triggers.
*/
if (resultRelInfo->ri_NumIndices > 0)
{
List *recheckIndexes;
recheckIndexes = ExecInsertIndexTuplesCompat(resultRelInfo,
buffer->slots[i],
estate,
false,
false,
NULL,
NIL,
false);
ExecARInsertTriggers(estate,
resultRelInfo,
slots[i],
recheckIndexes,
NULL /* transition capture */);
list_free(recheckIndexes);
}
/*
* There's no indexes, but see if we need to run AFTER ROW INSERT
* triggers anyway.
*/
else if (resultRelInfo->ri_TrigDesc != NULL &&
(resultRelInfo->ri_TrigDesc->trig_insert_after_row ||
resultRelInfo->ri_TrigDesc->trig_insert_new_table))
{
ExecARInsertTriggers(estate,
resultRelInfo,
slots[i],
NIL,
NULL /* transition capture */);
}
if (miinfo->has_continuous_aggregate && !ts_guc_skip_cagg_invalidation)
{
bool should_free;
HeapTuple tuple = ExecFetchSlotHeapTuple(slots[i], false, &should_free);
ts_cm_functions->continuous_agg_dml_invalidate(miinfo->ht->fd.id,
resultRelInfo->ri_RelationDesc,
tuple,
NULL,
false);
if (should_free)
{
heap_freetuple(tuple);
}
}
ExecClearTuple(slots[i]);
}
/* Mark that all slots are free */
buffer->nused = 0;
/* Chunk could be closed on a subsequent call of ts_chunk_dispatch_get_chunk_insert_state
* (e.g., due to timescaledb.max_open_chunks_per_insert). So, ensure the bulk insert is
* finished after the flush is complete.
*/
ResultRelInfo *result_relation_info = cis->result_relation_info;
Assert(result_relation_info != NULL);
table_finish_bulk_insert(result_relation_info->ri_RelationDesc, miinfo->ti_options);
/* Reset cur_lineno and line_buf_valid to what they were */
if (cstate != NULL)
{
cstate->line_buf_valid = line_buf_valid;
cstate->cur_lineno = save_cur_lineno;
}
return cis->chunk_id;
}
/*
* Drop used slots and free member for this buffer.
*
* The buffer must be flushed before cleanup.
*/
static inline void
TSCopyMultiInsertBufferCleanup(TSCopyMultiInsertInfo *miinfo, TSCopyMultiInsertBuffer *buffer)
{
int i;
/* Ensure buffer was flushed */
Assert(buffer->nused == 0);
switch (buffer->method)
{
case TS_CIM_SINGLE:
break;
case TS_CIM_MULTI_CONDITIONAL:
FreeBulkInsertState(buffer->bistate);
/* Since we only create slots on demand, just drop the non-null ones. */
for (i = 0; i < MAX_BUFFERED_TUPLES && buffer->slots[i] != NULL; i++)
{
ExecDropSingleTupleTableSlot(buffer->slots[i]);
}
FreeTupleDesc(buffer->tupdesc);
break;
case TS_CIM_COMPRESSION:
ts_cm_functions->compressor_close(buffer->compressor, buffer->bulk_writer);
pfree(buffer->compressor);
pfree(buffer->bulk_writer);
buffer->compressor = NULL;
buffer->bulk_writer = NULL;
break;
}
pfree(buffer->point);
pfree(buffer);
}
/* list_sort comparator to sort TSCopyMultiInsertBuffer by usage */
static int
TSCmpBuffersByUsage(const ListCell *a, const ListCell *b)
{
int b1 = ((const TSCopyMultiInsertBuffer *) lfirst(a))->nused;
int b2 = ((const TSCopyMultiInsertBuffer *) lfirst(b))->nused;
Assert(b1 >= 0);
Assert(b2 >= 0);
if (b1 > b2)
{
return 1;
}
if (b1 == b2)
{
return 0;
}
return -1;
}
/*
* Flush all buffers by writing the tuples to the chunks. In addition, trim down the
* amount of multi-insert buffers to MAX_PARTITION_BUFFERS by deleting the least used
* buffers (the buffers that store least tuples).
*/
static inline void
TSCopyMultiInsertInfoFlush(TSCopyMultiInsertInfo *miinfo, ChunkInsertState *cur_cis)
{
HASH_SEQ_STATUS status;
MultiInsertBufferEntry *entry;
int current_multi_insert_buffers;
int buffers_to_delete;
bool found;
int32 flushed_chunk_id;
List *buffer_list = NIL;
ListCell *lc;
current_multi_insert_buffers = hash_get_num_entries(miinfo->multiInsertBuffers);
int current_chunk_id = cur_cis ? cur_cis->chunk_id : 0;
/* Create a list of buffers that can be sorted by usage */
hash_seq_init(&status, miinfo->multiInsertBuffers);
for (entry = hash_seq_search(&status); entry != NULL; entry = hash_seq_search(&status))
{
buffer_list = lappend(buffer_list, entry->buffer);
}
buffers_to_delete = Max(current_multi_insert_buffers - MAX_PARTITION_BUFFERS, 0);
/* Sorting is only needed if we want to remove the least used buffers */
if (buffers_to_delete > 0)
{
list_sort(buffer_list, TSCmpBuffersByUsage);
}
/* Flush buffers and delete them if needed */
foreach (lc, buffer_list)
{
TSCopyMultiInsertBuffer *buffer = (TSCopyMultiInsertBuffer *) lfirst(lc);
flushed_chunk_id = TSCopyMultiInsertBufferFlush(miinfo, buffer);
if (buffers_to_delete > 0)
{
/*
* Reduce active multi-insert buffers. However, the current used buffer
* should not be deleted because it might reused for the next insert.
*/
if (current_chunk_id == 0 || flushed_chunk_id != current_chunk_id)
{
TSCopyMultiInsertBufferCleanup(miinfo, buffer);
hash_search(miinfo->multiInsertBuffers, &flushed_chunk_id, HASH_REMOVE, &found);
Assert(found);
buffers_to_delete--;
}
}
}
list_free(buffer_list);
/* All buffers have been flushed */
miinfo->bufferedTuples = 0;
miinfo->bufferedBytes = 0;
}
/*
* All existing buffers are flushed and the multi-insert states
* are freed. So, delete old hash map and create a new one for further
* inserts.
*/
static inline void
TSCopyMultiInsertInfoFlushAndCleanup(TSCopyMultiInsertInfo *miinfo)
{
TSCopyMultiInsertInfoFlush(miinfo, NULL);
HASH_SEQ_STATUS status;
MultiInsertBufferEntry *entry;
hash_seq_init(&status, miinfo->multiInsertBuffers);
for (entry = hash_seq_search(&status); entry != NULL; entry = hash_seq_search(&status))
{
TSCopyMultiInsertBuffer *buffer = entry->buffer;
TSCopyMultiInsertBufferCleanup(miinfo, buffer);
}
hash_destroy(miinfo->multiInsertBuffers);
}
/*
* Get the next TupleTableSlot that the next tuple should be stored in.
*
* Callers must ensure that the buffer is not full.
*
* Note: 'miinfo' is unused but has been included for consistency with the
* other functions in this area.
*/
static inline TupleTableSlot *
TSCopyMultiInsertInfoNextFreeSlot(TSCopyMultiInsertInfo *miinfo,
ResultRelInfo *result_relation_info,
TSCopyMultiInsertBuffer *buffer)
{
int nused = buffer->nused;
Assert(buffer != NULL);
Assert(nused < MAX_BUFFERED_TUPLES);
if (buffer->slots[nused] == NULL)
{
const TupleTableSlotOps *tts_cb =
table_slot_callbacks(result_relation_info->ri_RelationDesc);
buffer->slots[nused] = MakeSingleTupleTableSlot(buffer->tupdesc, tts_cb);
}
return buffer->slots[nused];
}
/*
* Record the previously reserved TupleTableSlot that was reserved by
* TSCopyMultiInsertInfoNextFreeSlot as being consumed.
*/
static inline void
TSCopyMultiInsertInfoStore(TSCopyMultiInsertInfo *miinfo, ResultRelInfo *rri,
TSCopyMultiInsertBuffer *buffer, TupleTableSlot *slot,
CopyFromState cstate)
{
Assert(buffer != NULL);
Assert(slot == buffer->slots[buffer->nused]);
/* Store the line number so we can properly report any errors later */
uint64 lineno = 0;
/* The structure CopyFromState is private in PG < 14. So we can not access
* the members like the line number or the size of the tuple.
*/
if (cstate != NULL)
{
lineno = cstate->cur_lineno;
}
buffer->linenos[buffer->nused] = lineno;
/* Record this slot as being used */
buffer->nused++;
/* Update how many tuples are stored and their size */
miinfo->bufferedTuples++;
/*
* Note: There is no reliable way to determine the in-memory size of a virtual
* tuple. So, we perform flushing in PG < 14 only based on the number of buffered
* tuples and not based on the size.
*/
if (cstate != NULL)
{
int tuplen = cstate->line_buf.len;
miinfo->bufferedBytes += tuplen;
}
}
static void
copy_chunk_state_destroy(CopyChunkState *ccstate)
{
ts_chunk_tuple_routing_destroy(ccstate->ctr);
FreeExecutorState(ccstate->estate);
}
static bool
next_copy_from(CopyChunkState *ccstate, ExprContext *econtext, Datum *values, bool *nulls)
{
Assert(ccstate->cstate != NULL);
return NextCopyFrom(ccstate->cstate, econtext, values, nulls);
}
/*
* Error context callback when copying from table to chunk.
*/
static void
copy_table_to_chunk_error_callback(void *arg)
{
TableScanDesc scandesc = (TableScanDesc) arg;
errcontext("copying from table %s", RelationGetRelationName(scandesc->rs_rd));
}
static TSCopyInsertMethod
choose_copy_method(Hypertable *ht, CopyChunkState *ccstate, ResultRelInfo *resultRelInfo)
{
if (!ts_guc_enable_optimizations)
{
ereport(DEBUG1,
(errmsg("Using normal unbuffered copy operation (TS_CIM_SINGLE) "
"because the optimizations are disabled.")));
return TS_CIM_SINGLE;
}
/*
* Multi-insert buffers (TS_CIM_MULTI_CONDITIONAL) can only be used if no triggers are
* defined on the target table. Otherwise, the tuples may be inserted in an out-of-order
* manner, which might violate the semantics of the triggers. So, they are inserted
* tuple-per-tuple (TS_CIM_SINGLE). However, the ts_block trigger on the hypertable can
* be ignored.
*/
/* Before INSERT Triggers */
bool has_before_insert_row_trig =
(resultRelInfo->ri_TrigDesc && resultRelInfo->ri_TrigDesc->trig_insert_before_row);
/* Instead of INSERT Triggers */
bool has_instead_insert_row_trig =
(resultRelInfo->ri_TrigDesc && resultRelInfo->ri_TrigDesc->trig_insert_instead_row);
bool has_after_insert_statement_trig =
(resultRelInfo->ri_TrigDesc && resultRelInfo->ri_TrigDesc->trig_insert_new_table);
/* Depending on the configured trigger, enable or disable the multi-insert buffers */
if (has_after_insert_statement_trig || has_before_insert_row_trig ||
has_instead_insert_row_trig)
{
ereport(DEBUG1,
(errmsg("Using normal unbuffered copy operation (TS_CIM_SINGLE) "
"because triggers are defined on the destination table.")));
if (ts_guc_enable_direct_compress_copy)
{
ereport(WARNING,
(errmsg("disabling direct compress copy due to presence of triggers on the "
"destination table")));
}
return TS_CIM_SINGLE;
}
if (TS_HYPERTABLE_HAS_COMPRESSION_ENABLED(ht) && ts_guc_enable_direct_compress_copy)
{
if (ts_indexing_relation_has_primary_or_unique_index(ccstate->rel))
{
ereport(WARNING,
(errmsg("disabling direct compress because the destination table has unique "
"constraints")));
}
else if (ts_indexing_relation_has_exclusion_constraint(ccstate->rel))
{
ereport(WARNING,
(errmsg("disabling direct compress because the destination table has exclusion "
"constraints")));
}
else if (resultRelInfo->ri_TrigDesc && resultRelInfo->ri_TrigDesc->numtriggers > 1)
{
ereport(WARNING,
(errmsg(
"disabling direct compress because the destination table has triggers")));
}
else
{
ccstate->ctr->create_compressed_chunk = true;
ereport(DEBUG1, (errmsg("Using compressed copy operation (TS_CIM_COMPRESSION).")));
return TS_CIM_COMPRESSION;
}
}
ereport(DEBUG1,
(errmsg("Using optimized multi-buffer copy operation (TS_CIM_MULTI_CONDITIONAL).")));
return TS_CIM_MULTI_CONDITIONAL;
}
/*
* Use COPY FROM to copy data from file to relation.
*/
static uint64
copyfrom(CopyChunkState *ccstate, ParseState *pstate, Hypertable *ht, MemoryContext copycontext,
void (*callback)(void *), void *arg)
{
ResultRelInfo *resultRelInfo;
ResultRelInfo *saved_resultRelInfo = NULL;
EState *estate = ccstate->estate; /* for ExecConstraints() */
ExprContext *econtext;
TupleTableSlot *singleslot;
MemoryContext oldcontext = CurrentMemoryContext;
ErrorContextCallback errcallback = {
.callback = callback,
.arg = arg,
};
CommandId mycid = GetCurrentCommandId(true);
TSCopyInsertMethod insertMethod; /* The insert method for the table */
TSCopyMultiInsertInfo multiInsertInfo = { 0 }; /* pacify compiler */
int ti_options = 0; /* start with default options for insert */
BulkInsertState bistate = NULL;
uint64 processed = 0;
ExprState *qualexpr = NULL;
Assert(pstate->p_rtable);
if (ccstate->rel->rd_rel->relkind != RELKIND_RELATION)
{
if (ccstate->rel->rd_rel->relkind == RELKIND_VIEW)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot copy to view \"%s\"", RelationGetRelationName(ccstate->rel))));
}
else if (ccstate->rel->rd_rel->relkind == RELKIND_MATVIEW)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot copy to materialized view \"%s\"",
RelationGetRelationName(ccstate->rel))));
}
else if (ccstate->rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot copy to foreign table \"%s\"",
RelationGetRelationName(ccstate->rel))));
}
else if (ccstate->rel->rd_rel->relkind == RELKIND_SEQUENCE)
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot copy to sequence \"%s\"",
RelationGetRelationName(ccstate->rel))));
}
else
{
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
errmsg("cannot copy to non-table relation \"%s\"",
RelationGetRelationName(ccstate->rel))));
}
}
/*----------
* Check to see if we can avoid writing WAL
*
* If archive logging/streaming is not enabled *and* either
* - table was created in same transaction as this COPY
* - data is being written to relfilenode created in this transaction
* then we can skip writing WAL. It's safe because if the transaction
* doesn't commit, we'll discard the table (or the new relfilenode file).
* If it does commit, we'll have done the heap_sync at the bottom of this
* routine first.
*
* As mentioned in comments in utils/rel.h, the in-same-transaction test
* is not always set correctly, since in rare cases rd_newRelfilenodeSubid
* can be cleared before the end of the transaction. The exact case is
* when a relation sets a new relfilenode twice in same transaction, yet
* the second one fails in an aborted subtransaction, e.g.
*
* BEGIN;
* TRUNCATE t;
* SAVEPOINT save;
* TRUNCATE t;
* ROLLBACK TO save;
* COPY ...
*
* Also, if the target file is new-in-transaction, we assume that checking
* FSM for free space is a waste of time, even if we must use WAL because
* of archiving. This could possibly be wrong, but it's unlikely.
*
* The comments for heap_insert and RelationGetBufferForTuple specify that
* skipping WAL logging is only safe if we ensure that our tuples do not
* go into pages containing tuples from any other transactions --- but this
* must be the case if we have a new table or new relfilenode, so we need
* no additional work to enforce that.
*----------
*/
/* createSubid is creation check, newRelfilenodeSubid is truncation check */
if (ccstate->rel->rd_createSubid != InvalidSubTransactionId ||
ccstate->rel->rd_newRelfilelocatorSubid != InvalidSubTransactionId)
{
ti_options |= HEAP_INSERT_SKIP_FSM;
}
/*
* We need a ResultRelInfo so we can use the regular executor's
* index-entry-making machinery. (There used to be a huge amount of code
* here that basically duplicated execUtils.c ...)
*
* WARNING. The dummy rangetable index is decremented by 1 (unchecked)
* inside `ExecConstraints` so unless you want to have a overflow, keep it
* above zero. See `rt_fetch` in parsetree.h.
*/
resultRelInfo = makeNode(ResultRelInfo);
#if PG18_LT
Assert(pstate->p_rteperminfos != NULL);
ExecInitRangeTable(estate, pstate->p_rtable, pstate->p_rteperminfos);
#else
/*
* PG18+ adds unpruned relids to ExecInitRangeTable
* We initialize it with 1 similar to upstream behavior,
* but since this is copy no pruning is expected to happen.
*/
Assert(pstate->p_rteperminfos != NULL);