sqlalchemy不会在出错时删除行

时间:2012-07-24 06:05:07

标签: python postgresql sqlalchemy

我使用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键吗?

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。

最后一行应该是:

if key_id:
    conn.execute("DELETE FROM temporary_data_key WHERE key='{0}'".format(guid))