#postgresql #数据库表 #结构体 #生成器 #数据库 #命令行应用程序 #命令行

应用 pgdb_to_struct

A Rust CLI应用程序,用于从PostgreSQL数据库表生成Rust结构体文件

4个版本

0.1.3 2023年8月18日
0.1.2 2023年8月18日
0.1.1 2023年8月18日
0.1.0 2023年8月18日

#11 in #数据库表

每月下载量37次

MIT许可证

17KB
261

pgdb_to_struct

这是一个用于从PostgreSQL数据库表生成Rust 结构体文件Rust CLI 应用程序。

假设我们有一个包含以下表的PostgreSQL数据库

CREATE TABLE public.customer (
	id serial4 NOT NULL,
	first_name varchar(40) NOT NULL,
	last_name varchar(40) NOT NULL,
	city varchar(40) NULL,
	country varchar(40) NULL,
	phone varchar(20) NULL,
	CONSTRAINT pk_customer PRIMARY KEY (id)
);

CREATE TABLE public.product (
	id serial4 NOT NULL,
	product_name varchar(50) NOT NULL,
	supplier_id int4 NOT NULL,
	unit_price numeric(12, 2) NULL DEFAULT 0,
	package varchar(30) NULL,
	is_discontinued bool NOT NULL DEFAULT false,
	CONSTRAINT pk_product PRIMARY KEY (id)
);

要生成代表这些表的Rust结构体,首先编辑文件 app.properties 以设置数据库连接属性和要使用的表名。

db_host: 127.0.0.1
db_port: 5432
db_name: sample_db
db_user: postgres
db_password: sample@123
db_schema: public
tables: customer, product
use_serde: false

然后使用 cargo 构建并运行

$ cargo build
$ cargo run
    Finished dev [unoptimized + debuginfo] target(s) in 0.07s
     Running `target/debug/pgdb_to_struct`
>> Creating struct for table: customer
>> Creating struct for table: product

将创建一个名为 gen 的新文件夹,其中包含两个Rust源文件

gen/
   customer.rs
   product.rs

以下是生成文件的内容

customer.rs

#[derive(Debug)]
pub struct Customer {
    pub id: i32,
    pub first_name: String,
    pub last_name: String,
    pub city: String,
    pub country: String,
    pub phone: String,
}

product.rs

#[derive(Debug)]
pub struct Product {
    pub id: i32,
    pub product_name: String,
    pub supplier_id: i32,
    pub unit_price: bigdecimal::BigDecimal,
    pub package: String,
    pub is_discontinued: bool,
}

可选地,您可以将 serde 库用于序列化和反序列化。在 app.properties 中设置 use_serde: true,您将得到

use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Customer {
    pub id: i32,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub first_name: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub last_name: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub city: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub country: String,
    #[serde(skip_serializing_if = "String::is_empty")]
    pub phone: String,
}

依赖项

~37–50MB
~865K SLoC