SQL to Diesel Model Generator

Convert SQL CREATE TABLE statements to Rust Diesel ORM model structs with proper type mapping, derive macros, and associations.

What is SQL to Diesel Model Generator?

Diesel is the most widely adopted ORM for Rust, built around the principle of compile-time query verification. Instead of discovering SQL errors at runtime, Diesel catches them during compilation by leveraging Rust's type system and its own DSL macros. This converter takes your SQL CREATE TABLE statements and produces Rust code including the table! macro schema definitions, model structs with Queryable and Selectable derive macros, optional Insertable implementations, and belongs_to association annotations derived from foreign key constraints. It supports all three Diesel backends: PostgreSQL, MySQL, and SQLite.

How to Use

  1. Select your database backend — PostgreSQL, MySQL, or SQLite — since Diesel generates different SQL type annotations per dialect
  2. Paste your SQL CREATE TABLE statements into the input panel
  3. Toggle "Include table! macro" to generate Diesel schema definitions required for compile-time query checking
  4. Toggle "Include Insertable" to add the Insertable derive macro for struct insertion into the database
  5. Toggle "Use newtype for primary keys" to wrap primary keys in dedicated types like UserId(i32) to prevent accidental mixing of IDs across tables
  6. Click "Generate Diesel Models" and copy the Rust code into your project

Why Use This Tool?

Produces Diesel model structs with Queryable and Selectable derives that map query results directly to typed Rust structs
The table! macro enables Diesel compile-time query verification — if your SQL query is wrong, your Rust code will not compile
Foreign key constraints are automatically converted to #[diesel(belongs_to)] annotations for Diesel association support
Newtype primary keys prevent entire categories of bugs where you accidentally pass a UserId where a PostId is expected
Cargo.toml feature flag hints are generated automatically so you know which Diesel features to enable for chrono, uuid, and serde_json

Tips & Best Practices

  • Always include the table! macro — without it, Diesel cannot verify your queries at compile time and you lose the primary benefit of using Diesel
  • Enable the newtype primary key option for any project with multiple tables — the type safety it provides far outweighs the small amount of additional code
  • Nullable columns are automatically wrapped in Option<T>, which is idiomatic Rust and integrates seamlessly with Diesel query building
  • After generating models, run diesel print-schema in your project to verify the output matches your actual database schema

Frequently Asked Questions

How are SQL types mapped to Rust and Diesel types?

The converter produces two layers of mapping: Diesel SQL types for the table! macro (Int4, Int8, Varchar, Text, Bool, Timestamp, Timestamptz, Uuid, Json, Jsonb, Numeric, Binary) and Rust types for model structs (i32, i64, String, bool, chrono::NaiveDateTime, chrono::NaiveDate, uuid::Uuid, serde_json::Value, bigdecimal::BigDecimal, Vec<u8>). Nullable columns wrap the Rust type in Option<T>.

When should I avoid using Diesel?

Diesel is not ideal when you need dynamic query construction at runtime (e.g., user-defined filters), when you want an async-first API (Diesel 2.x is synchronous, though async wrappers exist), or when your team prefers an Active Record pattern over Diesel Data Mapper approach. For those cases, consider sqlx or SeaORM.

What is the belongs_to association for?

The #[diesel(belongs_to)] annotation tells Diesel that one model is related to another via a foreign key. This enables Diesel association helpers like User::find_with_related(Post), letting you eagerly load related records in a single query instead of making separate queries.

Why does the output include Cargo.toml feature flags?

Diesel requires specific feature flags to support certain SQL types. For example, TIMESTAMP columns need the chrono feature, UUID columns need the uuid feature, and JSON columns need the serde_json feature. The converter detects which types your schema uses and lists the required features.

Is my SQL data sent to a server?

No. All parsing and code generation runs entirely in your browser. Your SQL schema is never transmitted over the network, and no external services are contacted during the conversion process.

Real-world Examples

Web API with typed Diesel models

A Rust web service built with Actix-web uses Diesel for database access. The developer pastes their PostgreSQL schema into this tool, generates model structs with Queryable and Insertable derives, and uses them in route handlers to deserialize query results directly into JSON responses.

Input
CREATE TABLE orders (
  id SERIAL PRIMARY KEY,
  customer_id INTEGER NOT NULL REFERENCES users(id),
  total NUMERIC(10,2) NOT NULL,
  status VARCHAR(20) DEFAULT 'pending',
  created_at TIMESTAMP DEFAULT NOW()
);
Output
#[derive(Debug, Queryable, Selectable, Insertable)]
#[diesel(table_name = orders)]
#[diesel(check_for_backend(diesel::pg::Pg))]
#[diesel(belongs_to(User, foreign_key = customer_id))]
pub struct Order {
    pub id: i32,
    pub customer_id: i32,
    pub total: bigdecimal::BigDecimal,
    pub status: String,
    pub created_at: chrono::NaiveDateTime,
}

Multi-table schema with newtype IDs

A project with 15+ tables enables the newtype primary key option. Each table gets a dedicated ID type like AccountId(i32) and TransactionId(i64), preventing accidental cross-table ID misuse in function signatures and query filters.

Related Tools