Skip to content

Commit b90d491

Browse files
committed
Adds trigger to automatically delete rows after 500
1 parent a760351 commit b90d491

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

async_substrate_interface/utils/cache.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,26 @@ def _check_if_local(chain: str) -> bool:
2525

2626
def _create_table(c, conn, table_name):
2727
c.execute(
28-
f"CREATE TABLE IF NOT EXISTS {table_name} (key BLOB PRIMARY KEY, value BLOB, chain TEXT)"
28+
f"""CREATE TABLE IF NOT EXISTS {table_name}
29+
(
30+
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
31+
key BLOB,
32+
value BLOB,
33+
chain TEXT,
34+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
35+
);
36+
"""
37+
)
38+
c.execute(
39+
f"""CREATE TRIGGER IF NOT EXISTS prune_rows_trigger AFTER INSERT ON {table_name}
40+
BEGIN
41+
DELETE FROM {table_name}
42+
WHERE rowid IN (
43+
SELECT rowid FROM {table_name}
44+
ORDER BY created_at DESC
45+
LIMIT -1 OFFSET 500
46+
);
47+
END;"""
2948
)
3049
conn.commit()
3150

@@ -46,7 +65,7 @@ def _retrieve_from_cache(c, table_name, key, chain):
4665
def _insert_into_cache(c, conn, table_name, key, result, chain):
4766
try:
4867
c.execute(
49-
f"INSERT OR REPLACE INTO {table_name} VALUES (?,?,?)",
68+
f"INSERT OR REPLACE INTO {table_name} (key, value, chain) VALUES (?,?,?)",
5069
(key, pickle.dumps(result), chain),
5170
)
5271
conn.commit()

0 commit comments

Comments
 (0)