Created
July 26, 2024 19:22
-
-
Save v/3e35bd306dab3a4a53e0cfff7ef24336 to your computer and use it in GitHub Desktop.
trying to break sqlite3 concurrency on my laptop
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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