chore: 基础设施 — 阿里云源、北京时间、HEX计数器、打印机配置
This commit is contained in:
26
backend/app/services/counter_service.py
Normal file
26
backend/app/services/counter_service.py
Normal file
@ -0,0 +1,26 @@
|
||||
"""16进制自增计数器 — 基于 PostgreSQL Sequence,生成 16 位 HEX 唯一 ID"""
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SEQUENCE_NAME = "product_hex_counter"
|
||||
|
||||
|
||||
async def ensure_sequence(db: AsyncSession) -> None:
|
||||
"""确保 counter sequence 存在(幂等)"""
|
||||
await db.execute(
|
||||
text(f"CREATE SEQUENCE IF NOT EXISTS {SEQUENCE_NAME} START 1;")
|
||||
)
|
||||
|
||||
|
||||
async def next_hex_id(db: AsyncSession, length: int = 16) -> str:
|
||||
"""
|
||||
生成下一个 hex ID。
|
||||
|
||||
示例: 1 → "0000000000000001"
|
||||
15 → "000000000000000F"
|
||||
16 → "0000000000000010"
|
||||
255 → "00000000000000FF"
|
||||
"""
|
||||
result = await db.execute(text(f"SELECT nextval('{SEQUENCE_NAME}');"))
|
||||
counter: int = result.scalar_one()
|
||||
return format(counter, f"0{length}X")
|
||||
Reference in New Issue
Block a user