Files
workspace/code/base-project/base-go-v2/internal/db/query.go
T
2025-11-06 22:50:03 +08:00

128 lines
2.9 KiB
Go

package db
import (
"base-go-v2/internal/utils/mapx"
"fmt"
"strings"
)
// ---------------- 通用查询方法 ----------------
// GetOne 根据主键查询单条记录,返回 mapx.M
func GetOne(table string, pkColumn string, pkValue interface{}) (mapx.M, error) {
query := fmt.Sprintf("SELECT * FROM %s WHERE %s=$1", table, pkColumn)
row := mapx.New()
err := DB.Get(&row, query, pkValue)
if err != nil {
return nil, err
}
return row, nil
}
// GetBatch 根据主键批量查询,返回 []mapx.M
func GetBatch(table string, pkColumn string, pkValues []interface{}) ([]mapx.M, error) {
if len(pkValues) == 0 {
return nil, nil
}
var rows []mapx.M
// 构建 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 根据条件查询多条记录,可选排序,返回 []mapx.M
func Find(table string, conditions map[string]interface{}, orderBy ...string) ([]mapx.M, 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 := "id DESC"
if len(orderBy) > 0 && orderBy[0] != "" {
order = orderBy[0]
}
query += " ORDER BY " + order
var rows []mapx.M
err := DB.Select(&rows, query, values...)
if err != nil {
return nil, err
}
return rows, nil
}
// FindAll 查询整个表,可选排序,返回 []mapx.M
func FindAll(table string, orderBy ...string) ([]mapx.M, error) {
query := fmt.Sprintf("SELECT * FROM %s", table)
order := "id DESC"
if len(orderBy) > 0 && orderBy[0] != "" {
order = orderBy[0]
}
query += " ORDER BY " + order
var rows []mapx.M
err := DB.Select(&rows, query)
if err != nil {
return nil, err
}
return rows, nil
}
// FindOne 根据条件查询单条记录,返回 mapx.M
func FindOne(table string, conditions map[string]interface{}, orderBy ...string) (mapx.M, 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 := "id DESC"
if len(orderBy) > 0 && orderBy[0] != "" {
order = orderBy[0]
}
query += " ORDER BY " + order + " LIMIT 1"
row := mapx.New()
err := DB.Get(&row, query, values...)
if err != nil {
return nil, err
}
return row, nil
}