feat(sql): Add new DML (DELETE, UPDATE)
This commit is contained in:
@@ -2,4 +2,6 @@ package sql
|
||||
|
||||
var (
|
||||
DML_INSERT_INTO = "INSERT INTO %s (%s) VALUES (%s);"
|
||||
DML_UPDATE = "UPDATE %s SET %s%s;"
|
||||
DML_DELETE = "DELETE FROM %s%s;"
|
||||
)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user