Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to define global variables in postgresql

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?

like image 823
Nuri Tasdemir Avatar asked Jul 09 '15 11:07

Nuri Tasdemir


People also ask

Can you declare a global variable?

Global variables refer to any variable that is defined outside of the function. Global variables can be accessed from any part of the script i.e. inside and outside of the function. So, a global variable can be declared just like other variable but it must be declared outside of function definition.

Can you declare variables in PostgreSQL?

PL/pgSQL variables can have any SQL data type, such as integer , varchar , and char . Here are some examples of variable declarations: user_id integer; quantity numeric(5); url varchar; myrow tablename%ROWTYPE; myfield tablename.

How do you define a global variable?

In computer programming, a global variable is a variable with global scope, meaning that it is visible (hence accessible) throughout the program, unless shadowed. The set of all global variables is known as the global environment or global state.


2 Answers

Postgresql does not support global variables on the DB level. Why not add it:

CREATE TABLE global_variables (
  key text not null PRIMARY KEY
  value text
);

INSERT INTO global_variables (key, value) VALUES ('error_code_for_spaceship_engine', '404');

If different types may be the values, consider JSON to be the type for value, but then deserialization code is required for each type.

like image 98
AlexGordon Avatar answered Oct 23 '22 11:10

AlexGordon


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.

like image 35
klin Avatar answered Oct 23 '22 11:10

klin