Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/** @jsxImportSource npm:hono/jsx **/
import { html, raw } from "npm:hono/html";
import { Hono } from "npm:hono@4.2.6";
const app = new Hono();
const title = "Click Button Demo";
const View = () => {
return (
<html>
<head>
<script src="https://cdn.jsdelivr.net/pyodide/v0.26.1/full/pyodide.js"></script>
</head>
<body>
<p>
Enter SQL to extract columns using the Python library <a href="https://sqlglot.com/">SQLGlot</a> running in
{" "}
<a href="https://pyodide.org/en/stable/">Pyodide</a> in the browser.
</p>
<textarea id="code" style="width: 100%;" rows="6" value="SELECT a, b + 1 AS c FROM d">
SELECT ec.event_date, uc.country, COUNT(DISTINCT ec.user_id) AS daily_active_users FROM temp_events_clean ec
JOIN main2.brickstream_stg_20240708_1444.user_crm uc ON ec.user_id = uc.user_id GROUP BY ec.event_date,
uc.country ORDER BY ec.event_date, daily_active_users DESC;
</textarea>
<button onclick="evaluatePython()">Extract</button>
<br />
<br />
<div>Output:</div>
<textarea id="output" style="width: 100%;" rows="12" disabled></textarea>
{html`
<script>
const output = document.getElementById("output");
const code = document.getElementById("code");
function addToOutput(s) {
console.log(code.value)
console.log(s)
output.value += ">>>\\n" + "cols extracted by SQLGlot:" + "\\n" + s + "\\n\\nFrom SQL query:\\n\\n" + code.value + "\\n";
}
output.value = "Initializing...\\n";
// init Pyodide
async function main() {
let pyodide = await loadPyodide();
await pyodide.loadPackage("micropip");
const micropip = pyodide.pyimport("micropip");
// await micropip.install("snowballstemmer");
await micropip.install("sqlglot");
output.value += "Ready!\\n";
return pyodide;
}
let pyodideReadyPromise = main();
async function evaluatePython() {
let pyodide = await pyodideReadyPromise;
try {
// Pass the SQL query from the input box to Python
pyodide.globals.set("sql_query", code.value);
let result = pyodide.runPython(\`
from sqlglot import parse_one, exp
# Retrieve the SQL query from JavaScript
sql_query = globals().get('sql_query')
# Generate a list of all column references (a and b)
column_references = [column.alias_or_name for column in parse_one(sql_query).find_all(exp.Column)]
print(column_references)
column_references
\`);
console.log(result);
addToOutput(result);
} catch (err) {
addToOutput(err);
}
}
</script>
`}
</body>
</html>
);
};
app.get("/", (c) => {
return c.html(<View />);
});
export default app.fetch;
tfayyaz-honojspyodide.web.val.run
July 11, 2024