The setup:
I use psycopg2 to access a (PostgreSQL) database I constructed in SQL.
I wanted to have different users, which can only access their own rows in a table. Therefore I added a UserId attribute to every table in the scheme. The value of UserId is available as a variable (let us name it pyUserId) to the program on execution.
All my calls to curs.execute() go through one function defined by me.
What I want to achieve:
Is it possible that I centrally set the value for an attribute, like UserId=pyUserId, for each query?
Else I had to pass the pyUserId as data on every query I already constructed, which also violates DRY, I suspect.
For example:
SELECT UserName FROM Users WHERE Age < 30 becomes:
SELECT UserName FROM Users WHERE Age < 30 AND UserId = pyUserId
or
INSERT INTO Profiles (Name, Bio, SoAccount) VALUES ('jon', 'blah...', '22656') becomes
INSERT INTO Profiles (Name, Bio, SoAccount, UserId) VALUES ('jon', 'blah...', '22656', pyUserId)
Same for DELETE etc.
What I tried:
- For
INSERTit is possible to dynamically ALTER the PostgreSQL DEFAULT constraint. But this would only apply to inserts. - According to string composition in psycopg2 docs, I can manipulate the SQL query string. But I guess there are a lot of pitfalls, operating on SQL strings.
- However, maybe there is a way to do this by manipulation of the prepared statement or the parse tree.
- I am not sure, if the idea is possible at all. If it is not, please explain why.