97 lines
2.4 KiB
Go
97 lines
2.4 KiB
Go
package db
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
// ---------------- 通用查询方法 ----------------
|
|
|
|
// GetOne 根据主键查询单条记录,返回 map[string]interface{}
|
|
func GetOne(table string, pkColumn string, pkValue interface{}) (map[string]interface{}, error) {
|
|
query := fmt.Sprintf("SELECT * FROM %s WHERE %s=$1", table, pkColumn)
|
|
|
|
row := make(map[string]interface{})
|
|
err := DB.Get(&row, query, pkValue)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return row, nil
|
|
}
|
|
|
|
// GetBatch 根据主键批量查询,返回 []map[string]interface{}
|
|
func GetBatch(table string, pkColumn string, pkValues []interface{}) ([]map[string]interface{}, error) {
|
|
if len(pkValues) == 0 {
|
|
return nil, nil
|
|
}
|
|
|
|
var rows []map[string]interface{}
|
|
|
|
// 构建 IN 占位符
|
|
placeholders := make([]string, len(pkValues))
|
|
for i := range pkValues {
|
|
placeholders[i] = fmt.Sprintf("$%d", i+1)
|
|
}
|
|
|
|
query := fmt.Sprintf("SELECT * FROM %s WHERE %s IN (%s)", table, pkColumn, strings.Join(placeholders, ","))
|
|
err := DB.Select(&rows, query, pkValues...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return rows, nil
|
|
}
|
|
|
|
// Find 根据条件查询多条记录,可选排序
|
|
// conditions: map[column]value, 将以 AND 拼接
|
|
// orderBy: 可选排序字段,如 "created_at ASC",为空默认 "b_id DESC"
|
|
func Find(table string, conditions map[string]interface{}, orderBy ...string) ([]map[string]interface{}, error) {
|
|
if len(conditions) == 0 {
|
|
return nil, fmt.Errorf("查询条件不能为空")
|
|
}
|
|
|
|
var whereParts []string
|
|
var values []interface{}
|
|
i := 1
|
|
for k, v := range conditions {
|
|
whereParts = append(whereParts, fmt.Sprintf("%s=$%d", k, i))
|
|
values = append(values, v)
|
|
i++
|
|
}
|
|
|
|
query := fmt.Sprintf("SELECT * FROM %s WHERE %s", table, strings.Join(whereParts, " AND "))
|
|
|
|
order := "b_id DESC"
|
|
if len(orderBy) > 0 && orderBy[0] != "" {
|
|
order = orderBy[0]
|
|
}
|
|
query += " ORDER BY " + order
|
|
|
|
var rows []map[string]interface{}
|
|
err := DB.Select(&rows, query, values...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return rows, nil
|
|
}
|
|
|
|
// FindAll 查询整个表,可选排序
|
|
func FindAll(table string, orderBy ...string) ([]map[string]interface{}, error) {
|
|
query := fmt.Sprintf("SELECT * FROM %s", table)
|
|
|
|
order := "b_id DESC"
|
|
if len(orderBy) > 0 && orderBy[0] != "" {
|
|
order = orderBy[0]
|
|
}
|
|
query += " ORDER BY " + order
|
|
|
|
var rows []map[string]interface{}
|
|
err := DB.Select(&rows, query)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return rows, nil
|
|
}
|