Skip to content

Instantly share code, notes, and snippets.

@v
Created July 26, 2024 19:22
Show Gist options
  • Save v/3e35bd306dab3a4a53e0cfff7ef24336 to your computer and use it in GitHub Desktop.
Save v/3e35bd306dab3a4a53e0cfff7ef24336 to your computer and use it in GitHub Desktop.
trying to break sqlite3 concurrency on my laptop
import asyncio
import sqlite3
async def check_and_insert(db, key, value):
try:
# Check if the key exists
cursor = db.execute("SELECT value FROM cache WHERE key = ?", (key,))
result = cursor.fetchone()
if result is None:
# Key doesn't exist, insert it
db.execute("INSERT INTO cache (key, value) VALUES (?, ?)", (key, value))
db.commit()
print(f"Inserted: {key}, {value}")
else:
print(f"Key {key} already exists")
except sqlite3.OperationalError as e:
print(f"Error: {e}")
async def main():
with sqlite3.connect('cache.db') as db:
db.execute("CREATE TABLE IF NOT EXISTS cache (key TEXT PRIMARY KEY, value TEXT)")
tasks = []
for i in range(10000):
tasks.append(check_and_insert(db, f"key{i}", f"value{i}"))
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment