The arena of a memtable relation does not yet survive a rollback. A rolled-back CREATE TABLE leaks its arena, and a rolled-back DROP TABLE loses an arena the table still needs. In this post you will see how to tie the lifetime of the arena to the outcome of the transaction to avoid both problems.
Part 4 gave every memtable relation an arena that is created by CREATE TABLE and released by DROP TABLE, as long as every transaction commits. As pointed out in the previous post, this fails when the transaction is rolled back.
What goes wrong
With the code from Part 4, both CREATE TABLE and DROP TABLE can go wrong when they are part of a transaction that rolls back:
- If a transaction creates a table and then rolls back, the table disappears together with its
pg_classrow, but the arena is still pinned, as described in the section on pinning in Part 3, and it is not known to any Postgres process. As a result, it stays around until the server is shut down or restarted. - If a transaction drops a table and then rolls back, the table is still there. The object access hook, however, has already released the arena. It ran as soon as the drop was processed, not when the drop was known to have committed. The table now has a
relfilenodepointing at a segment that no longer exists, and the nextDROP TABLEon it fails withcannot unpin unknown segment handle.
The first scenario can be reproduced by creating a table inside a transaction and then rolling it back:
START TRANSACTION;
CREATE TABLE customers (id int) USING memtable;
ROLLBACK;
The second scenario can be reproduced with an explicit ROLLBACK:
CREATE TABLE accounts (id bigint) USING memtable;
BEGIN;
DROP TABLE accounts;
ROLLBACK;
DROP TABLE accounts; -- ERROR: cannot unpin unknown segment handle
With the default dynamic_shared_memory_type on Linux, each DSM segment is a file named PostgreSQL. followed by the handle in /dev/shm, so the leak can be seen by listing the directory after the first scenario:
ls -l /dev/shm/PostgreSQL.*
Compared to the listing from before the transaction, one new file has appeared:
-rw------- 1 mats mats 1048576 Oct 13 18:32 /dev/shm/PostgreSQL.1563623712
The file is the 1 MiB arena, and nothing in pg_class refers to its handle. It stays there until the server is stopped. In the second scenario it is the other way around. The relfilenode of accounts still holds the handle, but there is no file with that name in /dev/shm.
A CREATE TABLE that fails after the callback has run, for example because of a constraint that Postgres checks later in the same statement, has a related problem. The ProcessUtility hook never gets to call memtable_finalize_new_relation, so the cache entry that the callback created is never removed. It stays in this backend’s cache for as long as the backend lives, and the arena leaks as in the first scenario above.
Releasing storage when the outcome is known
The problem is that Postgres has no way of undoing what happens to a DSM segment. The change to relfilenode rolls back by itself, because it is an ordinary transactional catalog write. A segment that has been unpinned and detached is gone for good, and a segment that was created stays around until somebody unpins it.
So the arena can only be released once it is known whether the transaction commits or aborts, and this depends on whether you create or drop a table:
| Statement | Arena | Release it when the transaction |
|---|---|---|
CREATE TABLE |
the new one | aborts |
DROP TABLE |
the existing one | commits |
What both rows have in common is that the decision has to be postponed to the end of the transaction. The rest of this section builds a small list of pending releases that is processed when the transaction ends.
The pending list
Each entry in the list says which handle to release, and on which transaction event. The relation is recorded too, since the backend-local cache entry for it is dropped at the same time:
typedef struct MemTablePendingCleanup {
Oid relid;
dsm_handle handle;
XactEvent event; /* release on this event */
} MemTablePendingCleanup;
static List* pending_cleanups = NIL;
The entry deliberately stores the handle and not a pointer to a dsm_segment. For DROP TABLE the handle comes from the catalog, and the segment associated with the handle might not have been mapped in this backend yet. It would be possible to attach to the segment to make sure that it is available, but attaching to the segment just to release it seems unnecessary. In addition, a handle is valid for as long as the segment exists, while a pointer would be invalid if the mapping were released in the meantime.
Scheduling a release is just a matter of appending it to the pending list. The list has to outlive the statement that adds to it, so it is allocated in TopMemoryContext:
static void memtable_schedule_cleanup(Oid relid, dsm_handle handle,
XactEvent event) {
MemoryContext oldcxt = MemoryContextSwitchTo(TopMemoryContext);
MemTablePendingCleanup* item = palloc_object(MemTablePendingCleanup);
item->relid = relid;
item->handle = handle;
item->event = event;
pending_cleanups = lappend(pending_cleanups, item);
MemoryContextSwitchTo(oldcxt);
}
The transaction callback
Postgres has a registration function, RegisterXactCallback, that allows you to register a function to be called for every event in the life of a transaction. A registered function stays registered until it is explicitly removed, so it needs to be registered once in _PG_init:
void _PG_init(void) {
...
RegisterXactCallback(memtable_xact_callback, NULL);
...
}
The callback is called for every transaction event, not just the final one. For example, XACT_EVENT_PRE_COMMIT is always delivered before XACT_EVENT_COMMIT. If the callback processed the list on that first event, it would empty the list before the event the entries are waiting for ever arrived. Only the two final events resolve the list, and every entry is freed afterward. Only the entries whose event matches the one that just fired release their arena, using the function from Part 4:
static void memtable_release_arena(dsm_handle handle) {
dsm_segment* seg = dsm_find_mapping(handle);
dsm_unpin_segment(handle); /* must precede the final detach */
if (seg != NULL)
dsm_detach(seg);
}
static void memtable_xact_callback(XactEvent event, void* arg) {
if (event == XACT_EVENT_PRE_PREPARE && pending_cleanups != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot PREPARE a transaction that has created or dropped "
"a memtable relation")));
if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_ABORT) {
ListCell* lc;
foreach (lc, pending_cleanups) {
MemTablePendingCleanup* item = lfirst(lc);
Assert(item->event == XACT_EVENT_COMMIT ||
item->event == XACT_EVENT_ABORT);
if (item->event == event && item->handle != DSM_HANDLE_INVALID)
memtable_release_arena(item->handle);
memtable_cache_remove(item->relid);
pfree(item);
}
list_free(pending_cleanups);
pending_cleanups = NIL;
}
}
Observe that the memtable_cache_remove function is called for every entry, whichever event it was waiting for. Normally memtable_finalize_new_relation has already removed the cache entry, but if standard_ProcessUtility fails after the TAM callback has created the entry, the finalize function is never reached and the entry would stay in the cache for as long as the backend lives. The callback runs for the abort that follows, and removing the entry here guarantees that it does not linger.
The callback runs before Postgres releases the resource owner of the transaction. Since memtable_release_arena detaches the mapping itself, it does not depend on any automatic cleanup.
Note: The callback also refuses
PREPARE TRANSACTIONwhen entries are pending. A prepared transaction is finished later, possibly by another backend, and there is no callback forCOMMIT PREPAREDorROLLBACK PREPARED. The pending list could therefore never be resolved at the right time, and its entries would fire at the end of some unrelated transaction instead.XACT_EVENT_PRE_PREPAREis delivered before the point of no return, so raising an error there is allowed, and the transaction is rolled back through the normal abort path. A transaction that has neither created nor dropped a memtable relation has no pending entries and can still be prepared. Prepared transactions are also disabled unlessmax_prepared_transactionsis set above zero.
CREATE TABLE: release on abort
With the pending list in place, CREATE TABLE only needs one more call inside memtable_relation_set_new_filelocator. After creating the arena, it schedules a release if the transaction aborts:
static void memtable_relation_set_new_filelocator(
Relation rel, const RelFileLocator* newrlocator, char persistence,
TransactionId* freezeXid, MultiXactId* minmulti) {
Oid relid = RelationGetRelid(rel);
MemTableStateCacheEntry* entry = memtable_cache_enter(relid);
dsm_handle handle = memtable_create_arena(rel, entry);
/* If this transaction aborts, don't leak the arena just created. */
memtable_schedule_cleanup(relid, handle, XACT_EVENT_ABORT);
*freezeXid = InvalidTransactionId;
*minmulti = InvalidMultiXactId;
}
DROP TABLE: release on commit
The object access hook from Part 4 released the arena as soon as the drop was processed. The only change needed is to schedule the release for the commit instead, so the call to memtable_release_arena becomes a call to memtable_schedule_cleanup:
static void memtable_object_access(ObjectAccessType access, Oid classId,
Oid objectId, int subId, void* arg) {
if (prev_object_access_hook)
prev_object_access_hook(access, classId, objectId, subId, arg);
if (access == OAT_DROP && classId == RelationRelationId && subId == 0) {
bool uses_memtable;
dsm_handle handle = memtable_catalog_lookup(objectId, &uses_memtable);
if (handle != DSM_HANDLE_INVALID && uses_memtable)
memtable_schedule_cleanup(objectId, handle, XACT_EVENT_COMMIT);
}
}
The earlier example now behaves as it should. The rolled-back drop leaves the table with its arena, and the second drop succeeds:
CREATE TABLE accounts (id bigint) USING memtable;
BEGIN;
DROP TABLE accounts;
ROLLBACK;
DROP TABLE accounts; -- works
Savepoints
There is one more way for a transaction to roll back part of what it did, and the code so far does not handle it. A subtransaction, started by SAVEPOINT, can be rolled back with ROLLBACK TO while the transaction as a whole goes on to commit. The transaction callback only runs for the outcome of the whole transaction, so everything that was scheduled inside the rolled-back subtransaction would stay in the list and be treated as if it belonged to the final commit:
BEGIN;
SAVEPOINT before_drop;
DROP TABLE accounts;
ROLLBACK TO before_drop; -- drop is undone
COMMIT; -- wrongly releases the arena of accounts
The same happens in the other direction. A CREATE TABLE inside the savepoint is undone by ROLLBACK TO, but the entry that was waiting for an abort never fires because the transaction commits, so the arena leaks.
This is fixed by resolving the entries of a subtransaction when it ends. For that, each entry records which subtransaction scheduled it:
typedef struct MemTablePendingCleanup {
Oid relid;
dsm_handle handle;
XactEvent event; /* release on this event */
SubTransactionId subid; /* innermost (sub)transaction that scheduled it */
} MemTablePendingCleanup;
memtable_schedule_cleanup fills in the subid field with GetCurrentSubTransactionId(). A callback registered with RegisterSubXactCallback is then called when a subtransaction ends. As with RegisterXactCallback, the registration goes in _PG_init:
void _PG_init(void) {
...
RegisterSubXactCallback(memtable_subxact_callback, NULL);
...
}
What it does depends on how the subtransaction ended:
- If it committed, its entries are handed over to the parent subtransaction. Whether they take effect is decided when the parent ends, and ultimately by the outcome of the whole transaction.
- If it aborted, its entries are resolved right away. The ones waiting for an abort release their arena now, and the ones waiting for a commit are discarded, since the work they belonged to has been undone.
static void memtable_subxact_callback(SubXactEvent event,
SubTransactionId mySubid,
SubTransactionId parentSubid, void* arg) {
ListCell* lc;
if (event != SUBXACT_EVENT_COMMIT_SUB && event != SUBXACT_EVENT_ABORT_SUB)
return;
foreach (lc, pending_cleanups) {
MemTablePendingCleanup* item = lfirst(lc);
if (item->subid != mySubid)
continue;
if (event == SUBXACT_EVENT_COMMIT_SUB) {
item->subid = parentSubid;
continue;
}
if (item->event == XACT_EVENT_ABORT && item->handle != DSM_HANDLE_INVALID) {
memtable_release_arena(item->handle);
memtable_cache_remove(item->relid);
}
pfree(item);
pending_cleanups = foreach_delete_current(pending_cleanups, lc);
}
}
Note: A
Listis an array, and removing a cell moves all later cells one position down. A plainforeachwould then step past the entry that just moved into the vacated position.foreach_delete_currentremoves the cell and also steps the loop back by one position, so that entry is visited next. It returns the updated list, which is why the result is assigned back topending_cleanups. When the last entry is removed, the list is freed andNILis returned.
Seeing it work
The savepoint cases can be tried from psql without any working INSERT or SELECT. After a rolled-back CREATE TABLE, the table is gone, and after a rolled-back DROP TABLE, it is still there with its arena, so it can be dropped for real afterward:
BEGIN;
SAVEPOINT before_create;
CREATE TABLE customers (id bigint) USING memtable;
ROLLBACK TO before_create;
COMMIT;
SELECT count(*) FROM pg_class WHERE relname = 'customers';
CREATE TABLE accounts (id bigint) USING memtable;
BEGIN;
SAVEPOINT before_drop;
DROP TABLE accounts;
ROLLBACK TO before_drop;
COMMIT;
DROP TABLE accounts; -- works
Next
Arena creation and dropping are now transactional, with and without savepoints. The next post adds TRUNCATE, which replaces an arena instead of creating or dropping one.
Appendix: the complete code
This is the complete memtable.c as it stands at the end of this post. It is also available as code/part5-transactions/memtable.c together with the Makefile, control file and SQL script from Part 2, which have not changed. Most of the callbacks that are not needed yet raise the error not yet implemented. The few that Postgres calls while creating a table or planning a query return harmless defaults instead. The table access method can therefore create and drop tables, also inside transactions and savepoints that roll back, but cannot read or write them.
#include <postgres.h>
#include <fmgr.h>
#include <access/heapam.h>
#include <access/htup_details.h>
#include <access/multixact.h>
#include <access/tableam.h>
#include <access/transam.h>
#include <access/xact.h>
#include <catalog/indexing.h>
#include <catalog/namespace.h>
#include <catalog/objectaccess.h>
#include <catalog/pg_class.h>
#include <commands/defrem.h>
#include <miscadmin.h>
#include <nodes/parsenodes.h>
#include <nodes/pg_list.h>
#include <storage/dsm.h>
#include <storage/ipc.h>
#include <storage/lwlock.h>
#include <tcop/utility.h>
#include <utils/builtins.h>
#include <utils/guc.h>
#include <utils/hsearch.h>
#include <utils/inval.h>
#include <utils/memutils.h>
#include <utils/rel.h>
#include <utils/syscache.h>
PG_MODULE_MAGIC;
#define MEMTABLE_EXTNAME "memtable"
#define NOT_IMPLEMENTED \
ereport(ERROR, \
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED), \
errmsg("memtable callback %s not yet implemented", __func__)))
/*
* Arena header
*/
typedef struct MemTableArenaHeader {
LWLock lock; /* serialises allocation */
uint64 tuple_free; /* bump-allocator cursor: next free byte */
uint64 size; /* segment capacity, fixed at creation */
} MemTableArenaHeader;
/*
* Per-backend local state: one entry per attached relation
*/
typedef struct MemTableStateCacheEntry {
Oid relid; /* hash key */
dsm_segment* seg;
void* arena_base;
MemTableArenaHeader* hdr;
dsm_handle handle; /* handle of the arena `seg` is attached to */
} MemTableStateCacheEntry;
static int MemTableArenaTranche = -1;
int memtable_arena_size_kb = 1024; /* 1 MiB, small enough for a toy */
static shmem_startup_hook_type prev_shmem_startup = NULL;
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
static HTAB* local_state_cache = NULL;
/*
* Get a memtable cache entry or create it if not found.
*/
static MemTableStateCacheEntry* memtable_cache_enter(Oid relid) {
bool found;
MemTableStateCacheEntry* entry;
if (local_state_cache == NULL) {
HASHCTL ctl = {
.keysize = sizeof(Oid),
.entrysize = sizeof(MemTableStateCacheEntry),
};
local_state_cache =
hash_create("memtable local state", 16, &ctl, HASH_ELEM | HASH_BLOBS);
}
entry = hash_search(local_state_cache, &relid, HASH_ENTER, &found);
if (!found) {
entry->seg = NULL;
entry->arena_base = NULL;
entry->hdr = NULL;
entry->handle = DSM_HANDLE_INVALID;
}
return entry;
}
static MemTableStateCacheEntry* memtable_cache_find(Oid relid) {
MemTableStateCacheEntry* entry = NULL;
if (local_state_cache != NULL) {
entry = hash_search(local_state_cache, &relid, HASH_FIND, NULL);
if (entry == NULL || entry->seg == NULL)
entry = NULL;
}
return entry;
}
static void memtable_cache_remove(Oid relid) {
if (local_state_cache != NULL)
hash_search(local_state_cache, &relid, HASH_REMOVE, NULL);
}
/*
* Read pg_class.relfilenode for relid, which holds the DSM handle of the
* relation's arena, and report whether the relation uses memtable. Returns
* DSM_HANDLE_INVALID if there is no pg_class row (yet) for relid.
*/
static dsm_handle memtable_catalog_lookup(Oid relid, bool* is_memtable) {
HeapTuple tup = SearchSysCache1(RELOID, ObjectIdGetDatum(relid));
if (HeapTupleIsValid(tup)) {
Form_pg_class classForm = (Form_pg_class)GETSTRUCT(tup);
dsm_handle handle = (dsm_handle)classForm->relfilenode;
Oid memtable_oid = get_table_am_oid(MEMTABLE_EXTNAME, true);
bool result = OidIsValid(memtable_oid) && classForm->relam == memtable_oid;
if (is_memtable != NULL)
*is_memtable = result;
ReleaseSysCache(tup);
return handle;
}
if (is_memtable != NULL)
*is_memtable = false;
return DSM_HANDLE_INVALID;
}
static void memtable_shmem_startup_hook(void) {
if (prev_shmem_startup)
prev_shmem_startup();
MemTableArenaTranche = LWLockNewTrancheId();
LWLockRegisterTranche(MemTableArenaTranche, MEMTABLE_EXTNAME "_arena");
}
/*
* Arena creation
*/
static dsm_handle memtable_create_arena(Relation rel,
MemTableStateCacheEntry* entry) {
size_t arena_size = (size_t)memtable_arena_size_kb * 1024;
dsm_segment* seg = dsm_create(arena_size, 0);
dsm_handle handle = dsm_segment_handle(seg);
void* arena_base = dsm_segment_address(seg);
MemTableArenaHeader* hdr = arena_base;
dsm_pin_segment(seg); /* survive backend detach */
dsm_pin_mapping(seg); /* survive end-of-transaction in this backend */
memset(hdr, 0, sizeof(*hdr));
LWLockInitialize(&hdr->lock, MemTableArenaTranche);
hdr->tuple_free = MAXALIGN(sizeof(MemTableArenaHeader));
hdr->size = arena_size;
entry->seg = seg;
entry->arena_base = arena_base;
entry->hdr = hdr;
entry->handle = handle;
return handle;
}
/*
* Called after CREATE TABLE completes, once the arena's real DSM
* handle can safely be written to pg_class.relfilenode.
*
* This function is a no-op if the relation is not in the cache, which could be
* the case if it wasn't given a dsm_handle. This makes it safe to call on any
* relid without having to check whether it uses the memtable access method
* first.
*
* After this, any backend can attach the arena with
* dsm_attach(rel->rd_locator.relNumber).
*/
static void memtable_finalize_new_relation(Oid relid) {
MemTableStateCacheEntry* entry = memtable_cache_find(relid);
if (entry != NULL) {
dsm_handle handle = dsm_segment_handle(entry->seg);
Relation pg_class_rel = table_open(RelationRelationId, RowExclusiveLock);
HeapTuple tup = SearchSysCacheCopy1(RELOID, ObjectIdGetDatum(relid));
memtable_cache_remove(relid); /* the handle is all that is needed now */
if (HeapTupleIsValid(tup)) {
Form_pg_class classForm = (Form_pg_class)GETSTRUCT(tup);
classForm->relfilenode = (RelFileNumber)handle;
CatalogTupleUpdate(pg_class_rel, &tup->t_self, tup);
heap_freetuple(tup);
CommandCounterIncrement();
CacheInvalidateRelcacheByRelid(relid);
} else {
ereport(ERROR, (errcode(ERRCODE_INTERNAL_ERROR),
errmsg("pg_class row for relid %u not found", relid)));
}
table_close(pg_class_rel, RowExclusiveLock);
}
}
/*
* ProcessUtility hook: finalize the arena's relfilenode once the DDL that
* created it has returned. pg_class doesn't have a row yet when our TAM
* callback runs (see memtable_finalize_new_relation's own comment).
*
* There is no need to work out from the parse tree which relations use
* memtable. memtable_finalize_new_relation does nothing for a relation that
* has no cache entry, and only relations whose storage was set up by
* memtable_relation_set_new_filelocator have one. That also covers a CREATE
* TABLE that ends up using memtable only because default_table_access_method
* is set, where CreateStmt->accessMethod is NULL.
*/
static void memtable_ProcessUtility(PlannedStmt* pstmt, const char* queryString,
bool readOnlyTree,
ProcessUtilityContext context,
ParamListInfo params,
QueryEnvironment* queryEnv,
DestReceiver* dest, QueryCompletion* qc) {
Node* parsetree = pstmt->utilityStmt;
if (prev_ProcessUtility)
prev_ProcessUtility(pstmt, queryString, readOnlyTree, context, params,
queryEnv, dest, qc);
else
standard_ProcessUtility(pstmt, queryString, readOnlyTree, context, params,
queryEnv, dest, qc);
if (IsA(parsetree, CreateStmt)) {
CreateStmt* cstmt = (CreateStmt*)parsetree;
Oid relid = RangeVarGetRelid(cstmt->relation, NoLock, true);
memtable_finalize_new_relation(relid);
}
}
/*
* Arena lifecycle cleanup -- deferred to transaction end
*
* Two different events can mean an arena needs to go away. DROP TABLE can
* still roll back, so the arena can't be torn down the moment
* object_access_hook sees the drop. It has to wait for the transaction to
* actually commit. Symmetrically, if CREATE TABLE itself rolls back, the arena
* it already created needs to be torn down on abort instead.
*/
typedef struct MemTablePendingCleanup {
Oid relid;
dsm_handle handle;
XactEvent event; /* release on this event */
SubTransactionId subid; /* innermost (sub)transaction that scheduled it */
} MemTablePendingCleanup;
static List* pending_cleanups = NIL;
static void memtable_release_arena(dsm_handle handle) {
dsm_segment* seg = dsm_find_mapping(handle);
dsm_unpin_segment(handle); /* must precede the final detach */
if (seg != NULL)
dsm_detach(seg);
}
static void memtable_xact_callback(XactEvent event, void* arg) {
/*
* A prepared transaction is finished later, possibly by another backend,
* and there is no callback for COMMIT PREPARED or ROLLBACK PREPARED, so the
* pending entries could never be resolved at the right time.
*/
if (event == XACT_EVENT_PRE_PREPARE && pending_cleanups != NIL)
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("cannot PREPARE a transaction that has created or dropped "
"a memtable relation")));
if (event == XACT_EVENT_COMMIT || event == XACT_EVENT_ABORT) {
ListCell* lc;
foreach (lc, pending_cleanups) {
MemTablePendingCleanup* item = lfirst(lc);
Assert(item->event == XACT_EVENT_COMMIT ||
item->event == XACT_EVENT_ABORT);
if (item->event == event && item->handle != DSM_HANDLE_INVALID)
memtable_release_arena(item->handle);
memtable_cache_remove(item->relid);
pfree(item);
}
list_free(pending_cleanups);
pending_cleanups = NIL;
}
}
/*
* A subtransaction that aborts undoes everything scheduled inside it.
*
* On abort, resolve the items scheduled in this subtransaction now: release
* the ones waiting for ABORT, discard the ones waiting for COMMIT. On commit,
* hand them to the parent, which decides when the top level ends.
*/
static void memtable_subxact_callback(SubXactEvent event,
SubTransactionId mySubid,
SubTransactionId parentSubid, void* arg) {
ListCell* lc;
if (event != SUBXACT_EVENT_COMMIT_SUB && event != SUBXACT_EVENT_ABORT_SUB)
return;
foreach (lc, pending_cleanups) {
MemTablePendingCleanup* item = lfirst(lc);
if (item->subid != mySubid)
continue;
if (event == SUBXACT_EVENT_COMMIT_SUB) {
item->subid = parentSubid;
continue;
}
/*
* Only an arena being released is what the local state entry points at;
* an item waiting for COMMIT (DROP) leaves it alone.
*/
if (item->event == XACT_EVENT_ABORT && item->handle != DSM_HANDLE_INVALID) {
memtable_release_arena(item->handle);
memtable_cache_remove(item->relid);
}
pfree(item);
pending_cleanups = foreach_delete_current(pending_cleanups, lc);
}
}
/*
* Schedule releasing the arena named by handle when the current transaction
* ends with the given event (COMMIT or ABORT).
*/
static void memtable_schedule_cleanup(Oid relid, dsm_handle handle,
XactEvent event) {
MemoryContext oldcxt = MemoryContextSwitchTo(TopMemoryContext);
MemTablePendingCleanup* item = palloc_object(MemTablePendingCleanup);
item->relid = relid;
item->handle = handle;
item->event = event;
item->subid = GetCurrentSubTransactionId();
pending_cleanups = lappend(pending_cleanups, item);
MemoryContextSwitchTo(oldcxt);
}
/*
* object_access_hook fires for every dropped object regardless of DDL
* shape (DROP TABLE, DROP TABLE CASCADE, ...), which is simpler than trying
* to pick apart DropStmt the way memtable_ProcessUtility picks apart
* CreateStmt.
*/
static object_access_hook_type prev_object_access_hook = NULL;
static void memtable_object_access(ObjectAccessType access, Oid classId,
Oid objectId, int subId, void* arg) {
if (prev_object_access_hook)
prev_object_access_hook(access, classId, objectId, subId, arg);
if (access == OAT_DROP && classId == RelationRelationId && subId == 0) {
bool uses_memtable;
dsm_handle handle = memtable_catalog_lookup(objectId, &uses_memtable);
if (handle != DSM_HANDLE_INVALID && uses_memtable)
memtable_schedule_cleanup(objectId, handle, XACT_EVENT_COMMIT);
}
}
/*
* Slot related callbacks
*/
static const TupleTableSlotOps* memtable_slot_callbacks(Relation rel) {
return &TTSOpsHeapTuple;
}
/*
* Table scan callbacks -- not yet: this post only covers the arena's
* lifecycle, not reading or writing tuples in it.
*/
static TableScanDesc memtable_scan_begin(Relation rel, Snapshot snapshot,
int nkeys, struct ScanKeyData* key,
ParallelTableScanDesc pscan,
uint32 flags) {
NOT_IMPLEMENTED;
return NULL;
}
static void memtable_scan_end(TableScanDesc sscan) {
NOT_IMPLEMENTED;
}
static void memtable_scan_rescan(TableScanDesc sscan, struct ScanKeyData* key,
bool set_params, bool allow_strat,
bool allow_sync, bool allow_pagemode) {
NOT_IMPLEMENTED;
}
static bool memtable_scan_getnextslot(TableScanDesc sscan,
ScanDirection direction,
TupleTableSlot* slot) {
NOT_IMPLEMENTED;
return false;
}
static void memtable_scan_set_tidrange(TableScanDesc scan, ItemPointer mintid,
ItemPointer maxtid) {
NOT_IMPLEMENTED;
}
static bool memtable_scan_getnextslot_tidrange(TableScanDesc scan,
ScanDirection direction,
TupleTableSlot* slot) {
NOT_IMPLEMENTED;
return false;
}
/*
* Parallel table scan related functions
*/
static Size memtable_parallelscan_estimate(Relation rel) {
NOT_IMPLEMENTED;
return 0;
}
static Size memtable_parallelscan_initialize(Relation rel,
ParallelTableScanDesc pscan) {
NOT_IMPLEMENTED;
return 0;
}
static void memtable_parallelscan_reinitialize(Relation rel,
ParallelTableScanDesc pscan) {
NOT_IMPLEMENTED;
}
/*
* Index scan callbacks -- no index yet
*/
static struct IndexFetchTableData* memtable_index_fetch_begin(Relation rel) {
NOT_IMPLEMENTED;
return NULL;
}
static void memtable_index_fetch_reset(struct IndexFetchTableData* data) {
NOT_IMPLEMENTED;
}
static void memtable_index_fetch_end(struct IndexFetchTableData* data) {
NOT_IMPLEMENTED;
}
static bool memtable_index_fetch_tuple(struct IndexFetchTableData* scan,
ItemPointer tid, Snapshot snapshot,
TupleTableSlot* slot, bool* call_again,
bool* all_dead) {
NOT_IMPLEMENTED;
return false;
}
/*
* Callbacks for non-modifying operations on individual tuples
*/
static bool memtable_tuple_fetch_row_version(Relation rel, ItemPointer tid,
Snapshot snapshot,
TupleTableSlot* slot) {
NOT_IMPLEMENTED;
return false;
}
static bool memtable_tuple_tid_valid(TableScanDesc scan, ItemPointer tid) {
NOT_IMPLEMENTED;
return false;
}
static void memtable_tuple_get_latest_tid(TableScanDesc scan, ItemPointer tid) {
NOT_IMPLEMENTED;
}
static bool memtable_tuple_satisfies_snapshot(Relation rel,
TupleTableSlot* slot,
Snapshot snapshot) {
NOT_IMPLEMENTED;
return false;
}
static TransactionId memtable_index_delete_tuples(Relation rel,
TM_IndexDeleteOp* delstate) {
NOT_IMPLEMENTED;
return InvalidTransactionId;
}
/*
* Manipulations of physical tuples
*/
static void memtable_tuple_insert(Relation rel, TupleTableSlot* slot,
CommandId cid, int options,
struct BulkInsertStateData* bistate) {
NOT_IMPLEMENTED;
}
static void memtable_tuple_insert_speculative(
Relation rel, TupleTableSlot* slot, CommandId cid, int options,
struct BulkInsertStateData* bistate, uint32 specToken) {
NOT_IMPLEMENTED;
}
static void memtable_tuple_complete_speculative(Relation rel,
TupleTableSlot* slot,
uint32 specToken,
bool succeeded) {
NOT_IMPLEMENTED;
}
static void memtable_multi_insert(Relation rel, TupleTableSlot** slots,
int nslots, CommandId cid, int options,
struct BulkInsertStateData* bistate) {
NOT_IMPLEMENTED;
}
static TM_Result memtable_tuple_delete(Relation rel, ItemPointer tid,
CommandId cid, Snapshot snapshot,
Snapshot crosscheck, bool wait,
TM_FailureData* tmfd,
bool changingPart) {
NOT_IMPLEMENTED;
return TM_Ok;
}
static TM_Result memtable_tuple_update(Relation rel, ItemPointer otid,
TupleTableSlot* slot, CommandId cid,
Snapshot snapshot, Snapshot crosscheck,
bool wait, TM_FailureData* tmfd,
LockTupleMode* lockmode,
TU_UpdateIndexes* update_indexes) {
NOT_IMPLEMENTED;
return TM_Ok;
}
static TM_Result memtable_tuple_lock(Relation rel, ItemPointer tid,
Snapshot snapshot, TupleTableSlot* slot,
CommandId cid, LockTupleMode mode,
LockWaitPolicy wait_policy, uint8 flags,
TM_FailureData* tmfd) {
NOT_IMPLEMENTED;
return TM_Ok;
}
/*
* DDL related functionality
*/
static void memtable_relation_set_new_filelocator(
Relation rel, const RelFileLocator* newrlocator, char persistence,
TransactionId* freezeXid, MultiXactId* minmulti) {
Oid relid = RelationGetRelid(rel);
MemTableStateCacheEntry* entry = memtable_cache_enter(relid);
dsm_handle handle = memtable_create_arena(rel, entry);
/* If this transaction aborts, don't leak the arena just created. */
memtable_schedule_cleanup(relid, handle, XACT_EVENT_ABORT);
*freezeXid = InvalidTransactionId;
*minmulti = InvalidMultiXactId;
}
static void memtable_relation_nontransactional_truncate(Relation rel) {
NOT_IMPLEMENTED;
}
static void memtable_relation_copy_data(Relation rel,
const RelFileLocator* newrlocator) {
NOT_IMPLEMENTED;
}
static void memtable_relation_copy_for_cluster(
Relation OldTable, Relation NewTable, 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 void memtable_relation_vacuum(Relation rel, struct VacuumParams* params,
BufferAccessStrategy bstrategy) {
NOT_IMPLEMENTED;
}
static bool memtable_scan_analyze_next_block(TableScanDesc scan,
ReadStream* stream) {
NOT_IMPLEMENTED;
return false;
}
static bool memtable_scan_analyze_next_tuple(TableScanDesc scan,
TransactionId OldestXmin,
double* liverows, double* deadrows,
TupleTableSlot* slot) {
NOT_IMPLEMENTED;
return false;
}
static double memtable_index_build_range_scan(
Relation table_rel, Relation index_rel, struct IndexInfo* index_info,
bool allow_sync, bool anyvisible, bool progress, BlockNumber start_blockno,
BlockNumber numblocks, IndexBuildCallback callback, void* callback_state,
TableScanDesc scan) {
NOT_IMPLEMENTED;
return 0;
}
static void memtable_index_validate_scan(Relation table_rel, Relation index_rel,
struct IndexInfo* index_info,
Snapshot snapshot,
struct ValidateIndexState* state) {
NOT_IMPLEMENTED;
}
/*
* Miscellaneous functions
*/
static uint64 memtable_relation_size(Relation rel, ForkNumber forkNumber) {
NOT_IMPLEMENTED;
return 0;
}
static bool memtable_relation_needs_toast_table(Relation rel) {
/* Queried during CREATE TABLE itself, so it can't just error out. */
return false;
}
static Oid memtable_relation_toast_am(Relation rel) {
NOT_IMPLEMENTED;
return InvalidOid;
}
static void memtable_relation_fetch_toast_slice(Relation toastrel, Oid valueid,
int32 attrsize,
int32 sliceoffset,
int32 slicelength,
struct varlena* result) {
NOT_IMPLEMENTED;
}
/*
* Planner related functions
*/
static void memtable_relation_estimate_size(Relation rel, int32* attr_widths,
BlockNumber* pages, double* tuples,
double* allvisfrac) {
/* No real cost model yet -- just enough for the planner to pick a
* sequential scan without erroring out. */
*pages = 1;
*tuples = 0;
*allvisfrac = 1.0;
}
/*
* Executor related functions
*/
static bool memtable_scan_bitmap_next_tuple(TableScanDesc scan,
TupleTableSlot* slot, bool* recheck,
uint64* lossy_pages,
uint64* exact_pages) {
NOT_IMPLEMENTED;
return false;
}
static bool memtable_scan_sample_next_block(TableScanDesc scan,
struct SampleScanState* scanstate) {
NOT_IMPLEMENTED;
return false;
}
static bool memtable_scan_sample_next_tuple(TableScanDesc scan,
struct SampleScanState* scanstate,
TupleTableSlot* slot) {
NOT_IMPLEMENTED;
return false;
}
/*
* The routine itself
*/
static const TableAmRoutine memtable_methods = {
.type = T_TableAmRoutine,
.slot_callbacks = memtable_slot_callbacks,
.scan_begin = memtable_scan_begin,
.scan_end = memtable_scan_end,
.scan_rescan = memtable_scan_rescan,
.scan_getnextslot = memtable_scan_getnextslot,
.scan_set_tidrange = memtable_scan_set_tidrange,
.scan_getnextslot_tidrange = memtable_scan_getnextslot_tidrange,
.parallelscan_estimate = memtable_parallelscan_estimate,
.parallelscan_initialize = memtable_parallelscan_initialize,
.parallelscan_reinitialize = memtable_parallelscan_reinitialize,
.index_fetch_begin = memtable_index_fetch_begin,
.index_fetch_reset = memtable_index_fetch_reset,
.index_fetch_end = memtable_index_fetch_end,
.index_fetch_tuple = memtable_index_fetch_tuple,
.tuple_fetch_row_version = memtable_tuple_fetch_row_version,
.tuple_tid_valid = memtable_tuple_tid_valid,
.tuple_get_latest_tid = memtable_tuple_get_latest_tid,
.tuple_satisfies_snapshot = memtable_tuple_satisfies_snapshot,
.index_delete_tuples = memtable_index_delete_tuples,
.tuple_insert = memtable_tuple_insert,
.tuple_insert_speculative = memtable_tuple_insert_speculative,
.tuple_complete_speculative = memtable_tuple_complete_speculative,
.multi_insert = memtable_multi_insert,
.tuple_delete = memtable_tuple_delete,
.tuple_update = memtable_tuple_update,
.tuple_lock = memtable_tuple_lock,
.finish_bulk_insert = NULL, /* the one optional callback */
.relation_set_new_filelocator = memtable_relation_set_new_filelocator,
.relation_nontransactional_truncate =
memtable_relation_nontransactional_truncate,
.relation_copy_data = memtable_relation_copy_data,
.relation_copy_for_cluster = memtable_relation_copy_for_cluster,
.relation_vacuum = memtable_relation_vacuum,
.scan_analyze_next_block = memtable_scan_analyze_next_block,
.scan_analyze_next_tuple = memtable_scan_analyze_next_tuple,
.index_build_range_scan = memtable_index_build_range_scan,
.index_validate_scan = memtable_index_validate_scan,
.relation_size = memtable_relation_size,
.relation_needs_toast_table = memtable_relation_needs_toast_table,
.relation_toast_am = memtable_relation_toast_am,
.relation_fetch_toast_slice = memtable_relation_fetch_toast_slice,
.relation_estimate_size = memtable_relation_estimate_size,
.scan_bitmap_next_tuple = memtable_scan_bitmap_next_tuple,
.scan_sample_next_block = memtable_scan_sample_next_block,
.scan_sample_next_tuple = memtable_scan_sample_next_tuple,
};
PG_FUNCTION_INFO_V1(memtable_handler);
Datum memtable_handler(PG_FUNCTION_ARGS) {
PG_RETURN_POINTER(&memtable_methods);
}
/*
* Module init
*/
void _PG_init(void) {
DefineCustomIntVariable("memtable.arena_size",
"Size of each memtable arena, in KB.", NULL,
&memtable_arena_size_kb, 1024, 64, 4 * 1024 * 1024,
PGC_USERSET, GUC_UNIT_KB, NULL, NULL, NULL);
prev_shmem_startup = shmem_startup_hook;
shmem_startup_hook = memtable_shmem_startup_hook;
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = memtable_ProcessUtility;
prev_object_access_hook = object_access_hook;
object_access_hook = memtable_object_access;
RegisterXactCallback(memtable_xact_callback, NULL);
RegisterSubXactCallback(memtable_subxact_callback, NULL);
} 
Comments