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.

improve: allow header comments in SQL cells. (#4090)

Akshay Agrawal430ade06141e
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index f92ab5a9bf..d22ee0f121 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -292,12 +292,31 @@ _df = mo.sql(
expect(offset).toBe(26);
});
+ it("should preserve Python comments", () => {
+ const pythonCode = '# hello\n_df = mo.sql("""SELECT * FROM {df}""")';
+ const [innerCode] = adapter.transformIn(pythonCode);
+ expect(innerCode).toBe("SELECT * FROM {df}");
+ adapter.lastQuotePrefix = "f";
+ adapter.dataframeName = "my_df";
+ const [wrappedCode, offset] = adapter.transformOut(innerCode);
+ expect(wrappedCode).toMatchInlineSnapshot(`
+ "# hello
+ my_df = mo.sql(
+ f"""
+ SELECT * FROM {df}
+ """
+ )"
+ `);
+ expect(offset).toBe(26);
+ });
+
it("should add engine connection when provided", () => {
const code = "SELECT * FROM table";
adapter.engine = "postgres_engine" as ConnectionName;
const [wrappedCode, offset] = adapter.transformOut(code);
expect(wrappedCode).toMatchInlineSnapshot(`
- "_df = mo.sql(
+ "# hello
+ _df = mo.sql(
f"""
SELECT * FROM table
""",
@@ -313,7 +332,8 @@ _df = mo.sql(
adapter.engine = "postgres_engine" as ConnectionName;
const [wrappedCode, offset] = adapter.transformOut(code);
expect(wrappedCode).toMatchInlineSnapshot(`
- "_df = mo.sql(
+ "# hello
+ _df = mo.sql(
f"""
SELECT * FROM table
""",
@@ -332,6 +352,14 @@ _df = mo.sql(
).toBe(true);
expect(adapter.isSupported("my_df = mo.sql('')")).toBe(true);
expect(adapter.isSupported('df = mo.sql("")')).toBe(true);
+ expect(adapter.isSupported('# this is a sql cell\ndf = mo.sql("")')).toBe(
+ true,
+ );
+ expect(
+ adapter.isSupported(
+ '# this is a sql cell\n# with multiple comments\ndf = mo.sql("")',
+ ),
+ ).toBe(true);
expect(adapter.isSupported(new SQLLanguageAdapter().defaultCode)).toBe(
true,
);
diff --git a/frontend/src/core/codemirror/language/sql.ts b/frontend/src/core/codemirror/language/sql.ts
index 33d8f31f87..b7951d2977 100644
--- a/frontend/src/core/codemirror/language/sql.ts
+++ b/frontend/src/core/codemirror/language/sql.ts
@@ -47,6 +47,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
dataframeName = "_df";
lastQuotePrefix: QuotePrefixKind = "f";
+ lastPythonCode = "";
showOutput = true;
engine = store.get(dataSourceConnectionsAtom).latestEngineSelected;
@@ -68,6 +69,7 @@ export class SQLLanguageAdapter implements LanguageAdapter {
return [transformedCode, offset];
}
+ this.lastPythonCode = pythonCode;
pythonCode = pythonCode.trim();
// Handle empty strings
@@ -103,6 +105,18 @@ export class SQLLanguageAdapter implements LanguageAdapter {
const prefix = upgradePrefixKind(this.lastQuotePrefix, code);
// Multiline code
+ // Retrieve any comments that the Python code may have started with
+ const lines = this.lastPythonCode.split("\n");
+ const commentLines = [];
+
+ for (const line of lines) {
+ if (line.startsWith("#")) {
+ commentLines.push(line);
+ } else {
+ break;
+ }
+ }
+
const start = `${this.dataframeName} = mo.sql(\n ${prefix}"""\n`;
const escapedCode = code.replaceAll('"""', String.raw`\"""`);
@@ -111,7 +125,10 @@ export class SQLLanguageAdapter implements LanguageAdapter {
this.engine === DEFAULT_ENGINE ? "" : `,\n engine=${this.engine}`;
const end = `\n """${showOutputParam}${engineParam}\n)`;
- return [start + indentOneTab(escapedCode) + end, start.length + 1];
+ return [
+ [...commentLines, start].join("\n") + indentOneTab(escapedCode) + end,
+ start.length + 1,
+ ];
}
isSupported(pythonCode: string): boolean {
@@ -282,11 +299,16 @@ interface SQLParseInfo {
startPosition: number;
}
+// Finds an assignment node that is preceded only by comments.
function findAssignment(cursor: TreeCursor): SyntaxNode | null {
do {
if (cursor.name === "AssignStatement") {
return cursor.node;
}
+
+ if (cursor.name !== "Comment") {
+ return null;
+ }
} while (cursor.next());
return null;
}
@@ -324,16 +346,17 @@ export function parseSQLStatement(code: string): SQLParseInfo | null {
const tree = parser.parse(code);
const cursor = tree.cursor();
- // Find assignment statement
+ // Trees start with a Script node.
+ if (cursor.name === "Script") {
+ cursor.next();
+ }
const assignStmt = findAssignment(cursor);
if (!assignStmt) {
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) {
+ // Code after the assignment statement is not allowed.
+ if (code.slice(assignStmt.to).trim().length > 0) {
return null;
}