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.
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) and exclusion (--exclude-tables _migrations) - Single-file or multi-file output
- Dry-run mode (preview on stdout)
Installation
Usage
PostgreSQL (multi-schema)
MySQL
SQLite
With extra derives
Exclude specific tables
Include SQL views
Dry run (preview without writing)
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 | |
--exclude-tables |
Exclude these tables/views (comma-separated) | none | |
--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 ;
use Uuid;
Enums:
License
MIT