美文网首页
Rust SeaOrm 如何指定字段默认时间为 current_

Rust SeaOrm 如何指定字段默认时间为 current_

作者: 子十一刻 | 来源:发表于2022-08-24 18:34 被阅读0次

需求

创建数据表包含 created_at 字段为 timestamp 时间戳类型

Table::create()
    .table(User::Entity)
    .if_not_exists()
    .col(ColumnDef::new(User::Id).uuid().not_null().primary_key())
    .col(
        ColumnDef::new(User::CreatedAt)
            .timestamp()
            .default()  // <== 这里想设置默认值 CURRENT_TIMESTAMP
            .not_null(),
    );

各种尝试 SeaOrm 目前版本是v0.9 还不支持默认值直接指定 current_timestamp

用关键字 current_timestamp 查找 sea-orm 项目 issues 列表

issue 查找结果

会查到这个 issue: 自动更新 create_at & updated_at 字段的时间戳问题

Automatically update created_at & updated_at timestamp columns on update

会链接到 PR: 在更新和插入时自动更新时间戳的PR

auto set timestamp column when update & insert

PR中总结了时间戳自动更新要处理的问题

1. 定义 timestamp 字段并指定默认值为 CURRENT_TIMESTAMP

2. 针对不同的数据库更新时间方案

PR就提到了 sea-query 项目的 issue

Table Column with Default Expression

这个 Issue就链接到了目前默认值的解决方案: 如何使用 postgresql 的 current_timestamp 做为默认值:

Can I use postgresql "CURRENT_TIMESTAMP" as a default value

解决方案

ColumnDef 支持 extra() 方法

.extra("DEFAULT CURRENT_TIMESTAMP".to_string())

源文件sea-query/tests/mysql/table.rs

#[test] 
 fn create_4() { 
     assert_eq!( 
         Table::create() 
             .table(Glyph::Table) 
             .col( 
                 ColumnDef::new(Glyph::Id) 
                     .integer() 
                     .not_null() 
                     .extra("ANYTHING I WANT TO SAY".to_owned()) 
             ) 
             .to_string(MysqlQueryBuilder), 
         vec![ 
             "CREATE TABLE `glyph` (", 
             "`id` int NOT NULL ANYTHING I WANT TO SAY", 
             ")", 
         ] 
         .join(" ") 
     ); 
 } 

相关文章

网友评论

      本文标题:Rust SeaOrm 如何指定字段默认时间为 current_

      本文链接:https://www.haomeiwen.com/subject/dcdzgrtx.html