Karma Database Package Quick Reference
Functions
FetchColumnNames
func FetchColumnNames(db *sqlx.DB, tableName string) ([]string, error)
Gets column names from table. Returns slice of column names and error.
ParseRows
func ParseRows(rows *sql.Rows, dest interface{}) error
Converts SQL rows to struct slice. Dest must be pointer to struct slice.
InsertStruct
func InsertStruct(db *sqlx.DB, tableName string, data interface{}) error
Inserts struct data into table. Data must be struct pointer.
UpdateStruct
func UpdateStruct(db *sqlx.DB, tableName string, data interface{}, conditionField string, conditionValue interface{}) error
Updates table record based on condition. Data must be struct pointer.
Struct Rules
- Fields must be CamelCase
- Use snake_case in json tags:
json:"user_name"
- For complex types (arrays, maps, structs, interfaces), add
db:"json"
tag - If using Karma ORM, add
TableName string \
karma_table:"table_name" json:"-"``
Example
type User struct {
TableName string `karma_table:"users" json:"-"` // For Karma ORM
Id int `json:"id"`
Username string `json:"username"`
Email string `json:"email"`
Tags []string `json:"tags" db:"json"` // Array needs db:"json"
Metadata map[string]interface{} `json:"metadata" db:"json"`
}
// Fetch columns
cols, _ := database.FetchColumnNames(db, "users")
// Parse query results
var users []User
rows, _ := db.Query("SELECT * FROM users")
database.ParseRows(rows, &users)
// Insert
user := User{Username: "john", Email: "j@ex.com", Tags: []string{"new"}}
database.InsertStruct(db, "users", &user)
// Update
database.UpdateStruct(db, "users", &user, "id", 1)
Import: github.com/MelloB1989/karma/database