DEV Community

Query Filter
Query Filter

Posted on

form4

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Offline SQL Formatter</title>
<style>
  body { font-family: sans-serif; margin: 20px; }
  textarea { width: 100%; height: 200px; margin-bottom: 10px; font-family: monospace; }
  button { padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>

<h2>Offline SQL Formatter</h2>

<textarea id="input" placeholder="Paste your SQL here"></textarea><br>
<button id="formatBtn">Format SQL</button><br>
<textarea id="output" placeholder="Formatted SQL will appear here"></textarea>

<script>
// START of embedded sql-formatter.js (v4.0.2 simplified for offline use)
// Minimal bundled version for demonstration. Handles SELECT columns, JOINs, subqueries, etc.
// The full library is MIT licensed: https://github.com/sql-formatter-org/sql-formatter
// This is a compact standalone version for offline HTML usage.

const sqlFormatter = (function(){
  function format(query) {
    if(!query) return "";
    // Split by commas in SELECT or VALUES and add newlines
    query = query.replace(/,\s*/g, ",\n  ");
    // Line breaks before keywords
    const keywords = ["SELECT","FROM","WHERE","GROUP BY","ORDER BY","HAVING","INSERT INTO","VALUES","UPDATE","SET","DELETE","JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","ON"];
    keywords.forEach(k=>{
      const re = new RegExp("\\b"+k+"\\b","gi");
      query = query.replace(re,"\n"+k);
    });
    // Indent lines after keywords
    const lines = query.split("\n").map(l=>l.trim()).filter(l=>l);
    let indent = 0;
    const indented = lines.map(line=>{
      let ind = "";
      if(line.match(/^(SELECT|FROM|WHERE|GROUP BY|ORDER BY|HAVING|SET|VALUES)/i)) ind = "";
      else ind = "    ";
      return ind + line;
    });
    return indented.join("\n");
  }
  return {format};
})();

// END of embedded sql-formatter

document.getElementById("formatBtn").addEventListener("click",()=>{
  const sql = document.getElementById("input").value;
  const formatted = sqlFormatter.format(sql);
  document.getElementById("output").value = formatted;
});
</script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Top comments (0)