共計 2288 個字符,預計需要花費 6 分鐘才能閱讀完成。
PostgreSQL 中有哪些鉤子函數,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
一、需求
刪除數據庫 pg12db 時,只能使用 pg12 用戶刪除,其他用戶(包括超級用戶)均不能刪除此數據庫。
二、實現步驟
刪除數據庫的命令是 drop database, 屬于 Utility 命令, 而 PG 提供了 ProcessUtility_hook 鉤子可供使用.
實現一個鉤子函數, 判斷 SQL 語句是否為 T_DropdbStmt, 如是, 則判斷數據庫名稱和用戶名稱是否匹配, 如不匹配, 則報錯, 源碼如下:
[pg12@localhost hookdemo_dbrestrict]$ cat hookdemo_dbrestrict.c
* This is a hook demo.
*
*/
#include postgres.h
#include miscadmin.h
#include tcop/utility.h
PG_MODULE_MAGIC;
void _PG_init(void);
void _PG_fini(void);
static char *undroppabledb = pg12db
static char *hooksuperuser = pg12
static ProcessUtility_hook_type prev_utility_hook = NULL;
static void hookdemodbrestrict_ProcessUtility(PlannedStmt *pstmt, const char *queryString,
ProcessUtilityContext context, ParamListInfo params,
QueryEnvironment *queryEnv,
DestReceiver *dest, char *completionTag)
/* Do our custom process on drop database */
switch(nodeTag(pstmt- utilityStmt))
{
case T_DropdbStmt:
{ DropdbStmt *stmt = (DropdbStmt *)pstmt- utilityStmt;
char *username = GetUserNameFromId(GetUserId(),false);
/*
* only user pg12 can drop pg12db.
*/
if (strcmp(stmt- dbname, undroppabledb) == 0
strcmp(username, hooksuperuser) != 0)
ereport(ERROR,(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),errmsg(Only superuser \ %s\ can drop database \ %s\ ,hooksuperuser,undroppabledb)));
break;
}
default:
break;
}
/*Standard process*/
standard_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, completionTag);
/* _PG_init */
_PG_init(void)
prev_utility_hook = ProcessUtility_hook;
ProcessUtility_hook = hookdemodbrestrict_ProcessUtility;
/* Uninstall */
_PG_fini(void)
ProcessUtility_hook = prev_utility_hook;
[pg12@localhost hookdemo_dbrestrict]$
三、實際效果
創建超級用戶 superx, 使用該用戶登錄, 創建 pg12db 數據庫, 刪除數據庫, 報錯.
[local:/data/run/pg12]:5120 pg12@testdb=# create user superx with superuser password root
CREATE ROLE
[local:/data/run/pg12]:5120 pg12@testdb=# \q
[pg12@localhost pg122db]$ psql -U superx
Expanded display is used automatically.
psql (12.2)
Type help for help.
[local:/data/run/pg12]:5120 superx@testdb=# create database pg12db;
CREATE DATABASE
[local:/data/run/pg12]:5120 superx@testdb=# drop database pg12db;
ERROR: Only superuser pg12 can drop database pg12db
[local:/data/run/pg12]:5120 superx@testdb=#
關于 PostgreSQL 中有哪些鉤子函數問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注丸趣 TV 行業資訊頻道了解更多相關知識。
正文完