forked from citusdata/cstore_fdw
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cstore_fdw.c
2414 lines (2055 loc) · 71.7 KB
/
cstore_fdw.c
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
/*-------------------------------------------------------------------------
*
* cstore_fdw.c
*
* This file contains the function definitions for scanning, analyzing, and
* copying into cstore_fdw foreign tables. Note that this file uses the API
* provided by cstore_reader and cstore_writer for reading and writing cstore
* files.
*
* Copyright (c) 2016, Citus Data, Inc.
*
* $Id$
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "cstore_fdw.h"
#include "cstore_version_compat.h"
#include <sys/stat.h>
#include <unistd.h>
#include <limits.h>
#include "access/htup_details.h"
#include "access/reloptions.h"
#include "access/sysattr.h"
#include "access/tuptoaster.h"
#include "catalog/namespace.h"
#include "catalog/pg_foreign_table.h"
#include "catalog/pg_namespace.h"
#include "commands/copy.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/explain.h"
#include "commands/extension.h"
#include "commands/vacuum.h"
#include "foreign/fdwapi.h"
#include "foreign/foreign.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "optimizer/cost.h"
#include "optimizer/pathnode.h"
#include "optimizer/planmain.h"
#include "optimizer/restrictinfo.h"
#if PG_VERSION_NUM >= 120000
#include "access/heapam.h"
#include "access/tableam.h"
#include "executor/tuptable.h"
#include "optimizer/optimizer.h"
#else
#include "optimizer/var.h"
#endif
#include "parser/parser.h"
#include "parser/parsetree.h"
#include "parser/parse_coerce.h"
#include "parser/parse_type.h"
#include "storage/fd.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
#if PG_VERSION_NUM >= 120000
#include "utils/snapmgr.h"
#else
#include "utils/tqual.h"
#endif
/* local functions forward declarations */
#if PG_VERSION_NUM >= 100000
static void CStoreProcessUtility(PlannedStmt *plannedStatement, const char *queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
QueryEnvironment *queryEnvironment,
DestReceiver *destReceiver, char *completionTag);
#else
static void CStoreProcessUtility(Node *parseTree, const char *queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
DestReceiver *destReceiver, char *completionTag);
#endif
static bool CopyCStoreTableStatement(CopyStmt* copyStatement);
static void CheckSuperuserPrivilegesForCopy(const CopyStmt* copyStatement);
static void CStoreProcessCopyCommand(CopyStmt *copyStatement, const char *queryString,
char *completionTag);
static uint64 CopyIntoCStoreTable(const CopyStmt *copyStatement,
const char *queryString);
static uint64 CopyOutCStoreTable(CopyStmt* copyStatement, const char* queryString);
static void CStoreProcessAlterTableCommand(AlterTableStmt *alterStatement);
static List * DroppedCStoreFilenameList(DropStmt *dropStatement);
static List * FindCStoreTables(List *tableList);
static List * OpenRelationsForTruncate(List *cstoreTableList);
static void TruncateCStoreTables(List *cstoreRelationList);
static void DeleteCStoreTableFiles(char *filename);
static void InitializeCStoreTableFile(Oid relationId, Relation relation);
static bool CStoreTable(Oid relationId);
static bool CStoreServer(ForeignServer *server);
static bool DistributedTable(Oid relationId);
static bool DistributedWorkerCopy(CopyStmt *copyStatement);
static void CreateCStoreDatabaseDirectory(Oid databaseOid);
static bool DirectoryExists(StringInfo directoryName);
static void CreateDirectory(StringInfo directoryName);
static void RemoveCStoreDatabaseDirectory(Oid databaseOid);
static StringInfo OptionNamesString(Oid currentContextId);
static HeapTuple GetSlotHeapTuple(TupleTableSlot *tts);
static CStoreFdwOptions * CStoreGetOptions(Oid foreignTableId);
static char * CStoreGetOptionValue(Oid foreignTableId, const char *optionName);
static void ValidateForeignTableOptions(char *filename, char *compressionTypeString,
char *stripeRowCountString,
char *blockRowCountString);
static char * CStoreDefaultFilePath(Oid foreignTableId);
static CompressionType ParseCompressionType(const char *compressionTypeString);
static void CStoreGetForeignRelSize(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId);
static void CStoreGetForeignPaths(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId);
#if PG_VERSION_NUM >= 90500
static ForeignScan * CStoreGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId, ForeignPath *bestPath,
List *targetList, List *scanClauses,
Plan *outerPlan);
#else
static ForeignScan * CStoreGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId, ForeignPath *bestPath,
List *targetList, List *scanClauses);
#endif
static double TupleCountEstimate(RelOptInfo *baserel, const char *filename);
static BlockNumber PageCount(const char *filename);
static List * ColumnList(RelOptInfo *baserel, Oid foreignTableId);
static void CStoreExplainForeignScan(ForeignScanState *scanState,
ExplainState *explainState);
static void CStoreBeginForeignScan(ForeignScanState *scanState, int executorFlags);
static TupleTableSlot * CStoreIterateForeignScan(ForeignScanState *scanState);
static void CStoreEndForeignScan(ForeignScanState *scanState);
static void CStoreReScanForeignScan(ForeignScanState *scanState);
static bool CStoreAnalyzeForeignTable(Relation relation,
AcquireSampleRowsFunc *acquireSampleRowsFunc,
BlockNumber *totalPageCount);
static int CStoreAcquireSampleRows(Relation relation, int logLevel,
HeapTuple *sampleRows, int targetRowCount,
double *totalRowCount, double *totalDeadRowCount);
static List * CStorePlanForeignModify(PlannerInfo *plannerInfo, ModifyTable *plan,
Index resultRelation, int subplanIndex);
static void CStoreBeginForeignModify(ModifyTableState *modifyTableState,
ResultRelInfo *relationInfo, List *fdwPrivate,
int subplanIndex, int executorflags);
static void CStoreBeginForeignInsert(ModifyTableState *modifyTableState,
ResultRelInfo *relationInfo);
static TupleTableSlot * CStoreExecForeignInsert(EState *executorState,
ResultRelInfo *relationInfo,
TupleTableSlot *tupleSlot,
TupleTableSlot *planSlot);
static void CStoreEndForeignModify(EState *executorState, ResultRelInfo *relationInfo);
static void CStoreEndForeignInsert(EState *executorState, ResultRelInfo *relationInfo);
#if PG_VERSION_NUM >= 90600
static bool CStoreIsForeignScanParallelSafe(PlannerInfo *root, RelOptInfo *rel,
RangeTblEntry *rte);
#endif
/* declarations for dynamic loading */
PG_MODULE_MAGIC;
PG_FUNCTION_INFO_V1(cstore_ddl_event_end_trigger);
PG_FUNCTION_INFO_V1(cstore_table_size);
PG_FUNCTION_INFO_V1(cstore_fdw_handler);
PG_FUNCTION_INFO_V1(cstore_fdw_validator);
PG_FUNCTION_INFO_V1(cstore_clean_table_resources);
/* saved hook value in case of unload */
static ProcessUtility_hook_type PreviousProcessUtilityHook = NULL;
/*
* _PG_init is called when the module is loaded. In this function we save the
* previous utility hook, and then install our hook to pre-intercept calls to
* the copy command.
*/
void _PG_init(void)
{
PreviousProcessUtilityHook = ProcessUtility_hook;
ProcessUtility_hook = CStoreProcessUtility;
}
/*
* _PG_fini is called when the module is unloaded. This function uninstalls the
* extension's hooks.
*/
void _PG_fini(void)
{
ProcessUtility_hook = PreviousProcessUtilityHook;
}
/*
* cstore_ddl_event_end_trigger is the event trigger function which is called on
* ddl_command_end event. This function creates required directories after the
* CREATE SERVER statement and valid data and footer files after the CREATE FOREIGN
* TABLE statement.
*/
Datum
cstore_ddl_event_end_trigger(PG_FUNCTION_ARGS)
{
EventTriggerData *triggerData = NULL;
Node *parseTree = NULL;
/* error if event trigger manager did not call this function */
if (!CALLED_AS_EVENT_TRIGGER(fcinfo))
{
ereport(ERROR, (errmsg("trigger not fired by event trigger manager")));
}
triggerData = (EventTriggerData *) fcinfo->context;
parseTree = triggerData->parsetree;
if (nodeTag(parseTree) == T_CreateForeignServerStmt)
{
CreateForeignServerStmt *serverStatement = (CreateForeignServerStmt *) parseTree;
char *foreignWrapperName = serverStatement->fdwname;
if (strncmp(foreignWrapperName, CSTORE_FDW_NAME, NAMEDATALEN) == 0)
{
CreateCStoreDatabaseDirectory(MyDatabaseId);
}
}
else if (nodeTag(parseTree) == T_CreateForeignTableStmt)
{
CreateForeignTableStmt *createStatement = (CreateForeignTableStmt *) parseTree;
char *serverName = createStatement->servername;
bool missingOK = false;
ForeignServer *server = GetForeignServerByName(serverName, missingOK);
if (CStoreServer(server))
{
Oid relationId = RangeVarGetRelid(createStatement->base.relation,
AccessShareLock, false);
Relation relation = heap_open(relationId, AccessExclusiveLock);
/*
* Make sure database directory exists before creating a table.
* This is necessary when a foreign server is created inside
* a template database and a new database is created out of it.
* We have no chance to hook into server creation to create data
* directory for it during database creation time.
*/
CreateCStoreDatabaseDirectory(MyDatabaseId);
InitializeCStoreTableFile(relationId, relation);
heap_close(relation, AccessExclusiveLock);
}
}
PG_RETURN_NULL();
}
/*
* CStoreProcessUtility is the hook for handling utility commands. This function
* customizes the behaviour of "COPY cstore_table" and "DROP FOREIGN TABLE
* cstore_table" commands. For all other utility statements, the function calls
* the previous utility hook or the standard utility command via macro
* CALL_PREVIOUS_UTILITY.
*/
#if PG_VERSION_NUM >= 100000
static void
CStoreProcessUtility(PlannedStmt *plannedStatement, const char *queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
QueryEnvironment *queryEnvironment,
DestReceiver *destReceiver, char *completionTag)
#else
static void
CStoreProcessUtility(Node * parseTree, const char *queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
DestReceiver *destReceiver, char *completionTag)
#endif
{
#if PG_VERSION_NUM >= 100000
Node *parseTree = plannedStatement->utilityStmt;
#endif
if (nodeTag(parseTree) == T_CopyStmt)
{
CopyStmt *copyStatement = (CopyStmt *) parseTree;
if (CopyCStoreTableStatement(copyStatement))
{
CStoreProcessCopyCommand(copyStatement, queryString, completionTag);
}
else
{
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
}
}
else if (nodeTag(parseTree) == T_DropStmt)
{
DropStmt *dropStmt = (DropStmt *) parseTree;
if (dropStmt->removeType == OBJECT_EXTENSION)
{
bool removeCStoreDirectory = false;
ListCell *objectCell = NULL;
foreach(objectCell, dropStmt->objects)
{
Node *object = (Node *) lfirst(objectCell);
char *objectName = NULL;
#if PG_VERSION_NUM >= 100000
Assert(IsA(object, String));
objectName = strVal(object);
#else
Assert(IsA(object, List));
objectName = strVal(linitial((List *) object));
#endif
if (strncmp(CSTORE_FDW_NAME, objectName, NAMEDATALEN) == 0)
{
removeCStoreDirectory = true;
}
}
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
if (removeCStoreDirectory)
{
RemoveCStoreDatabaseDirectory(MyDatabaseId);
}
}
else
{
ListCell *fileListCell = NULL;
List *droppedTables = DroppedCStoreFilenameList((DropStmt *) parseTree);
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
foreach(fileListCell, droppedTables)
{
char *fileName = lfirst(fileListCell);
DeleteCStoreTableFiles(fileName);
}
}
}
else if (nodeTag(parseTree) == T_TruncateStmt)
{
TruncateStmt *truncateStatement = (TruncateStmt *) parseTree;
List *allTablesList = truncateStatement->relations;
List *cstoreTablesList = FindCStoreTables(allTablesList);
List *otherTablesList = list_difference(allTablesList, cstoreTablesList);
List *cstoreRelationList = OpenRelationsForTruncate(cstoreTablesList);
ListCell *cstoreRelationCell = NULL;
if (otherTablesList != NIL)
{
truncateStatement->relations = otherTablesList;
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
/* restore the former relation list. Our
* replacement could be freed but still needed
* in a cached plan. A truncate can be cached
* if run from a pl/pgSQL function */
truncateStatement->relations = allTablesList;
}
TruncateCStoreTables(cstoreRelationList);
foreach(cstoreRelationCell, cstoreRelationList)
{
Relation relation = (Relation) lfirst(cstoreRelationCell);
heap_close(relation, AccessExclusiveLock);
}
}
else if (nodeTag(parseTree) == T_AlterTableStmt)
{
AlterTableStmt *alterTable = (AlterTableStmt *) parseTree;
CStoreProcessAlterTableCommand(alterTable);
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
}
else if (nodeTag(parseTree) == T_DropdbStmt)
{
DropdbStmt *dropDdStmt = (DropdbStmt *) parseTree;
bool missingOk = true;
Oid databaseOid = get_database_oid(dropDdStmt->dbname, missingOk);
/* let postgres handle error checking and dropping of the database */
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
if (databaseOid != InvalidOid)
{
RemoveCStoreDatabaseDirectory(databaseOid);
}
}
/* handle other utility statements */
else
{
CALL_PREVIOUS_UTILITY(parseTree, queryString, context, paramListInfo,
destReceiver, completionTag);
}
}
/*
* CopyCStoreTableStatement check whether the COPY statement is a "COPY cstore_table FROM
* ..." or "COPY cstore_table TO ...." statement. If it is then the function returns
* true. The function returns false otherwise.
*/
static bool
CopyCStoreTableStatement(CopyStmt* copyStatement)
{
bool copyCStoreTableStatement = false;
if (copyStatement->relation != NULL)
{
Oid relationId = RangeVarGetRelid(copyStatement->relation,
AccessShareLock, true);
bool cstoreTable = CStoreTable(relationId);
if (cstoreTable)
{
bool distributedTable = DistributedTable(relationId);
bool distributedCopy = DistributedWorkerCopy(copyStatement);
if (distributedTable || distributedCopy)
{
/* let COPY on distributed tables fall through to Citus */
copyCStoreTableStatement = false;
}
else
{
copyCStoreTableStatement = true;
}
}
}
return copyCStoreTableStatement;
}
/*
* CheckSuperuserPrivilegesForCopy checks if superuser privilege is required by
* copy operation and reports error if user does not have superuser rights.
*/
static void
CheckSuperuserPrivilegesForCopy(const CopyStmt* copyStatement)
{
/*
* We disallow copy from file or program except to superusers. These checks
* are based on the checks in DoCopy() function of copy.c.
*/
if (copyStatement->filename != NULL && !superuser())
{
if (copyStatement->is_program)
{
ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to COPY to or from a program"),
errhint("Anyone can COPY to stdout or from stdin. "
"psql's \\copy command also works for anyone.")));
}
else
{
ereport(ERROR, (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
errmsg("must be superuser to COPY to or from a file"),
errhint("Anyone can COPY to stdout or from stdin. "
"psql's \\copy command also works for anyone.")));
}
}
}
/*
* CStoreProcessCopyCommand handles COPY <cstore_table> FROM/TO ... statements.
* It determines the copy direction and forwards execution to appropriate function.
*/
static void
CStoreProcessCopyCommand(CopyStmt *copyStatement, const char* queryString,
char *completionTag)
{
uint64 processedCount = 0;
if (copyStatement->is_from)
{
processedCount = CopyIntoCStoreTable(copyStatement, queryString);
}
else
{
processedCount = CopyOutCStoreTable(copyStatement, queryString);
}
if (completionTag != NULL)
{
snprintf(completionTag, COMPLETION_TAG_BUFSIZE, "COPY " UINT64_FORMAT,
processedCount);
}
}
/*
* CopyIntoCStoreTable handles a "COPY cstore_table FROM" statement. This
* function uses the COPY command's functions to read and parse rows from
* the data source specified in the COPY statement. The function then writes
* each row to the file specified in the cstore foreign table options. Finally,
* the function returns the number of copied rows.
*/
static uint64
CopyIntoCStoreTable(const CopyStmt *copyStatement, const char *queryString)
{
uint64 processedRowCount = 0;
Relation relation = NULL;
Oid relationId = InvalidOid;
TupleDesc tupleDescriptor = NULL;
uint32 columnCount = 0;
CopyState copyState = NULL;
bool nextRowFound = true;
Datum *columnValues = NULL;
bool *columnNulls = NULL;
TableWriteState *writeState = NULL;
CStoreFdwOptions *cstoreFdwOptions = NULL;
MemoryContext tupleContext = NULL;
/* Only superuser can copy from or to local file */
CheckSuperuserPrivilegesForCopy(copyStatement);
Assert(copyStatement->relation != NULL);
/*
* Open and lock the relation. We acquire ShareUpdateExclusiveLock to allow
* concurrent reads, but block concurrent writes.
*/
relation = heap_openrv(copyStatement->relation, ShareUpdateExclusiveLock);
relationId = RelationGetRelid(relation);
/* allocate column values and nulls arrays */
tupleDescriptor = RelationGetDescr(relation);
columnCount = tupleDescriptor->natts;
columnValues = palloc0(columnCount * sizeof(Datum));
columnNulls = palloc0(columnCount * sizeof(bool));
cstoreFdwOptions = CStoreGetOptions(relationId);
/*
* We create a new memory context called tuple context, and read and write
* each row's values within this memory context. After each read and write,
* we reset the memory context. That way, we immediately release memory
* allocated for each row, and don't bloat memory usage with large input
* files.
*/
tupleContext = AllocSetContextCreate(CurrentMemoryContext,
"CStore COPY Row Memory Context",
ALLOCSET_DEFAULT_SIZES);
/* init state to read from COPY data source */
#if (PG_VERSION_NUM >= 100000)
{
ParseState *pstate = make_parsestate(NULL);
pstate->p_sourcetext = queryString;
copyState = BeginCopyFrom(pstate, relation, copyStatement->filename,
copyStatement->is_program,
NULL,
copyStatement->attlist,
copyStatement->options);
free_parsestate(pstate);
}
#else
copyState = BeginCopyFrom(relation, copyStatement->filename,
copyStatement->is_program,
copyStatement->attlist,
copyStatement->options);
#endif
/* init state to write to the cstore file */
writeState = CStoreBeginWrite(cstoreFdwOptions->filename,
cstoreFdwOptions->compressionType,
cstoreFdwOptions->stripeRowCount,
cstoreFdwOptions->blockRowCount,
tupleDescriptor);
while (nextRowFound)
{
/* read the next row in tupleContext */
MemoryContext oldContext = MemoryContextSwitchTo(tupleContext);
#if PG_VERSION_NUM >= 120000
nextRowFound = NextCopyFrom(copyState, NULL, columnValues, columnNulls);
#else
nextRowFound = NextCopyFrom(copyState, NULL, columnValues, columnNulls, NULL);
#endif
MemoryContextSwitchTo(oldContext);
/* write the row to the cstore file */
if (nextRowFound)
{
CStoreWriteRow(writeState, columnValues, columnNulls);
processedRowCount++;
}
MemoryContextReset(tupleContext);
CHECK_FOR_INTERRUPTS();
}
/* end read/write sessions and close the relation */
EndCopyFrom(copyState);
CStoreEndWrite(writeState);
heap_close(relation, ShareUpdateExclusiveLock);
return processedRowCount;
}
/*
* CopyFromCStoreTable handles a "COPY cstore_table TO ..." statement. Statement
* is converted to "COPY (SELECT * FROM cstore_table) TO ..." and forwarded to
* postgres native COPY handler. Function returns number of files copied to external
* stream. Copying selected columns from cstore table is not currently supported.
*/
static uint64
CopyOutCStoreTable(CopyStmt* copyStatement, const char* queryString)
{
uint64 processedCount = 0;
RangeVar *relation = NULL;
char *qualifiedName = NULL;
List *queryList = NIL;
Node *rawQuery = NULL;
StringInfo newQuerySubstring = makeStringInfo();
if (copyStatement->attlist != NIL)
{
ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("copy column list is not supported"),
errhint("use 'copy (select <columns> from <table>) to "
"...' instead")));
}
relation = copyStatement->relation;
qualifiedName = quote_qualified_identifier(relation->schemaname,
relation->relname);
appendStringInfo(newQuerySubstring, "select * from %s", qualifiedName);
queryList = raw_parser(newQuerySubstring->data);
/* take the first parse tree */
rawQuery = linitial(queryList);
/*
* Set the relation field to NULL so that COPY command works on
* query field instead.
*/
copyStatement->relation = NULL;
#if (PG_VERSION_NUM >= 100000)
/*
* raw_parser returns list of RawStmt* in PG 10+ we need to
* extract actual query from it.
*/
{
ParseState *pstate = make_parsestate(NULL);
RawStmt *rawStatement = (RawStmt *) rawQuery;
pstate->p_sourcetext = newQuerySubstring->data;
copyStatement->query = rawStatement->stmt;
DoCopy(pstate, copyStatement, -1, -1, &processedCount);
free_parsestate(pstate);
}
#else
copyStatement->query = rawQuery;
DoCopy(copyStatement, queryString, &processedCount);
#endif
return processedCount;
}
/*
* CStoreProcessAlterTableCommand checks if given alter table statement is
* compatible with underlying data structure. Currently it only checks alter
* column type. The function errors out if current column type can not be safely
* converted to requested column type. This check is more restrictive than
* PostgreSQL's because we can not change existing data.
*/
static void
CStoreProcessAlterTableCommand(AlterTableStmt *alterStatement)
{
ObjectType objectType = alterStatement->relkind;
RangeVar *relationRangeVar = alterStatement->relation;
Oid relationId = InvalidOid;
List *commandList = alterStatement->cmds;
ListCell *commandCell = NULL;
/* we are only interested in foreign table changes */
if (objectType != OBJECT_TABLE && objectType != OBJECT_FOREIGN_TABLE)
{
return;
}
relationId = RangeVarGetRelid(relationRangeVar, AccessShareLock, true);
if (!CStoreTable(relationId))
{
return;
}
foreach(commandCell, commandList)
{
AlterTableCmd *alterCommand = (AlterTableCmd *) lfirst(commandCell);
if(alterCommand->subtype == AT_AlterColumnType)
{
char *columnName = alterCommand->name;
ColumnDef *columnDef = (ColumnDef *) alterCommand->def;
Oid targetTypeId = typenameTypeId(NULL, columnDef->typeName);
char *typeName = TypeNameToString(columnDef->typeName);
AttrNumber attributeNumber = get_attnum(relationId, columnName);
Oid currentTypeId = InvalidOid;
if (attributeNumber <= 0)
{
/* let standard utility handle this */
continue;
}
currentTypeId = get_atttype(relationId, attributeNumber);
/*
* We are only interested in implicit coersion type compatibility.
* Erroring out here to prevent further processing.
*/
if (!can_coerce_type(1, ¤tTypeId, &targetTypeId, COERCION_IMPLICIT))
{
ereport(ERROR, (errmsg("Column %s cannot be cast automatically to "
"type %s", columnName, typeName)));
}
}
}
}
/*
* DropppedCStoreFilenameList extracts and returns the list of cstore file names
* from DROP table statement
*/
static List *
DroppedCStoreFilenameList(DropStmt *dropStatement)
{
List *droppedCStoreFileList = NIL;
if (dropStatement->removeType == OBJECT_FOREIGN_TABLE)
{
ListCell *dropObjectCell = NULL;
foreach(dropObjectCell, dropStatement->objects)
{
List *tableNameList = (List *) lfirst(dropObjectCell);
RangeVar *rangeVar = makeRangeVarFromNameList(tableNameList);
Oid relationId = RangeVarGetRelid(rangeVar, AccessShareLock, true);
if (CStoreTable(relationId))
{
CStoreFdwOptions *cstoreFdwOptions = CStoreGetOptions(relationId);
char *defaultfilename = CStoreDefaultFilePath(relationId);
/*
* Skip files that are placed in default location, they are handled
* by sql drop trigger. Both paths are generated by code, use
* of strcmp is safe here.
*/
if (strcmp(defaultfilename, cstoreFdwOptions->filename) == 0)
{
continue;
}
droppedCStoreFileList = lappend(droppedCStoreFileList,
cstoreFdwOptions->filename);
}
}
}
return droppedCStoreFileList;
}
/* FindCStoreTables returns list of CStore tables from given table list */
static List *
FindCStoreTables(List *tableList)
{
List *cstoreTableList = NIL;
ListCell *relationCell = NULL;
foreach(relationCell, tableList)
{
RangeVar *rangeVar = (RangeVar *) lfirst(relationCell);
Oid relationId = RangeVarGetRelid(rangeVar, AccessShareLock, true);
if (CStoreTable(relationId) && !DistributedTable(relationId))
{
cstoreTableList = lappend(cstoreTableList, rangeVar);
}
}
return cstoreTableList;
}
/*
* OpenRelationsForTruncate opens and locks relations for tables to be truncated.
*
* It also performs a permission checks to see if the user has truncate privilege
* on tables.
*/
static List *
OpenRelationsForTruncate(List *cstoreTableList)
{
ListCell *relationCell = NULL;
List *relationIdList = NIL;
List *relationList = NIL;
foreach(relationCell, cstoreTableList)
{
RangeVar *rangeVar = (RangeVar *) lfirst(relationCell);
Relation relation = heap_openrv(rangeVar, AccessExclusiveLock);
Oid relationId = relation->rd_id;
AclResult aclresult = pg_class_aclcheck(relationId, GetUserId(),
ACL_TRUNCATE);
if (aclresult != ACLCHECK_OK)
{
aclcheck_error(aclresult, ACLCHECK_OBJECT_TABLE, get_rel_name(relationId));
}
/* check if this relation is repeated */
if (list_member_oid(relationIdList, relationId))
{
heap_close(relation, AccessExclusiveLock);
}
else
{
relationIdList = lappend_oid(relationIdList, relationId);
relationList = lappend(relationList, relation);
}
}
return relationList;
}
/* TruncateCStoreTable truncates given cstore tables */
static void
TruncateCStoreTables(List *cstoreRelationList)
{
ListCell *relationCell = NULL;
foreach(relationCell, cstoreRelationList)
{
Relation relation = (Relation) lfirst(relationCell);
Oid relationId = relation->rd_id;
CStoreFdwOptions *cstoreFdwOptions = NULL;
Assert(CStoreTable(relationId));
cstoreFdwOptions = CStoreGetOptions(relationId);
DeleteCStoreTableFiles(cstoreFdwOptions->filename);
InitializeCStoreTableFile(relationId, relation);
}
}
/*
* DeleteCStoreTableFiles deletes the data and footer files for a cstore table
* whose data filename is given.
*/
static void
DeleteCStoreTableFiles(char *filename)
{
int dataFileRemoved = 0;
int footerFileRemoved = 0;
StringInfo tableFooterFilename = makeStringInfo();
appendStringInfo(tableFooterFilename, "%s%s", filename, CSTORE_FOOTER_FILE_SUFFIX);
/* delete the footer file */
footerFileRemoved = unlink(tableFooterFilename->data);
if (footerFileRemoved != 0)
{
ereport(WARNING, (errcode_for_file_access(),
errmsg("could not delete file \"%s\": %m",
tableFooterFilename->data)));
}
/* delete the data file */
dataFileRemoved = unlink(filename);
if (dataFileRemoved != 0)
{
ereport(WARNING, (errcode_for_file_access(),
errmsg("could not delete file \"%s\": %m",
filename)));
}
}
/*
* InitializeCStoreTableFile creates data and footer file for a cstore table.
* The function assumes data and footer files do not exist, therefore
* it should be called on empty or non-existing table. Notice that the caller
* is expected to acquire AccessExclusiveLock on the relation.
*/
static void InitializeCStoreTableFile(Oid relationId, Relation relation)
{
TableWriteState *writeState = NULL;
TupleDesc tupleDescriptor = RelationGetDescr(relation);
CStoreFdwOptions* cstoreFdwOptions = CStoreGetOptions(relationId);
/*
* Initialize state to write to the cstore file. This creates an
* empty data file and a valid footer file for the table.
*/
writeState = CStoreBeginWrite(cstoreFdwOptions->filename,
cstoreFdwOptions->compressionType, cstoreFdwOptions->stripeRowCount,
cstoreFdwOptions->blockRowCount, tupleDescriptor);
CStoreEndWrite(writeState);
}
/*
* CStoreTable checks if the given table name belongs to a foreign columnar store
* table. If it does, the function returns true. Otherwise, it returns false.
*/
static bool
CStoreTable(Oid relationId)
{
bool cstoreTable = false;
char relationKind = 0;
if (relationId == InvalidOid)
{
return false;
}
relationKind = get_rel_relkind(relationId);
if (relationKind == RELKIND_FOREIGN_TABLE)
{
ForeignTable *foreignTable = GetForeignTable(relationId);
ForeignServer *server = GetForeignServer(foreignTable->serverid);
if (CStoreServer(server))
{
cstoreTable = true;
}
}
return cstoreTable;
}
/*
* CStoreServer checks if the given foreign server belongs to cstore_fdw. If it
* does, the function returns true. Otherwise, it returns false.
*/
static bool
CStoreServer(ForeignServer *server)
{
ForeignDataWrapper *foreignDataWrapper = GetForeignDataWrapper(server->fdwid);
bool cstoreServer = false;
char *foreignWrapperName = foreignDataWrapper->fdwname;
if (strncmp(foreignWrapperName, CSTORE_FDW_NAME, NAMEDATALEN) == 0)
{
cstoreServer = true;
}
return cstoreServer;
}
/*
* DistributedTable checks if the given relationId is the OID of a distributed table,
* which may also be a cstore_fdw table, but in that case COPY should be handled by
* Citus.
*/
static bool
DistributedTable(Oid relationId)
{
bool distributedTable = false;
Oid partitionOid = InvalidOid;
Relation heapRelation = NULL;
TableScanDesc scanDesc = NULL;
const int scanKeyCount = 1;
ScanKeyData scanKey[1];
HeapTuple heapTuple = NULL;
bool missingOK = true;
Oid extensionOid = get_extension_oid(CITUS_EXTENSION_NAME, missingOK);
if (extensionOid == InvalidOid)
{
/* if the citus extension isn't created, no tables are distributed */
return false;
}