|
1 | 1 | import { createClient } from '@clickhouse/client' // or '@clickhouse/client-web' |
2 | 2 |
|
3 | 3 | // Ephemeral columns documentation: https://clickhouse.com/docs/en/sql-reference/statements/create/table#ephemeral |
4 | | -// This example is inspired by https://github.com/ClickHouse/clickhouse-js/issues/217 |
5 | 4 | void (async () => { |
6 | 5 | const tableName = 'insert_ephemeral_columns' |
7 | | - const client = createClient({ |
8 | | - clickhouse_settings: { |
9 | | - allow_experimental_object_type: 1, // allows JSON type usage |
10 | | - }, |
11 | | - }) |
| 6 | + const client = createClient({}) |
12 | 7 |
|
13 | 8 | await client.command({ |
14 | 9 | query: ` |
15 | 10 | CREATE OR REPLACE TABLE ${tableName} |
16 | 11 | ( |
17 | | - event_type LowCardinality(String) DEFAULT JSONExtractString(message_raw, 'type'), |
18 | | - repo_name LowCardinality(String) DEFAULT JSONExtractString(message_raw, 'repo', 'name'), |
19 | | - message JSON DEFAULT message_raw, |
20 | | - message_raw String EPHEMERAL |
| 12 | + id UInt64, |
| 13 | + message String DEFAULT message_default, |
| 14 | + message_default String EPHEMERAL |
21 | 15 | ) |
22 | 16 | ENGINE MergeTree() |
23 | | - ORDER BY (event_type, repo_name) |
| 17 | + ORDER BY (id) |
24 | 18 | `, |
25 | 19 | }) |
26 | 20 |
|
27 | 21 | await client.insert({ |
28 | 22 | table: tableName, |
29 | 23 | values: [ |
30 | 24 | { |
31 | | - message_raw: { |
32 | | - type: 'MyEventType', |
33 | | - repo: { |
34 | | - name: 'foo', |
35 | | - }, |
36 | | - }, |
| 25 | + id: '42', |
| 26 | + message_default: 'foo', |
37 | 27 | }, |
38 | 28 | { |
39 | | - message_raw: { |
40 | | - type: 'SomeOtherType', |
41 | | - repo: { |
42 | | - name: 'bar', |
43 | | - }, |
44 | | - }, |
| 29 | + id: '144', |
| 30 | + message_default: 'bar', |
45 | 31 | }, |
46 | 32 | ], |
47 | 33 | format: 'JSONEachRow', |
48 | 34 | // The name of the ephemeral column has to be specified here |
49 | 35 | // to trigger the default values logic for the rest of the columns |
50 | | - columns: ['message_raw'], |
| 36 | + columns: ['id', 'message_default'], |
51 | 37 | }) |
52 | 38 |
|
53 | 39 | const rows = await client.query({ |
54 | | - query: `SELECT * FROM ${tableName}`, |
55 | | - format: 'JSONCompactEachRowWithNames', |
| 40 | + query: `SELECT * |
| 41 | + FROM ${tableName}`, |
| 42 | + format: 'JSONEachRow', |
56 | 43 | }) |
57 | 44 |
|
58 | | - console.info(await rows.text()) |
| 45 | + console.info(await rows.json()) |
59 | 46 | await client.close() |
60 | 47 | })() |
0 commit comments