55// Parser failures are never reads; lexical checks retain hard-deny protection.
66
77import { hasMongoWriteStage , normalizeMqlCommand } from "@altimateai/drivers"
8- import { maskSql , statementsOf , tokenizeSql } from "./sql-tokenize"
8+ import { isModeledDialect , maskSql , statementsOf , tokenizeSql } from "./sql-tokenize"
99import { sqlFunctionCalls , sqlLiteral } from "./sql-functions"
1010import { hasSideEffectFunction , isReadOnlyNestedFunction } from "./sql-function-policy"
1111
@@ -190,13 +190,54 @@ function classifyFallback(sql: string, dialect?: string): { queryType: "read" |
190190 // When quoting or comments cannot be read with certainty, no reading of the literals or comments
191191 // can be trusted to hide a hard deny (a misread literal can make a real statement look like a
192192 // comment), so the words alone decide; the TRUNCATE() function does not count.
193- if ( ! tokenizeSql ( sql , dialect ) . complete && mentionsHardDeny ( sql ) ) blocked = true
193+ const lexical = tokenizeSql ( sql , dialect )
194+ if ( ! lexical . complete ) {
195+ if ( mentionsHardDeny ( sql ) ) blocked = true
196+ } else {
197+ // Read with certainty: the statement words in code (literals, identifiers and comments masked,
198+ // so DROP/**/SCHEMA reads as DROP SCHEMA) decide too, since T-SQL runs `SELECT 1 DROP DATABASE x`
199+ // as two statements with no ; and a parser may read a literal differently from the engine.
200+ const masked = maskSql ( lexical . tokens )
201+ if ( CODE_HARD_DENY . test ( masked ) ) blocked = true
202+ // Dynamic SQL (EXEC('...'), EXECUTE IMMEDIATE, PREPARE ... FROM, DO $$...$$) runs a string, so
203+ // the words in its literals count too. A statement built by concatenation is not seen.
204+ else if ( DYNAMIC_SQL . test ( masked ) && mentionsHardDeny ( sql ) ) blocked = true
205+ }
194206 return { queryType : "write" , blocked }
195207}
196208
197- /** The word DROP with DATABASE or SCHEMA anywhere after it, or TRUNCATE not followed by `(`. Only
198- * words count: quotes and comments are ignored, since how they read is what is uncertain, so no
199- * comment or quote placement can separate the words. One forward pass. */
209+ /** Where statements need no separator (T-SQL) or the dialect is not one the lexer models, a read
210+ * must hold no statement keyword in its code (literals, identifiers and comments masked): the
211+ * engine would run `SELECT ... DELETE FROM t` as two statements however a parser reads it. */
212+ function batchedStatement ( masked : string , dialect ?: string ) : boolean {
213+ return ( / ^ ( s q l s e r v e r | t s q l | m s s q l | f a b r i c ) $ / i. test ( dialect ?? "" ) || ! isModeledDialect ( dialect ) ) && BATCH_STATEMENT . test ( masked )
214+ }
215+
216+ // T-SQL statements that can follow a read in the same batch. Words that are also common column names
217+ // or clauses (USE, FETCH, OPEN, CLOSE, ENABLE, DISABLE, RENAME, THROW, ADD, MOVE, SEND, RECEIVE, END)
218+ // count only in their statement forms.
219+ const BATCH_STATEMENT = new RegExp (
220+ "\\b(INSERT|UPDATE|DELETE|MERGE|DROP|ALTER|CREATE|TRUNCATE|EXEC|EXECUTE|GRANT|REVOKE|DENY|BACKUP|RESTORE|DBCC|KILL|SHUTDOWN|BULK|WAITFOR|DECLARE|SET|INTO|" +
221+ "OPENROWSET|OPENQUERY|OPENDATASOURCE|OPENXML|CHECKPOINT|RECONFIGURE|RAISERROR|GOTO|BEGIN|COMMIT|ROLLBACK|SAVE|DEALLOCATE|" +
222+ "READTEXT|UPDATETEXT|WRITETEXT|SETUSER|REVERT|PRINT)\\b" +
223+ "|\\b(ENABLE|DISABLE)\\s+TRIGGER\\b|\\bRENAME\\s+(OBJECT|DATABASE)\\b|\\bTHROW\\s*($|;|[\\d@])" +
224+ // USE except OPTION (USE HINT/PLAN) and USE INDEX; FETCH except OFFSET paging (FETCH NEXT 10 ROWS ONLY).
225+ "|\\bUSE\\b(?!\\s+(HINT|PLAN|INDEX|KEY)\\b)|\\bFETCH\\b(?!\\s+(FIRST|NEXT)\\s+([\\w@().+-]+\\s+)?(PERCENT\\s+)?ROWS?\\b)" +
226+ "|\\b(OPEN|CLOSE)\\s+(GLOBAL\\s+)?[\\w@#]+\\s*(;|\\b(SELECT|WITH)\\b)|\\bADD\\s+(SENSITIVITY|SIGNATURE|COUNTER)\\b" +
227+ "|\\bMOVE\\s+CONVERSATION\\b|\\bSEND\\s+ON\\b|\\bRECEIVE\\s+(TOP\\b|\\*|\\w+\\s+FROM\\b)|\\bEND\\s+CONVERSATION\\b" ,
228+ "i" ,
229+ )
230+
231+ const CODE_HARD_DENY = / \b D R O P \s + ( D A T A B A S E | S C H E M A ) \b | \b T R U N C A T E \b (? ! \s * \( ) / i
232+ const DYNAMIC_SQL = / \b E X E C ( U T E ) ? \b | ( ^ | ; ) \s * ( P R E P A R E | D O ) \b / i
233+ // Sequence advances outside PostgreSQL's nextval(): NEXT VALUE FOR s (SQL Server, DB2), s.NEXTVAL
234+ // (Oracle, Snowflake).
235+ const SEQUENCE_ADVANCE = / \b N E X T \s + V A L U E \s + F O R \b | \. \s * N E X T V A L \b / i
236+
237+ /** The word DROP with DATABASE or SCHEMA anywhere after it, or TRUNCATE not directly followed by `(`
238+ * (the TRUNCATE() function; a comment before the `(` does not count, since where a comment ends is
239+ * part of what is uncertain). Only words count: quotes and comments are ignored, since how they read
240+ * is what is uncertain, so no comment or quote placement can separate the words. One forward pass. */
200241function mentionsHardDeny ( sql : string ) : boolean {
201242 let drop = false
202243 let i = 0
@@ -210,18 +251,7 @@ function mentionsHardDeny(sql: string): boolean {
210251 const word = sql . slice ( i , j ) . toUpperCase ( )
211252 if ( word === "DROP" ) drop = true
212253 else if ( drop && ( word === "DATABASE" || word === "SCHEMA" ) ) return true
213- else if ( word === "TRUNCATE" ) {
214- // The TRUNCATE() function: "(" next, past whitespace and closed block comments.
215- let k = j
216- for ( ; ; ) {
217- while ( k < sql . length && / \s / . test ( sql [ k ] ) ) k ++
218- if ( ! sql . startsWith ( "/*" , k ) ) break
219- const end = sql . indexOf ( "*/" , k + 2 )
220- if ( end < 0 ) break
221- k = end + 2
222- }
223- if ( sql [ k ] !== "(" ) return true
224- }
254+ else if ( word === "TRUNCATE" && ! / ^ [ \t \r \n ] * \( / . test ( sql . slice ( j , j + 64 ) ) ) return true
225255 i = j
226256 }
227257 return false
@@ -295,7 +325,7 @@ function functionSafety(sql: string, dialect: string | undefined, depth: number,
295325 Object . hasOwn ( SQL_ARGUMENTS , call . name ) && call . qualifier === undefined && ! hasSideEffectFunction ( call . name )
296326 if ( depth > 0 && ! nestedExecutor && ! isReadOnlyNestedFunction ( call . name , call . qualifier ) ) write = true
297327 // SQL Server's XML .query() takes XQuery, not executable SQL.
298- if ( call . name === "query" && / ^ ( s q l s e r v e r | t s q l | m s s q l ) $ / i. test ( dialect ?? "" ) ) continue
328+ if ( call . name === "query" && / ^ ( s q l s e r v e r | t s q l | m s s q l | f a b r i c ) $ / i. test ( dialect ?? "" ) ) continue
299329 const argument = Object . hasOwn ( SQL_ARGUMENTS , call . name ) ? SQL_ARGUMENTS [ call . name ] : undefined
300330 if ( ! argument ) continue
301331 const inner = sqlLiteral ( call . args [ argument . index ] , dialect )
@@ -328,7 +358,8 @@ function classifySql(sql: string, dialect: string | undefined, depth: number): {
328358 parseError ?: string
329359} {
330360 if ( ! sql || typeof sql !== "string" ) return { queryType : "read" , blocked : false }
331- if ( ! tokenizeSql ( sql , dialect ) . complete ) {
361+ const lexical = tokenizeSql ( sql , dialect )
362+ if ( ! lexical . complete ) {
332363 return { ...classifyFallback ( sql , dialect ) , parseError : "SQL contains unterminated or unsupported quoted text or comments" }
333364 }
334365 if ( ! getStatementTypes ) return { ...classifyFallback ( sql , dialect ) , parseError : "SQL parser is unavailable" }
@@ -341,6 +372,7 @@ function classifySql(sql: string, dialect: string | undefined, depth: number): {
341372 // A generic parser can treat MySQL arithmetic (--2) as a comment and omit
342373 // trailing statements. Keep dialect-aware lexical hard denies authoritative.
343374 const functions = functionSafety ( sql , dialect , depth )
375+ const masked = maskSql ( lexical . tokens )
344376 const blocked =
345377 functions . blocked ||
346378 classifyFallback ( sql , dialect ) . blocked ||
@@ -349,7 +381,14 @@ function classifySql(sql: string, dialect: string | undefined, depth: number): {
349381 )
350382
351383 return {
352- queryType : ! functions . write && ! blocked && otherIsReadOnly ( sql , result . statements , dialect ) ? "read" : "write" ,
384+ queryType :
385+ ! functions . write &&
386+ ! blocked &&
387+ ! batchedStatement ( masked , dialect ) &&
388+ ! SEQUENCE_ADVANCE . test ( masked ) &&
389+ otherIsReadOnly ( sql , result . statements , dialect )
390+ ? "read"
391+ : "write" ,
353392 blocked,
354393 }
355394 } catch ( error ) {
0 commit comments