84 lines
1.3 KiB
Go
84 lines
1.3 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
func (c *Client) Delete(
|
|
ctx context.Context,
|
|
table string,
|
|
keyField string,
|
|
data map[string]any,
|
|
) error {
|
|
if keyField == "" {
|
|
return fmt.Errorf("keyField 不能为空")
|
|
}
|
|
|
|
keyVal, err := validateData(table, keyField, data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
sql := fmt.Sprintf(
|
|
"DELETE FROM %s WHERE %s = $1",
|
|
table,
|
|
keyField,
|
|
)
|
|
|
|
_, err = c.exec().Exec(ctx, sql, keyVal)
|
|
return err
|
|
}
|
|
|
|
func (c *Client) BatchDelete(
|
|
ctx context.Context,
|
|
table string,
|
|
keyField string,
|
|
dataList []map[string]any,
|
|
) error {
|
|
|
|
if table == "" {
|
|
return fmt.Errorf("表名不能为空")
|
|
}
|
|
|
|
if keyField == "" {
|
|
return fmt.Errorf("主键字段不能为空")
|
|
}
|
|
|
|
if len(dataList) == 0 {
|
|
return fmt.Errorf("数据不能为空")
|
|
}
|
|
|
|
var (
|
|
placeholders []string
|
|
args []any
|
|
argIndex = 1
|
|
)
|
|
|
|
for _, data := range dataList {
|
|
keyVal, err := validateData(table, keyField, data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if keyVal == nil {
|
|
return fmt.Errorf("主键字段值不能为空")
|
|
}
|
|
|
|
placeholders = append(placeholders, fmt.Sprintf("$%d", argIndex))
|
|
args = append(args, keyVal)
|
|
argIndex++
|
|
}
|
|
|
|
sql := fmt.Sprintf(
|
|
"DELETE FROM %s WHERE %s IN (%s)",
|
|
table,
|
|
keyField,
|
|
strings.Join(placeholders, ", "),
|
|
)
|
|
|
|
_, err := c.exec().Exec(ctx, sql, args...)
|
|
return err
|
|
}
|