Skip to content

布尔类型字段

在 VEF Framework 中,布尔类型字段有多种选择,根据数据库支持和业务需求选择合适的类型。

类型对比

类型可空数据库存储适用场景
bool原生 boolean 或 0/1非空布尔值,数据库支持原生 boolean
sql.Bool0/1 (smallint/tinyint)非空布尔值,数据库不支持原生 boolean
null.Boolboolean 或 0/1,可为 NULL三态逻辑(true/false/unknown)

决策指南

需要三态逻辑(true/false/unknown)?
├── 是 → 使用 null.Bool
└── 否 → 数据库支持原生 boolean?
    ├── 是 → 使用 bool
    └── 否 → 使用 sql.Bool

决策表

使用场景推荐类型数据库列类型
非空布尔值,数据库支持原生 booleanboolboolean / 原生类型
可空布尔值(三态)null.Boolbooleansmallint/tinyint
非空布尔值,需要 0/1 存储兼容性sql.Boolsmallint/tinyint (0/1)
仅 Go 内部使用(不存储)bool + bun:"-"N/A

类型详解

1. 原生 bool

最简单的布尔类型,推荐用于支持原生 boolean 的数据库:

go
type User struct {
    orm.Model
    Username string `bun:"username,notnull" json:"username"`
    
    // Plain bool - recommended for native boolean columns
    IsActive bool `bun:"is_active,notnull,default:true" json:"isActive"`
    IsAdmin  bool `bun:"is_admin,notnull,default:false" json:"isAdmin"`
}

特点:

  • 只有两个值:truefalse
  • 默认值为 false
  • 适用于 PostgreSQL、MySQL 8.0+ 等支持原生 boolean 的数据库

2. sql.Bool

用于需要 0/1 数字存储的场景:

go
import "github.com/ilxqx/vef-framework-go/sql"

type Config struct {
    orm.Model
    Key   string   `bun:"key,notnull" json:"key"`
    
    // sql.Bool - stores as 0/1 for database compatibility
    Enabled sql.Bool `bun:"enabled,notnull,default:1" json:"enabled"`
}

特点:

  • 存储为 0(false)或 1(true)
  • 适用于不支持原生 boolean 的数据库
  • 适用于需要与旧系统兼容的场景

3. null.Bool

用于需要三态逻辑的场景:

go
import "github.com/ilxqx/vef-framework-go/null"

type Survey struct {
    orm.Model
    Question string    `bun:"question,notnull" json:"question"`
    
    // null.Bool - three-state logic (true/false/null)
    // null represents "not answered" or "unknown"
    Answer   null.Bool `bun:"answer" json:"answer"`
}

特点:

  • 三个状态:truefalsenull(未知/未回答)
  • 适用于问卷调查、可选设置等场景
  • 数据库列可以为 NULL

三态逻辑示例

go
import "github.com/ilxqx/vef-framework-go/null"

type UserPreference struct {
    orm.Model
    UserId string `bun:"user_id,notnull" json:"userId"`
    
    // Three-state preferences
    // null = use system default
    // true = explicitly enabled
    // false = explicitly disabled
    EmailNotifications null.Bool `bun:"email_notifications" json:"emailNotifications"`
    DarkMode           null.Bool `bun:"dark_mode" json:"darkMode"`
}

// Usage example
func GetEffectivePreference(pref null.Bool, systemDefault bool) bool {
    if pref.Valid {
        return pref.Bool  // User has set a preference
    }
    return systemDefault  // Use system default
}

仅 Go 内部使用的字段

对于不需要存储到数据库的计算字段:

go
type Order struct {
    orm.Model
    Status string `bun:"status,notnull" json:"status"`
    
    // Computed field - not stored in database
    IsPaid bool `bun:"-" json:"isPaid,omitempty"`
}

// Set computed field after query
func (o *Order) AfterScan(ctx context.Context) error {
    o.IsPaid = o.Status == "paid"
    return nil
}

常见模式

状态标志

go
type Article struct {
    orm.Model
    Title     string `bun:"title,notnull" json:"title"`
    
    // Status flags
    IsPublished bool `bun:"is_published,notnull,default:false" json:"isPublished"`
    IsFeatured  bool `bun:"is_featured,notnull,default:false" json:"isFeatured"`
    IsArchived  bool `bun:"is_archived,notnull,default:false" json:"isArchived"`
}

权限标志

go
type Role struct {
    orm.Model
    Name string `bun:"name,notnull" json:"name"`
    
    // Permission flags
    CanRead   bool `bun:"can_read,notnull,default:true" json:"canRead"`
    CanWrite  bool `bun:"can_write,notnull,default:false" json:"canWrite"`
    CanDelete bool `bun:"can_delete,notnull,default:false" json:"canDelete"`
    CanAdmin  bool `bun:"can_admin,notnull,default:false" json:"canAdmin"`
}

可选设置

go
type NotificationSettings struct {
    orm.Model
    UserId string `bun:"user_id,notnull" json:"userId"`
    
    // Optional settings (null = use default)
    EmailEnabled null.Bool `bun:"email_enabled" json:"emailEnabled"`
    SmsEnabled   null.Bool `bun:"sms_enabled" json:"smsEnabled"`
    PushEnabled  null.Bool `bun:"push_enabled" json:"pushEnabled"`
}

数据库兼容性

PostgreSQL

sql
-- Native boolean type
CREATE TABLE users (
    id UUID PRIMARY KEY,
    is_active BOOLEAN NOT NULL DEFAULT TRUE
);

MySQL

sql
-- MySQL 8.0+ supports BOOLEAN (alias for TINYINT(1))
CREATE TABLE users (
    id VARCHAR(36) PRIMARY KEY,
    is_active BOOLEAN NOT NULL DEFAULT TRUE
);

-- For older MySQL or explicit numeric storage
CREATE TABLE users (
    id VARCHAR(36) PRIMARY KEY,
    is_active TINYINT(1) NOT NULL DEFAULT 1
);

SQLite

sql
-- SQLite stores boolean as INTEGER (0 or 1)
CREATE TABLE users (
    id TEXT PRIMARY KEY,
    is_active INTEGER NOT NULL DEFAULT 1
);

下一步

基于 Apache License 2.0 许可发布