我使用 sqlalchemy 编写了以下函数(我的底层数据库是 PostgreSQL 8.4)。我有以下架构:
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
);
如果发生错误,我希望该函数能够自行清理(即删除temporary_table_key 表中生成的键) - 由于某种原因,发生异常时不会清除该表。
这是功能:
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
任何人都可以发现为什么该函数没有清理temporary_data 键作为异常处理的一部分吗?