{"id":45750660,"url":"https://github.com/leadcodedev/sqlx_gen","last_synced_at":"2026-03-04T11:00:31.404Z","repository":{"id":340607600,"uuid":"1166814875","full_name":"LeadcodeDev/sqlx_gen","owner":"LeadcodeDev","description":null,"archived":false,"fork":false,"pushed_at":"2026-02-25T16:52:17.000Z","size":33,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-02-25T19:58:08.630Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LeadcodeDev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-02-25T16:30:40.000Z","updated_at":"2026-02-25T16:51:54.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/LeadcodeDev/sqlx_gen","commit_stats":null,"previous_names":["leadcodedev/sqlx_gen"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/LeadcodeDev/sqlx_gen","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LeadcodeDev%2Fsqlx_gen","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LeadcodeDev%2Fsqlx_gen/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LeadcodeDev%2Fsqlx_gen/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LeadcodeDev%2Fsqlx_gen/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LeadcodeDev","download_url":"https://codeload.github.com/LeadcodeDev/sqlx_gen/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LeadcodeDev%2Fsqlx_gen/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":30078397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-04T08:01:56.766Z","status":"ssl_error","status_checked_at":"2026-03-04T08:00:42.919Z","response_time":59,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-02-25T18:15:35.294Z","updated_at":"2026-03-04T11:00:31.392Z","avatar_url":"https://github.com/LeadcodeDev.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# sqlx-gen\n\nGenerate Rust structs and CRUD repositories from your database schema — with correct types, derives, and `sqlx` annotations.\n\nSupports **PostgreSQL**, **MySQL**, and **SQLite**. Introspects tables, views, enums, composite types, and domains.\n\n[![Crates.io](https://img.shields.io/crates/v/sqlx-gen.svg)](https://crates.io/crates/sqlx-gen)\n[![docs.rs](https://docs.rs/sqlx-gen/badge.svg)](https://docs.rs/sqlx-gen)\n[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)\n\n## Features\n\n- Multi-database: PostgreSQL, MySQL, SQLite\n- Multi-schema support (PostgreSQL)\n- Generates `#[derive(sqlx::FromRow)]` structs with `Serialize`, `Deserialize`, `PartialEq`, `Eq`\n- PostgreSQL enums → `#[derive(sqlx::Type)]` enums\n- PostgreSQL composite types and domains\n- MySQL inline ENUM detection\n- Correct nullable handling (`Option\u003cT\u003e`)\n- Primary key detection across all backends\n- Custom derives (`--derives Hash`)\n- Type overrides (`--type-overrides jsonb=MyType`)\n- SQL views support (`--views`)\n- Table filtering (`--tables users,orders`) and exclusion (`--exclude-tables _migrations`)\n- Single-file or multi-file output\n- Dry-run mode (preview on stdout)\n- **CRUD repository generation** from generated entity files (no DB connection required)\n- `#[sqlx_gen(...)]` annotations on all generated types for tooling integration\n- Automatic `rustfmt` formatting (edition detected from `Cargo.toml`)\n- Automatic `mod.rs` management for generated CRUD files\n\n## Installation\n\n```sh\ncargo install sqlx-gen\n```\n\n## Commands\n\nsqlx-gen uses subcommands:\n\n```\nsqlx-gen generate entities   # Generate entity structs from DB schema\nsqlx-gen generate crud       # Generate CRUD repository from an entity file\n```\n\n## Generate Entities\n\n### PostgreSQL (multi-schema)\n```sh\nsqlx-gen generate entities -u postgres://user:pass@localhost/mydb -s public,auth -o src/models\n```\n\n### MySQL\n```sh\nsqlx-gen generate entities -u mysql://user:pass@localhost/mydb -o src/models\n```\n\n### SQLite\n```sh\nsqlx-gen generate entities -u sqlite:./local.db -o src/models\n```\n\n### With extra derives\n```sh\nsqlx-gen generate entities -u postgres://... -D Hash -o src/models\n```\n\n### Exclude specific tables\n```sh\nsqlx-gen generate entities -u postgres://... -x _migrations,schema_versions -o src/models\n```\n\n### Include SQL views\n```sh\nsqlx-gen generate entities -u postgres://... -v -o src/models\n```\n\n### Dry run (preview without writing)\n```sh\nsqlx-gen generate entities -u postgres://... -n\n```\n\n### Entities CLI Options\n\n| Flag | Short | Description | Default |\n|------|-------|-------------|---------|\n| `--database-url` | `-u` | Database connection URL (or `DATABASE_URL` env var) | required |\n| `--schemas` | `-s` | Schemas to introspect (comma-separated) | `public` |\n| `--output-dir` | `-o` | Output directory | `src/models` |\n| `--derives` | `-D` | Additional derive macros (comma-separated) | none |\n| `--type-overrides` | `-T` | Type overrides `sql_type=RustType` (comma-separated) | none |\n| `--single-file` | `-S` | Write everything to a single `models.rs` | `false` |\n| `--tables` | `-t` | Only generate these tables (comma-separated) | all |\n| `--exclude-tables` | `-x` | Exclude these tables/views (comma-separated) | none |\n| `--views` | `-v` | Also generate structs for SQL views | `false` |\n| `--dry-run` | `-n` | Print to stdout, don't write files | `false` |\n\n## Generate CRUD\n\nGenerate a repository from an already-generated entity file. No database connection is required — the generator reads the Rust source file directly.\n\nYou must specify which methods to generate with `--methods` (`-m`):\n\n```sh\n# Generate all CRUD methods\nsqlx-gen generate crud \\\n  -f src/models/users.rs \\\n  -d postgres \\\n  -m '*' \\\n  -o src/repositories\n\n# Generate only specific methods\nsqlx-gen generate crud \\\n  -f src/models/users.rs \\\n  -d postgres \\\n  -m get_all,get,insert\n\n# With explicit module path (auto-detected by default)\nsqlx-gen generate crud \\\n  -f src/models/users.rs \\\n  -d postgres \\\n  -e crate::models::users \\\n  -m '*'\n\n# With compile-time checked macros\nsqlx-gen generate crud \\\n  -f src/models/users.rs \\\n  -d postgres \\\n  -m '*' \\\n  -q\n```\n\n### Module path auto-detection\n\nThe `--entities-module` (`-e`) option is **optional**. When omitted, the module path is automatically derived from the `--entity-file` path by locating `src/` and converting to a Rust module path:\n\n| File path | Derived module |\n|-----------|---------------|\n| `src/models/users.rs` | `crate::models::users` |\n| `src/db/entities/agent.rs` | `crate::db::entities::agent` |\n| `src/models/mod.rs` | `crate::models` |\n| `../project/src/models/users.rs` | `crate::models::users` |\n\n### Views\n\nViews are automatically detected via the `#[sqlx_gen(kind = \"view\")]` annotation — write methods (`insert`, `update`, `delete`) are never generated for views even if requested.\n\n### Pool field visibility\n\nBy default, the `pool` field in generated repositories is private. Use `--pool-visibility` (`-p`) to change it:\n\n```sh\n# Public pool field\nsqlx-gen generate crud -f src/models/users.rs -d postgres -m '*' -p pub\n\n# Crate-visible pool field\nsqlx-gen generate crud -f src/models/users.rs -d postgres -m '*' -p 'pub(crate)'\n```\n\n### Compile-time checked macros\n\nBy default, the CRUD generator uses `sqlx::query_as::\u003c_, T\u003e()` with `.bind()` chains (runtime). Pass `--query-macro` (`-q`) to generate `sqlx::query_as!()` / `sqlx::query!()` macros instead, which are checked at compile time (requires `DATABASE_URL` at build time).\n\n### Available methods\n\n| Method | Description |\n|--------|------------|\n| `*` | Generate all methods below |\n| `get_all` | `SELECT *` returning `Vec\u003cT\u003e` |\n| `paginate` | `SELECT *` with `LIMIT` / `OFFSET` returning `Vec\u003cT\u003e` |\n| `get` | `SELECT *` by primary key returning `Option\u003cT\u003e` |\n| `insert` | `INSERT` with a params struct, `RETURNING *` |\n| `update` | `UPDATE` by primary key with a params struct, `RETURNING *` |\n| `delete` | `DELETE` by primary key |\n\n### mod.rs management\n\nWhen writing a CRUD file (not in dry-run mode), sqlx-gen automatically updates or creates a `mod.rs` in the output directory with the corresponding `pub mod` declaration.\n\n### Formatting\n\nGenerated files are automatically formatted with `rustfmt`. The Rust edition is detected from the nearest `Cargo.toml` in the output directory's parent chain (defaults to `2021` if not found).\n\n### CRUD CLI Options\n\n| Flag | Short | Description | Default |\n|------|-------|-------------|---------|\n| `--entity-file` | `-f` | Path to the generated entity `.rs` file | required |\n| `--db-kind` | `-d` | Database kind: `postgres`, `mysql`, `sqlite` | required |\n| `--entities-module` | `-e` | Rust module path (e.g. `crate::models::users`). Auto-detected from file path if omitted. | auto |\n| `--output-dir` | `-o` | Output directory | `src/crud` |\n| `--methods` | `-m` | Methods to generate (comma-separated): `*`, `get_all`, `paginate`, `get`, `insert`, `update`, `delete` | required |\n| `--query-macro` | `-q` | Use `sqlx::query_as!()` macros (compile-time checked) | `false` |\n| `--pool-visibility` | `-p` | Visibility of the `pool` field: `private`, `pub`, `pub(crate)` | `private` |\n| `--dry-run` | `-n` | Print to stdout, don't write files | `false` |\n\n## Example Output\n\n### Entity (table)\n\n```rust\n// Auto-generated by sqlx-gen. Do not edit.\n// Table: public.users\n\nuse chrono::{DateTime, Utc};\nuse serde::{Serialize, Deserialize};\nuse uuid::Uuid;\n\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, sqlx::FromRow)]\n#[sqlx_gen(kind = \"table\", table = \"users\")]\npub struct Users {\n    #[sqlx_gen(primary_key)]\n    pub id: Uuid,\n    pub email: String,\n    pub name: Option\u003cString\u003e,\n    pub created_at: DateTime\u003cUtc\u003e,\n}\n```\n\n### Entity (view)\n\n```rust\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, sqlx::FromRow)]\n#[sqlx_gen(kind = \"view\", table = \"active_users\")]\npub struct ActiveUsers {\n    pub id: Uuid,\n    pub email: String,\n}\n```\n\n### Enum\n\n```rust\n#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, sqlx::Type)]\n#[sqlx_gen(kind = \"enum\")]\n#[sqlx(type_name = \"status\")]\npub enum Status {\n    #[sqlx(rename = \"active\")]\n    Active,\n\n    #[sqlx(rename = \"inactive\")]\n    Inactive,\n}\n```\n\n### CRUD Repository (default — runtime)\n\n```rust\nimpl UsersRepository {\n    pub async fn get(\u0026self, id: \u0026Uuid) -\u003e Result\u003cOption\u003cUsers\u003e, sqlx::Error\u003e {\n        sqlx::query_as::\u003c_, Users\u003e(\"SELECT * FROM users WHERE id = $1\")\n            .bind(id)\n            .fetch_optional(\u0026self.pool)\n            .await\n    }\n\n    pub async fn insert(\u0026self, params: \u0026InsertUsersParams) -\u003e Result\u003cUsers, sqlx::Error\u003e {\n        sqlx::query_as::\u003c_, Users\u003e(\n            \"INSERT INTO users (email, name, created_at) VALUES ($1, $2, $3) RETURNING *\",\n        )\n            .bind(\u0026params.email)\n            .bind(\u0026params.name)\n            .bind(\u0026params.created_at)\n            .fetch_one(\u0026self.pool)\n            .await\n    }\n    // ...\n}\n```\n\n### CRUD Repository (`--query-macro` — compile-time checked)\n\n```rust\nimpl UsersRepository {\n    pub async fn get(\u0026self, id: \u0026Uuid) -\u003e Result\u003cOption\u003cUsers\u003e, sqlx::Error\u003e {\n        sqlx::query_as!(Users, \"SELECT * FROM users WHERE id = $1\", id)\n            .fetch_optional(\u0026self.pool)\n            .await\n    }\n\n    pub async fn insert(\u0026self, params: \u0026InsertUsersParams) -\u003e Result\u003cUsers, sqlx::Error\u003e {\n        sqlx::query_as!(\n            Users,\n            \"INSERT INTO users (email, name, created_at) VALUES ($1, $2, $3) RETURNING *\",\n            params.email, params.name, params.created_at\n        )\n            .fetch_one(\u0026self.pool)\n            .await\n    }\n    // ...\n}\n```\n\n## Annotations\n\nAll generated types include `#[sqlx_gen(...)]` annotations for tooling:\n\n| Type | Annotation |\n|------|-----------|\n| Table struct | `#[sqlx_gen(kind = \"table\", table = \"name\")]` |\n| View struct | `#[sqlx_gen(kind = \"view\", table = \"name\")]` |\n| Enum | `#[sqlx_gen(kind = \"enum\")]` |\n| Composite type | `#[sqlx_gen(kind = \"composite\")]` |\n| Domain type | `#[sqlx_gen(kind = \"domain\")]` |\n| Primary key field | `#[sqlx_gen(primary_key)]` |\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleadcodedev%2Fsqlx_gen","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fleadcodedev%2Fsqlx_gen","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fleadcodedev%2Fsqlx_gen/lists"}