Files
docs/build/snippets/python/code-samples/sql-agent-sanitize-sql-js.mdx
T
2026-07-29 10:28:19 +00:00

31 lines
930 B
Plaintext

```ts
const DENY_RE =
/\b(INSERT|UPDATE|DELETE|ALTER|DROP|CREATE|REPLACE|TRUNCATE)\b/i;
const HAS_LIMIT_TAIL_RE = /\blimit\b\s+\d+(\s*,\s*\d+)?\s*;?\s*$/i;
function sanitizeSqlQuery(q) {
let query = String(q ?? "").trim();
// block multiple statements (allow one optional trailing ;)
const semis = [...query].filter((c) => c === ";").length;
if (semis > 1 || (query.endsWith(";") && query.slice(0, -1).includes(";"))) {
throw new Error("multiple statements are not allowed.");
}
query = query.replace(/;+\s*$/g, "").trim();
// read-only gate
if (!query.toLowerCase().startsWith("select")) {
throw new Error("Only SELECT statements are allowed");
}
if (DENY_RE.test(query)) {
throw new Error("DML/DDL detected. Only read-only queries are permitted.");
}
// append LIMIT only if not already present
if (!HAS_LIMIT_TAIL_RE.test(query)) {
query += " LIMIT 5";
}
return query;
}
```