Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/database/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import time
from dataclasses import dataclass
from pathlib import Path
from typing import cast

import aiosqlite

Expand Down Expand Up @@ -177,4 +178,5 @@ async def execute(self, sql: str, params: tuple = ()) -> aiosqlite.Cursor:

async def execute_fetchall(self, sql: str, params: tuple = ()) -> list:
assert self.db is not None
return await self.db.execute_fetchall(sql, params)
# aiosqlite stubs declare Iterable[Row]; at runtime this is a list.
return cast(list, await self.db.execute_fetchall(sql, params))
14 changes: 8 additions & 6 deletions src/database/facade.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,20 +273,22 @@ async def transaction(self) -> AsyncIterator[aiosqlite.Connection]:
Not reentrant — nesting would deadlock asyncio.Lock.
"""
assert self._db is not None
# Local binding keeps the narrowed (non-optional) type visible inside the lambda.
db = self._db
async with self._write_lock:
await self._with_busy_retry(
"transaction begin",
lambda: begin_immediate(self._db),
lambda: begin_immediate(db),
)
committed = False
try:
yield self._db
await self._db.execute("COMMIT")
yield db
await db.execute("COMMIT")
committed = True
finally:
if not committed:
try:
await self._db.execute("ROLLBACK")
await db.execute("ROLLBACK")
except aiosqlite.OperationalError:
pass

Expand Down Expand Up @@ -578,15 +580,15 @@ async def create_rename_event(
if existing:
return existing["id"]
try:
cur = await self.execute_write(
write_cur = await self.execute_write(
"""
INSERT INTO channel_rename_events
(channel_id, old_title, new_title, old_username, new_username)
VALUES (?, ?, ?, ?, ?)
""",
(channel_id, old_title, new_title, old_username, new_username),
)
return cur.lastrowid or 0
return write_cur.lastrowid or 0
except sqlite3.IntegrityError:
# Concurrent INSERT won the race; re-select the existing row
cur = await self._read(
Expand Down
4 changes: 3 additions & 1 deletion src/database/migrations.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
from collections.abc import Mapping, Sequence
from pathlib import Path
from typing import cast

import aiosqlite

Expand Down Expand Up @@ -242,7 +243,8 @@ async def _dedupe_primary_accounts(db: aiosqlite.Connection) -> None:
if "is_primary" not in await table_columns(db, "accounts"):
return
cur = await db.execute("SELECT id FROM accounts WHERE is_primary = 1 ORDER BY id ASC")
rows = await cur.fetchall()
# aiosqlite stubs declare fetchall() as Iterable[Row]; at runtime it is a list.
rows = cast("list[aiosqlite.Row]", await cur.fetchall())
if len(rows) <= 1:
return
keep_id = rows[0][0]
Expand Down
9 changes: 5 additions & 4 deletions src/database/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import asyncio
from collections.abc import Sequence
from contextlib import asynccontextmanager
from typing import Any, AsyncIterator, Protocol
from typing import Any, AsyncIterator, Protocol, cast

import aiosqlite

Expand Down Expand Up @@ -167,13 +167,14 @@ async def execute(self, sql: str, params: Sequence[Any] = ()) -> BufferedCursor:
_reject_writes(sql)
async with self._pool.acquire_read() as conn:
cur = await conn.execute(sql, params)
# fetchall() returns a fresh owned list, so BufferedCursor can take it directly.
return BufferedCursor(await cur.fetchall())
# fetchall() returns a fresh owned list (stubs say Iterable[Row]), so
# BufferedCursor can take it directly.
return BufferedCursor(cast("list[Any]", await cur.fetchall()))

async def execute_fetchall(self, sql: str, params: Sequence[Any] = ()) -> list[Any]:
_reject_writes(sql)
async with self._pool.acquire_read() as conn:
return await conn.execute_fetchall(sql, params)
return cast("list[Any]", await conn.execute_fetchall(sql, params))

async def create_function(self, name: str, narg: int, func: Any, **kwargs: Any) -> None:
"""Register a UDF on every read connection (filter queries call this lazily)."""
Expand Down
3 changes: 2 additions & 1 deletion src/database/repositories/collection_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def _deserialize_payload(
) -> (
dict[str, Any] | StatsAllTaskPayload | SqStatsTaskPayload | FilterAnalyzeTaskPayload
| PipelineRunTaskPayload | ContentGenerateTaskPayload | ContentPublishTaskPayload
| TranslateBatchTaskPayload | None
| TranslateBatchTaskPayload | ExportTaskPayload | None
):
if not raw:
return None
Expand Down Expand Up @@ -109,6 +109,7 @@ def _serialize_payload(
| ContentGenerateTaskPayload
| ContentPublishTaskPayload
| TranslateBatchTaskPayload
| ExportTaskPayload
| None
),
) -> str | None:
Expand Down
5 changes: 3 additions & 2 deletions src/database/repositories/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import asyncio
import logging
import re
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, cast

import aiosqlite

Expand Down Expand Up @@ -370,7 +370,8 @@ async def _run_on_conn(
params: tuple = (),
) -> list[aiosqlite.Row]:
cur = await conn.execute(sql, params)
return await cur.fetchall()
# aiosqlite stubs declare fetchall() as Iterable[Row]; at runtime it is a list.
return cast("list[aiosqlite.Row]", await cur.fetchall())

async def fetch_maps_parallel(
self,
Expand Down
3 changes: 2 additions & 1 deletion src/database/repositories/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ async def _set_setting(self, key: str, value: str) -> None:
async def get_embedding_dimensions(self) -> int | None:
"""Размерность векторов индекса эмбеддингов (из настроек), либо ``None`` если индекс ещё не создан."""
raw_value = await self._get_setting(_EMBEDDING_DIMENSIONS_SETTING)
if raw_value in (None, ""):
if raw_value is None or raw_value == "":
return None
try:
return int(raw_value)
Expand Down Expand Up @@ -1217,6 +1217,7 @@ async def get_fts_daily_stats_batch(
union_parts = []
all_params: list = []
for sq in chunk:
assert sq.id is not None # ``valid`` filtered out None ids above
fts_query = self._build_fts_match(sq.query, sq.is_fts)
extra_conds, extra_params = self._build_extra_conditions(sq)
where_parts = [
Expand Down
Loading