PostgreSQL 中有哪些钩子函数
PostgreSQL 中有哪些钩子函数,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
一、需求删除数据库pg12db时,只能使用pg12用户删除,其他用户(包括超级用户)均不能删除此数据库。
二、实现步骤删除数据库的命令是drop database,属于Utility命令,而PG提供了ProcessUtility_hook钩子可供使用.
实现一个钩子函数,判断SQL语句是否为T_DropdbStmt,如是,则判断数据库名称和用户名称是否匹配,如不匹配,则报错,源码如下:
[pg12@localhosthookdemo_dbrestrict]$cathookdemo_dbrestrict.c/**Thisisahookdemo.**/#include"postgres.h"#include"miscadmin.h"#include"tcop/utility.h"PG_MODULE_MAGIC;void_PG_init(void);void_PG_fini(void);staticchar*undroppabledb="pg12db";staticchar*hooksuperuser="pg12";staticProcessUtility_hook_typeprev_utility_hook=NULL;staticvoidhookdemodbrestrict_ProcessUtility(PlannedStmt*pstmt,constchar*queryString,ProcessUtilityContextcontext,ParamListInfoparams,QueryEnvironment*queryEnv,DestReceiver*dest,char*completionTag){/*Doourcustomprocessondropdatabase*/switch(nodeTag(pstmt->utilityStmt)){caseT_DropdbStmt:{DropdbStmt*stmt=(DropdbStmt*)pstmt->utilityStmt;char*username=GetUserNameFromId(GetUserId(),false);/**onlyuserpg12candroppg12db.*/if(strcmp(stmt->dbname,undroppabledb)==0&&strcmp(username,hooksuperuser)!=0)ereport(ERROR,(errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),errmsg("Onlysuperuser\"%s\"candropdatabase\"%s\"",hooksuperuser,undroppabledb)));break;}default:break;}/*Standardprocess*/standard_ProcessUtility(pstmt,queryString,context,params,queryEnv,dest,completionTag);}/*_PG_init*/void_PG_init(void){prev_utility_hook=ProcessUtility_hook;ProcessUtility_hook=hookdemodbrestrict_ProcessUtility;}/*Uninstall*/void_PG_fini(void){ProcessUtility_hook=prev_utility_hook;}[pg12@localhosthookdemo_dbrestrict]$三、实际效果
创建超级用户superx,使用该用户登录,创建pg12db数据库,删除数据库,报错.
[local:/data/run/pg12]:5120pg12@testdb=#createusersuperxwithsuperuserpassword'root';CREATEROLE[local:/data/run/pg12]:5120pg12@testdb=#\q[pg12@localhostpg122db]$psql-UsuperxExpandeddisplayisusedautomatically.psql(12.2)Type"help"forhelp.[local:/data/run/pg12]:5120superx@testdb=#createdatabasepg12db;CREATEDATABASE[local:/data/run/pg12]:5120superx@testdb=#dropdatabasepg12db;ERROR:Onlysuperuser"pg12"candropdatabase"pg12db"[local:/data/run/pg12]:5120superx@testdb=#
关于PostgreSQL 中有哪些钩子函数问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。