forked from citusdata/cstore_fdw
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcstore_fdw.c
1765 lines (1491 loc) · 53.5 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) 2015, Citus Data, Inc.
*
* $Id$
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "cstore_fdw.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 "commands/copy.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/explain.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"
#include "optimizer/var.h"
#include "parser/parser.h"
#include "parser/parsetree.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/lsyscache.h"
#include "utils/rel.h"
/* local functions forward declarations */
static void CStoreProcessUtility(Node *parseTree, const char *queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
DestReceiver *destReceiver, char *completionTag);
static void CallPreviousProcessUtility(Node* parseTree, const char* queryString,
ProcessUtilityContext context,
ParamListInfo paramListInfo,
DestReceiver* destReceiver, char* completionTag);
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 List * DroppedCStoreFilenameList(DropStmt *dropStatement);
static void DeleteCStoreTableFiles(char *filename);
static bool CStoreTable(Oid relationId);
static void CreateCStoreDatabaseDirectory(Oid databaseOid);
static bool DirectoryExists(StringInfo directoryName);
static void CreateDirectory(StringInfo directoryName);
static StringInfo OptionNamesString(Oid currentContextId);
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);
static ForeignScan * CStoreGetForeignPlan(PlannerInfo *root, RelOptInfo *baserel,
Oid foreignTableId, ForeignPath *bestPath,
List *targetList, List *scanClauses);
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 TupleTableSlot * CStoreExecForeignInsert(EState *executorState,
ResultRelInfo *relationInfo,
TupleTableSlot *tupleSlot,
TupleTableSlot *planSlot);
static void CStoreEndForeignModify(EState *executorState, ResultRelInfo *relationInfo);
/* 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);
/* 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;
Oid relationId = RangeVarGetRelid(createStatement->base.relation,
AccessShareLock, false);
if (CStoreTable(relationId))
{
TableWriteState *writeState = NULL;
Relation relation = heap_open(relationId, ExclusiveLock);
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);
heap_close(relation, ExclusiveLock);
}
}
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.
*/
static void
CStoreProcessUtility(Node *parseTree, const char *queryString,
ProcessUtilityContext context, ParamListInfo paramListInfo,
DestReceiver *destReceiver, char *completionTag)
{
if (nodeTag(parseTree) == T_CopyStmt)
{
CopyStmt *copyStatement = (CopyStmt *) parseTree;
if (CopyCStoreTableStatement(copyStatement))
{
CStoreProcessCopyCommand(copyStatement, queryString, completionTag);
}
else
{
CallPreviousProcessUtility(parseTree, queryString, context,
paramListInfo, destReceiver, completionTag);
}
}
else if (nodeTag(parseTree) == T_DropStmt)
{
ListCell *fileListCell = NULL;
List *droppedTables = DroppedCStoreFilenameList((DropStmt*) parseTree);
CallPreviousProcessUtility(parseTree, queryString, context,
paramListInfo, destReceiver, completionTag);
foreach(fileListCell, droppedTables)
{
char *fileName = lfirst(fileListCell);
DeleteCStoreTableFiles(fileName);
}
}
/* handle other utility statements */
else
{
CallPreviousProcessUtility(parseTree, queryString, context,
paramListInfo, destReceiver, completionTag);
}
}
/*
* CallPreviousProcessUtility calls the previously registered utility hook. If no
* utility hook is registered, it calls the standard process utility handler.
*/
static void
CallPreviousProcessUtility(Node* parseTree, const char* queryString,
ProcessUtilityContext context, ParamListInfo paramListInfo,
DestReceiver* destReceiver, char* completionTag)
{
if (PreviousProcessUtilityHook != NULL)
{
PreviousProcessUtilityHook(parseTree, queryString, context,
paramListInfo, destReceiver, completionTag);
}
else
{
standard_ProcessUtility(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, false);
copyCStoreTableStatement = CStoreTable(relationId);
}
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_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
/* init state to read from COPY data source */
copyState = BeginCopyFrom(relation, copyStatement->filename,
copyStatement->is_program,
copyStatement->attlist,
copyStatement->options);
/* 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);
nextRowFound = NextCopyFrom(copyState, NULL, columnValues, columnNulls, NULL);
MemoryContextSwitchTo(oldContext);
/* write the row to the cstore file */
if (nextRowFound)
{
CStoreWriteRow(writeState, columnValues, columnNulls);
processedRowCount++;
}
MemoryContextReset(tupleContext);
}
/* 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;
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 */
copyStatement->query = linitial(queryList);
/*
* Set the relation field to NULL so that COPY command works on
* query field instead.
*/
copyStatement->relation = NULL;
DoCopy(copyStatement, queryString, &processedCount);
return processedCount;
}
/*
* 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);
droppedCStoreFileList = lappend(droppedCStoreFileList,
cstoreFdwOptions->filename);
}
}
}
return droppedCStoreFileList;
}
/*
* 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)));
}
}
/*
* 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);
ForeignDataWrapper *foreignDataWrapper = GetForeignDataWrapper(server->fdwid);
char *foreignWrapperName = foreignDataWrapper->fdwname;
if (strncmp(foreignWrapperName, CSTORE_FDW_NAME, NAMEDATALEN) == 0)
{
cstoreTable = true;
}
}
return cstoreTable;
}
/*
* CreateCStoreDatabaseDirectory creates the directory (and parent directories,
* if needed) used to store automatically managed cstore_fdw files. The path to
* the directory is $PGDATA/cstore_fdw/{databaseOid}.
*/
static void
CreateCStoreDatabaseDirectory(Oid databaseOid)
{
bool cstoreDirectoryExists = false;
bool databaseDirectoryExists = false;
StringInfo cstoreDatabaseDirectoryPath = NULL;
StringInfo cstoreDirectoryPath = makeStringInfo();
appendStringInfo(cstoreDirectoryPath, "%s/%s", DataDir, CSTORE_FDW_NAME);
cstoreDirectoryExists = DirectoryExists(cstoreDirectoryPath);
if (!cstoreDirectoryExists)
{
CreateDirectory(cstoreDirectoryPath);
}
cstoreDatabaseDirectoryPath = makeStringInfo();
appendStringInfo(cstoreDatabaseDirectoryPath, "%s/%s/%u", DataDir,
CSTORE_FDW_NAME, databaseOid);
databaseDirectoryExists = DirectoryExists(cstoreDatabaseDirectoryPath);
if (!databaseDirectoryExists)
{
CreateDirectory(cstoreDatabaseDirectoryPath);
}
}
/* DirectoryExists checks if a directory exists for the given directory name. */
static bool
DirectoryExists(StringInfo directoryName)
{
bool directoryExists = true;
struct stat directoryStat;
int statOK = stat(directoryName->data, &directoryStat);
if (statOK == 0)
{
/* file already exists; check that it is a directory */
if (!S_ISDIR(directoryStat.st_mode))
{
ereport(ERROR, (errmsg("\"%s\" is not a directory", directoryName->data),
errhint("You need to remove or rename the file \"%s\".",
directoryName->data)));
}
}
else
{
if (errno == ENOENT)
{
directoryExists = false;
}
else
{
ereport(ERROR, (errcode_for_file_access(),
errmsg("could not stat directory \"%s\": %m",
directoryName->data)));
}
}
return directoryExists;
}
/* CreateDirectory creates a new directory with the given directory name. */
static void
CreateDirectory(StringInfo directoryName)
{
int makeOK = mkdir(directoryName->data, S_IRWXU);
if (makeOK != 0)
{
ereport(ERROR, (errcode_for_file_access(),
errmsg("could not create directory \"%s\": %m",
directoryName->data)));
}
}
/*
* cstore_table_size returns the total on-disk size of a cstore table in bytes.
* The result includes the sizes of data file and footer file.
*/
Datum
cstore_table_size(PG_FUNCTION_ARGS)
{
Oid relationId = PG_GETARG_OID(0);
int64 tableSize = 0;
CStoreFdwOptions *cstoreFdwOptions = NULL;
char *dataFilename = NULL;
StringInfo footerFilename = NULL;
int dataFileStatResult = 0;
int footerFileStatResult = 0;
struct stat dataFileStatBuffer;
struct stat footerFileStatBuffer;
bool cstoreTable = CStoreTable(relationId);
if (!cstoreTable)
{
ereport(ERROR, (errmsg("relation is not a cstore table")));
}
cstoreFdwOptions = CStoreGetOptions(relationId);
dataFilename = cstoreFdwOptions->filename;
dataFileStatResult = stat(dataFilename, &dataFileStatBuffer);
if (dataFileStatResult != 0)
{
ereport(ERROR, (errcode_for_file_access(),
errmsg("could not stat file \"%s\": %m", dataFilename)));
}
footerFilename = makeStringInfo();
appendStringInfo(footerFilename, "%s%s", dataFilename,
CSTORE_FOOTER_FILE_SUFFIX);
footerFileStatResult = stat(footerFilename->data, &footerFileStatBuffer);
if (footerFileStatResult != 0)
{
ereport(ERROR, (errcode_for_file_access(),
errmsg("could not stat file \"%s\": %m",
footerFilename->data)));
}
tableSize += dataFileStatBuffer.st_size;
tableSize += footerFileStatBuffer.st_size;
PG_RETURN_INT64(tableSize);
}
/*
* cstore_fdw_handler creates and returns a struct with pointers to foreign
* table callback functions.
*/
Datum
cstore_fdw_handler(PG_FUNCTION_ARGS)
{
FdwRoutine *fdwRoutine = makeNode(FdwRoutine);
fdwRoutine->GetForeignRelSize = CStoreGetForeignRelSize;
fdwRoutine->GetForeignPaths = CStoreGetForeignPaths;
fdwRoutine->GetForeignPlan = CStoreGetForeignPlan;
fdwRoutine->ExplainForeignScan = CStoreExplainForeignScan;
fdwRoutine->BeginForeignScan = CStoreBeginForeignScan;
fdwRoutine->IterateForeignScan = CStoreIterateForeignScan;
fdwRoutine->ReScanForeignScan = CStoreReScanForeignScan;
fdwRoutine->EndForeignScan = CStoreEndForeignScan;
fdwRoutine->AnalyzeForeignTable = CStoreAnalyzeForeignTable;
fdwRoutine->PlanForeignModify = CStorePlanForeignModify;
fdwRoutine->BeginForeignModify = CStoreBeginForeignModify;
fdwRoutine->ExecForeignInsert = CStoreExecForeignInsert;
fdwRoutine->EndForeignModify = CStoreEndForeignModify;
PG_RETURN_POINTER(fdwRoutine);
}
/*
* cstore_fdw_validator validates options given to one of the following commands:
* foreign data wrapper, server, user mapping, or foreign table. This function
* errors out if the given option name or its value is considered invalid.
*/
Datum
cstore_fdw_validator(PG_FUNCTION_ARGS)
{
Datum optionArray = PG_GETARG_DATUM(0);
Oid optionContextId = PG_GETARG_OID(1);
List *optionList = untransformRelOptions(optionArray);
ListCell *optionCell = NULL;
char *filename = NULL;
char *compressionTypeString = NULL;
char *stripeRowCountString = NULL;
char *blockRowCountString = NULL;
foreach(optionCell, optionList)
{
DefElem *optionDef = (DefElem *) lfirst(optionCell);
char *optionName = optionDef->defname;
bool optionValid = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++)
{
const CStoreValidOption *validOption = &(ValidOptionArray[optionIndex]);
if ((optionContextId == validOption->optionContextId) &&
(strncmp(optionName, validOption->optionName, NAMEDATALEN) == 0))
{
optionValid = true;
break;
}
}
/* if invalid option, display an informative error message */
if (!optionValid)
{
StringInfo optionNamesString = OptionNamesString(optionContextId);
ereport(ERROR, (errcode(ERRCODE_FDW_INVALID_OPTION_NAME),
errmsg("invalid option \"%s\"", optionName),
errhint("Valid options in this context are: %s",
optionNamesString->data)));
}
if (strncmp(optionName, OPTION_NAME_FILENAME, NAMEDATALEN) == 0)
{
filename = defGetString(optionDef);
}
else if (strncmp(optionName, OPTION_NAME_COMPRESSION_TYPE, NAMEDATALEN) == 0)
{
compressionTypeString = defGetString(optionDef);
}
else if (strncmp(optionName, OPTION_NAME_STRIPE_ROW_COUNT, NAMEDATALEN) == 0)
{
stripeRowCountString = defGetString(optionDef);
}
else if (strncmp(optionName, OPTION_NAME_BLOCK_ROW_COUNT, NAMEDATALEN) == 0)
{
blockRowCountString = defGetString(optionDef);
}
}
if (optionContextId == ForeignTableRelationId)
{
ValidateForeignTableOptions(filename, compressionTypeString,
stripeRowCountString, blockRowCountString);
}
PG_RETURN_VOID();
}
/*
* OptionNamesString finds all options that are valid for the current context,
* and concatenates these option names in a comma separated string. The function
* is unchanged from mongo_fdw.
*/
static StringInfo
OptionNamesString(Oid currentContextId)
{
StringInfo optionNamesString = makeStringInfo();
bool firstOptionAppended = false;
int32 optionIndex = 0;
for (optionIndex = 0; optionIndex < ValidOptionCount; optionIndex++)
{
const CStoreValidOption *validOption = &(ValidOptionArray[optionIndex]);
/* if option belongs to current context, append option name */
if (currentContextId == validOption->optionContextId)
{
if (firstOptionAppended)
{
appendStringInfoString(optionNamesString, ", ");
}
appendStringInfoString(optionNamesString, validOption->optionName);
firstOptionAppended = true;
}
}
return optionNamesString;
}
/*
* CStoreGetOptions returns the option values to be used when reading and writing
* the cstore file. To resolve these values, the function checks options for the
* foreign table, and if not present, falls back to default values. This function
* errors out if given option values are considered invalid.
*/
static CStoreFdwOptions *
CStoreGetOptions(Oid foreignTableId)
{
CStoreFdwOptions *cstoreFdwOptions = NULL;
char *filename = NULL;
CompressionType compressionType = DEFAULT_COMPRESSION_TYPE;
int32 stripeRowCount = DEFAULT_STRIPE_ROW_COUNT;
int32 blockRowCount = DEFAULT_BLOCK_ROW_COUNT;
char *compressionTypeString = NULL;
char *stripeRowCountString = NULL;
char *blockRowCountString = NULL;
filename = CStoreGetOptionValue(foreignTableId, OPTION_NAME_FILENAME);
compressionTypeString = CStoreGetOptionValue(foreignTableId,
OPTION_NAME_COMPRESSION_TYPE);
stripeRowCountString = CStoreGetOptionValue(foreignTableId,
OPTION_NAME_STRIPE_ROW_COUNT);
blockRowCountString = CStoreGetOptionValue(foreignTableId,
OPTION_NAME_BLOCK_ROW_COUNT);
ValidateForeignTableOptions(filename, compressionTypeString,
stripeRowCountString, blockRowCountString);
/* parse provided options */
if (compressionTypeString != NULL)
{
compressionType = ParseCompressionType(compressionTypeString);
}
if (stripeRowCountString != NULL)
{
stripeRowCount = pg_atoi(stripeRowCountString, sizeof(int32), 0);
}
if (blockRowCountString != NULL)
{
blockRowCount = pg_atoi(blockRowCountString, sizeof(int32), 0);
}
/* set default filename if it is not provided */
if (filename == NULL)
{
filename = CStoreDefaultFilePath(foreignTableId);
}
cstoreFdwOptions = palloc0(sizeof(CStoreFdwOptions));
cstoreFdwOptions->filename = filename;
cstoreFdwOptions->compressionType = compressionType;
cstoreFdwOptions->stripeRowCount = stripeRowCount;
cstoreFdwOptions->blockRowCount = blockRowCount;
return cstoreFdwOptions;
}
/*
* CStoreGetOptionValue walks over foreign table and foreign server options, and
* looks for the option with the given name. If found, the function returns the
* option's value. This function is unchanged from mongo_fdw.
*/
static char *
CStoreGetOptionValue(Oid foreignTableId, const char *optionName)
{
ForeignTable *foreignTable = NULL;
ForeignServer *foreignServer = NULL;
List *optionList = NIL;
ListCell *optionCell = NULL;
char *optionValue = NULL;
foreignTable = GetForeignTable(foreignTableId);
foreignServer = GetForeignServer(foreignTable->serverid);
optionList = list_concat(optionList, foreignTable->options);
optionList = list_concat(optionList, foreignServer->options);
foreach(optionCell, optionList)
{
DefElem *optionDef = (DefElem *) lfirst(optionCell);
char *optionDefName = optionDef->defname;
if (strncmp(optionDefName, optionName, NAMEDATALEN) == 0)
{
optionValue = defGetString(optionDef);
break;
}
}
return optionValue;
}
/*
* ValidateForeignTableOptions verifies if given options are valid cstore_fdw
* foreign table options. This function errors out if given option value is
* considered invalid.
*/
static void
ValidateForeignTableOptions(char *filename, char *compressionTypeString,
char *stripeRowCountString, char *blockRowCountString)
{
/* we currently do not have any checks for filename */
(void) filename;
/* check if the provided compression type is valid */
if (compressionTypeString != NULL)
{
CompressionType compressionType = ParseCompressionType(compressionTypeString);
if (compressionType == COMPRESSION_TYPE_INVALID)
{
ereport(ERROR, (errmsg("invalid compression type"),
errhint("Valid options are: %s",
COMPRESSION_STRING_DELIMITED_LIST)));
}
}
/* check if the provided stripe row count has correct format and range */
if (stripeRowCountString != NULL)
{
/* pg_atoi() errors out if the given string is not a valid 32-bit integer */
int32 stripeRowCount = pg_atoi(stripeRowCountString, sizeof(int32), 0);
if (stripeRowCount < STRIPE_ROW_COUNT_MINIMUM ||
stripeRowCount > STRIPE_ROW_COUNT_MAXIMUM)
{
ereport(ERROR, (errmsg("invalid stripe row count"),
errhint("Stripe row count must be an integer between "