mirror of
https://github.com/langchain-ai/docs.git
synced 2026-08-27 02:41:59 -04:00
31 lines
930 B
Plaintext
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;
|
|
}
|
|
```
|