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.