110 lines
2.0 KiB
Go
110 lines
2.0 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
)
|
|
|
|
func buildInsertSQL(table string, data map[string]any) (string, []any) {
|
|
var (
|
|
cols []string
|
|
vals []string
|
|
args []any
|
|
i = 1
|
|
)
|
|
|
|
for k, v := range data {
|
|
cols = append(cols, quoteCol(k))
|
|
vals = append(vals, fmt.Sprintf("$%d", i))
|
|
args = append(args, v)
|
|
i++
|
|
}
|
|
|
|
return fmt.Sprintf(
|
|
"INSERT INTO %s (%s) VALUES (%s)",
|
|
quoteTable(table),
|
|
strings.Join(cols, ", "),
|
|
strings.Join(vals, ", "),
|
|
), args
|
|
}
|
|
|
|
func (c *Client) Insert(ctx context.Context, table, keyField string, data map[string]any) error {
|
|
if _, err := validateInsertData(table, keyField, data); err != nil {
|
|
return err
|
|
}
|
|
|
|
ensureID(data, keyField)
|
|
|
|
data = applyMetaFields(ctx, table, data, true)
|
|
|
|
sql, args := buildInsertSQL(table, data)
|
|
|
|
_, err := c.pool.Exec(ctx, sql, args...)
|
|
return err
|
|
}
|
|
|
|
func (c *Client) BatchInsert(ctx context.Context, table, keyField string, list []map[string]any) error {
|
|
|
|
if len(list) == 0 {
|
|
return fmt.Errorf("empty data")
|
|
}
|
|
|
|
first := list[0]
|
|
if _, err := validateInsertData(table, keyField, first); err != nil {
|
|
return err
|
|
}
|
|
|
|
tableSQL := quoteTable(table)
|
|
|
|
// 固定字段顺序(稳定性关键)
|
|
var cols []string
|
|
for k := range first {
|
|
cols = append(cols, k)
|
|
}
|
|
sort.Strings(cols)
|
|
|
|
var (
|
|
args []any
|
|
values []string
|
|
argIndex = 1
|
|
)
|
|
|
|
for _, row := range list {
|
|
ensureID(row, keyField)
|
|
|
|
row = applyMetaFields(ctx, table, row, true)
|
|
|
|
var place []string
|
|
|
|
for _, col := range cols {
|
|
v, ok := row[col]
|
|
if !ok {
|
|
return fmt.Errorf("missing field: %s", col)
|
|
}
|
|
|
|
place = append(place, fmt.Sprintf("$%d", argIndex))
|
|
args = append(args, v)
|
|
argIndex++
|
|
}
|
|
|
|
values = append(values, fmt.Sprintf("(%s)", strings.Join(place, ",")))
|
|
}
|
|
|
|
var quotedCols []string
|
|
for _, col := range cols {
|
|
quotedCols = append(quotedCols, quoteCol(col))
|
|
}
|
|
|
|
sql := fmt.Sprintf(
|
|
"INSERT INTO %s (%s) VALUES %s",
|
|
tableSQL,
|
|
strings.Join(quotedCols, ", "),
|
|
strings.Join(values, ", "),
|
|
)
|
|
|
|
_, err := c.pool.Exec(ctx, sql, args...) // ⭐关键修复
|
|
return err
|
|
}
|