fix(db): TEXT 列不能带 DEFAULT —— 上一版 hashtags 用 TEXT 直接把服务搞崩了
Deploy VitePress site to Pages / build (push) Canceled after 0s
Deploy VitePress site to Pages / Deploy (push) Canceled after 0s

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:
butubb
2026-10-22 17:22:46 +08:00
parent 74fc19a8e3
commit ae9af5e53f
3 changed files with 37 additions and 3 deletions
+9 -1
View File
@@ -44,7 +44,7 @@ from contextlib import asynccontextmanager
from pathlib import Path from pathlib import Path
from typing import AsyncIterator, Optional 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.dialects import mysql
from sqlalchemy.schema import CreateColumn from sqlalchemy.schema import CreateColumn
from sqlalchemy.ext.asyncio import ( 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 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 reaches the DDL -- and a NOT NULL column added to a populated table needs a
value for the rows already sitting there. 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())) ddl = str(CreateColumn(column).compile(dialect=mysql.dialect()))
if not column.nullable and column.server_default is None: if not column.nullable and column.server_default is None:
if isinstance(column.type, (Text, LargeBinary)):
return ddl
seed = _implicit_default(column) seed = _implicit_default(column)
if seed is not None: if seed is not None:
ddl += f" DEFAULT {seed}" ddl += f" DEFAULT {seed}"
+5 -1
View File
@@ -226,7 +226,11 @@ class MonitorNote(MonitorBase):
title: Mapped[str] = mapped_column(Text, nullable=False, default="") title: Mapped[str] = mapped_column(Text, nullable=False, default="")
# 话题列表(`#a #b`)。**不能只靠 title 打标签**:抖音的 desc 会被截断,后半段 # 话题列表(`#a #b`)。**不能只靠 title 打标签**:抖音的 desc 会被截断,后半段
# 话题不在里面;`text_extra` 才是完整的那份。小红书暂不提供,存空串。 # 话题不在里面;`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="") note_url: Mapped[str] = mapped_column(Text, nullable=False, default="")
cover: Mapped[str] = mapped_column(Text, nullable=False, default="") cover: Mapped[str] = mapped_column(Text, nullable=False, default="")
# 创作者匿名哈希。爬虫刻意不落原始 user_id(见 tools/user_hash.py), # 创作者匿名哈希。爬虫刻意不落原始 user_id(见 tools/user_hash.py),
+23 -1
View File
@@ -10,7 +10,7 @@ work from the model metadata.
""" """
import pytest import pytest
from sqlalchemy import Boolean, Column, Integer, MetaData, String, Table from sqlalchemy import Boolean, Column, Integer, LargeBinary, MetaData, String, Table, Text
from api.monitor import db from api.monitor import db
from api.monitor.models import MonitorBase from api.monitor.models import MonitorBase
@@ -54,6 +54,10 @@ def test_not_null_columns_carry_a_default(column):
""" """
if column.nullable: if column.nullable:
pytest.skip("nullable column needs no seed value") pytest.skip("nullable column needs no seed value")
# TEXT/BLOB 例外:MySQL 5.7 直接拒绝 DEFAULT(报 1101)。这类列靠 MySQL 给已有行
# 填隐式默认值 —— 真踩过,启动时的 ALTER 失败会让整个服务反复重启。
if isinstance(column.type, (Text, LargeBinary)):
pytest.skip("TEXT/BLOB 不能带 DEFAULT(MySQL 5.7)")
assert "DEFAULT" in db._column_ddl(column) assert "DEFAULT" in db._column_ddl(column)
@@ -81,3 +85,21 @@ def test_a_not_null_column_without_a_model_default_falls_back_to_zero():
ddl = _ddl(Column("n", Integer, nullable=False)) ddl = _ddl(Column("n", Integer, nullable=False))
assert "DEFAULT 0" in ddl assert "DEFAULT 0" in ddl
def test_text_columns_never_get_a_default():
"""MySQL 5.7 不允许 TEXT/BLOB 列带 DEFAULT。
补列在**启动阶段**跑:一旦拼出 `TEXT NOT NULL DEFAULT ''`,ALTER 直接报 1101,
应用起不来、容器反复重启。真的踩过(hashtags 列)。
"""
ddl = db._column_ddl(Column("hashtags", Text, nullable=False))
assert "DEFAULT" not in ddl.upper()
def test_varchar_columns_still_get_a_default():
"""VARCHAR 可以带 DEFAULT,而且带了对已有行更友好 —— 别一刀切。"""
ddl = db._column_ddl(Column("hashtags", String(2000), nullable=False))
assert "DEFAULT ''" in ddl