Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: add checks for code outside sql statement (#3742)

Shahmir Varqhadc431704dbe8
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index 82562282f3..14010988d7 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -358,6 +358,31 @@ _df = mo.sql(
expect(adapter.isSupported(pythonCode)).toBe(false);
});
+ it("should return false when there are multiple sql strings", () => {
+ const pythonCode = `
+ _df = mo.sql("""SELECT * FROM table1""")
+ _df2 = mo.sql("""SELECT * FROM table2""")
+ `;
+ expect(adapter.isSupported(pythonCode)).toBe(false);
+ });
+
+ it("should return false when there are non sql strings with sql string", () => {
+ const pythonCode = `print("Hello, World!") \n_df = mo.sql("SELECT * FROM table")`;
+ expect(adapter.isSupported(pythonCode)).toBe(false);
+
+ const pythonCode2 = `_df = mo.sql("""SELECT * FROM table""") \n print("Hello, World!")`;
+ expect(adapter.isSupported(pythonCode2)).toBe(false);
+ });
+
+ it("should return true for sql strings with whitespace before or after", () => {
+ expect(
+ adapter.isSupported(' df = mo.sql("""SELECT * FROM table""")'),
+ ).toBe(true);
+ expect(
+ adapter.isSupported('df = mo.sql("""SELECT * FROM table""") '),
+ ).toBe(true);
+ });
+
it("should support SQL strings with output flag", () => {
expect(
adapter.isSupported(
diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.ts
index 469fc20d79..857d1028cb 100644
--- a/frontend/src/core/codemirror/language/sql.ts
+++ b/frontend/src/core/codemirror/language/sql.ts
@@ -227,6 +227,13 @@ export function parseSQLStatement(code: string): SQLConfig | null {
return null;
}
+ // Code outside of the assignment statement is not allowed
+ const outsideCode =
+ code.slice(0, assignStmt.from) + code.slice(assignStmt.to);
+ if (outsideCode.trim().length > 0) {
+ return null;
+ }
+
let dfName: string | null = null;
let sqlString: string | null = null;
let engine: string | undefined;