import sqlite3

conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE refunds (id INTEGER PRIMARY KEY, amount INT)")
conn.execute("CREATE TABLE requests (key TEXT PRIMARY KEY, amount INT, result INT)")


def refund(key, amount):
    if type(amount) is not int or amount <= 0:
        raise ValueError("金额必须是正整数分")
    conn.execute("BEGIN IMMEDIATE")
    try:
        row = conn.execute(
            "SELECT amount, result FROM requests WHERE key=?", (key,)
        ).fetchone()
        if row:
            if row[0] != amount:
                raise ValueError("相同操作编号的参数发生变化")
            result = row[1]
        else:
            result = conn.execute(
                "INSERT INTO refunds(amount) VALUES (?)", (amount,)
            ).lastrowid
            conn.execute("INSERT INTO requests VALUES (?,?,?)",
                         (key, amount, result))
        conn.commit()
        return result
    except Exception:
        conn.rollback()
        raise


assert refund("refund-17", 500) == refund("refund-17", 500)
try:
    refund("refund-17", 600)
except ValueError:
    pass
else:
    raise AssertionError("参数变化必须被拒绝")
assert conn.execute("SELECT COUNT(*) FROM refunds").fetchone()[0] == 1
conn.close()
print("重复请求复用结果，没有产生第二笔退款")
