sqlx-gen 0.2.0

Generate Rust structs from database schema introspection
Documentation

sqlx-gen

Generate Rust structs from your database schema — with correct types, derives, and sqlx::FromRow annotations.

Supports PostgreSQL, MySQL, and SQLite. Introspects tables, views, enums, composite types, and domains.

Crates.io docs.rs License: MIT

Features

  • Multi-database: PostgreSQL, MySQL, SQLite
  • Multi-schema support (PostgreSQL)
  • Generates #[derive(sqlx::FromRow)] structs
  • PostgreSQL enums → #[derive(sqlx::Type)] enums
  • PostgreSQL composite types and domains
  • MySQL inline ENUM detection
  • Correct nullable handling (Option<T>)
  • Custom derives (--derives Serialize,Deserialize)
  • Type overrides (--type-overrides jsonb=MyType)
  • SQL views support (--views)
  • Table filtering (--tables users,orders)
  • Single-file or multi-file output
  • Dry-run mode (preview on stdout)

Installation

cargo install sqlx-gen

Usage

PostgreSQL (multi-schema)

sqlx-gen -u postgres://user:pass@localhost/mydb -s public,auth -o src/models

MySQL

sqlx-gen -u mysql://user:pass@localhost/mydb -o src/models

SQLite

sqlx-gen -u sqlite:./local.db -o src/models

With extra derives

sqlx-gen -u postgres://... --derives Serialize,Deserialize -o src/models

Include SQL views

sqlx-gen -u postgres://... --views -o src/models

Dry run (preview without writing)

sqlx-gen -u postgres://... --dry-run

CLI Options

Flag Short Description Default
--database-url -u Database connection URL (or DATABASE_URL env) required
--output-dir -o Output directory src/models
--schemas -s Schemas to introspect (comma-separated) public
--derives Additional derive macros (comma-separated) none
--type-overrides Type overrides sql_type=RustType (comma-separated) none
--tables Only generate these tables (comma-separated) all
--views Also generate structs for SQL views false
--single-file Write everything to a single models.rs false
--dry-run Print to stdout, don't write files false

Example Output

// Auto-generated by sqlx-gen. Do not edit.
// Table: public.users

use chrono::{DateTime, Utc};
use uuid::Uuid;

#[derive(Debug, Clone, sqlx::FromRow)]
pub struct Users {
    pub id: Uuid,
    pub email: String,
    pub name: Option<String>,
    pub created_at: DateTime<Utc>,
}

Enums:

#[derive(Debug, Clone, PartialEq, sqlx::Type)]
#[sqlx(type_name = "status")]
pub enum Status {
    #[sqlx(rename = "active")]
    Active,

    #[sqlx(rename = "inactive")]
    Inactive,
}

License

MIT