Skip to content

Commit a578fc6

Browse files
authored
Merge pull request #551 from jcbl1/upstream/04-db-indexes
perf(db): index expiry, recency and chunk lookup columns
2 parents 2073f9b + 080fecf commit a578fc6

4 files changed

Lines changed: 126 additions & 12 deletions

File tree

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from tortoise import connections
2+
3+
# 高频查询字段索引。真实部署的 schema 全部由迁移建立
4+
# (init_db 不调用 generate_schemas),因此索引必须写在迁移里;
5+
# apps/base/models.py 中的 index/Meta 仅用于测试的 generate_schemas 路径。
6+
#
7+
# - filecodes(expired_at):过期扫描(delete_expire_files)与后台过期统计。
8+
# - filecodes(created_at):后台默认倒序列表、首页最近记录、今日/昨日统计。
9+
# - uploadchunk(upload_id, chunk_index):分片状态检查与合并;其前缀同时
10+
# 覆盖仅按 upload_id 的删除/清理查询(原先没有对应索引)。
11+
# 已知缺口:clean_incomplete_uploads 的 chunk_index=-1 AND created_at<? 用不上
12+
# 该复合索引,待清理任务改为分批查询后再评估。
13+
14+
15+
async def migrate():
16+
conn = connections.get("default")
17+
await conn.execute_script(
18+
"""
19+
CREATE INDEX IF NOT EXISTS idx_filecodes_expired_at
20+
ON filecodes (expired_at);
21+
CREATE INDEX IF NOT EXISTS idx_filecodes_created_at
22+
ON filecodes (created_at);
23+
CREATE INDEX IF NOT EXISTS idx_uploadchunk_upload_chunk
24+
ON uploadchunk (upload_id, chunk_index);
25+
"""
26+
)

‎apps/base/models.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@ class FileCodes(models.Model):
2121
file_path = fields.CharField(max_length=255, null=True)
2222
size = fields.BigIntField(default=0)
2323
text = fields.TextField(null=True)
24-
expired_at = fields.DatetimeField(null=True)
24+
# 过期扫描与后台过期统计的高频过滤列
25+
expired_at = fields.DatetimeField(null=True, index=True)
2526
# -1 = 时间式(看 expired_at),<=0 的 0 = 次数耗尽。默认 -1 而非 0:
2627
# 0 语义是"次数已用完即过期",忘传该字段的创建路径会得到立即过期的记录。
2728
expired_count = fields.IntField(default=-1)
2829
used_count = fields.IntField(default=0)
29-
created_at = fields.DatetimeField(auto_now_add=True)
30+
# 后台默认按创建时间倒序、今日/昨日统计均落在该列
31+
created_at = fields.DatetimeField(auto_now_add=True, index=True)
3032
file_hash = fields.CharField(max_length=64, null=True)
3133
is_chunked = fields.BooleanField(default=False)
3234
upload_id = fields.CharField(max_length=36, null=True)
@@ -44,7 +46,9 @@ async def get_file_path(self):
4446

4547
class UploadChunk(models.Model):
4648
id = fields.IntField(pk=True)
47-
upload_id = fields.CharField(max_length=36, index=True)
49+
# 上传会话/分片查询始终同时带 upload_id;复合索引前缀已覆盖仅按 upload_id
50+
# 的删除与清理查询,单列索引会造成重复。
51+
upload_id = fields.CharField(max_length=36)
4852
chunk_index = fields.IntField()
4953
chunk_hash = fields.CharField(max_length=64)
5054
total_chunks = fields.IntField()
@@ -55,6 +59,9 @@ class UploadChunk(models.Model):
5559
created_at = fields.DatetimeField(auto_now_add=True)
5660
completed = fields.BooleanField(default=False)
5761

62+
class Meta:
63+
indexes = [("upload_id", "chunk_index")]
64+
5865

5966
class KeyValue(Model):
6067
# 与 FileCodes 保持同一风格:类属性不写值注解(等号右侧的 Field 描述符

‎tests/test_migration_indexes.py‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
"""迁移 008 建立的索引存在且被查询计划实际选用。
2+
3+
跑真实迁移链(不 generate_schemas),与部署升级形态一致;用
4+
EXPLAIN QUERY PLAN 断言索引名出现在执行计划中,避免"建了索引但查询用不上"。
5+
"""
6+
import pytest
7+
from tortoise import Tortoise
8+
9+
import apps.base.config as config_module
10+
from core.database import execute_migrations
11+
from tests.helpers import MEMORY_DB_CONFIG, close_db
12+
13+
INDEXES = {
14+
"idx_filecodes_expired_at",
15+
"idx_filecodes_created_at",
16+
"idx_uploadchunk_upload_chunk",
17+
}
18+
19+
20+
@pytest.fixture
21+
async def migrated_db():
22+
config_module._config_cached_until = 0.0
23+
if Tortoise._inited:
24+
await Tortoise.close_connections()
25+
await Tortoise.init(config=MEMORY_DB_CONFIG)
26+
conn = Tortoise.get_connection("default")
27+
await conn.execute_script(
28+
"CREATE TABLE IF NOT EXISTS migrates ("
29+
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
30+
"migration_file VARCHAR(255) NOT NULL UNIQUE, "
31+
"executed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)"
32+
)
33+
await execute_migrations()
34+
try:
35+
yield conn
36+
finally:
37+
await close_db()
38+
39+
40+
async def _plan(conn, sql: str) -> str:
41+
_, rows = await conn.execute_query(f"EXPLAIN QUERY PLAN {sql}")
42+
return " | ".join(str(row["detail"]) for row in rows)
43+
44+
45+
@pytest.mark.asyncio
46+
class TestMigrationIndexes:
47+
async def test_indexes_exist(self, migrated_db):
48+
_, rows = await migrated_db.execute_query(
49+
"SELECT name FROM sqlite_master WHERE type='index'"
50+
)
51+
names = {row["name"] for row in rows}
52+
assert INDEXES <= names
53+
54+
async def test_expiry_scan_uses_index(self, migrated_db):
55+
plan = await _plan(
56+
migrated_db,
57+
"SELECT id FROM filecodes WHERE expired_at < '2024-01-01 00:00:00'",
58+
)
59+
assert "idx_filecodes_expired_at" in plan
60+
61+
async def test_recent_listing_uses_created_at_index(self, migrated_db):
62+
plan = await _plan(
63+
migrated_db,
64+
"SELECT id FROM filecodes ORDER BY created_at DESC LIMIT 8",
65+
)
66+
assert "idx_filecodes_created_at" in plan
67+
68+
async def test_chunk_lookup_uses_composite_index(self, migrated_db):
69+
plan = await _plan(
70+
migrated_db,
71+
"SELECT chunk_index FROM uploadchunk "
72+
"WHERE upload_id = 'abc' AND chunk_index = 3",
73+
)
74+
assert "idx_uploadchunk_upload_chunk" in plan
75+
76+
async def test_chunk_cleanup_uses_upload_id_prefix(self, migrated_db):
77+
plan = await _plan(
78+
migrated_db,
79+
"DELETE FROM uploadchunk WHERE upload_id = 'abc'",
80+
)
81+
assert "idx_uploadchunk_upload_chunk" in plan

‎tests/test_migration_runner.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""Migration runner coverage: discovery order, registration, idempotency,
2-
and failure propagation. Runs the REAL migrations (001-007) against an
2+
and failure propagation. Runs the REAL migrations (001-008) against an
33
in-memory database — the same code path a deployment upgrade takes.
44
"""
55
import pytest
@@ -8,7 +8,7 @@
88
from core.database import execute_migrations
99
from tests.helpers import MEMORY_DB_CONFIG, close_db
1010

11-
EXPECTED = [f"migrations_{i:03d}.py" for i in range(1, 8)]
11+
EXPECTED = [f"migrations_{i:03d}.py" for i in range(1, 9)]
1212

1313

1414
@pytest.fixture
@@ -60,15 +60,15 @@ async def test_pre_registered_subset_skips_those(self, fresh_db):
6060
"""部分已登记(模拟中途升级):只执行缺口,顺序保持。"""
6161
conn = Tortoise.get_connection("default")
6262
await conn.execute_query("DELETE FROM migrates")
63-
# 预登记 006/007(模拟已执行过全部迁移的库),验证 runner 只跑缺口
64-
# 001-005 且跳过已登记的 006/007(跳过语义 = 不再执行其 DDL)
65-
for name in EXPECTED[-2:]:
63+
# 预登记 006/007/008(模拟已执行过末尾迁移的库),验证 runner 只跑缺口
64+
# 001-005 且跳过已登记的 006/007/008(跳过语义 = 不再执行其 DDL)
65+
for name in EXPECTED[-3:]:
6666
await conn.execute_query(
6767
"INSERT INTO migrates (migration_file) VALUES (?)", [name]
6868
)
6969
await execute_migrations()
7070
registered = await _registered()
71-
# 预登记的 006/007 占据登记序前列——断言用集合:7 个全登记、无重复
71+
# 预登记的 006/007/008 占据登记序前列——断言用集合:全部登记、无重复
7272
assert sorted(registered) == sorted(EXPECTED)
7373
assert len(registered) == len(EXPECTED)
7474
tables = {
@@ -107,7 +107,7 @@ async def test_failure_propagates_and_halts(self, fresh_db, monkeypatch):
107107
"""迁移执行失败必须向上抛(启动失败可见),不能静默吞掉。"""
108108
import importlib
109109

110-
# 构造一个会失败的执行缺口:007 未登记,且其模块 migrate 抛错
110+
# 构造一个会失败的执行缺口:008 未登记,且其模块 migrate 抛错
111111
conn = Tortoise.get_connection("default")
112112
await conn.execute_query("DELETE FROM migrates")
113113
for name in EXPECTED[:-1]:
@@ -117,7 +117,7 @@ async def test_failure_propagates_and_halts(self, fresh_db, monkeypatch):
117117
real_import = importlib.import_module
118118

119119
def fake_import(name):
120-
if name.endswith("migrations_007"):
120+
if name.endswith("migrations_008"):
121121
class FakeMod:
122122
@staticmethod
123123
async def migrate():
@@ -130,4 +130,4 @@ async def migrate():
130130
with pytest.raises(RuntimeError, match="boom"):
131131
await execute_migrations()
132132
# 失败的迁移不得登记
133-
assert "migrations_007.py" not in await _registered()
133+
assert "migrations_008.py" not in await _registered()

0 commit comments

Comments
 (0)