peewee 有两种获取 crud 操作对应的 sql 语句的形式:
- 应用 logging,代理 peewee,以输入日志的形式打印 sql
- 拜访 modelinsert 等类实例的
__str__
办法
我当初要讲的是后者:
获取插入操作的 sql
def save_record(user_id: int, long_url: str, short_uuid: str) -> InsertResult:
insert_obj = TinyUrl.insert(
user_id=user_id,
long_url=long_url,
long_url_hash=md5_helper.get_string_md5(long_url),
short_uuid=short_uuid
)
sql = str(insert_obj)
started_at = time.time()
row_id = insert_obj.execute()
ended_at = time.time()
return InsertResult(
tracks=[
DBCrudTrack(
sql=sql,
pay_time=ended_at - started_at
)
],
row_id=row_id
)
获取查问操作的 sql
def get_row_by_user_id_long_url_hash(user_id: int, long_url_hash: str) -> SelectResult:
query: ModelSelect = TinyUrl.select().where((TinyUrl.user_id == user_id) &
(TinyUrl.long_url_hash == long_url_hash)
)
sql = str(query)
start_at = time.time()
rows: list[dict] = list(query.dicts()
)
end_at = time.time()
return SelectResult(
tracks=[
DBCrudTrack(
sql=sql,
pay_time=end_at - start_at
)
],
rows=[Row(**row)
for row in rows
]
)