62 lines
1.7 KiB
Python
62 lines
1.7 KiB
Python
import aiosqlite
|
|
from time import time
|
|
|
|
time = int(time()) # we dont need no stinkin floats
|
|
|
|
# db = await aiosqlite.connect("studspider.db") # type: ignore
|
|
|
|
|
|
async def close(db):
|
|
await db.close()
|
|
|
|
|
|
async def fetch(table, sqobj):
|
|
"""
|
|
Asynchronously fetch a record from the REVIEW table by sq_object.
|
|
|
|
Args:
|
|
sqobj (str): The sq_object identifier to search for.
|
|
Returns:
|
|
dict or None: The fetched record as a dictionary, or None if not found.
|
|
"""
|
|
async with aiosqlite.connect("studspider.db") as db: # type: ignore
|
|
async with db.execute(
|
|
f"SELECT * FROM {table} WHERE sq_object = {sqobj}"
|
|
) as cursor:
|
|
async for row in cursor:
|
|
return row
|
|
|
|
return None
|
|
|
|
|
|
async def upsert(table: str, data: dict, unique_key: str) -> bool:
|
|
"""
|
|
Asynchronously insert or update a record in the specified table.
|
|
|
|
Args:
|
|
table (str): The name of the table to upsert into.
|
|
data (dict): A dictionary of column-value pairs to insert or update.
|
|
unique_key (str): The column name that serves as the unique key for upsert.
|
|
|
|
Returns:
|
|
None
|
|
"""
|
|
print(f"Upserting into {table}: {data}")
|
|
|
|
columns = ", ".join(data.keys())
|
|
placeholders = ", ".join("?" * len(data))
|
|
updates = ", ".join(
|
|
f"{col}=excluded.{col}" for col in data.keys() if col != unique_key
|
|
)
|
|
|
|
sql = f"""
|
|
INSERT INTO {table} ({columns})
|
|
VALUES ({placeholders})
|
|
ON CONFLICT({unique_key}) DO UPDATE SET
|
|
{updates};
|
|
"""
|
|
async with aiosqlite.connect("studspider.db") as db: # type: ignore
|
|
async with db.execute(sql, tuple(data.values())) as cursor:
|
|
await db.commit()
|
|
return True
|