feat(sql): Add new DML (DELETE, UPDATE)

This commit is contained in:
Björn Benouarets
2025-11-06 17:10:24 +01:00
parent 4ed1cd3b88
commit ad2eaa6ebb
8 changed files with 196 additions and 19 deletions

View File

@@ -3,6 +3,7 @@ package sql
import (
"fmt"
"regexp"
"sort"
"strings"
"git.secnex.io/secnex/pgson/schema"
@@ -118,3 +119,68 @@ func ValidateComment(comment *string) error {
func QuoteIdent(name string) string {
return `"` + strings.ReplaceAll(name, `"`, `""`) + `"`
}
// QuoteLiteral escapes a string literal for use in SQL queries
// It doubles single quotes to prevent SQL injection
func QuoteLiteral(s string) string {
return "'" + strings.ReplaceAll(s, "'", "''") + "'"
}
// QuoteValue formats a value according to its type for use in SQL queries
// It handles strings, numbers, booleans, null, and UUIDs safely
func QuoteValue(v any) string {
if v == nil {
return "NULL"
}
switch val := v.(type) {
case string:
// Check if it's a valid UUID format
if matched, _ := regexp.MatchString(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`, strings.ToLower(val)); matched {
return QuoteLiteral(val)
}
return QuoteLiteral(val)
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
return fmt.Sprintf("%v", val)
case float32, float64:
return fmt.Sprintf("%v", val)
case bool:
if val {
return "TRUE"
}
return "FALSE"
default:
// For unknown types, convert to string and escape
return QuoteLiteral(fmt.Sprintf("%v", val))
}
}
// BuildWhereClause safely builds a WHERE clause from conditions
// conditions is a map of column names to values (uses = operator)
// Returns empty string if no conditions provided
func BuildWhereClause(conditions map[string]any) (string, error) {
if len(conditions) == 0 {
return "", nil
}
var clauses []string
keys := make([]string, 0, len(conditions))
for k := range conditions {
keys = append(keys, k)
}
sort.Strings(keys)
for _, col := range keys {
if err := ValidateIdent(col); err != nil {
return "", fmt.Errorf("invalid column identifier in WHERE clause: %s", col)
}
value := conditions[col]
if value == nil {
clauses = append(clauses, fmt.Sprintf("%s IS NULL", QuoteIdent(col)))
} else {
clauses = append(clauses, fmt.Sprintf("%s = %s", QuoteIdent(col), QuoteValue(value)))
}
}
return " WHERE " + strings.Join(clauses, " AND "), nil
}