perf(utils): compile SQL-validation regexps once instead of per call
checkSQLInjectionRisks and InjectAndConditions compiled their regexps with regexp.MustCompile on every invocation. Both run on the datasource SQL path — InjectAndConditions is called once per security filter (tenant, soft-delete, hidden-KB, search-scope), so a single secured query recompiled ~20 patterns. InjectAndConditions also compiled the identical tail-clause pattern twice. Hoist them to package-level vars (compiled once at init). Behavior is unchanged — same patterns, covered by the existing TestValidateSQL_* and TestInjectAndConditions tests. Benchmarks (apple M, -benchmem): InjectAndConditions 4347 ns, 72 allocs -> 1023 ns, 7 allocs checkSQLInjectionRisks 36074 ns, 560 allocs -> 12984 ns, 12 allocs Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -448,3 +448,17 @@ func TestInjectAndConditions(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkInjectAndConditions(b *testing.B) {
|
||||
const sql = "SELECT id, title FROM docs WHERE status = 'active' ORDER BY created_at LIMIT 50"
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = InjectAndConditions(sql, "tenant_id = 1")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCheckSQLInjectionRisks(b *testing.B) {
|
||||
const where = "status = 'active' AND name LIKE '%foo%' AND (deleted_at IS NULL OR archived = false)"
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = checkSQLInjectionRisks(where)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user