数据库字段命名约定
本文档定义数据库字段的命名约定,以确保在 PostgreSQL 和 SQLite 数据库中的类型一致性和正确处理。
布尔字段
PostgreSQL 中的布尔字段应使用 BOOLEAN 类型并设置 DEFAULT true/false。SQLite 使用 INTEGER 类型亲和性(0/1),但语义上是布尔值。
布尔字段命名模式
命名布尔字段时,使用以下模式以确保它们能被正确检测和处理:
| 模式 | 示例 | 说明 |
|---|---|---|
is_* | is_admin、is_active、is_published、is_public、is_featured | 状态标志 |
*_enabled | email_enabled、push_enabled、content_filter_enabled | 功能开关 |
allow_* | allow_comments、allow_copy | 权限标志 |
must_* | must_change_password | 必须动作标志 |
can_* | can_edit、can_delete(未来) | 能力标志 |
has_* | has_permission、has_access(未来) | 拥有标志 |
天然布尔词
有些词即使没有前缀/后缀模式,语义上也是布尔值:
read- 已读状态(如 alerts.read)success- 操作是否成功(如 audit_logs.success)acknowledged- 确认状态verified、confirmed、approved、rejected、completed- 状态指示
正确的布尔字段定义
PostgreSQL:
is_admin boolean DEFAULT false,
is_active boolean DEFAULT true,
must_change_password boolean DEFAULT false,
read boolean DEFAULT false,
SQLite:
is_admin integer DEFAULT 0, -- boolean: admin status
is_active integer DEFAULT 1, -- boolean: active status
must_change_password integer DEFAULT 0, -- boolean: password change required
read integer DEFAULT 0, -- boolean: read status (0=unread, 1=read)
计数字段
计数字段应使用 INTEGER 类型,且不得被当作布尔值处理。
计数字段命名模式
| 模式 | 示例 | 说明 |
|---|---|---|
*_count | view_count、use_count、message_count | 计数器 |
*_used | tokens_used、requests_used | 用量计数 |
*_made | requests_made | 动作计数 |
*_limit | daily_token_limit、monthly_token_limit | 限额 |
*_quota | monthly_token_quota | 配额值 |
total_* | total_tokens、total_requests、total_sessions | 合计 |
*_tokens | input_tokens、output_tokens、cache_tokens | 令牌数 |
*_users | active_users、new_users | 用户数 |
*_seconds | total_duration_seconds | 时长 |
*_requests | total_requests | 请求数 |
正确的计数字段定义
PostgreSQL 与 SQLite 通用:
view_count integer DEFAULT 0,
tokens_used integer DEFAULT 0,
total_tokens integer DEFAULT 0,
message_count integer DEFAULT 0,
代码中布尔值的用法
在 SQL 查询中写布尔值时,使用 app/repositories/database.py 中的助手函数:
from app.repositories.database import adapt_boolean_value, adapt_boolean_condition
# For INSERT/UPDATE values
is_active_val = adapt_boolean_value(True) # PostgreSQL: True, SQLite: 1
# For WHERE conditions
condition = adapt_boolean_condition("is_active", True) # PostgreSQL: "(is_active)::int != 0", SQLite: "is_active = 1"