_PG_init首先使用DefineCustomTypeVariable定义GUC变量,以pgaudit.log为例,auditLog是pgaudit.c中定义的char *指针变量,check_pgaudit_log和assign_pgaudit_log是pgaudit.c中定义的函数。
/* Define GUC variables and install hooks upon module load. */
void _PG_init(void) {
...
/* Define pgaudit.log */
DefineCustomStringVariable(
"pgaudit.log",
"Specifies which classes of statements will be logged by session audit "
"logging. Multiple classes can be provided using a comma-separated "
"list and classes can be subtracted by prefacing the class with a "
"- sign.",
NULL,
&auditLog,
"none",
PGC_SUSET,
GUC_LIST_INPUT | GUC_NOT_IN_SAMPLE,
check_pgaudit_log,
assign_pgaudit_log,
NULL);
....
将我们定义的钩子加入PG的钩子链。如下图就是pgaudit.c中定义的临时钩子指针变量,用于保存PG已经引入的钩子变量,然后将我们定义的钩子挂在标准的钩子上,也就是我们熟悉的单链表头插法。
/* Install our hook functions after saving the existing pointers to preserve the chains. */
next_ExecutorStart_hook = ExecutorStart_hook;
ExecutorStart_hook = pgaudit_ExecutorStart_hook;
next_ExecutorCheckPerms_hook = ExecutorCheckPerms_hook;
ExecutorCheckPerms_hook = pgaudit_ExecutorCheckPerms_hook;
next_ProcessUtility_hook = ProcessUtility_hook;
ProcessUtility_hook = pgaudit_ProcessUtility_hook;
next_object_access_hook = object_access_hook;
object_access_hook = pgaudit_object_access_hook;
/* The following hook functions are required to get rows */
next_ExecutorRun_hook = ExecutorRun_hook;
ExecutorRun_hook = pgaudit_ExecutorRun_hook;
next_ExecutorEnd_hook = ExecutorEnd_hook;
ExecutorEnd_hook = pgaudit_ExecutorEnd_hook;
以pgaudit_ExecutorStart_hook为例,先执行pgaudit_ExecutorStart_hook钩子函数,最后判断后续有没有钩子需要继续执行,没有就执行执行PG标准应该执行的函数。
下一篇博客集中讲解pgaudit_ExecutorCheckPerms_hook、pgaudit_ExecutorStart_hook、pgaudit_ProcessUtility_hook、pgaudit_object_access_hook、pgaudit_ExecutorRun_hook和pgaudit_ExecutorEnd_hook的实现。
https://github.com/pgaudit/pgaudit/blob/master/pgaudit.c