Every table in pg_memtable gets its own arena, a Dynamic Shared Memory segment. The tricky part is how other backends find it. This post stores the segment’s handle in pg_class.relfilenode, so any backend can attach with one call, and hooks CREATE TABLE and DROP TABLE to create and release the arena.
Part 3 covered how to create a DSM segment, how to pin it so it survives, and the generic problem of getting its handle to whichever backend needs it. In this post you will see how this can be used to create a storage arena for the memtable relation.
For the time being, transactions are ignored, so everything in this post assumes that the transactions involved commit. Dealing with transactions is the topic for the next post.
The plan
To implement support for the storage, three things need to be handled:
- Allocate storage when the relation is created.
- Save the DSM handle somewhere so that the storage can be accessed when reading and writing the table.
- Release the storage when the relation is dropped.
Part 2 discussed the per-relation field relfilenode, which holds a filenode number to the storage allocated to the relation and is assigned when the relation is created. This is a 32-bit number, exactly like a dsm_handle, and pg_class is a catalog every backend can already read. So instead of building a side table to hold the handle, or storing it in shared memory, pg_memtable writes the DSM handle straight into relfilenode.
Once that write has happened, a simple dsm_attach(rel->rd_locator.relNumber) is enough for any backend to find the arena for that relation. No side table, no extra LWLock to protect it, no second source of truth that could ever drift from pg_class itself.
There is one problem though, and there was a hint at it in the previous post: relation_set_new_filelocator runs too early to touch the catalog.
Part 2 walked through what DefineRelation sets in motion to create the relation and assign its storage, down to the point where relation_set_new_filelocator gets called. The full call sequence when executing a utility statement looks like this:
1. ProcessUtility()
2. └─ standard_ProcessUtility()
3. └─ DefineRelation()
4. └─ heap_create_with_catalog()
5. ├─ GetNewRelFileNumber()
6. ├─ heap_create()
7. │ └─ relation_set_new_filelocator()
8. └─ AddNewRelationTuple()
This is the problem: the callback relation_set_new_filelocator runs at step 7, but the pg_class row isn’t inserted until step 8. The callback is handed a RelFileLocator for a catalog row that doesn’t exist yet, so there’s nothing to update.
Fortunately, Postgres already has a hook ProcessUtility_hook in ProcessUtility that can be used. If a hook is installed, it is executed at step 2 instead of standard_ProcessUtility, and it is then up to the hook to make sure that standard_ProcessUtility is called.
So instead of writing the handle to the catalog from the callback, this is implemented in four parts:
- Create a backend-local cache to store the handle.
- Create a function that creates the segment and writes the handle to the cache.
- Create a function that updates the
relfilenodeentry inpg_classfor the relation. - Add a hook that calls that function once the
pg_classrow exists.
Note: Utility commands are any commands that do not go through the planning and optimizing phase, which are the DDL and administrative commands. The “optimizable” statements are
SELECT,DELETE,UPDATE, andINSERTand they typically go through a planning and optimization phase, hence are not utility commands.
Building a backend-local cache
Building a backend-local cache is straightforward and is usually done using a hash table. Since the cache is only used inside one backend, there is no need for a lock. It also does not need to be invalidated when another backend changes something, because an entry is meant to live only for the duration of one CREATE TABLE statement. It is created by the callback and consumed and removed by the hook shortly afterward, in the same backend. This holds as long as the statement succeeds, and the next post shows what happens when it does not.
The cache is built by implementing three functions:
memtable_cache_enterto fetch a cache entry or create a new one if it does not exist.memtable_cache_findto fetch an entry if it exists, but not create it if it does not exist.memtable_cache_removeto remove an entry.
The local state cache
The cache itself is just a hash table HTAB stored in a static variable in the module:
static HTAB* local_state_cache = NULL;
Each entry in the hash table is a MemTableStateCacheEntry, which is defined as:
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;
As mentioned in Leveraging Prepared Statements to Improve Performance, for hash table entry structures, the first field(s) have to be the key. It is common to define a dedicated structure to represent the key if you have a multi-position key, but in this case it is just the relation OID, stored directly in the structure.
Adding new cache entries
This function fetches or creates the entry for a relation. It is a thin wrapper around Postgres’s own hash_search, creates the hash table on first use, and initializes the fields of a newly created entry:
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;
}
Finding cache entries
memtable_cache_enter creates a blank entry when there is none. Code that only needs to ask “is there something cached for this relid” should not do that, which is what memtable_cache_find is for:
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;
}
It returns NULL both when there is no entry for relid and when there is one that does not point at a live segment. Every caller treats those two cases the same way.
Removing cache entries
Removing an entry is the third and simplest function:
static void memtable_cache_remove(Oid relid) {
if (local_state_cache != NULL)
hash_search(local_state_cache, &relid, HASH_REMOVE, NULL);
}
Creating the arena
The segment needs a small header before it can hold anything at all, which is used in future posts. For now that header just says how big the arena is and where the next free byte would start:
typedef struct MemTableArenaHeader {
LWLock lock; /* serialises allocation */
uint64 tuple_free; /* bump-allocator cursor: next free byte */
uint64 size; /* segment capacity, fixed at creation */
} MemTableArenaHeader;
And here is the function that creates the segment, writes that header, and records everything in the cache entry:
static dsm_segment* 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 seg;
}
dsm_createanddsm_segment_handleare used to create a new segment and fetch a handle for the segment.dsm_pin_segmentanddsm_pin_mappingwere described in Part 3. The first keeps the segment alive even when no backend has it mapped. The second keeps this backend’s mapping of it from being released automatically at the end of the transaction.LWLockInitializeis used to initialize theLWLockthat controls access to the segment later.- The
tuple_freefield points to the beginning of the free area just past the header. No tuples are allocated in this post since there’s no support forINSERTyet.
Setting storage for the table
All the pieces needed to start implementing storage for the table access method are now in place. When Postgres sets the file locator for a new table through the relation_set_new_filelocator callback, the arena is created and its handle ends up in the cache:
static void memtable_relation_set_new_filelocator(
Relation rel, const RelFileLocator* newrlocator, char persistence,
TransactionId* freezeXid, MultiXactId* minmulti) {
MemTableStateCacheEntry* entry = memtable_cache_enter(RelationGetRelid(rel));
memtable_create_arena(rel, entry);
*freezeXid = InvalidTransactionId;
*minmulti = InvalidMultiXactId;
}
Finalizing the entry in the catalog
The segment now exists and its handle is sitting in this backend’s local cache. What’s still missing is a function that copies that handle into relfilenode, and a hook that calls it at the right moment, once the pg_class row actually exists.
The function memtable_finalize_new_relation fetches the cache entry and persists the handle into the catalog row. By the time this runs, memtable_relation_set_new_filelocator has already populated the cache entry for this exact relid in this exact backend, as part of the very same statement, so there is no cross-backend gap to worry about. Once the handle has been read out of the entry, the entry has done its job and is removed.
The function does nothing if there is no entry for the relation. That is not an error, because the hook calls this function for every CREATE TABLE, and only the tables that use memtable have an entry. It also means the hook never has to work out which access method a new table uses. A missing pg_class row, on the other hand, can only mean that something is internally inconsistent, so that case is reported loudly:
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);
}
}
Raising ERROR here aborts the whole CREATE TABLE, and ERRCODE_INTERNAL_ERROR is the standard Postgres error code for a problem that should be impossible by construction. Continuing without an error would leave behind a relation whose relfilenode never got set, which would fail in other, less obvious way the first time anything tried to attach to its arena.
Two more calls make the new relfilenode visible:
CommandCounterIncrementmakes the updated row visible to the rest of the transaction.CacheInvalidateRelcacheByRelidmakes every other backend refresh its cached copy of the relation, so that they see the newrelfilenodethe next time they open it.
Installing a hook to finalize the catalog row
The final step is to ensure that the finalize function is called after the catalog row for the relation has been added. Since CREATE TABLE is a utility command, the right place to call memtable_finalize_new_relation once the row exists is the utility hook. This requires the extension to be added to shared_preload_libraries, which is just a limitation in how Postgres processes hooks and loads shared libraries. Hooking in to the ProcessUtility_hook is done in _PG_init, which saves away the old hook value and installs memtable_ProcessUtility in its place:
static ProcessUtility_hook_type prev_ProcessUtility = NULL;
void _PG_init(void) {
...
prev_ProcessUtility = ProcessUtility_hook;
ProcessUtility_hook = memtable_ProcessUtility;
...
}
The hook function calls standard_ProcessUtility first, and only afterward calls the finalize function for the new relation. Because the finalize function ignores relations without a cache entry, there is no need to check anything at all. The parse tree is still perfectly fine to read after the call, since nothing about running the statement frees it or rewrites its fields:
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);
}
}
Note: The hook never looks at
cstmt->accessMethod, which isNULLunlessUSINGwas written explicitly. Checking it before running the statement would have missed a table that ends up usingmemtableonly becausedefault_table_access_methodis set.
Now CREATE TABLE works: a segment is created, pinned so it survives, and its handle lands in relfilenode right after the row is inserted.
Next step is dealing with releasing the arena when the table is dropped.
Implementing DROP TABLE
If you look through the list of callbacks, you will notice that there is no callback for DROP TABLE, or any other callback that can release storage when a relation is dropped. Instead, the object access hook is used. An object access hook allows any extension to observe actions being taken on database objects, which includes DROP TABLE, but there are other accesses that can be monitored as well. DROP TABLE uses deleteOneObject to delete the objects, and calls the object_access_hook with OAT_DROP just before each object is dropped:
1. ProcessUtility()
2. └─ standard_ProcessUtility()
3. └─ ExecDropStmt()
4. └─ RemoveRelations()
5. └─ performMultipleDeletions()
6. └─ deleteOneObject()
7. ├─ RunObjectDropHook()
8. │ └─ (*object_access_hook)(OAT_DROP, ...)
9. └─ doDeletion()
RunObjectDropHook is what actually makes the indirect call through the object_access_hook pointer. Only after that does deleteOneObject move on to doDeletion, which is what removes the pg_class row. This means the hook fires while the row named by objectId is still available to read, and that makes it possible to find the handle of the arena that has to be released.
The hook is installed in _PG_init, the same way as the utility hook, and the function that handles it needs two things from the catalog:
- the handle stored in
relfilenode, and - whether the relation uses memtable at all, since the hook fires for every object that is dropped.
A simple catalog lookup function is created that will deal with both:
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;
}
The second argument of get_table_am_oid (suitably named missing_ok) says that it is fine if no access method with that name exists. In that case it returns InvalidOid instead of raising an error.
With the handle, the arena can be released in two steps:
dsm_unpin_segmenthas to be called to let the segment go away once nothing is attached to it. Since the segment was pinned usingdsm_pin_segment, it needs to be unpinned.dsm_detachhas to be called if this backend has the segment mapped. Whether it does can be found out by callingdsm_find_mapping, which returns the mapping, orNULLif there is none. The backend that created the arena has a mapping, becausedsm_pin_mappingkept it from being released at the end of the transaction. Any other backend may not have one.
The unpin comes first so that the final detach is allowed to destroy the segment:
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);
}
The hook function itself is then simply:
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_release_arena(handle);
}
}
Concluding remarks and next steps
You now have code that can create and drop tables using CREATE TABLE and DROP TABLE respectively. Try it from psql, and watch the handle appear in relfilenode:
CREATE TABLE t (id bigint) USING memtable;
SELECT relfilenode FROM pg_class WHERE relname = 't';
DROP TABLE t;
Transactions and TRUNCATE are not handled in this post, and a transaction that rolls back can leak memory.
In the next post, you will see how to handle transactions and after that you’ll learn about TRUNCATE, how it works, and how pg_memtable deals with it.
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/part4-arena-lifecycle/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 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_segment* 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 seg;
}
/*
* 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);
}
}
/* ------------------------------------------------------------------------
* DROP TABLE
* ------------------------------------------------------------------------ */
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);
}
/*
* 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.
*
* The arena is released right away here, which is only correct if the
* transaction commits.
*/
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_release_arena(handle);
}
}
/* ------------------------------------------------------------------------
* 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) {
MemTableStateCacheEntry* entry = memtable_cache_enter(RelationGetRelid(rel));
memtable_create_arena(rel, entry);
*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;
} 
Comments