Karma Database Package
Thekarma/database package provides utilities to work with PostgreSQL using Go structs. It helps you insert, update, and parse query results without writing verbose SQL.
π¦ Installation
π Database Connection
Use the built-inPostgresConn function to connect to your database using .env values.
π§ Environment Configuration
Your.env file must define one of the following:
ENVIRONMENT variable.
π§© Struct Definition Rules
To enable Karmaβs ORM helpers, your struct must follow specific tag and format rules.
β Guidelines
- CamelCase field names in Go
- snake_case keys for JSON and DB tags
- For arrays/maps/structs, always add
db:"<column_name>"for PostgreSQL compatibility - Include
TableNamefield withkarma_tabletag for ORM functionality
π§ Function Reference
FetchColumnNames
ParseRows
dest must be a pointer to a slice of structs.
InsertStruct
UpdateStruct
π§ͺ Full Example
π§ Pro Tips
- For dynamic field updates (only update changed fields), use
sqlx.NamedExecmanually. - Use
karma/configfor all env loading. Never hardcode secrets. - Combine with
karma/middlewareto add request logging or panic recovery around DB operations.