是否可以在postgresql中定义全局变量 [英] Is it possible to define global variables in postgresql

查看:1516
本文介绍了是否可以在postgresql中定义全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用postgresql 9.4,并且在编写函数时我想使用自定义的error_codes(int)。但是,我可能希望稍后更改确切的数值

例如

-1表示USER_NOT_FOUND。

-2表示USER_DOES_NOT_HAVE_PERMISSION。


我可以在一个表codes_table(code_name :: text,code_value :: integer)中定义它们,并在函数中使用它们,如下所示:

 (SELECT codes_table.code_value FROM codes_table WHERE codes_table.code_name ='USER_NOT_FOUND')

有没有另外一种方法。也许是全局变量?

解决方案

Postgres没有全局变量。
但是您可以定义自定义配置参数。
为了保持清晰,请使用给定的前缀定义自己的参数,比如 glb



函数将更容易将参数放置在查询中:

 创建或替换函数glb(代码文本)
返回整数语言sql as $$
select current_setting('glb。'|| code):: integer;
$$;

将glb.user_not_found设为-1;
将glb.user_does_not_have_permission设置为-2;

选择glb('user_not_found'),glb('user_does_not_have_permission');

用户定义的参数在会话中是本地的,因此参数应该在每个会话。


I am using postgresql 9.4 and while writing functions I want to use self-defined error_codes (int). However I may want to change the exact numeric values later.
For instance
-1 means USER_NOT_FOUND.
-2 means USER_DOES_NOT_HAVE_PERMISSION.

I can define these in a table codes_table(code_name::text, code_value::integer) and use them in functions as follows

(SELECT codes_table.code_value FROM codes_table WHERE codes_table.code_name = 'USER_NOT_FOUND')

Is there another way for this. Maybe global variables?

解决方案

Postgres does not have global variables. However you can define custom configuration parameters. To keep things clear define your own parameters with a given prefix, say glb.

This simple function will make it easier to place the parameter in queries:

create or replace function glb(code text)
returns integer language sql as $$
    select current_setting('glb.' || code)::integer;
$$;

set glb.user_not_found to -1;
set glb.user_does_not_have_permission to -2;

select glb('user_not_found'), glb('user_does_not_have_permission');

User-defined parameters are local in the session, therefore the parameters should be defined at the beginning of each session.

这篇关于是否可以在postgresql中定义全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆