import {
ClickHouseSettings,
createClient,
DataFormat,
QueryParams,
} from "@clickhouse/[email protected]";
/**
* @param parse_into Name of the method that should be used to parse the results.
*
* @param format Format of the resulting dataset. Wrap the format name with `"` in the
* argument editor.
*
* @param clickhouse_settings ClickHouse settings that can be applied on query level.
*
* @param query_params Parameters for query binding.
*
* @param query_params AbortSignal instance to cancel a query in progress.
*/
type Clickhouse = {
host: string;
username: string;
password: string;
};
export async function main(
auth: Clickhouse,
query: string,
parse_into: "json" | "text" = "json",
format?: DataFormat,
clickhouse_settings?: ClickHouseSettings,
query_params?: Record<string, unknown>,
abort_signal?: AbortSignal,
) {
const client = createClient(removeObjectEmptyFields(auth));
const params = removeObjectEmptyFields({
query,
format,
clickhouse_settings,
query_params,
abort_signal,
}) as QueryParams;
const result = await client.query(params);
await client.close();
return await result[parse_into]();
}
function removeObjectEmptyFields(
object?: Record<string, any>,
removeEmptyArraysAndObjects = true,
createNewObject = true,
) {
if (!object || typeof object !== "object") return {}
const obj = createNewObject ? { ...object } : object
const emptyValues = [undefined, null, ""]
for (const key in obj) {
const value = obj[key]
if (emptyValues.includes(value)) {
delete obj[key]
} else if (typeof value === "object") {
if (Object.keys(value).length) {
obj[key] = removeObjectEmptyFields(value, removeEmptyArraysAndObjects, false)
}
if (!Object.keys(value).length && removeEmptyArraysAndObjects) {
delete obj[key]
}
}
}
return obj
}
Submitted by hugo989 17 days ago