Files
workspace/code/allapp/allapp-go-v3/pkg/db/select.go
T
2026-04-16 21:29:38 +08:00

93 lines
1.7 KiB
Go

package db
import (
"context"
"fmt"
"strings"
)
func (c *Client) LoadData(
ctx context.Context,
viewName string,
searchCondition string,
orderBy string,
searchColumns []string,
args []any,
) ([]map[string]any, error) {
var where string
// WHERE 构造
if searchCondition != "" && len(searchColumns) > 0 {
var conditions []string
for _, col := range searchColumns {
conditions = append(conditions, fmt.Sprintf("%s LIKE ?", col))
}
where = " WHERE (" + strings.Join(conditions, " OR ") + ")"
// 自动加 %
for i := range args {
if s, ok := args[i].(string); ok {
args[i] = "%" + s + "%"
}
}
}
// ORDER BY
var order string
if orderBy != "" {
order = " ORDER BY " + orderBy
}
sql := fmt.Sprintf("SELECT * FROM %s%s%s", viewName, where, order)
return c.query(ctx, sql, args...)
}
func (c *Client) LoadDataBySQL(
ctx context.Context,
sql string,
args []any,
) ([]map[string]any, error) {
return c.query(ctx, sql, args...)
}
// ==========================
// 核心查询方法(已升级)
// ==========================
func (c *Client) query(ctx context.Context, sql string, args ...any) ([]map[string]any, error) {
sql = convertPlaceholder(sql)
rows, err := c.exec().Query(ctx, sql, args...)
if err != nil {
return nil, err
}
defer rows.Close()
// 获取字段名
fields := rows.FieldDescriptions()
result := make([]map[string]any, 0, 16)
for rows.Next() {
values, err := rows.Values()
if err != nil {
return nil, err
}
row := make(map[string]any, len(values))
for i, f := range fields {
if i < len(values) {
row[string(f.Name)] = values[i]
}
}
result = append(result, row)
}
return result, rows.Err()
}