I have written the following function using sqlalchemy (my underlying db is PostgreSQL 8.4). I have the following schema:
CREATE TABLE temporary_data_key (
id SERIAL PRIMARY KEY,
key VARCHAR(36) NOT NULL
);
CREATE UNIQUE INDEX idxu_temp_data_nm ON temporary_data_key (key);
CREATE TABLE temporary_data (
key_id INTEGER REFERENCES temporary_data_key(id) ON UPDATE CASCADE ON DELETE RESTRICT NOT NULL,
id_value INTEGER CHECK (id_value > 0) NOT NULL
);
I expect the function to clean up after itself (i.e. remove the generated key in temporary_table_key table) if an error occurs - for some reason, the table is not been cleared when an exception occurs.
Here is the function:
def storeIdsInTemporaryTable(dbinfo, id_list):
conn = dbinfo['db_connection']
metadata = dbinfo['metadata']
tableinfo = Table('temporary_data', metadata, autoload=True)
datarows = []
temp_dbinfo = {'db_connection': conn, 'table': tableinfo, 'datarows': datarows }
guid = genutils.getGUID()
sql = "INSERT INTO temporary_data_key (key) VALUES ('{0}') RETURNING id".format(guid)
key_id = executeSQLonDbConnection(temp_dbinfo, sql, return_field='id')
for id_value in id_list:
datarows.append( { 'key_id': key_id, 'id_value': id_value } )
try:
insertToDb(temp_dbinfo)
except Exception as e:
print 'ERROR:',e
guid = None # to indicate an error occured
if key_id:
conn.execute("DELETE FROM temporary_data_key WHERE key='{0}'".format(key_id))
return guid
Can anyone spot why the function is not cleaning up the temporary_data key as part of exception handling?