Skip to main content

Karma Database Package

The karma/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-in PostgresConn function to connect to your database using .env values.
You can optionally pass pool config:

🔧 Environment Configuration

Your .env file must define one of the following:
Karma will choose the right URL based on the 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 TableName field with karma_table tag for ORM functionality

🔧 Function Reference

FetchColumnNames

Returns a list of column names for a given table.

ParseRows

Scans SQL rows into a slice of structs.
dest must be a pointer to a slice of structs.

InsertStruct

Inserts a struct into a table.

UpdateStruct

Updates a table row based on a given condition.

🧪 Full Example


🧠 Pro Tips

  • For dynamic field updates (only update changed fields), use sqlx.NamedExec manually.
  • Use karma/config for all env loading. Never hardcode secrets.
  • Combine with karma/middleware to add request logging or panic recovery around DB operations.