forked from mtusi2026/mtusi2026lab2
Implement lab2 PostgreSQL authentication and Redis sessions
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
"""Show PostgreSQL rollback after partial composite operation, without modifying API code.
|
||||
Same two-table transaction pattern used by POST /chats, inject a FK failure midway.
|
||||
"""
|
||||
import os
|
||||
import uuid
|
||||
import psycopg
|
||||
from psycopg.errors import ForeignKeyViolation
|
||||
|
||||
|
||||
def main():
|
||||
with psycopg.connect(os.environ['DATABASE_URL']) as conn:
|
||||
uid = conn.execute('SELECT id FROM users LIMIT 1').fetchone()
|
||||
if uid is None:
|
||||
print('Create a user with make test first')
|
||||
raise SystemExit(1)
|
||||
cid = uuid.uuid4()
|
||||
try:
|
||||
with conn.transaction():
|
||||
conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s)', (cid, b'Rollback test'))
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,0)', (cid, uid[0]))
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id,position) VALUES (%s,%s,1)', (cid, uuid.uuid4()))
|
||||
raise AssertionError('FK should have failed')
|
||||
except ForeignKeyViolation:
|
||||
pass
|
||||
# Connection still usable because transaction block rolled back.
|
||||
orphan = conn.execute('SELECT 1 FROM chats WHERE id=%s', (cid,)).fetchone()
|
||||
assert orphan is None, 'partial chat remained after rollback'
|
||||
print('PASS: composite chat insert was fully rolled back after FK failure')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user