fix(db): TEXT 列不能带 DEFAULT —— 上一版 hashtags 用 TEXT 直接把服务搞崩了
MySQL 5.7 报 1101:`BLOB, TEXT, GEOMETRY or JSON column 'hashtags' can't have a default value`。而补列发生在**启动阶段**,ALTER 一失败应用就起不来,容器反复重启。 两处修: * `monitor_note.hashtags` 改成 `VARCHAR(2000)` —— 话题列表本来也不长,能带 DEFAULT; * `_column_ddl` 对 TEXT/BLOB **一律不加 DEFAULT**,靠 MySQL 给已有行填隐式默认值。 这是结构性保护:以后谁再给 NOT NULL 的 Text 列写 default,也不会再把启动弄挂。 并把「所有 NOT NULL 列都必须带 DEFAULT」那条测试限定到非 TEXT/BLOB —— 那条假设正是 这次事故的根源。
This commit is contained in:
+9
-1
@@ -44,7 +44,7 @@ from contextlib import asynccontextmanager
|
||||
from pathlib import Path
|
||||
from typing import AsyncIterator, Optional
|
||||
|
||||
from sqlalchemy import Column, event, text
|
||||
from sqlalchemy import Column, LargeBinary, Text, event, text
|
||||
from sqlalchemy.dialects import mysql
|
||||
from sqlalchemy.schema import CreateColumn
|
||||
from sqlalchemy.ext.asyncio import (
|
||||
@@ -256,9 +256,17 @@ def _column_ddl(column: Column) -> str:
|
||||
separately because a model's ``default=`` is applied by the ORM and never
|
||||
reaches the DDL -- and a NOT NULL column added to a populated table needs a
|
||||
value for the rows already sitting there.
|
||||
|
||||
**TEXT/BLOB columns never get a DEFAULT.** MySQL 5.7 rejects it outright
|
||||
("BLOB, TEXT, GEOMETRY or JSON column can't have a default value"), and this
|
||||
runs during startup: the whole service fails to boot and the container
|
||||
crash-loops. MySQL still fills existing rows with the type's implicit default,
|
||||
which is what we want anyway.
|
||||
"""
|
||||
ddl = str(CreateColumn(column).compile(dialect=mysql.dialect()))
|
||||
if not column.nullable and column.server_default is None:
|
||||
if isinstance(column.type, (Text, LargeBinary)):
|
||||
return ddl
|
||||
seed = _implicit_default(column)
|
||||
if seed is not None:
|
||||
ddl += f" DEFAULT {seed}"
|
||||
|
||||
@@ -226,7 +226,11 @@ class MonitorNote(MonitorBase):
|
||||
title: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 话题列表(`#a #b`)。**不能只靠 title 打标签**:抖音的 desc 会被截断,后半段
|
||||
# 话题不在里面;`text_extra` 才是完整的那份。小红书暂不提供,存空串。
|
||||
hashtags: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
#
|
||||
# **用 VARCHAR 不用 TEXT**:MySQL 5.7 不允许 TEXT/BLOB 列带 DEFAULT,而自动补列
|
||||
# 会给 NOT NULL 列拼一个 DEFAULT —— 用 TEXT 的话 ALTER 直接报 1101,应用启动失败、
|
||||
# 容器反复重启。话题列表本来也不会很长,2000 够用。
|
||||
hashtags: Mapped[str] = mapped_column(String(2000), nullable=False, default="")
|
||||
note_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
cover: Mapped[str] = mapped_column(Text, nullable=False, default="")
|
||||
# 创作者匿名哈希。爬虫刻意不落原始 user_id(见 tools/user_hash.py),
|
||||
|
||||
Reference in New Issue
Block a user