如何在自定义类型中实现压缩与解压?

解读

国内互联网、金融、政务类项目常把大字段(JSON、长文本、日志报文、图像元数据)落库,为了节省存储与网络带宽,需要在ORM 层透明做压缩/解压,而不能让业务代码感知。面试官想确认四点:

  1. 是否知道 SQLAlchemy 的TypeDecorator扩展点;
  2. 是否理解可逆转换必须放在 bind_processor / result_processor 中,而不是 process_bind_param / process_result_value(后者已废弃);
  3. 是否考虑字节与字符串的编解码、空值、异常兜底;
  4. 是否兼顾性能(避免每次全表解压)与迁移兼容性(老数据未压缩如何灰度)。

知识点

  • TypeDecorator:官方推荐的“自定义类型”基类,单向或双向转换均可。
  • impl:必须指定底层真实 SQL 类型,压缩后变 LargeBinary,所以 impl = LargeBinary。
  • bind_processor(dialect):Python→数据库,返回 callable;压缩后返回 bytes。
  • result_processor(dialect, coltype):数据库→Python,返回 callable;解压后返回 str。
  • 缓存压缩器:避免每次创建 zlib.compressobj,可用单例或线程局部缓存。
  • Alembic 自动检测:自定义类型不会触发字段长度变化,需在迁移脚本里手动改列类型为 BYTEA/BLOB。
  • 灰度方案:新增列 content_compressed,双写后切换读,再删旧列;或利用SQLAlchemy 事件在读取时判断魔术头。

答案

import zlib
import sqlalchemy.types as types
from sqlalchemy.dialects.postgresql import BYTEA

class CompressedText(types.TypeDecorator):
    """透明压缩/解压大文本,存成二进制"""
    impl = BYTEA          # 跨库可换成 types.LargeBinary
    cache_ok = True       # 标记可缓存,提高性能

    def bind_processor(self, dialect):
        # Python 层 str -> 数据库 bytes
        def process(value):
            if value is None:
                return None
            if not isinstance(value, (str, bytes)):
                value = str(value)
            if isinstance(value, str):
                value = value.encode("utf-8")
            return zlib.compress(value, level=6)
        return process

    def result_processor(self, dialect, coltype):
        # 数据库 bytes -> Python 层 str
        def process(value):
            if value is None:
                return None
            try:
                decompressed = zlib.decompress(value)
                return decompressed.decode("utf-8")
            except (zlib.error, UnicodeDecodeError):
                # 兜底:老数据未压缩直接返回
                if isinstance(value, bytes):
                    return value.decode("utf-8", errors="replace")
                return value
        return process

# 模型层零侵入
class LogRecord(Base):
    __tablename__ = "log_record"
    id = Column(Integer, primary_key=True)
    content = Column(CompressedText, nullable=False)

使用注意

  1. 压缩率>50% 时,索引失效,不要在该字段上建 BTREE 索引;如需检索,可冗余哈希字段或倒排表。
  2. 事务回滚时,压缩 CPU 开销已发生,对高并发写要做连接池隔离或异步任务压缩。
  3. 国内等保/密评场景,zlib 属于通用压缩,若需国密 SM4 加密后再压缩,可套一层自定义加密类型形成管道。

拓展思考

  • 异步场景:AsyncSession 下自定义类型仍同步执行,若压缩算法很重,可改用SQLAlchemy 事件(before_insert、after_select)把 CPU 任务丢到线程池或外部微服务。
  • 分片键兼容:压缩后长度不可预测,不要用该字段做 sharding key;可再存原长哈希作为分片键。
  • 监控与回退:在类型内部加Prometheus Counter,统计压缩失败/解压失败次数;上线时通过配置开关 ENABLE_COMPRESS 快速回退到明文。
  • 与 pydantic 联合:FastAPI 请求体仍接收明文,CompressedText 只在落盘时生效,保证接口契约不变,满足国内银行“接口不变,内部优化”的评审要求。