ORM (对象关系映射)

当前处于Alpha阶段

V语言内置ORM支持SQLite、MySQL和PostgreSQL(即将支持MS SQL和Oracle)主要特性:

核心优势

  • 统一语法兼容所有SQL
  • V原生语法构建查询(无需额外学习)
  • 自动防SQL注入攻击
  • 编译时类型检查(预防运行时错误)
  • 自动结果集映射(避免手动解析)
import db.sqlite

// 自定义表名(默认使用结构体名)
@[table: 'customers']
struct Customer {
    id        int @[primary; serial]  // 首字段需为int类型id
    name      string
    nr_orders int
    country   ?string  // 可空字段
}

fn main() {
    db := sqlite.connect('customers.db')!
    
    // 自动建表(SQL: CREATE TABLE IF NOT EXISTS...)
    sql db {
        create table Customer
    }!
    
    // 插入数据
    new_customer := Customer{name: 'Bob', country: 'uk', nr_orders: 10}
    sql db {
        insert new_customer into Customer
    }!

    // 更新数据(支持V语法表达式)
    sql db {
        update Customer set nr_orders = nr_orders + 1 where name == 'Bob'
    }!
    
    // 查询数据(自动映射为结构体数组)
    uk_customers := sql db {
        select from Customer where country == 'uk' && nr_orders > 0
    }!
    for c in uk_customers {
        println('客户: ${c.id}, ${c.name}, 订单数:${c.nr_orders}')
    }
    
    // 聚合查询
    total := sql db {
        select count from Customer
    }!
    println("客户总数: ${total}")
}

关键特性详解

  1. 结构体映射
    • @[table] 自定义表名
    • @[primary] 标记主键
    • ?string 表示可空字段
  1. 查询构建
// 条件查询 (自动转义)
select from User where age > 18 and name.contains("张")

// 空值处理
select from Customer where country is none
  1. 安全机制
    • 所有查询参数自动消毒
    • 编译时验证字段有效性
    • 事务支持(开发中)

更多示例参考:vlib/orm 模块源码