11
This commit is contained in:
+59
-24
@@ -1,4 +1,10 @@
|
||||
import aiosqlite
|
||||
import logging
|
||||
import re
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
logger = logging.getLogger("AsyncSQLite")
|
||||
|
||||
|
||||
class AsyncSQLite:
|
||||
def __init__(self, db_path: str):
|
||||
@@ -15,28 +21,65 @@ class AsyncSQLite:
|
||||
await self.conn.close()
|
||||
self.conn = None
|
||||
|
||||
async def fetch_one(self, sql: str, params=None):
|
||||
def _format_sql(self, sql: str, params):
|
||||
"""生成完整 SQL(安全打印)"""
|
||||
|
||||
if not params:
|
||||
return sql
|
||||
|
||||
def escape(value):
|
||||
if value is None:
|
||||
return "NULL"
|
||||
if isinstance(value, (int, float)):
|
||||
return str(value)
|
||||
# 转义单引号
|
||||
value = str(value).replace("'", "''")
|
||||
return f"'{value}'"
|
||||
|
||||
final_sql = sql
|
||||
for v in params:
|
||||
final_sql = final_sql.replace("?", escape(v), 1)
|
||||
|
||||
return final_sql
|
||||
|
||||
async def _log_and_execute(self, sql: str, params=None, fetch: str = None):
|
||||
await self.init()
|
||||
async with self.conn.execute(sql, params or ()) as cursor: # type: ignore
|
||||
row = await cursor.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
# 打印原始 SQL 和参数
|
||||
logger.debug(f"[SQLite] SQL Raw: {sql}")
|
||||
logger.debug(f"[SQLite] Params: {params}")
|
||||
|
||||
# 打印最终执行 SQL
|
||||
final_sql = self._format_sql(sql, params or ())
|
||||
logger.debug(f"[SQLite] SQL Final: {final_sql}")
|
||||
|
||||
async with self.conn.execute(sql, params or ()) as cursor:
|
||||
if fetch == "one":
|
||||
row = await cursor.fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
if fetch == "all":
|
||||
rows = await cursor.fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
await self.conn.commit()
|
||||
return True
|
||||
|
||||
async def fetch_one(self, sql: str, params=None):
|
||||
return await self._log_and_execute(sql, params, fetch="one")
|
||||
|
||||
async def fetch_all(self, sql: str, params=None):
|
||||
await self.init()
|
||||
async with self.conn.execute(sql, params or ()) as cursor: # type: ignore
|
||||
rows = await cursor.fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
return await self._log_and_execute(sql, params, fetch="all")
|
||||
|
||||
async def execute(self, sql: str, params=None):
|
||||
await self.init()
|
||||
async with self.conn.execute(sql, params or ()): # type: ignore
|
||||
await self.conn.commit() # type: ignore
|
||||
return True
|
||||
return await self._log_and_execute(sql, params)
|
||||
|
||||
async def executemany(self, sql: str, params_list):
|
||||
await self.init()
|
||||
await self.conn.executemany(sql, params_list) # type: ignore
|
||||
await self.conn.commit() # type: ignore
|
||||
logger.debug(f"[SQLite] SQL (executemany): {sql}")
|
||||
logger.debug(f"[SQLite] Params List: {params_list}")
|
||||
await self.conn.executemany(sql, params_list)
|
||||
await self.conn.commit()
|
||||
return True
|
||||
|
||||
async def insert_record(self, table: str, data: dict):
|
||||
@@ -58,13 +101,5 @@ class AsyncSQLite:
|
||||
return await self.execute(sql, tuple(where.values()))
|
||||
|
||||
async def clear_table(self, table: str):
|
||||
"""
|
||||
清空指定表中的所有记录。
|
||||
Args:
|
||||
table: 要清空的表名。
|
||||
Returns:
|
||||
如果操作成功则返回 True。
|
||||
"""
|
||||
sql = f"DELETE FROM `{table}`"
|
||||
# 使用 execute 函数执行 DELETE 语句
|
||||
return await self.execute(sql)
|
||||
sql = f"DELETE FROM `{table}`"
|
||||
return await self.execute(sql)
|
||||
|
||||
Reference in New Issue
Block a user