syncer.py 1.23 KB
from app.core.log import setup_logging

logger = setup_logging('sync_brand')


def preprocess_text(text):
    if not text:
        return ""
    return str(text).strip()


def sync_brands(conn, brand_rows):
    """
    将品牌数据写入 SQLite carbrands FTS5 表。

    数据已在调用前完成 DROP 重建表,此处直接 INSERT。
    按 brand id 去重,只保留首次出现的品牌。
    """
    batch_data = []
    seen_ids = set()

    for item in brand_rows:
        b_id = item.get("bid")
        b_name = item.get("brand")
        if b_id is not None and b_id not in seen_ids:
            batch_data.append((str(b_id), preprocess_text(b_name)))
            seen_ids.add(b_id)

    if not batch_data:
        logger.warning("解析后无有效品牌数据,未执行写入。")
        return

    brand_names = [item[1] for item in batch_data]
    logger.info(f"准备写入以下品牌: {', '.join(brand_names)}")

    cursor = conn.cursor()
    cursor.executemany(
        "INSERT INTO carbrands (brandId, name) VALUES (?, ?);",
        batch_data
    )
    conn.commit()

    logger.info(
        f"品牌同步成功!共从 MySQL 获取 {len(brand_rows)} 条记录,"
        f"写入 {len(batch_data)} 条品牌数据。"
    )