0.1.3 2022年5月1日
0.1.2 2022年5月1日
0.1.1 2022年5月1日
0.1.0 2022年4月30日

#2 in #reveser

MIT/Apache

53KB
783 代码行数

sql_reveser

根据 MySQL/PostgreSQL 表结构生成 RUST 结构

Version info Downloads docs dependency status

安装

cargo install sql_reveser

执行,你需要确保你处于与模板相同的目录中。

sql_reveser mysql -f reverse.yml
sql_reveser postgres -f reverse.yml

自定义执行

sql_reveser mysql -f reverse.yml -p 'templates/*' -n base.tera
sql_reveser postgres -f reverse.yml -p 'templates/*' -n base.tera

reverse.yml

host: 127.0.0.1
post: 3306
username: root
password: ''
database: db_name
schemaname: test # only postgres enable
include_tables: # Include tables, can be ignored.
#  - table_name
exclude_tables: # Exclude, tables, can be ignored.
#  - table_name
output_dir: ./dir # code output directory

模板结构

#[derive(Serialize)]
pub struct Template {
    pub table_name: String,
    pub struct_name: String,
    pub fields: Vec<Field>, 
    pub comment: String,
}

#[derive(Serialize, Clone)]
pub struct Field {
    pub field_name: String,
    pub field_type: String,
    pub comment: String,
    /// only supported mysql
    pub index_key: Vec<Vec<String>>
    /// 1: 是, 0: 否
    pub is_null: u8,
}

模板

use serde_derive;
use chrono::prelude::*;

{% if template.comment -%}
    /// {{ template.comment }}
{% endif -%}
#[crud_table]
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)]
pub struct {{ template.struct_name }} {
{%- for v in template.fields %}
    {% if v.comment -%}
        /// {{ v.comment }}
    {% endif -%}
    {% if v.is_null == 1 -%}
        pub {{ v.field_name }}: Option<{{ v.field_type }}>,
    {%- else -%}
        pub {{ v.field_name }}: {{ v.field_type }},
    {%- endif -%}
{%- endfor %}
}

生成结构示例

use serde_derive;
use chrono::prelude::*;

/// Test
#[crud_table]
#[derive(Default, Debug, Clone, PartialEq, serde_derive::Serialize, serde_derive::Deserialize)
pub struct Test {
    pub id: Option<u32>,
    /// uuid
    pub uuid: Option<String>,
    /// 数据
    pub content: Option<String>,
    /// 版本
    pub version: Option<i8>,
    /// 1:删除, 0:未删除
    pub is_deleted: Option<u8>,
    /// 更新时间
    pub updated_at: Option<NaiveDateTime>,
    /// 创建时间
    pub created_at: Option<NaiveDateTime>,
}

依赖项

~30–45MB
~771K SLoC