summaryrefslogtreecommitdiff
path: root/evals/fixtures/test-driven-development-persistence/vault.py
blob: ba2caa5231f957be45451b2ea0eb9fa150709025 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sqlite3


def initialize(path):
    with sqlite3.connect(path) as connection:
        connection.execute("CREATE TABLE secret (value TEXT NOT NULL)")
        connection.execute("CREATE TABLE audit (value TEXT NOT NULL)")
        connection.execute("INSERT INTO secret VALUES ('old')")


def snapshot(path):
    with sqlite3.connect(path) as connection:
        value = connection.execute("SELECT value FROM secret").fetchone()[0]
        audit = connection.execute("SELECT value FROM audit").fetchall()
        return value, audit


def replace_secret(path, value, after_write=lambda: None):
    connection = sqlite3.connect(path)
    previous = connection.execute("SELECT value FROM secret").fetchone()[0]
    try:
        connection.execute("UPDATE secret SET value = ?", (value,))
        connection.commit()
        after_write()
        connection.execute("INSERT INTO audit VALUES (?)", (value,))
        connection.commit()
    except Exception:
        connection.rollback()
        connection.execute("UPDATE secret SET value = ?", (previous,))
        connection.commit()
        raise
    finally:
        connection.close()