pgdbtostruct

This is a Rust CLI app to generate Rust struct files from PostgreSQL database tables.

Let's assume we have a PostgreSQL database with the following tables:

```sql CREATE TABLE public.customer ( id serial4 NOT NULL, firstname varchar(40) NOT NULL, lastname 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, productname varchar(50) NOT NULL, supplierid int4 NOT NULL, unitprice numeric(12, 2) NULL DEFAULT 0, package varchar(30) NULL, isdiscontinued bool NOT NULL DEFAULT false, CONSTRAINT pk_product PRIMARY KEY (id) );

```

To generate Rust structs that represent these tables, first edit the file app.properties to set the database connection properties and the table names to be used.

yaml 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

Then build and run using cargo:

shell $ cargo build

``shell $ cargo run Finished dev [unoptimized + debuginfo] target(s) in 0.07s Runningtarget/debug/pgdbtostruct`

Creating struct for table: customer Creating struct for table: product ```

A new folder named gen will be created with two Rust source files:

shell gen/ customer.rs product.rs

Here is the content of the generated files:

customer.rs

```rust

[derive(Debug)]

pub struct Customer { pub id: i32, pub firstname: String, pub lastname: String, pub city: String, pub country: String, pub phone: String, } ```

product.rs

```rust

[derive(Debug)]

pub struct Product { pub id: i32, pub productname: String, pub supplierid: i32, pub unitprice: bigdecimal::BigDecimal, pub package: String, pub isdiscontinued: bool, } ```

Optionally you can include serde lib for serialization/deserialization. In app.properties make use_serde: true and you will get:

```rust use serde::{Deserialize, Serialize};

[derive(Debug, Serialize, Deserialize)]

pub struct Customer { pub id: i32, #[serde(skipserializingif = "String::isempty")] pub firstname: String, #[serde(skipserializingif = "String::isempty")] pub lastname: String, #[serde(skipserializingif = "String::isempty")] pub city: String, #[serde(skipserializingif = "String::isempty")] pub country: String, #[serde(skipserializingif = "String::is_empty")] pub phone: String, } ```