extractWhereClause extracts the WHERE clause from a SQL query string
(query string)
| 170 | |
| 171 | // extractWhereClause extracts the WHERE clause from a SQL query string |
| 172 | func extractWhereClause(query string) string { |
| 173 | // Find WHERE and get everything after it |
| 174 | wherePattern := regexp.MustCompile(`(?is)WHERE\s+(.*)`) |
| 175 | whereMatches := wherePattern.FindStringSubmatch(query) |
| 176 | if len(whereMatches) < 2 { |
| 177 | return "" |
| 178 | } |
| 179 | |
| 180 | whereClause := whereMatches[1] |
| 181 | |
| 182 | // Remove ORDER BY, LIMIT, OFFSET clauses from the end |
| 183 | whereClause = regexp.MustCompile(`(?is)\s+(ORDER BY|LIMIT|OFFSET).*$`).ReplaceAllString(whereClause, "") |
| 184 | |
| 185 | // Remove SQL comments |
| 186 | whereClause = regexp.MustCompile(`(?m)--.*$`).ReplaceAllString(whereClause, "") |
| 187 | |
| 188 | // Normalize indentation so subquery wrapping doesn't cause |
| 189 | // mismatches. |
| 190 | lines := strings.Split(whereClause, "\n") |
| 191 | for i, line := range lines { |
| 192 | lines[i] = strings.TrimLeft(line, " \t") |
| 193 | } |
| 194 | whereClause = strings.Join(lines, "\n") |
| 195 | |
| 196 | return strings.TrimSpace(whereClause) |
| 197 | } |
no test coverage detected