### Installing clickhouse-ts-client with npm/yarn (Shell) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Provides the command-line instructions to install the clickhouse-ts-client library using either the npm or yarn package managers. This is the standard way to add the dependency to your Node.js project. ```shell npm install clickhouse-ts-client # or yarn add clickhouse-ts-client ``` -------------------------------- ### Basic Usage Example with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Demonstrates a complete basic workflow using the client: initializing, defining query and input operations, creating a table, inserting sample data, querying the data with parsing, and finally dropping the table. Shows the use of `query`, `input`, `exec`, `loader`, and `ParseMode.Rows` for data handling. ```javascript import clickhouse, { ParseMode } from "clickhouse-ts-client"; const { query, input } = clickhouse(); const createTab = query("CREATE TABLE IF NOT EXISTS clicks (time DateTime, ip IPv4) ENGINE = Memory").exec; const dropTab = query("DROP TABLE IF EXISTS clicks").exec; const insertData = input("INSERT INTO clicks"); const getDailyStats = query("SELECT toDate(time) as dt, uniq(ip) FROM clicks GROUP BY dt") .loader({ mode: ParseMode.Rows }); await createTab(); await insertData([ { time: "2023-06-16 23:45:00", ip: "192.168.1.0" }, { time: "2023-06-17 00:01:15", ip: "192.168.1.1" }, { time: "2023-06-17 14:47:01", ip: "192.168.1.1" } ]); console.table([["Date", "Uniq clicks"], ...await getDailyStats()]); await dropTab(); ``` -------------------------------- ### Sending Data to ClickHouse with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Illustrates various methods for inserting data into ClickHouse using the input function. Examples include inserting data from a CSV string, an array of objects, an array of rows, a raw stream, a stream of objects, and a stream of rows. ```javascript import { createReadStream } from "fs"; import { Readable } from "stream"; import clickhouse, { createStreamInput } from "clickhouse-ts-client"; const { input } = clickhouse(); const insertData = input("INSERT INTO clicks FORMAT CSV"); // Insert data from CSV string: await insertData(`2023-06-16 23:45:00,192.168.1.0\n2023-06-17 00:01:15,192.168.1.1`); // Insert data from array of objects: await insertData([ { time: "2023-06-16 23:45:00", ip: "192.168.1.0" }, { time: "2023-06-17 00:01:15", ip: "192.168.1.1" } ]); // Insert data from array of rows: await insertData({ rows: [ ["2023-06-17 14:47:01", "192.168.1.0"], ["2023-06-17 00:01:15", "192.168.1.1"] ] }); // Insert data from raw stream: await insertData(createReadStream("clicks.csv")); // Insert data from stream of objects (we use generator here to create a stream): async function *generateClicks(n=100) { for (let i=0; i setTimeout(resolve, 500)); } } await insertData(Readable.from(generateClicks())); // Insert data from stream of rows // (we use util function createStreamInput here to create a temporary stream): const rows = createStreamInput(); (async (n=100) => { for (let i=0; i setTimeout(resolve, 500)); } rows.end(); })().catch(console.error); await insertData({ rows }); ``` -------------------------------- ### Loading Whole Query Results with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Demonstrates how to fetch the entire result set of a query into memory using the `.loader()` method. It shows examples using different `ParseMode` options: `Raw` for the unprocessed string output, `Objects` to parse into an array of JavaScript objects, and `Rows` to parse into an array of arrays. Using `Objects` or `Rows` overrides any FORMAT clause in the query string. ```javascript const last100ClicksQuery = query("SELECT * FROM clicks ORDER BY time DESC LIMIT 100 FORMAT PrettyCompact"); // Don't parse data, just return raw string as it was received from DB: const loadRaw = last100ClicksQuery.loader(); // default mode is ParseMode.Raw console.log(await loadRaw()); // Parse data as array of objects: const loadClicks = last100ClicksQuery.loader({ mode: ParseMode.Objects }); const uniqIps = new Set((await loadClicks()).map(({ ip }) => ip)); // Parse data as array of rows: const loadRows = last100ClicksQuery.loader({ mode: ParseMode.Rows }); console.table(await loadRows()); ``` -------------------------------- ### Type-Safe Data Input with clickhouse-ts-client (TypeScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Explains how to apply generic types to the input function to enforce type checking for the data being inserted into ClickHouse. Provides examples demonstrating correct and incorrect type usage for both object and row input modes. ```typescript import { Row } from "clickhouse-ts-client"; interface Click { time: string; ip: number; } type ClickRow = Row; // [string, number]; const { input } = clickhouse(); const insertClicks = input("INSERT INTO clicks"); await insertData([ { time: "2023-06-16 23:45:00", ip: 3232235776 /* "192.168.1.0" in a long format */ } ]); // OK await insertData([ { time: "2023-06-16 23:45:00", ip: "192.168.1.0" } ]); // compile error! const insertClickRows = input("INSERT INTO clicks (time, ip)"); await insertClickRows({ rows: [ ["2023-06-16 23:45:00", 3232235776] ] }); // OK await insertClickRows({ rows: [ ["2023-06-16 23:45:00", "192.168.1.0"] ] }); // compile error! await insertClickRows([ { time: "2023-06-16 23:45:00", ip: 3232235776 /* "192.168.1.0" in a long format */ } ]); // compile error! ``` -------------------------------- ### Type-Safe Query Results with clickhouse-ts-client (TypeScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Demonstrates how to use generic types with the loader and reader functions to achieve type checking for query results in both object and row parsing modes. Includes examples showing correct type usage and compile-time errors for incorrect usage. ```typescript import { Row } from "clickhouse-ts-client"; interface Click { time: string; ip: number; } type ClickRow = Row; // [string, number]; const last100ClicksQuery = query("SELECT time, ip FROM clicks ORDER BY time DESC LIMIT 100"); // we can pass type in both rows and objects mode: const loadClicks = last100ClicksQuery.loader({ mode: ParseMode.Objects }); // () => Promise const loadClickRows = last100ClicksQuery.loader({ mode: ParseMode.Rows }); // () => Promise // same for stream: const readClicks = last100ClicksQuery.reader({ mode: ParseMode.Objects }); // () => TypedReadable const readClickRows = last100ClicksQuery.reader({ mode: ParseMode.Rows }); // () => TypedReadable // TS will emit an error if you try to pass wrong type for the current parse mode const loadClicksE = last100ClicksQuery.loader(); // compile error! const loadClickRowsE = last100ClicksQuery.loader({ mode: ParseMode.Objects }); // compile error! ``` -------------------------------- ### Streaming Query Results with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Illustrates how to handle potentially large query results efficiently by streaming them using the `.reader()` method. Examples show streaming raw data to a file using Node.js streams, and streaming parsed data (objects or rows) using `for await...of`. Similar to `.loader()`, using `Objects` or `Rows` mode overrides the query's FORMAT clause and sets the stream to object mode. ```javascript import {createWriteStream} from "fs"; import {pipeline} from "stream/promises"; const last100ClicksQuery = query("SELECT * FROM clicks ORDER BY time DESC LIMIT 100 FORMAT CSV"); // Stream response without parsing: const readRaw = last100ClicksQuery.reader(); // default mode is ParseMode.Raw await pipeline(readRaw(), createWriteStream("clicks.csv")); // Create a stream of objects: const read = last100ClicksQuery.reader({ mode: ParseMode.Objects }); for await (const { time, ip } of read()) { console.log(`${time};${ip}`); } // Stream as parsed rows: const readRows = last100ClicksQuery.reader({ mode: ParseMode.Rows }); for await (const [time, ip] of readRows()) { console.log(`${time};${ip}`); } ``` -------------------------------- ### Setting up Connection with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Illustrates two common ways to initialize the clickhouse-ts-client connector: by providing connection details as a configuration object or by using a Data Source Name (DSN) connection string. Note that calling the default function creates the connector object, but the actual connection is established lazily on the first query execution. ```javascript import clickhouse from "clickhouse-ts-client"; // using settings object: const conn1 = clickhouse({ proto: "https", host: "192.168.1.0", port: 18123, // you can pass string here as well user: "tester", pwd: "secret", db: "test" }); // using DSN string: const conn2 = clickhouse("https://tester:secret@192.168.1.0:18123/?database=test"); ``` -------------------------------- ### Executing a Query with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Shows the basic pattern for executing a query that does not return a result set (like DDL or DML statements). You define the query string using the `query` function and then call the `.exec()` method on the returned object to send the query to the database. ```javascript const { query } = clickhouse(); await query("CREATE TABLE IF NOT EXISTS clicks (time DateTime, ip IPv4) ENGINE = Memory)").exec(); ``` -------------------------------- ### Using Parameterized Queries with clickhouse-ts-client (JavaScript) Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md Shows how to use ClickHouse's parameterized query feature with the client library. Demonstrates using {name:type} placeholders in the query string and passing parameter values as an object to the query function, which helps prevent SQL injection. ```javascript const { query } = clickhouse(); const loadData = query("select * from clicks where toDate(time) = {date:String}"); const someApiHandler = async (req, res) => { const { date } = req.query; res.json(await loadData({ date })); }; ``` -------------------------------- ### Handling Clickhouse-ts-client Errors in JavaScript Source: https://github.com/safronizator/clickhouse-ts-client/blob/master/README.md This snippet demonstrates how to catch and handle specific error types (ConnectionError, DataProcessingError, QueryingError) thrown by the clickhouse-ts-client when executing a query. It uses a try-catch block and instanceof checks to differentiate between error types, allowing for specific error handling logic. ```javascript import clickhouse, { ClickhouseError, ConnectionError, DataProcessingError, QueryingError } from "clickhouse-ts-client"; const { query } = clickhouse( { host: "wrong.host" } ); try { await query("INSERT INTO clicks VALUES (1, 2, 3)").exec(); } catch (err) { if (err instanceof ClickhouseError) { switch (true) { case err instanceof ConnectionError: // handle ConnectionError case err instanceof DataProcessingError: // handle DataProcessingError case err instanceof QueryingError: // handle QueryingError default: // handle other ClickhouseError (normally it should not happen) } } else { throw err; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.