class ClickHouseDatabaseClient {
constructor(url) {
this.url = url;
}
async query(q) {
let res = await fetch(this.url, { method: "POST", body: q });
if (res.status == 200) {
let text = await res.text();
text = text.trim();
if (text === "") return [];
res = JSON.parse(text);
console.log(res.statistics);
return res.data;
} else {
throw new Error(await res.text());
}
}
async sql(strings, ...args) {
let q = "";
for (let i = 0; i < strings.length; i++) {
q += strings[i];
if (args[i] !== undefined) q += args[i];
}
return this.query(q);
}
async describe(table, cached) {
return Inputs.table(
await this.query(
`select name, type, formatReadableSize(data_compressed_bytes) as compressed_bytes, formatReadableSize(data_uncompressed_bytes) as uncompressed_bytes, data_uncompressed_bytes / data_compressed_bytes as compression_ratio, compression_codec, is_in_partition_key, is_in_sorting_key, is_in_primary_key, is_in_sampling_key
from system.columns
where database = 'default' and table = '${table}'`,
cached && `${table}_describe`
),
{ layout: "auto" }
);
}
async preview(table, limit = 10, cached = false) {
return Inputs.table(
await this.query(
`select * from ${table} limit ${limit}`,
cached && `${table}_preview`
),
{ layout: "auto" }
);
}
}