# pgm - PostgreSQL Query Mapper A lightweight ORM built on top of [jackc/pgx](https://github.com/jackc/pgx) database connection pool. ## ORMs I Like in the Go Ecosystem - [ent](https://github.com/ent/ent) - [sqlc](https://github.com/sqlc-dev/sqlc) ## Why Not Use `ent`? `ent` is a feature-rich ORM with schema definition, automatic migrations, integration with `gqlgen` (GraphQL server), and more. It provides nearly everything you could want in an ORM. However, it can be overkill. The generated code supports a wide range of features, many of which you may not use, significantly increasing the compiled binary size. ## Why Not Use `sqlc`? `sqlc` is a great tool, but it often feels like the database layer introduces its own models. This forces you to either map your application’s models to these database models or use the database models directly, which may not align with your application’s design. ## Issues with Existing ORMs Here are some common pain points with ORMs: - **Auto Migrations**: Many ORMs either lack robust migration support or implement complex methods for simple schema changes. This can obscure the database schema, making it harder to understand and maintain. A database schema should be defined in clear SQL statements that can be tested in a SQL query editor. Tools like [dbmate](https://github.com/amacneil/dbmate) provide a mature solution for managing migrations, usable via CLI or in code. - **Excessive Code Generation**: ORMs often generate excessive code for various conditions and scenarios, much of which goes unused. - **Generated Models for Queries**: Auto-generated models for `SELECT` queries force you to either adopt them or map them to your application’s models, adding complexity. ## A Hybrid Approach: Plain SQL Queries with `pgm` Plain SQL queries are not inherently bad but come with challenges: - **Schema Change Detection**: Changes in the database schema are not easily detected. - **SQL Injection Risks**: Without parameterized queries, SQL injection becomes a concern. `pgm` addresses these issues by providing a lightweight CLI tool that generates Go files for your database schema. These files help you write SQL queries while keeping track of schema changes, avoiding hardcoded table and column names. ## Generating `pgm` Schema Files Run the following command to generate schema files: ```bash go run code.partial.tech/go/pgm/cmd -o ./db ./schema.sql