RBQL Example

csv
js
javascript
data-wrangling
rbql
Author

@hrbrmstr

Published

September 16, 2023

This is a companion piece to Bonus Drop #25 to show how to use RBQL in a vanilla JS/HTML context.

Our table:


Query

ERROR

Output




JS/HTML Code

<!-- where we'll put the origin table -->
<pre id="input"></pre>

<!-- query/submit box/button -->
<div>
<textarea id="query" cols=80 style="font-family: monospace">
select wt, mpg where cyl == 4
</textarea>
<input id="run-query" type="submit" value="Run Query"/>
</div>

<!-- if there is an error in the query we'll display it here -->
<p id="query-error" style="display: table-row; visibility: collapse; color: red">ERROR</p>

<!-- where the output of the query goes -->
<pre id="output"></pre>

<!-- load up RBQL -->
<script src="https://cdn.jsdelivr.net/npm/rbql@0.27.0/rbql.js"></script>

<!-- our JS code -->
<script type="module">

  // some D3 helpers
  import { csv } from 'https://cdn.jsdelivr.net/npm/d3-fetch@3.0.1/+esm'
  import { autoType } from 'https://cdn.jsdelivr.net/npm/d3-dsv@3.0.1/+esm'

  // where we will display mtcars
  const input = document.getElementById("input")

  // read it in
  var mtcars = await csv('/data/mtcars.csv', autoType )
  const mtcarsCols = mtcars.columns // get colnames
  mtcars = mtcars.map(d => Object.values(d)) // put it into the format RBQL wants

  // poor dude's table formatter
  input.innerText = mtcarsCols.join("\t") + "\n" + mtcars.map(d => d.join("\t")).join("\n")

  // we'll run this each time the button is pressed
  function executeQuery() {

    const output = document.getElementById("output")
    const query = document.getElementById("query")
    const queryError = document.getElementById("query-error")

    var result = []     // RBQL will store output here
    var warnings = []   // RBQL will display warnings here
    var outputCols = [] // RBQL will return the output colum names here

    // hide the error message if it was displayed
    queryError.style.visibility = "collapse"

    rbql.query_table(
      query.value, // user_query
      mtcars,      // input_table
      result,      // output_table
      warnings,    // output_warnings
      null,        // join_table
      mtcarsCols,  // input_column_names
      null,        // join_column_names
      outputCols,  // output_column_names
      false        // normalize_column_names
    ).then(d => {
      output.innerText = outputCols.join("\t") + "\n" + result.map(d => d.join("\t")).join("\n")
    }).catch(e => {
      queryError.innerText = e
      queryError.style.visibility = "visible"
    })

  }

  document.getElementById("run-query").onclick = executeQuery

</script>