20260507213409
This commit is contained in:
1 parent
3070eac71b
commit
4c7f516a03
204 files changed
+3623
No files matched your search
@@ -0,0 +1,122 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"allapp-go/pkg/logger"
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (c *Client) LoadData(
|
||||
ctx context.Context,
|
||||
viewName string,
|
||||
searchCondition string,
|
||||
orderBy string,
|
||||
searchColumns []string,
|
||||
args []any,
|
||||
) ([]map[string]any, error) {
|
||||
|
||||
selectCols := "*"
|
||||
if len(searchColumns) > 0 {
|
||||
selectCols = strings.Join(searchColumns, ", ")
|
||||
}
|
||||
|
||||
where := ""
|
||||
if searchCondition != "" {
|
||||
where = " WHERE " + searchCondition
|
||||
}
|
||||
|
||||
order := ""
|
||||
if orderBy != "" {
|
||||
order = " ORDER BY " + orderBy
|
||||
}
|
||||
|
||||
sql := fmt.Sprintf(
|
||||
"SELECT %s FROM %s%s%s",
|
||||
selectCols,
|
||||
viewName,
|
||||
where,
|
||||
order,
|
||||
)
|
||||
|
||||
logger.FromCtx(ctx).Info("LoadData",
|
||||
zap.String("sql", sql),
|
||||
zap.Any("args", args),
|
||||
)
|
||||
|
||||
return c.query(ctx, sql, args...)
|
||||
}
|
||||
|
||||
func (c *Client) LoadDataBySQL(
|
||||
ctx context.Context,
|
||||
sql string,
|
||||
args []any,
|
||||
) ([]map[string]any, error) {
|
||||
|
||||
logger.FromCtx(ctx).Info("LoadDataBySQL",
|
||||
zap.String("sql", sql),
|
||||
zap.Any("args", args),
|
||||
)
|
||||
|
||||
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.pool.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 := range fields {
|
||||
if i < len(values) {
|
||||
row[string(fields[i].Name)] = values[i]
|
||||
}
|
||||
}
|
||||
|
||||
result = append(result, row)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func convertPlaceholder(sql string) string {
|
||||
var sb strings.Builder
|
||||
sb.Grow(len(sql))
|
||||
|
||||
argIndex := 1
|
||||
|
||||
for i := 0; i < len(sql); i++ {
|
||||
if sql[i] == '?' {
|
||||
sb.WriteByte('$')
|
||||
sb.WriteString(strconv.Itoa(argIndex))
|
||||
argIndex++
|
||||
} else {
|
||||
sb.WriteByte(sql[i])
|
||||
}
|
||||
}
|
||||
|
||||
return sb.String()
|
||||
}
|
||||
Reference in new issue
Block a user