FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

feat(utils): add SQL query validator utility by ROSPL07 · Pull Request #621 · sql-js/sql.js · GitHub

/ sql.js Public
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .js  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
31 changes: 31 additions & 0 deletions src/validateQuery.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Utility function to validate SQL queries before execution
// Helps prevent accidental destructive queries like DROP or DELETE.

function validateQuery(sqlQuery) {
if (typeof sqlQuery !== "string") {
throw new Error("Query must be a string.");
}

const dangerousCommands = ["DROP", "DELETE", "ALTER", "TRUNCATE"];
const upperQuery = sqlQuery.toUpperCase();

for (const cmd of dangerousCommands) {
if (upperQuery.includes(cmd)) {
return {
isSafe: false,
reason: `Query contains dangerous command: ${cmd}`,
};
}
}

return {
isSafe: true,
reason: "Query passed validation.",
};
}

module.exports = validateQuery;

// Example usage (for testing):
// const { isSafe, reason } = validateQuery("SELECT * FROM users;");
// console.log(isSafe, reason);
11 changes: 11 additions & 0 deletions test/validateQuery.test.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const validateQuery = require("../src/utils/validateQuery");

test("returns safe for harmless queries", () => {
const { isSafe } = validateQuery("SELECT * FROM users;");
expect(isSafe).toBe(true);
});

test("detects dangerous query (DROP)", () => {
const result = validateQuery("DROP TABLE users;");
expect(result.isSafe).toBe(false);
});

Back | FazBrowse Home | New Git URL