83 lines
1.4 KiB
Go
83 lines
1.4 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,
|
|
) ([][]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,
|
|
) ([][]any, error) {
|
|
return c.query(ctx, sql, args...)
|
|
}
|
|
|
|
// 统一查询方法(核心优化)
|
|
func (c *Client) query(ctx context.Context, sql string, args ...any) ([][]any, error) {
|
|
sql = convertPlaceholder(sql)
|
|
|
|
rows, err := c.exec().Query(ctx, sql, args...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
result := make([][]any, 0, 16)
|
|
|
|
for rows.Next() {
|
|
values, err := rows.Values()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
row := make([]any, len(values))
|
|
copy(row, values)
|
|
|
|
result = append(result, row)
|
|
}
|
|
|
|
return result, rows.Err()
|
|
}
|