Published
Edited
Dec 5, 2021
1 star
Insert cell
# Prototype client for querying Datasette instances from Observable SQL cells

This `DatasetteDatabaseClient` class lets you query Datasette using the Observable SQL cells.

A _much_ better version of this is is the one by Alex Garcia here: https://observablehq.com/@ambassadors/datasette-client - you should use his instead! This one was a learning exercise for me.
Insert cell
covidDb
select date, county, state, fips, cases, deaths
from ny_times_us_counties
order by date desc limit 1000
Insert cell
powerPlantsDb
select * from [global-power-plants] limit 100
Insert cell
class DatasetteDatabaseClient {
constructor(host) {
this.host = host;
}
describe() {
throw new Error("not supported");
}
async sql(strings, ...args) {
return fetch(`${this.host}?${new URLSearchParams({sql: strings[0]})}`)
.then(response => response.json())
.then(formatResults);
}
}
Insert cell
function formatResults({ rows, columns }) {
let results = rows.map((row) => {
return Object.fromEntries(
columns.map((column, i) => {
return [column, row[i]];
})
);
});
results.columns = columns;
return results;
}
Insert cell
fixturesDb = new DatasetteDatabaseClient(
"https://latest.datasette.io/fixtures.json"
)
Insert cell
covidDb = new DatasetteDatabaseClient(
"https://covid-19.datasettes.com/covid.json"
)
Insert cell
powerPlantsDb = new DatasetteDatabaseClient(
"https://global-power-plants.datasettes.com/global-power-plants.json"
)
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more