57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
package build
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"git.secnex.io/secnex/pgson/schema"
|
|
"git.secnex.io/secnex/pgson/utils"
|
|
)
|
|
|
|
func UpdateSQL(s *schema.Table, data map[string]any, where string) (string, error) {
|
|
if s == nil {
|
|
return "", fmt.Errorf("nil table provided")
|
|
}
|
|
if s.Name == "" || !utils.IsValidIdentifier(s.Name) {
|
|
return "", fmt.Errorf("invalid table name: %q", s.Name)
|
|
}
|
|
if s.PrimaryKey == "" || !utils.IsValidIdentifier(s.PrimaryKey) {
|
|
return "", fmt.Errorf("invalid primary key: %q", s.PrimaryKey)
|
|
}
|
|
|
|
fieldMap := make(map[string]*schema.Field)
|
|
for i := range s.Schema {
|
|
fieldMap[s.Schema[i].Name] = &s.Schema[i]
|
|
}
|
|
|
|
setClause := make([]string, 0, len(data))
|
|
for field, value := range data {
|
|
if !utils.IsValidIdentifier(field) {
|
|
return "", fmt.Errorf("invalid field name: %q", field)
|
|
}
|
|
|
|
if schemaField, exists := fieldMap[field]; exists && schemaField.Type == "hash" && schemaField.Algorithm != nil {
|
|
valueStr := fmt.Sprintf("%v", value)
|
|
hashed, err := utils.Hash(valueStr, *schemaField.Algorithm)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
value = hashed
|
|
}
|
|
|
|
setClause = append(setClause, fmt.Sprintf("%s = %s", utils.SQLQuoteIdent(field), utils.SQLQuoteValue(value)))
|
|
}
|
|
|
|
setClause = append(setClause, "updated_at = CURRENT_TIMESTAMP")
|
|
|
|
query := fmt.Sprintf(
|
|
"UPDATE %s SET %s WHERE %s = %s",
|
|
utils.SQLQuoteIdent(s.Name),
|
|
strings.Join(setClause, ", "),
|
|
utils.SQLQuoteIdent(s.PrimaryKey),
|
|
utils.SQLQuoteValue(where),
|
|
)
|
|
|
|
return query, nil
|
|
}
|