This repository has been archived by the owner on Jun 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
pg_cryogen.c
1461 lines (1227 loc) · 42 KB
/
pg_cryogen.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
#include "postgres.h"
#include "access/generic_xlog.h"
#include "access/heapam.h"
#include "access/multixact.h"
#include "access/relscan.h"
#include "access/skey.h"
#include "access/tableam.h"
#include "access/visibilitymap.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/storage.h"
#include "catalog/storage_xlog.h"
#include "commands/vacuum.h"
#include "executor/executor.h"
#include "executor/tuptable.h"
#include "miscadmin.h"
#include "nodes/execnodes.h"
#include "storage/bufmgr.h"
#include "storage/checksum.h"
#include "storage/lmgr.h"
#include "storage/procarray.h"
#include "storage/smgr.h"
#include "utils/inval.h"
#include "utils/relcache.h"
#include "utils/snapmgr.h"
#include "cache.h"
#include "compression.h"
#include "scan_iterator.h"
#include "storage.h"
PG_MODULE_MAGIC;
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define NOT_IMPLEMENTED \
do { \
elog(ERROR, "function \"%s\" is not implemented", __func__); \
} while (0)
typedef struct CryoScanDescData
{
TableScanDescData rs_base;
uint32 nblocks;
BlockNumber cur_block;
uint32 cur_item;
SeqScanIterator *iterator;
CacheEntry cacheEntry; /* cached decompressed page reference */
} CryoScanDescData;
typedef CryoScanDescData *CryoScanDesc;
typedef struct
{
IndexFetchTableData base;
CacheEntry cacheEntry; /* cached decompressed page reference */
} IndexFetchCryoData;
typedef struct CryoModifyState
{
Relation relation;
BlockNumber target_block;
uint32 tuples_inserted;
CacheEntry cacheEntry; /* cached decompressed page reference */
char *data; /* decompressed data */
} CryoModifyState;
CryoModifyState modifyState = {
.tuples_inserted = 0,
.relation = NULL
};
PG_FUNCTION_INFO_V1(cryo_tableam_handler);
static Buffer cryo_load_meta(Relation rel, int lockmode);
static void cryo_preserve(CryoModifyState *state, bool advance);
static BlockNumber cryo_reserve_blockno(Relation rel);
void _PG_init(void);
static void
flush_modify_state(void)
{
if (!RelationIsValid(modifyState.relation))
return;
if (modifyState.tuples_inserted)
cryo_preserve(&modifyState, true);
modifyState.tuples_inserted = 0;
cryo_cache_release(modifyState.cacheEntry);
modifyState.relation = NULL;
}
static void
init_modify_state(Relation rel)
{
CryoDataHeader *hdr;
/* init meta page */
if (RelationGetNumberOfBlocks(rel) == 0)
{
Buffer metabuf;
metabuf = cryo_load_meta(rel, BUFFER_LOCK_SHARE);
UnlockReleaseBuffer(metabuf);
}
/*
* We need to allocate a single block which number will serve as an
* identification for ItemPointers. Read comment in scan_iterator.c for
* details.
*/
modifyState.target_block = cryo_reserve_blockno(rel);
modifyState.cacheEntry = cryo_cache_allocate(rel, modifyState.target_block);
modifyState.data = cryo_cache_get_data(modifyState.cacheEntry);
hdr = (CryoDataHeader *) modifyState.data;
/* initialize modify state */
if (modifyState.target_block == 0)
{
/* This is a first data block in the relation */
cryo_init_page(hdr);
modifyState.target_block = 1;
}
else
{
/*
* In order to ensure that storage is consistent we create entirely
* new block for every multi_insert instead of adding tuples to an
* existing one. This also makes visibility check much simpler and
* faster: we just check transaction id in a block header.
*/
cryo_init_page(hdr);
}
modifyState.relation = rel;
modifyState.tuples_inserted = 0;
}
static void
cryo_xact_callback(XactEvent event, void *arg)
{
switch (event)
{
case XACT_EVENT_PRE_COMMIT:
(void) flush_modify_state();
break;
case XACT_EVENT_ABORT:
modifyState.relation = NULL;
modifyState.tuples_inserted = 0;
break;
default:
/* do nothing */
;
}
}
static void
cryo_relcache_callback(Datum arg, Oid relid)
{
cryo_cache_invalidate_relation(relid);
}
void
_PG_init(void)
{
cryo_init_cache();
cryo_define_compression_gucs();
RegisterXactCallback(cryo_xact_callback, NULL);
CacheRegisterRelcacheCallback(cryo_relcache_callback, (Datum) 0);
}
static const TupleTableSlotOps *
cryo_slot_callbacks(Relation relation)
{
// return &TTSOpsBufferHeapTuple;
return &TTSOpsHeapTuple;
}
static TableScanDesc
cryo_beginscan(Relation relation, Snapshot snapshot,
int nkeys, ScanKey key,
ParallelTableScanDesc parallel_scan,
uint32 flags)
{
CryoScanDesc scan;
RelationIncrementReferenceCount(relation);
/*
* allocate and initialize scan descriptor
*/
scan = (CryoScanDesc) palloc(sizeof(CryoScanDescData));
scan->rs_base.rs_rd = relation;
scan->rs_base.rs_snapshot = snapshot;
scan->rs_base.rs_nkeys = nkeys;
scan->rs_base.rs_flags = flags;
scan->cur_item = 0;
scan->cur_block = 0;
scan->nblocks = 0;
scan->cacheEntry = InvalidCacheEntry;
scan->iterator = cryo_seqscan_iter_create();
return (TableScanDesc) scan;
}
static bool
xid_is_visible(Snapshot snapshot, TransactionId xid)
{
switch (snapshot->snapshot_type)
{
case SNAPSHOT_MVCC:
if (TransactionIdIsCurrentTransactionId(xid))
return true;
else if (XidInMVCCSnapshot(xid, snapshot))
return false;
else if (TransactionIdDidCommit(xid))
return true;
else
{
/* it must have been aborted or crashed */
return false;
}
case SNAPSHOT_ANY:
return true;
default:
elog(ERROR,
"pg_cryogen: visibility check for snapshot type %d is not implemented",
snapshot->snapshot_type);
}
}
static bool
cryo_getnextslot(TableScanDesc sscan, ScanDirection direction, TupleTableSlot *slot)
{
CryoScanDesc scan = (CryoScanDesc) sscan;
CryoDataHeader *hdr;
Relation rel = scan->rs_base.rs_rd;
CryoError err;
ExecClearTuple(slot);
/* TODO: handle direction */
if (direction == BackwardScanDirection)
elog(ERROR, "pg_cryogen: backward scan is not implemented");
read_block:
if (scan->cur_item == 0)
{
scan->cur_block = cryo_seqscan_iter_next(scan->iterator);
/*
* TODO: probably read the number of block just once and store in the
* scan state
*/
if (RelationGetNumberOfBlocks(rel) <= scan->cur_block)
return false;
err = cryo_read_data(rel, scan->iterator, scan->cur_block,
&scan->cacheEntry);
if (err != CRYO_ERR_SUCCESS)
{
if (err == CRYO_ERR_EMPTY_BLOCK)
{
/* that's ok, just read the next block*/
goto read_block;
}
ereport(ERROR,
(errcode(ERRCODE_INTERNAL_ERROR),
errmsg("pg_cryogen: %s", cryo_cache_err(err)),
errhint("block number: %u", scan->cur_block)));
}
scan->nblocks = cryo_cache_get_pg_nblocks(scan->cacheEntry);
scan->cur_item = 1;
if (!xid_is_visible(sscan->rs_snapshot, cryo_cache_get_xid(scan->cacheEntry)))
{
/*
* Transaction created this block is not visible, proceed to the
* next block
*/
scan->cur_item = 0;
goto read_block;
}
}
hdr = (CryoDataHeader *) cryo_cache_get_data(scan->cacheEntry);
if ((scan->cur_item) * sizeof(CryoItemId) < hdr->lower)
{
/* read tuple */
HeapTuple tuple;
tuple = palloc0(sizeof(HeapTupleData));
cryo_storage_fetch(hdr, scan->cur_item, tuple);
tuple->t_tableOid = RelationGetRelid(scan->rs_base.rs_rd);
ItemPointerSet(&tuple->t_self, scan->cur_block, scan->cur_item);
ExecStoreHeapTuple(tuple, slot, true);
scan->cur_item++;
return true;
}
else
{
scan->cur_item = 0;
goto read_block;
}
return false;
}
static void
cryo_rescan(TableScanDesc sscan, ScanKey key, bool set_params,
bool allow_strat, bool allow_sync, bool allow_pagemode)
{
CryoScanDesc scan = (CryoScanDesc) sscan;
scan->cur_item = 0;
scan->cur_block = 0;
scan->nblocks = 0;
scan->cacheEntry = InvalidCacheEntry;
}
static void
cryo_endscan(TableScanDesc sscan)
{
CryoScanDesc scan = (CryoScanDesc) sscan;
/*
* decrement relation reference count and free scan descriptor storage
*/
RelationDecrementReferenceCount(scan->rs_base.rs_rd);
/*
if (scan->rs_base.rs_key)
pfree(scan->rs_base.rs_key);
*/
if (scan->rs_base.rs_flags & SO_TEMP_SNAPSHOT)
UnregisterSnapshot(scan->rs_base.rs_snapshot);
pfree(scan);
}
static IndexFetchTableData *
cryo_index_fetch_begin(Relation rel)
{
IndexFetchCryoData *cscan = palloc0(sizeof(IndexFetchCryoData));
cscan->base.rel = rel;
return &cscan->base;
}
static void
cryo_index_fetch_reset(IndexFetchTableData *scan)
{
/* nothing to reset yet */
}
static void
cryo_index_fetch_end(IndexFetchTableData *scan)
{
pfree(scan);
}
/*
* Currently it's a super inefficient implementation that reads and
* decompresses entire block for every iteration. Need to add a buffer cache
* for cryo pages.
*/
static bool
cryo_index_fetch_tuple(struct IndexFetchTableData *scan,
ItemPointer tid,
Snapshot snapshot,
TupleTableSlot *slot,
bool *call_again, bool *all_dead)
{
IndexFetchCryoData *cscan = (IndexFetchCryoData *) scan;
CryoDataHeader *hdr;
HeapTuple tuple;
CryoError err;
err = cryo_read_data(cscan->base.rel,
NULL, /* TODO */
ItemPointerGetBlockNumber(tid),
&cscan->cacheEntry);
if (err != CRYO_ERR_SUCCESS)
elog(ERROR, "pg_cryogen: %s", cryo_cache_err(err));
if (!xid_is_visible(snapshot, cryo_cache_get_xid(cscan->cacheEntry)))
return false;
hdr = (CryoDataHeader *) cryo_cache_get_data(cscan->cacheEntry);
tuple = palloc0(sizeof(HeapTupleData));
tuple->t_tableOid = RelationGetRelid(cscan->base.rel);
ItemPointerCopy(tid, &tuple->t_self);
cryo_storage_fetch(hdr, ItemPointerGetOffsetNumber(tid), tuple);
ExecStoreHeapTuple(tuple, slot, true);
return true;
}
static bool
cryo_scan_bitmap_next_block(TableScanDesc scan,
struct TBMIterateResult *tbmres)
{
CryoScanDesc cscan = (CryoScanDesc) scan;
BlockNumber blockno;
CryoError err;
cscan->cur_block = InvalidBlockNumber;
blockno = tbmres->blockno;
err = cryo_read_data(cscan->rs_base.rs_rd, NULL, blockno,
&cscan->cacheEntry);
switch (err)
{
case CRYO_ERR_SUCCESS:
/* everything is fine, carry on */
break;
case CRYO_ERR_WRONG_STARTING_BLOCK:
/*
* This is a usual case for BRIN index. It just scans every blockno
* in a range. Notify bitmapscan node that there are no tuples in
* this block and proceed to the next one.
*/
return false;
default:
/* some actual error */
elog(ERROR, "pg_cryogen: %s", cryo_cache_err(err));
}
cscan->nblocks = cryo_cache_get_pg_nblocks(cscan->cacheEntry);
if (cscan->nblocks == 0)
return false;
cscan->cur_block = blockno;
/* lossy scan? */
if (tbmres->ntuples < 0)
{
/* for lossy scan we interpret cur_item as a position in the block */
cscan->cur_item = 1;
}
else
{
/*
* ...and for non-lossy cur_item points to the position in
* tbmres->offsets.
*/
cscan->cur_item = 0;
}
return true;
}
static bool
cryo_scan_bitmap_next_tuple(TableScanDesc scan,
struct TBMIterateResult *tbmres,
TupleTableSlot *slot)
{
CryoScanDesc cscan = (CryoScanDesc) scan;
CryoDataHeader *hdr;
HeapTuple tuple;
int pos;
/* prevent reading in the middle of cryo blocks */
if (tbmres->blockno != cscan->cur_block)
return false;
if (!xid_is_visible(scan->rs_snapshot, cryo_cache_get_xid(cscan->cacheEntry)))
return false;
hdr = (CryoDataHeader *) cryo_cache_get_data(cscan->cacheEntry);
if (tbmres->ntuples >= 0)
{
if (cscan->cur_item >= tbmres->ntuples)
return false;
pos = tbmres->offsets[cscan->cur_item];
}
else
{
if (cscan->cur_item * sizeof(CryoItemId) >= hdr->lower)
return false;
pos = cscan->cur_item;
}
tuple = palloc0(sizeof(HeapTupleData));
cryo_storage_fetch(hdr, pos, tuple);
tuple->t_tableOid = RelationGetRelid(cscan->rs_base.rs_rd);
ItemPointerSet(&tuple->t_self, cscan->cur_block, pos);
ExecStoreHeapTuple(tuple, slot, true);
cscan->cur_item++;
return true;
}
static bool
cryo_fetch_row_version(Relation relation,
ItemPointer tid,
Snapshot snapshot,
TupleTableSlot *slot)
{
NOT_IMPLEMENTED;
}
static bool
cryo_tuple_tid_valid(TableScanDesc scan, ItemPointer tid)
{
NOT_IMPLEMENTED;
}
static bool
cryo_tuple_satisfies_snapshot(Relation rel, TupleTableSlot *slot,
Snapshot snapshot)
{
NOT_IMPLEMENTED;
}
static Buffer
cryo_load_meta(Relation rel, int lockmode)
{
Buffer metabuf;
CryoMetaPage *metapage;
if (RelationGetNumberOfBlocks(rel) == 0)
{
GenericXLogState *xlogState;
/* This is a brand new relation. Initialize a metapage */
LockRelationForExtension(rel, ExclusiveLock);
/*
* Check that while we where locking relation nobody else has created
* metapage. Because that would be just terrible.
*/
if (RelationGetNumberOfBlocks(rel) == 0)
{
xlogState = GenericXLogStart(rel);
metabuf = ReadBuffer(rel, P_NEW);
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
UnlockRelationForExtension(rel, ExclusiveLock);
metapage = (CryoMetaPage *)
GenericXLogRegisterBuffer(xlogState, metabuf,
GENERIC_XLOG_FULL_IMAGE);
/*
* Can't leave pd_upper = 0 because then page will be considered new
* (see PageIsNew) and won't pass PageIsVerified check
*/
metapage->base.pd_upper = BLCKSZ;
metapage->base.pd_lower = sizeof(CryoMetaPage);
metapage->base.pd_special = BLCKSZ;
metapage->version = STORAGE_VERSION;
/* No target block yet */
PageSetChecksumInplace((Page) metapage, CRYO_META_PAGE);
GenericXLogFinish(xlogState);
UnlockReleaseBuffer(metabuf);
}
else
{
UnlockRelationForExtension(rel, ExclusiveLock);
}
}
metabuf = ReadBuffer(rel, CRYO_META_PAGE);
metapage = (CryoMetaPage *) BufferGetPage(metabuf);
LockBuffer(metabuf, lockmode);
return metabuf;
}
static BlockNumber
cryo_reserve_blockno(Relation rel)
{
Buffer buf;
BlockNumber res;
LockRelationForExtension(rel, ExclusiveLock);
buf = ReadBuffer(rel, P_NEW);
UnlockRelationForExtension(rel, ExclusiveLock);
res = BufferGetBlockNumber(buf);
ReleaseBuffer(buf);
return res;
}
static inline void
cryo_multi_insert_internal(Relation rel,
TupleTableSlot **slots,
int ntuples,
XactCallback callback)
{
CryoDataHeader *hdr;
int i;
if (!RelationIsValid(modifyState.relation))
{
init_modify_state(rel);
}
else if (RelationGetRelid(modifyState.relation) != RelationGetRelid(rel))
{
/*
* Flush whatever changes we currently have in the modifyState and
* reinitialize it for a new relation.
*
* XXX: that isn't the optimal solution in case when user inserts
* into several tables out of order in a single transaction. Other
* option would be to have separate cache slot for every table we are
* inserting to, but then there is a risk to exhaust all cache slots.
*/
flush_modify_state();
init_modify_state(rel);
}
hdr = (CryoDataHeader *) modifyState.data;
for (i = 0; i < ntuples; ++i)
{
HeapTuple tuple;
int pos;
CHECK_FOR_INTERRUPTS();
tuple = ExecCopySlotHeapTuple(slots[i]);
if ((pos = cryo_storage_insert(hdr, tuple)) < 0)
{
/*
* Compress and flush current block to the disk (if needed),
* create a new one and retry insertion
*/
flush_modify_state();
init_modify_state(rel);
hdr = (CryoDataHeader *) modifyState.data;
if ((pos = cryo_storage_insert(hdr, tuple)) < 0)
{
elog(ERROR, "tuple is too large to fit the cryo block");
}
}
pfree(tuple);
modifyState.tuples_inserted++;
slots[i]->tts_tableOid = RelationGetRelid(rel);
/* position in item pointer starts with 1 */
ItemPointerSet(&slots[i]->tts_tid, modifyState.target_block, pos);
}
}
bool flag = false;
static void
cryo_tuple_insert(Relation relation, TupleTableSlot *slot, CommandId cid,
int options, BulkInsertState bistate)
{
(void) cryo_multi_insert_internal(relation, &slot, 1, cryo_xact_callback);
}
static void
cryo_tuple_insert_speculative(Relation relation, TupleTableSlot *slot,
CommandId cid, int options,
BulkInsertState bistate, uint32 specToken)
{
NOT_IMPLEMENTED;
}
static void
cryo_tuple_complete_speculative(Relation relation, TupleTableSlot *slot,
uint32 specToken, bool succeeded)
{
NOT_IMPLEMENTED;
}
/*
* Number of postgres pages needed to fit data block of the specified size.
*/
static inline uint8
cryo_pages_needed(Size size)
{
int pages = 1;
Size page_sz = BLCKSZ - sizeof(CryoPageHeader);
Assert(size > 0);
size -= BLCKSZ - sizeof(CryoFirstPageHeader);
pages += size > 0 ? (size + page_sz - 1) / page_sz : 0;
return pages;
}
/*
* Compress and store data in postgres buffers, write WAL and all that stuff.
* If advance flag is set true, then also shift target_block of the state to
* the next block after the last written page.
*/
static void
cryo_preserve(CryoModifyState *state, bool advance)
{
GenericXLogState *xlog_state;
CryoMetaPage *metapage;
CompressionMethod method = compression_method_guc;
Relation rel = state->relation;
Size size;
char *compressed, *p;
int npages;
Buffer metabuf;
Buffer *buffers;
int i;
BlockNumber block;
p = compressed = cryo_compress(method, state->data, &size);
metabuf = cryo_load_meta(state->relation, BUFFER_LOCK_EXCLUSIVE);
metapage = (CryoMetaPage *) BufferGetPage(metabuf);
block = state->target_block;
/* split data into pages */
npages = cryo_pages_needed(size);
buffers = palloc(npages * sizeof(Buffer));
block = MAX(1, block);
/*
* If we need more than one page then lock relation for extension
*
* XXX don't need to do that for local relations but thats unlikely
* the case
*/
if (npages > 1)
LockRelationForExtension(state->relation, ExclusiveLock);
/* allocate and lock bufferes */
for (i = 0; i < npages; ++i)
{
/* the first block was preallocated in init_modify_state */
buffers[i] = ReadBuffer(rel, block);
LockBuffer(buffers[i], BUFFER_LOCK_EXCLUSIVE);
/* but the rest of the blocks must be allocated here */
block = P_NEW;
}
if (npages > 1)
UnlockRelationForExtension(state->relation, ExclusiveLock);
/* copy data into buffers and release them*/
for (i = 0; i < npages; ++i)
{
CryoPageHeader *hdr;
Size hdr_size;
Size content_size;
xlog_state = GenericXLogStart(state->relation);
hdr = (CryoPageHeader *)
GenericXLogRegisterBuffer(xlog_state, buffers[i],
GENERIC_XLOG_FULL_IMAGE);
hdr->first = BufferGetBlockNumber(buffers[0]);
hdr->next = (i + 1 < npages) ? BufferGetBlockNumber(buffers[i + 1]) : InvalidBlockNumber;
/* write additional info into the first page */
if (i == 0)
{
CryoFirstPageHeader *first_hdr = (CryoFirstPageHeader *) hdr;
first_hdr->npages = npages;
first_hdr->compression_method = method;
first_hdr->compressed_size = size;
first_hdr->created_xid = GetCurrentTransactionId();
}
block = BufferGetBlockNumber(buffers[i]);
hdr_size = CryoPageHeaderSize(hdr, block);
content_size = BLCKSZ - hdr_size;
/*
* Can't leave pd_upper = 0 because then page will be considered new
* (see PageIsNew) and won't pass PageIsVerified check
*/
hdr->base.pd_upper = BLCKSZ;
hdr->base.pd_lower = hdr_size + MIN(content_size, size);
hdr->base.pd_special = BLCKSZ;
memcpy((char *) hdr + hdr_size,
p,
MIN(content_size, size));
PageSetChecksumInplace((Page) hdr, block);
size -= content_size;
p += content_size;
MarkBufferDirty(buffers[i]);
GenericXLogFinish(xlog_state);
}
/* update metadata */
xlog_state = GenericXLogStart(state->relation);
metapage = (CryoMetaPage *)
GenericXLogRegisterBuffer(xlog_state, metabuf,
GENERIC_XLOG_FULL_IMAGE);
if (advance)
block += i;
state->target_block = block;
metapage->ntuples += state->tuples_inserted;
PageSetChecksumInplace((Page) metapage, CRYO_META_PAGE);
MarkBufferDirty(metabuf);
GenericXLogFinish(xlog_state);
/* Release resources */
for (i = 0; i < npages; ++i)
UnlockReleaseBuffer(buffers[i]);
UnlockReleaseBuffer(metabuf);
pfree(buffers);
pfree(compressed);
}
static void
cryo_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples,
CommandId cid, int options, BulkInsertState bistate)
{
(void) cryo_multi_insert_internal(relation, slots, ntuples, NULL);
}
static void
cryo_finish_bulk_insert(Relation rel, int options)
{
if (!RelationIsValid(rel))
return;
flush_modify_state();
}
static TM_Result
cryo_tuple_delete(Relation relation, ItemPointer tid, CommandId cid,
Snapshot snapshot, Snapshot crosscheck, bool wait,
TM_FailureData *tmfd, bool changingPart)
{
elog(ERROR, "pg_cryogen is an append only storage");
}
static TM_Result
cryo_tuple_update(Relation relation, ItemPointer otid, TupleTableSlot *slot,
CommandId cid, Snapshot snapshot, Snapshot crosscheck,
bool wait, TM_FailureData *tmfd,
LockTupleMode *lockmode, bool *update_indexes)
{
elog(ERROR, "pg_cryogen is an append only storage");
}
static TM_Result
cryo_tuple_lock(Relation relation, ItemPointer tid, Snapshot snapshot,
TupleTableSlot *slot, CommandId cid, LockTupleMode mode,
LockWaitPolicy wait_policy, uint8 flags,
TM_FailureData *tmfd)
{
CryoDataHeader *hdr;
CryoError err;
CacheEntry cacheEntry;
HeapTuple tuple;
err = cryo_read_data(relation, NULL, ItemPointerGetBlockNumber(tid),
&cacheEntry);
if (err != CRYO_ERR_SUCCESS)
elog(ERROR, "pg_cryogen: %s", cryo_cache_err(err));
if (!xid_is_visible(snapshot, cryo_cache_get_xid(cacheEntry)))
return TM_Invisible;
hdr = (CryoDataHeader *) cryo_cache_get_data(cacheEntry);
tuple = palloc0(sizeof(HeapTupleData));
cryo_storage_fetch(hdr, ItemPointerGetOffsetNumber(tid), tuple);
tuple->t_tableOid = RelationGetRelid(relation);
ItemPointerCopy(tid, &tuple->t_self);
ExecStoreHeapTuple(tuple, slot, true);
/*
* We don't do any actual locking since data is not going anywhere as it's
* an append-only storage
*/
return TM_Ok;
}
static void
cryo_get_latest_tid(TableScanDesc scan,
ItemPointer tid)
{
NOT_IMPLEMENTED;
}
static TransactionId
cryo_compute_xid_horizon_for_tuples(Relation rel,
ItemPointerData *items,
int nitems)
{
NOT_IMPLEMENTED;
}
static void
cryo_relation_set_new_filenode(Relation rel,
const RelFileNode *newrnode,
char persistence,
TransactionId *freezeXid,
MultiXactId *minmulti)
{
SMgrRelation srel;
/*
* Initialize to the minimum XID that could put tuples in the table. We
* know that no xacts older than RecentXmin are still running, so that
* will do.
*/
*freezeXid = RecentXmin;
/*
* Similarly, initialize the minimum Multixact to the first value that
* could possibly be stored in tuples in the table. Running transactions
* could reuse values from their local cache, so we are careful to
* consider all currently running multis.
*
* XXX this could be refined further, but is it worth the hassle?
*/
*minmulti = GetOldestMultiXactId();
srel = RelationCreateStorage(*newrnode, persistence);
/*
* If required, set up an init fork for an unlogged table so that it can
* be correctly reinitialized on restart. An immediate sync is required
* even if the page has been logged, because the write did not go through
* shared_buffers and therefore a concurrent checkpoint may have moved the
* redo pointer past our xlog record. Recovery may as well remove it
* while replaying, for example, XLOG_DBASE_CREATE or XLOG_TBLSPC_CREATE
* record. Therefore, logging is necessary even if wal_level=minimal.
*/
if (persistence == RELPERSISTENCE_UNLOGGED)
{
Assert(rel->rd_rel->relkind == RELKIND_RELATION ||
rel->rd_rel->relkind == RELKIND_MATVIEW ||
rel->rd_rel->relkind == RELKIND_TOASTVALUE);
smgrcreate(srel, INIT_FORKNUM, false);
log_smgrcreate(newrnode, INIT_FORKNUM);
smgrimmedsync(srel, INIT_FORKNUM);
}
smgrclose(srel);
}
static void
cryo_relation_nontransactional_truncate(Relation rel)
{
NOT_IMPLEMENTED;
}
static void
cryo_relation_copy_data(Relation rel, const RelFileNode *newrnode)
{
NOT_IMPLEMENTED;
}
static void
cryo_relation_copy_for_cluster(Relation OldHeap, Relation NewHeap,
Relation OldIndex, bool use_sort,
TransactionId OldestXmin,
TransactionId *xid_cutoff,
MultiXactId *multi_cutoff,
double *num_tuples,
double *tups_vacuumed,
double *tups_recently_dead)
{
NOT_IMPLEMENTED;
}
static bool
cryo_scan_analyze_next_block(TableScanDesc scan, BlockNumber blockno,
BufferAccessStrategy bstrategy)
{
CryoPageHeader *page;
CryoScanDesc cscan = (CryoScanDesc) scan;
Buffer buf;
CryoError err;
/* Skip metapage */
if (blockno == 0)
return false;
/*