Cornucopia v0.3 : Generate Rust from your PostgreSQL, now with custom types!
Cornucopia is a CLI based on tokio-postgres designed to validate and generate type-checked Rust from your PostgreSQL queries. It supports many base types, custom user types (domains, composites and enums), nullable return columns, transactions, and much more. For example, let's say you have this migration
create type custom_enum as enum (
'Wow', 'Very', 'Cool'
);
create table example (
col1 TEXT,
col2 custom_enum
);
Then, from the following queries,
--! select_example()
SELECT * FROM example;
--! select_col1() {col1}
SELECT col1 FROM example;
Cornucopia will generate these Rust modules for you:
mod types {
pub enum CustomEnum {
Wow,
Very,
Cool,
}
}
mod queries {
pub async fn select_example(client: &Client) -> Result<(String, CustomEnum), Error> {
/* omitted for brevitty */
}
pub struct SelectCol1 {
pub col1: String,
}
pub async fn select_col1(client: &Client) -> Result<SelectCol1, Error> {
/* omitted for brevitty */
}
}
Notice how Cornucopia has picked up appropriate types for you, type checked directly against your database, including custom user types.
This example is only for demonstration purposes, there's actually a bit more going on behind the scenes, and Cornucopia also has other features which are not covered here. You can learn more by taking a look a the example or the readme.