Re: creating variable views - Mailing list pgsql-sql

From Richard Huxton
Subject Re: creating variable views
Date
Msg-id 00b701c1015a$b330f8a0$1101a8c0@archonet.com
Whole thread Raw
In response to creating variable views  (Dado Feigenblatt <dado@wildbrain.com>)
List pgsql-sql
From: "Dado Feigenblatt" <dado@wildbrain.com>

> Hi. New to the list.

Welcome aboard :-)

> I'm building a database that will hold data for many different projects.
> Some people, or groups of people, will have access to just the rows of
data of their
> projects.
> Some are very granular. Let's use for this example the data about the
people itself.
> Other than the administrators, I want people to see only their own data.
> Instead of creating a view for each person, is it possible to create a
single view with
> variable data?
>
> CREATE VIEW user_info AS
> SELECT * FROM users
> WHERE user_name = pg_user
>
> where pg_user is the user name that person used to log into the database.
> Is there a way to get the user name in Postgresql?
> Even if the variable pg_user is not available,
> is it possible to create views using variables like that?

Nice idea, and seems to work:

richardh=> \c richardh richardh
You are now connected to database richardh as user richardh.
richardh=> \d usertest              Table "usertest"Attribute |         Type          | Modifier
-----------+-----------------------+----------username  | character varying(64) | not nullnum       | integer
   |
 
Index: usertest_name_idx

richardh=> \d utview               View "utview"Attribute |         Type          | Modifier
-----------+-----------------------+----------username  | character varying(64) |num       | integer               |
View definition: SELECT usertest.username, usertest.num FROM usertest WHERE
(name(usertest.username) = "current_user"());

richardh=> select * from usertest;username | num
----------+-----richardh |   1andy     |   2
(2 rows)

richardh=> select * from utview;username | num
----------+-----richardh |   1
(1 row)

richardh=> \c richardh andy
You are now connected to database richardh as user andy.
richardh=> select * from usertest;
ERROR:  usertest: Permission denied.
richardh=> select * from utview;username | num
----------+-----andy     |   2
(1 row)

richardh=> select version();                          version
-------------------------------------------------------------PostgreSQL 7.1.1 on i586-pc-linux-gnu, compiled by GCC
2.96



Interesting (to me anyway) to note that the view definition is based on a
compiled query, not what I typed since I used "username::name" in the cast
and CURRENT_USER rather than current_user()

HTH

- Richard Huxton



pgsql-sql by date:

Previous
From: "Kapil Tilwani"
Date:
Subject: Re: [GENERAL]
Next
From: "Josh Berkus"
Date:
Subject: Date validation?