The best way to separate users and applications within a single database is to use schemas:
link
A schema is part of the qualification of an object. When a t
table is created on the base b
its full name will be b.[esquema].t
:
b=> create table t (c text);
CREATE TABLE
b=> \d t
Table "public.t"
Column | Type | Modifiers
--------+------+-----------
c | text |
b=> select * from b.public.t;
c
---
(0 rows)
The schema used in the name, if not specified, is the current schema:
b=> select current_schema;
current_schema
----------------
public
The current schema is the first schema in the search path that exists:
b=> show search_path;
search_path
-----------------
"$user", public
If there was a schema with the user name of the session this would be the current schema.
To make a schema the current schema, point the search path to that schema:
b=> set search_path to s1;
SET
b=> show search_path;
search_path
-------------
s1
If we select the current scheme it will return null because there is no scheme s1:
b=> select current_schema;
current_schema
----------------
(1 row)
To create the schema:
b=> create schema s1;
CREATE SCHEMA
b=> select current_schema;
current_schema
----------------
s1
Now we can create a t
table in the s1
schema without needing to qualify the schema:
b=> create table t (c text);
CREATE TABLE
Since there was already a t
table in the public
schema, there are now two. One in the public
scheme and the other in the s1
schema:
b=> \d *.t
Table "public.t"
Column | Type | Modifiers
--------+------+-----------
c | text |
Table "s1.t"
Column | Type | Modifiers
--------+------+-----------
c | text |
As the current schema is s1
it is not necessary to qualify the name to insert in s1.t
:
b=> insert into t (c) values ('texto');
INSERT 0 1
b=> select * from t;
c
-------
texto
(1 row)
b=> select * from public.t;
c
---
(0 rows)
If the schema is no longer needed:
b=> drop schema s1 cascade;
NOTICE: drop cascades to table t
DROP SCHEMA
cascade
collapses all dependent objects. Go back to the default search path:
b=> set search_path to "$user", public;
SET
b=> select current_schema;
current_schema
----------------
public