diff --git a/architecture-artenova.png b/architecture-artenova.png new file mode 100644 index 0000000..6ac70c6 Binary files /dev/null and b/architecture-artenova.png differ diff --git a/src/assets/architecture-artenova.png b/src/assets/architecture-artenova.png new file mode 100644 index 0000000..6ac70c6 Binary files /dev/null and b/src/assets/architecture-artenova.png differ diff --git a/src/components/CodeWorkspace.tsx b/src/components/CodeWorkspace.tsx index be80d4d..dfaccaf 100644 --- a/src/components/CodeWorkspace.tsx +++ b/src/components/CodeWorkspace.tsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from "react"; -import { Download, History, Play, Plus, Save, Share2, Square, Trash2, Upload } from "lucide-react"; +import { Download, History, LoaderCircle, Play, Plus, Save, Share2, Trash2, Upload } from "lucide-react"; +import { PGliteWorker } from "@electric-sql/pglite/worker"; import { Button } from "./ui/button"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "./ui/select"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "./ui/dialog"; @@ -8,6 +9,17 @@ import { decodeWorkspace, encodeWorkspace, type EditorSnapshot } from "../lib/ed const STORAGE = "merphy-editor-history-v1"; const initialRows = [["Ville", "Température", "Humidité"], ["Dakar", "28", "75"], ["Thiès", "30", "65"]]; +type SqlRow = Record; +function displayCell(value: unknown) { + if (value === null || value === undefined) return "NULL"; + return typeof value === "object" ? JSON.stringify(value) : String(value); +} +function displayType(value: unknown) { + if (value === null || value === undefined) return "NULL"; + if (typeof value === "number") return "Numérique"; + if (typeof value === "boolean") return "Booléen"; + return value instanceof Date ? "Date" : "Texte"; +} function sample(id: string) { const item = codeEditors.find((e) => e.id === id); if (!item) return ""; @@ -19,6 +31,83 @@ function sample(id: string) { return ""; } +function escapeHtml(value: string) { + return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """).replace(/'/g, "'"); +} + +function isWordStart(character: string) { + return (character >= "a" && character <= "z") || (character >= "A" && character <= "Z") || character === "_"; +} + +function isWordPart(character: string) { + return isWordStart(character) || (character >= "0" && character <= "9"); +} + +function highlightCode(source: string, editorId: string) { + const language = ["sql", "postgresql"].includes(editorId) ? "sql" : editorId === "dax" ? "dax" : "python"; + const keywords = language === "sql" + ? new Set("select from where and or not like ilike order by desc asc limit offset join inner left right outer on group having count sum avg min max as distinct insert into values update set delete create table drop alter returning null is case when then else end union all with".split(" ")) + : language === "dax" + ? new Set("calculate sum sumx average averagex count countrows filter all allexcept related relatedtable divide if switch return var true false blank".split(" ")) + : new Set("and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield true false none".split(" ")); + + let html = ""; + let index = 0; + while (index < source.length) { + const start = index; + const character = source[index]; + let color = ""; + + if ((language !== "python" && character === "-" && source[index + 1] === "-") || character === "#") { + color = "text-amber-300"; + while (index < source.length && source[index] !== "\n") index += 1; + } else if (language !== "python" && character === "/" && source[index + 1] === "*") { + color = "text-amber-300"; + index += 2; + while (index < source.length && !(source[index] === "*" && source[index + 1] === "/")) index += 1; + if (index < source.length) index += 2; + } else if (character === "'" || character === '"') { + color = "text-emerald-300"; + const delimiter = language === "python" && source.slice(index, index + 3) === character.repeat(3) ? character.repeat(3) : character; + index += delimiter.length; + while (index < source.length) { + if (source[index] === "\\") { + index += Math.min(2, source.length - index); + } else if (source.slice(index, index + delimiter.length) === delimiter) { + index += delimiter.length; + break; + } else { + index += 1; + } + } + } else if (character >= "0" && character <= "9") { + color = "text-sky-300"; + index += 1; + while (index < source.length && source[index] >= "0" && source[index] <= "9") index += 1; + if (source[index] === "." && source[index + 1] >= "0" && source[index + 1] <= "9") { + index += 1; + while (index < source.length && source[index] >= "0" && source[index] <= "9") index += 1; + } + } else if (isWordStart(character)) { + index += 1; + while (index < source.length && isWordPart(source[index])) index += 1; + const word = source.slice(start, index); + let next = index; + while (next < source.length && source[next].trim() === "") next += 1; + if (keywords.has(word.toLowerCase())) color = "text-purple-300"; + else if (source[next] === "(") color = "text-cyan-300"; + } else { + index += 1; + } + + const token = source.slice(start, index); + const escaped = escapeHtml(token); + html += color ? `${escaped}` : escaped; + } + + return html; +} + export function CodeWorkspace() { const [editorId, setEditorId] = useState("postgresql"); const [code, setCode] = useState(""); @@ -27,14 +116,20 @@ export function CodeWorkspace() { const [history, setHistory] = useState([]); const [historyOpen, setHistoryOpen] = useState(false); const [output, setOutput] = useState(""); + const [sqlRows, setSqlRows] = useState(null); + const [executionMs, setExecutionMs] = useState(null); + const [queryHistory, setQueryHistory] = useState<{ code: string; rowCount: number; durationMs: number; ranAt: string }[]>([]); const [images, setImages] = useState([]); const [busy, setBusy] = useState(false); const [message, setMessage] = useState(""); + const [pgReady, setPgReady] = useState(false); const [stdin, setStdin] = useState("Alice\n30"); const [files, setFiles] = useState<{ name: string; bytes: Uint8Array }[]>([]); - const worker = useRef(null); const input = useRef(null); const drafts = useRef>({}); + const latestCode = useRef(code); + const pgRef = useRef(null); + latestCode.current = code; const editor = codeEditors.find((e) => e.id === editorId) ?? codeEditors[0]; useEffect(() => { @@ -55,7 +150,14 @@ export function CodeWorkspace() { setMessage("Document partagé chargé."); } } catch { setMessage("La sauvegarde ou le lien partagé est invalide."); } - return () => worker.current?.terminate(); + + // Initialiser PGlite dans un Worker dédié + const pg = new PGliteWorker( + new Worker(new URL("../lib/pglite-worker.ts", import.meta.url), { type: "module" }) + ); + pgRef.current = pg; + pg.waitReady.then(() => setPgReady(true)).catch(() => setMessage("Échec de l'initialisation du moteur PostgreSQL.")); + return () => { pg.close().catch(() => {}); }; }, []); function changeEditor(id: string) { @@ -120,17 +222,78 @@ export function CodeWorkspace() { } catch { setMessage("Impossible de lire ce fichier."); } } - function run() { - if (!worker.current) { - worker.current = new Worker(new URL("../lib/editor-runtime.worker.ts", import.meta.url), { type: "module" }); - worker.current.onmessage = (event) => { - if (event.data.status) setOutput(event.data.status); - if (event.data.done) { setOutput(event.data.output); setImages(event.data.images ?? []); setBusy(false); } - }; - worker.current.onerror = () => { setOutput("Le moteur n’a pas pu démarrer. Vérifiez votre connexion et réessayez."); setBusy(false); worker.current?.terminate(); worker.current = null; }; + async function run() { + const pg = pgRef.current; + if (!pg || !pgReady) { + setOutput("Le moteur PostgreSQL n'est pas encore prêt. Patientez un instant."); + return; + } + setBusy(true); + setSqlRows(null); + setOutput(""); + setImages([]); + const start = performance.now(); + try { + const results = await pg.exec(code); + const durationMs = Math.round(performance.now() - start); + setExecutionMs(durationMs); + // exec() retourne un tableau de Results (une par instruction) + const last = results[results.length - 1]; + if (last && last.rows.length > 0) { + setSqlRows(last.rows as SqlRow[]); + setOutput(`OK — ${last.rows.length} ligne(s)`); + setQueryHistory((prev) => [ + { code, rowCount: last.rows.length, durationMs, ranAt: new Date().toISOString() }, + ...prev.slice(0, 49), + ]); + } else { + // Requête DDL/DML sans résultat tabulaire + const affectedCmd = last?.affectedRows != null ? ` (${last.affectedRows} ligne(s) affectée(s))` : ""; + setOutput(`Requête exécutée avec succès${affectedCmd}.`); + setSqlRows([]); + setQueryHistory((prev) => [ + { code, rowCount: 0, durationMs, ranAt: new Date().toISOString() }, + ...prev.slice(0, 49), + ]); + } + } catch (err) { + const durationMs = Math.round(performance.now() - start); + setExecutionMs(durationMs); + const msg = err instanceof Error ? err.message : String(err); + setOutput(`Erreur PostgreSQL :\n${msg}`); + setSqlRows(null); + } finally { + setBusy(false); + } + } + + async function exportSqlRows(format: "csv" | "xlsx") { + if (!sqlRows) return; + try { + let blob: Blob; + if (format === "csv") { + const columns = Object.keys(sqlRows[0] ?? {}); + const csv = [columns, ...sqlRows.map((row) => columns.map((column) => displayCell(row[column])))] + .map((line) => line.map((value) => `"${value.replace(/"/g, '""')}"`).join(",")) + .join("\r\n"); + blob = new Blob(["\\uFEFF", csv], { type: "text/csv;charset=utf-8" }); + } else { + const XLSX = await import("xlsx"); + const worksheet = XLSX.utils.json_to_sheet(sqlRows); + const workbook = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(workbook, worksheet, "Résultats"); + blob = new Blob([XLSX.write(workbook, { type: "array", bookType: "xlsx" })], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }); + } + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = `resultats-sql.${format}`; + link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + setMessage(`Résultats exportés en ${format.toUpperCase()}.`); + } catch { + setMessage("L’export des résultats a échoué."); } - setBusy(true); setOutput("Exécution…"); setImages([]); - worker.current.postMessage({ editorId, code, stdin, files }); } return
@@ -150,16 +313,49 @@ export function CodeWorkspace() {
setName(e.target.value)} className="min-w-0 max-w-full rounded border border-input bg-background px-2 py-1 text-sm" /> - {editorId !== "excel" && editorId !== "dax" && } + {editorId !== "excel" && editorId !== "dax" && ( + ["postgresql", "sql"].includes(editorId) + ? + : + )} {editorId === "dax" && DAX · édition uniquement, exécution dans Power BI}
{editorId === "excel" ?
{rows.map((row, i) => {row.map((cell, j) => )})}
{i + 1} setRows(rows.map((r, ri) => ri === i ? r.map((c, ci) => ci === j ? e.target.value : c) : r))} />
-
: