Changeset 527c097 for uc_reserve.py
- Timestamp:
- 04/05/26 20:02:04 (3 months ago)
- Branches:
- main
- Parents:
- 95cf703
- File:
-
- 1 edited
-
uc_reserve.py (modified) (3 diffs)
Legend:
- Unmodified
- Added
- Removed
-
uc_reserve.py
r95cf703 r527c097 1 1 import datetime 2 2 3 from db import get_connection, pick_from_list, print_table, input_date, input_time3 from db import get_connection, get_transaction, pick_from_list, print_table, input_date, input_time 4 4 5 5 … … 96 96 return 97 97 98 # Step 7: INSERT 99 conn = get_connection() 98 # Step 7: INSERT (transaction: re-check conflicts + insert atomically) 100 99 try: 101 with conn.cursor() as cur: 102 cur.execute( 103 """ 104 INSERT INTO reservations 105 (start_time, end_time, status, purpose, created_at, user_id, resource_id) 106 VALUES (%s, %s, 'pending', %s, CURRENT_TIMESTAMP, %s, %s) 107 RETURNING reservation_id, status, created_at 108 """, 109 (start_dt, end_dt, purpose, user_id, rid), 110 ) 111 result = cur.fetchone() 112 conn.commit() 100 with get_transaction() as conn: 101 with conn.cursor() as cur: 102 # Re-check conflicts inside the transaction to prevent 103 # race conditions (another user inserting between our 104 # check and insert) 105 cur.execute( 106 """ 107 SELECT COUNT(*) FROM reservations 108 WHERE resource_id = %s 109 AND status IN ('approved', 'pending') 110 AND start_time < %s AND end_time > %s 111 """, 112 (rid, end_dt, start_dt), 113 ) 114 if cur.fetchone()[0] > 0: 115 raise RuntimeError("Conflict: another reservation was just created for this time slot") 116 117 cur.execute( 118 """ 119 INSERT INTO reservations 120 (start_time, end_time, status, purpose, created_at, user_id, resource_id) 121 VALUES (%s, %s, 'pending', %s, CURRENT_TIMESTAMP, %s, %s) 122 RETURNING reservation_id, status, created_at 123 """, 124 (start_dt, end_dt, purpose, user_id, rid), 125 ) 126 result = cur.fetchone() 127 # Transaction committed automatically 113 128 print(f"\n Reservation created successfully!") 114 129 print(f" Reservation ID: {result[0]}") … … 117 132 return 118 133 except Exception as e: 119 conn.rollback()134 # Transaction rolled back automatically 120 135 print(f"\n Error creating reservation: {e}") 121 136 return 122 finally:123 conn.close()124 137 125 138
Note:
See TracChangeset
for help on using the changeset viewer.
