escapeStringLiteral escapes a string for safe inclusion in a single-quoted SQL literal, handling characters that can lead to SQL injection.
(s string)
| 100 | // escapeStringLiteral escapes a string for safe inclusion in a single-quoted |
| 101 | // SQL literal, handling characters that can lead to SQL injection. |
| 102 | func escapeStringLiteral(s string) string { |
| 103 | var b strings.Builder |
| 104 | b.Grow(len(s)) |
| 105 | for _, r := range s { |
| 106 | switch r { |
| 107 | case '\'': |
| 108 | b.WriteString("''") |
| 109 | case '\\': |
| 110 | b.WriteString(`\\`) |
| 111 | case '\x00': |
| 112 | // Drop null bytes - invalid in SQL string literals. |
| 113 | case '\n': |
| 114 | b.WriteString(`\n`) |
| 115 | case '\r': |
| 116 | b.WriteString(`\r`) |
| 117 | case '\x1a': // Ctrl-Z (EOF on Windows) |
| 118 | b.WriteString(`\Z`) |
| 119 | default: |
| 120 | b.WriteRune(r) |
| 121 | } |
| 122 | } |
| 123 | return b.String() |
| 124 | } |
| 125 | |
| 126 | // SQL returns the SQL literal representation of this value. |
| 127 | // Strings are single-quoted with proper escaping; NULLs are returned as "NULL"; |