PostgreSQL 预编译语句 prepare,execute 语句
PostgreSQL 支持预编译语句功能,即同一类型的 SQL 语句,只是参数不同,这样的 SQL 语句只需要一次编译(prepare),就可以多次 执行(execute),在执行时传入不同的参数。
语法示例:
prepare p1(text,int) as update t set name=$1 where id=$2;
execute p1('a', 1);
execute p1('b', 2);
select * from pg_prepared_statement(); -- 查询所有缓存的prepare语句
deallocate p1; -- 释放缓存的p1
deallocate all; -- 释放所有缓存的prepare语句
内核实现分析:
prepare/execute 语句的实现代码主要在 src/backend/commands/prepare.c 文件。
backend 进程会缓存 prepare 语句,通过其名称将一个 prepare 语句放入 hash 表中,连接断开,缓存的 prepare 语句就会丢失。
static HTAB *prepared_queries = NULL;
执行 prepare 语句时,对应的处理函数如下:
void
PrepareQuery(ParseState *pstate, PrepareStmt *stmt,
int stmt_location, int stmt_len)
执行 execute 语句时,对应的处理函数如下:
void
ExecuteQuery(ParseState *pstate,
ExecuteStmt *stmt, IntoClause *intoClause,
ParamListInfo params,
DestReceiver *dest, QueryCompletion *qc)
执行 explain execute 语句时,对应的处理函数如下:
void
ExplainExecuteQuery(ExecuteStmt *execstmt, IntoClause *into, ExplainState *es,
const char *queryString, ParamListInfo params,
QueryEnvironment *queryEnv) 文章评论
共0条评论