QWED

Type to search pages, engines and advisories.

    Looking for API details?Search the docs

    Engines

    Is LLM-generated SQL safe to run? How to check it first

    A model that turns a question into SQL (text-to-SQL) will sometimes write a query that deletes rows, carries an injection pattern, reads a column it should not or calls a function that reaches outside the database. QWED parses the query with SQLGlot before it runs and returns a decision: only a query with no finding that denies is admitted. Your application then runs it or holds it.

    QWED project · Published · Updated

    The short answer

    Not without a check. A guardrail for LLM-generated SQL should parse the query before it runs and admit only a read of the tables you declared, not ask another model whether it looks safe. QWED does this as open-source code (Apache-2.0) that runs in your process or on your own server: its SQLVerifier parses the query with SQLGlot, refuses writes, injection patterns, protected columns and calls that reach outside the database, checks every table and column against your schema, and admits the query only when nothing denies it.

    What can go wrong with LLM-generated SQL?

    Text-to-SQL is useful because a person can ask a question in plain words. The risk is that the model is as confident about a harmful query as about a correct one. The mistakes that matter most are structural, which is why a parser can catch them:

    • It changes data. A question about orders comes back as an UPDATE or a DELETE.
    • It carries an injection pattern. A WHERE clause ends with OR 1 = 1, or a second statement follows a semicolon.
    • It reads what it should not. A join pulls in a password, salary or card column.
    • It reaches outside the database. A function such as pg_read_file reads a file, or what looks like a table is a URL.
    • It runs away. Ten joins and nested subqueries on a production database.

    What does QWED check in a query?

    The SQL engine is part of QWED's open-source core. It parses the query into a syntax tree with SQLGlot and inspects the tree. It never connects to your database. A finding that denies stops the query from being admitted; a finding that warns is reported and the query can still be admitted.

    What triggers itEffectFinding
    Changes and admin
    DELETE, UPDATE, INSERT, DROP, ALTER, TRUNCATE, CREATE, MERGE and SELECT ... INTO, anywhere in the query, including inside a CTE or subqueryDeniesdestructive_command
    GRANT, REVOKE, SET, USE, transactions, COPY, ATTACH, DETACH, PRAGMA, LOAD DATA, VACUUM, EXPORT, CALL, EXECUTE and statements SQLGlot does not model, such as SHOW and EXPLAIN, anywhere in the queryDeniesadmin_command
    Any other statement that is not a read-only query (SELECT, UNION, INTERSECT, EXCEPT, WITH)Deniesnon_read_only_statement
    Reaching outside the database
    A function that reads or writes files, loads code or reaches the OS or another server, such as pg_read_file or read_csv; a file, URL or stage named as a table; and Spark and Hive ${...} substitutionDeniesdangerous_function
    A function, operator or type not known to stay inside the database: a function SQLGlot does not know and QWED has not listed as computing only from its arguments, an @@ server value, a cast to a type that is not built in, and in PostgreSQL an operator that is not built in, such as pgvector’s <=>Deniesunknown_function
    Injection patterns
    A comparison or filter that is always true, such as 1 = 1, 1 IN (1), 'a' LIKE 'a' or WHERE 1Deniesinjection_tautology
    OR with a side that is always true, such as OR TRUE, OR 1 or OR NOT FALSEDeniesinjection_or_true
    An OR whose sides do not each restrict a column to values: a range on each side, <>, NOT IN, a wildcard LIKE, IS NOT NULL, a subquery, or an optional-parameter idiom such as id = $1 OR $1 IS NULLDeniesunrestricted_or_operand
    A second statement after a semicolonDeniesstacked_queries
    Text that SQLGlot and the database could split into tokens differently: a backslash, -- with no space after it, a nested /*, a lone carriage return, and in MySQL, Spark, Databricks and Hive a string in double quotes. Named in the result’s constraint_id.Deniessql_verifier.ambiguous_tokenization
    UNIONWarnsunion_query
    A comment that starts with two hyphens and a spaceWarnscomment_detected
    Protected columns
    Reading a blocked column, by default password, secret, api_key, token, ssn, salary, credit_card, bank_account, balance, private_key and similarDeniessensitive_column_access
    SELECT * or t.* over a table whose declared schema has a blocked column (needs a schema)Deniessensitive_column_access
    A whole-row read of such a table, such as row_to_json(u) or SELECT uDeniessensitive_column_access
    Schema, when you pass one
    A table that is not in the schema. Names are compared part by part, so public.users is not the declared usersDeniesschema_table_missing
    A column, in any clause, that is not a column of a table in scopeDeniesschema_column_missing
    A query with PIVOT or UNPIVOT, whose columns cannot be checkedDeniesschema_column_missing
    Size
    More than 10 tables, 5 joins, 3 levels of subquery or an estimated cost over 1,000Deniescomplexity_*
    More than 50 columns or 20 conditionsWarnscomplexity_*

    MySQL and MariaDB executable comments (/*! ... */) are expanded before the checks run, so a pattern hidden inside one is still seen.

    What does the check return?

    Every check returns a result and a decision, as on the rest of the platform. For SQL there are three outcomes:

    • Proven correct. VERIFIED · ADMIT

      A query that parses and has no finding that denies, for example a plain SELECT of declared columns. A warning, such as a UNION, does not stop it.

    • Proven wrong. VERIFIED · DENY

      A data change or admin statement, an always-true filter, a stacked statement, a protected column, or a call that reaches outside the database. The result lists each finding as evidence.

    • Cannot be checked. BLOCKED · DENY

      The query or the schema does not parse, a table or column is not in the schema, an OR does not restrict a column to values, a function, operator or type is not known to stay inside the database, the text could be split into tokens two ways, or the query is over the size limits.

    When a query has findings of both kinds, the proof that it is unsafe decides: it comes back VERIFIED · DENY. A verified result carries a proof_ref: a SHA-256 commitment to the parsed query, the decision and the settings it was checked with, so a later reader can tell exactly what was checked. It is a record, not a proof that the query answers the question.

    Try it

    In Python, with the core package (pip install qwed). This is the example from the README, with the output of a run on qwed 13.0.0:

    python
    from qwed_new.core.sql_verifier import SQLVerifierfrom qwed_new.core.diagnostics import admission_decisionresult = SQLVerifier().verify_sql(    "DELETE FROM users WHERE id = 1 OR 1 = 1",    schema_ddl="CREATE TABLE users (id INT)",)print(result.status.value, admission_decision(result).value)# VERIFIED BLOCKED# (status VERIFIED, admission BLOCKED: the API's spelling of DENY)print(sorted({issue["type"] for issue in result.developer_fields["issues"]}))# ['destructive_command', 'injection_or_true', 'injection_tautology', 'unrestricted_or_operand']

    BLOCKED in the second value is the admission decision; in a Verification Context record the same decision is written DENY.

    Over the self-hosted API, send the query with the schema it should run against. The API requires schema_ddl and accepts a dialect (SQLite when you leave it out):

    request
    POST /verify/sql{  "query": "SELECT id, name FROM users WHERE id = 42",  "schema_ddl": "CREATE TABLE users (id INT, name TEXT)",  "dialect": "postgres"}

    Where does the check sit?

    1. The model writes a query from the user's question.
    2. Your application sends the query and your schema to QWED.
    3. On VERIFIED · ADMIT, your application runs the query, ideally with a database role that can only read.
    4. On anything else, your application does not run it: it shows the findings, asks the model to try again, or holds it for a person.

    QWED returns the decision; your application enforces it. Keep the database's own permissions in place as well: QWED checks the query's shape, not what the connection is allowed to do.

    The same package has SQLGuard, a quicker pre-filter for one statement, for example in an agent's tool. It refuses more than one statement, any write (unless you allow writes) or admin statement, and calls that reach outside the database, with the same lists as SQLVerifier. It does not check the schema, and its pass is not an admission: send a query that must be admitted to SQLVerifier or /verify/sql.

    Which settings does it take?

    In the library, SQLVerifier takes:

    • blocked_columns: more column names to deny. They are added to the defaults; the defaults cannot be removed.
    • complexity_limits: your own limits for tables, joins, subquery depth, columns, conditions and cost. check_complexity=False skips them.
    • allow_destructive=True: admits data changes inside the database for jobs that need them: INSERT, UPDATE, DELETE, MERGE, TRUNCATE, SELECT ... INTO, and CREATE, DROP or ALTER of a table, view, index, sequence or schema. Everything else is still denied, such as GRANT, INSTALL, KILL, EXEC or CREATE FUNCTION, and so is a table stored outside the database. Tables and columns are still checked against the schema.
    • dialect: passed to SQLGlot, for example postgres (the library's default), mysql or sqlite. Some checks depend on it, such as the operators PostgreSQL builds in and the strings MySQL reads in double quotes.

    The API uses the defaults; only the dialect can be set per request.

    What does it not check?

    • Whether it is the right query. A valid SELECT that answers a different question is still admitted. QWED does not check intent.
    • How your database resolves a name. QWED compares table names part by part, as the dialect folds them, but it does not know your search path. Declare each table under the name your queries use: with users declared, public.users is refused.
    • Anything inside the database. No connection is made, so row counts, permissions, row-level policies and the data itself are out of scope. Whether some functions do harm depends on how a database is set up, so a function QWED does not know is refused rather than guessed at.
    • Tables, columns and stars, when no schema is given. In the library, the schema is optional; without it, table and column names are not checked and SELECT * cannot be expanded, so a star over a table with a blocked column is not caught. The API always requires a schema.
    • Warnings. UNION and -- comments followed by a space are reported but do not deny on their own.
    • A different SQLGlot. The checks are written for SQLGlot 28.0.0 and later, and a SQLGlot release can read the same text differently. The server image pins one version.

    Results are only as sound as SQLGlot and QWED's own rules. Everything QWED does not verify

    Track record

    Problems in this engine are published, not hidden. Each of these was a false accept: a query the engine admitted when it should have been denied. Each is fixed, and tests cover it.

    • GHSA-jm6g-2j2p-cprr, fixed in qwed 13.0.0. The schema check compared only the last part of a table name, skipped any table named like a CTE defined anywhere in the query, and did not check columns, so hr.users passed as the declared users. Names are now compared part by part, a CTE name counts only where it is in scope, and every column in every clause is checked.
    • GHSA-4527-8wjv-h94g, fixed in qwed 13.0.0. With allow_destructive=True, only a list of administrative statement types was refused, so INSTALL httpfs FROM a URL (DuckDB), KILL (MySQL) and EXEC sp_executesql (T-SQL) were admitted. In that mode only data changes inside the database are admitted now.
    • GHSA-wgcp-398q-m296, fixed in qwed 11.0.0. A SELECT that read files, URLs or programs through a function the dangerous-function list did not name was admitted. Now only reads of tables and functions known to compute from their arguments are admitted.
    • GHSA-xpfc-qm4c-xf6q, fixed in qwed 11.0.0. Column tautologies in an OR, such as name LIKE '%', whole-row reads of a table with a protected column, such as row_to_json(u), and a MySQL --x, which MySQL does not read as a comment, were admitted. Each is now refused.
    • GHSA-6m2h-98rq-4f53, fixed in qwed 11.0.0. SELECT ... INTO, which creates a table and writes rows into it, was admitted as a read-only query. It is now a destructive command, as CREATE TABLE ... AS SELECT is.
    • GHSA-jvhg-jw63-gr5g, fixed in qwed 9.0.0. Always-true filters built with IN, IS, LIKE, BETWEEN, division, concatenation, CAST, COALESCE or a function call, such as OR 1 IN (1), were admitted: the fix for GHSA-6cpx-8jrq-r7h3 had folded only comparisons and arithmetic. They are now refused too.
    • GHSA-6p94-4f75-g2wq, fixed in qwed 7.3.0. A data change hidden in a CTE (WITH d AS (DELETE FROM t RETURNING *) SELECT * FROM d) was admitted because only the outermost statement was classified, and statement families such as COPY, ATTACH and PRAGMA were in no deny list. The whole query is now checked, and only read-only statements are admitted.
    • GHSA-6cpx-8jrq-r7h3, fixed in qwed 7.3.0. SELECT * FROM users was admitted even when the schema declared a password column, and always-true filters such as OR 1 or 1 = 1.0 slipped past a check that matched fixed shapes. Stars are now expanded against the schema, and filters are tested by value.
    • GHSA-q5g6-6cw2-cjm3, fixed in qwed 7.2.3. A pattern inside a MySQL executable comment (WHERE id = 1 /*!50000 OR 1=1 */) was admitted, and a table outside the declared schema produced only a warning. Both now deny.

    SQLGuard has its own: GHSA-45jv-2j44-4c2q, fixed in qwed 8.0.0. It parsed only the first statement and checked it against a short list, so stacked statements, COPY ... TO PROGRAM, ATTACH and load_extension were reported as verified. It now uses SQLVerifier's lists and is a pre-filter only.

    These checks are a screening step, not a replacement for a database role that can only read. The full track record

    Other parts of QWED look at SQL from different sides: QWED Security flags SQL built by string concatenation in your code, and Open Responses can block destructive statements in an agent's tool-call arguments.

    Sources and further reading

    Written and reviewed by the QWED maintainers under the project's governance model. Found an error? Contact us.