-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathescapeSQL.ts
More file actions
43 lines (40 loc) · 1.36 KB
/
Copy pathescapeSQL.ts
File metadata and controls
43 lines (40 loc) · 1.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* SQL Escape Utilities
* Provides functions to safely escape user input for SQL queries
*/
/**
* Escape special characters in LIKE patterns
*
* Escapes % and _ characters that have special meaning in SQL LIKE clauses.
* This prevents user input from being interpreted as wildcards.
*
* @param input - User input to escape
* @returns Escaped string safe for LIKE patterns
*
* @example
* escapeLikePattern('test%') // Returns: 'test\\%'
* escapeLikePattern('a_b%c') // Returns: 'a\\_b\\%c'
* escapeLikePattern('Starbucks') // Returns: 'Starbucks'
* escapeLikePattern('Café WiFi') // Returns: 'Café WiFi'
* escapeLikePattern('') // Returns: ''
* escapeLikePattern(null) // Returns: ''
*
* @example
* // Usage in LIKE query
* const userInput = 'test%';
* const escaped = escapeLikePattern(userInput);
* const pattern = `%${escaped}%`;
* // Query: WHERE ssid ILIKE $1 with parameter: '%test\\%%'
*/
function escapeLikePattern(input: unknown): string {
// Handle null, undefined, or non-string input
if (input === null || typeof input !== 'string') {
return '';
}
// Escape backslash first (to avoid double-escaping), then % and _
return input
.replace(/\\/g, '\\\\') // Backslash → \\
.replace(/%/g, '\\%') // Percent → \%
.replace(/_/g, '\\_'); // Underscore → \_
}
export { escapeLikePattern };