From 318cfaded13c1a4c674c189865c2b07aaf09972d Mon Sep 17 00:00:00 2001
From: Phil Eaton <phil.eaton@enterprisedb.com>
Date: Tue, 14 May 2024 14:50:57 -0400
Subject: [PATCH v3] Add minimal C example and SQL registration example for
 custom table access methods.

---
 doc/src/sgml/tableam.sgml | 55 +++++++++++++++++++++++++++++++++++++--
 1 file changed, 53 insertions(+), 2 deletions(-)

diff --git a/doc/src/sgml/tableam.sgml b/doc/src/sgml/tableam.sgml
index 4b37f2e5a6..df12afe73f 100644
--- a/doc/src/sgml/tableam.sgml
+++ b/doc/src/sgml/tableam.sgml
@@ -35,13 +35,64 @@
   argument of type <type>internal</type> and to return the pseudo-type
   <type>table_am_handler</type>.  The argument is a dummy value that simply
   serves to prevent handler functions from being called directly from SQL commands.
+ </para>
+
+ <para>
+  Here is an example of how to register an extension that provides a
+  table access method handler:
+ </para>
+
+<screen>
+CREATE OR REPLACE FUNCTION my_tableam_handler(internal)
+RETURNS table_am_handler AS 'myextension', 'my_tableam_handler'
+LANGUAGE C STRICT;
 
+CREATE ACCESS METHOD myam TYPE TABLE HANDLER my_tableam_handler;
+</screen>
+
+ <para>
   The result of the function must be a pointer to a struct of type
   <structname>TableAmRoutine</structname>, which contains everything that the
   core code needs to know to make use of the table access method. The return
   value needs to be of server lifetime, which is typically achieved by
-  defining it as a <literal>static const</literal> variable in global
-  scope. The <structname>TableAmRoutine</structname> struct, also called the
+  defining it as a <literal>static const</literal> variable in global scope.
+ </para>
+
+ <para>
+  Here is what <filename>myextension.c</filename> with the table
+  access method handler might look like:
+ </para>
+
+<screen>
+#include "postgres.h"
+#include "fmgr.h"
+#include "access/tableam.h"
+#include "access/heapam.h"
+#include "nodes/execnodes.h"
+#include "catalog/index.h"
+#include "commands/vacuum.h"
+#include "utils/builtins.h"
+#include "executor/tuptable.h"
+
+PG_MODULE_MAGIC;
+
+const TableAmRoutine my_am_methods = {
+  .type = T_TableAmRoutine,
+
+  /* Methods from TableAmRoutine omitted from example, but all
+     non-optional ones must be provided here. */
+};
+
+PG_FUNCTION_INFO_V1(mem_tableam_handler);
+
+Datum mem_tableam_handler(PG_FUNCTION_ARGS)
+{
+        PG_RETURN_POINTER(&#038;my_am_methods);
+}
+</screen>
+
+ <para>
+  The <structname>TableAmRoutine</structname> struct, also called the
   access method's <firstterm>API struct</firstterm>, defines the behavior of
   the access method using callbacks. These callbacks are pointers to plain C
   functions and are not visible or callable at the SQL level. All the
-- 
2.39.3 (Apple Git-146)

