@hypequery/clickhouse 0.2.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/cli/bin.js +128 -36
  2. package/dist/cli/generate-types.js +101 -12
  3. package/dist/core/connection.d.ts +145 -0
  4. package/dist/core/connection.d.ts.map +1 -1
  5. package/dist/core/connection.js +75 -0
  6. package/dist/core/cross-filter.d.ts +85 -0
  7. package/dist/core/features/aggregations.d.ts +102 -0
  8. package/dist/core/features/analytics.d.ts +66 -0
  9. package/dist/core/features/executor.d.ts +19 -0
  10. package/dist/core/features/filtering.d.ts +29 -0
  11. package/dist/core/features/joins.d.ts +29 -0
  12. package/dist/core/features/pagination.d.ts +23 -0
  13. package/dist/core/features/query-modifiers.d.ts +119 -0
  14. package/dist/core/formatters/sql-formatter.d.ts +9 -0
  15. package/dist/core/join-relationships.d.ts +50 -0
  16. package/dist/core/query-builder.d.ts +197 -0
  17. package/dist/core/tests/index.d.ts +2 -0
  18. package/dist/core/tests/integration/setup.d.ts +40 -0
  19. package/dist/core/tests/integration/setup.d.ts.map +1 -1
  20. package/dist/core/tests/integration/setup.js +279 -237
  21. package/dist/core/tests/integration/test-initializer.d.ts +7 -0
  22. package/dist/core/tests/integration/test-initializer.d.ts.map +1 -0
  23. package/dist/core/tests/integration/test-initializer.js +32 -0
  24. package/dist/core/tests/test-utils.d.ts +30 -0
  25. package/dist/core/utils/logger.d.ts +37 -0
  26. package/dist/core/utils/sql-expressions.d.ts +59 -0
  27. package/dist/core/utils.d.ts +3 -0
  28. package/dist/core/validators/filter-validator.d.ts +8 -0
  29. package/dist/core/validators/value-validator.d.ts +6 -0
  30. package/dist/formatters/index.d.ts +1 -0
  31. package/dist/index.d.ts +10 -27
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +14 -2
  34. package/dist/types/base.d.ts +76 -0
  35. package/dist/types/clickhouse-types.d.ts +13 -0
  36. package/dist/types/filters.d.ts +37 -0
  37. package/dist/types/index.d.ts +3 -0
  38. package/package.json +15 -8
package/dist/cli/bin.js CHANGED
@@ -37,27 +37,84 @@ ${colors.dim}Generate TypeScript types from your ClickHouse database schema${col
37
37
  function showHelp() {
38
38
  console.log(`
39
39
  ${colors.bright}Usage:${colors.reset}
40
- npx hypequery-generate-types [output-path] [options]
40
+ npx hypequery-generate-types [options]
41
41
 
42
- ${colors.bright}Arguments:${colors.reset}
43
- output-path Path where TypeScript definitions will be saved (default: "./generated-schema.ts")
42
+ ${colors.bright}Options:${colors.reset}
43
+ --output=<path> Path where TypeScript definitions will be saved (default: "./generated-schema.ts")
44
+ --host=<url> ClickHouse server URL (default: http://localhost:8123)
45
+ --username=<user> ClickHouse username (default: default)
46
+ --password=<password> ClickHouse password
47
+ --database=<db> ClickHouse database name (default: default)
48
+ --include-tables=<tables> Comma-separated list of tables to include (default: all)
49
+ --exclude-tables=<tables> Comma-separated list of tables to exclude (default: none)
50
+ --secure Use HTTPS/TLS for connection
51
+ --help, -h Show this help text
44
52
 
45
53
  ${colors.bright}Environment variables:${colors.reset}
46
- CLICKHOUSE_HOST ClickHouse server URL (default: http://localhost:8123)
47
- CLICKHOUSE_USER ClickHouse username (default: default)
54
+ CLICKHOUSE_HOST ClickHouse server URL
55
+ VITE_CLICKHOUSE_HOST Alternative variable for Vite projects
56
+ NEXT_PUBLIC_CLICKHOUSE_HOST Alternative variable for Next.js projects
57
+
58
+ CLICKHOUSE_USER ClickHouse username
59
+ VITE_CLICKHOUSE_USER Alternative variable for Vite projects
60
+ NEXT_PUBLIC_CLICKHOUSE_USER Alternative variable for Next.js projects
61
+
48
62
  CLICKHOUSE_PASSWORD ClickHouse password
49
- CLICKHOUSE_DATABASE ClickHouse database name (default: default)
63
+ VITE_CLICKHOUSE_PASSWORD Alternative variable for Vite projects
64
+ NEXT_PUBLIC_CLICKHOUSE_PASSWORD Alternative variable for Next.js projects
65
+
66
+ CLICKHOUSE_DATABASE ClickHouse database name
67
+ VITE_CLICKHOUSE_DATABASE Alternative variable for Vite projects
68
+ NEXT_PUBLIC_CLICKHOUSE_DATABASE Alternative variable for Next.js projects
50
69
 
51
70
  ${colors.bright}Examples:${colors.reset}
52
71
  npx hypequery-generate-types
53
- npx hypequery-generate-types ./src/types/db-schema.ts
54
- CLICKHOUSE_HOST=http://my-clickhouse:8123 npx hypequery-generate-types
55
-
56
- ${colors.bright}Options:${colors.reset}
57
- --help, -h Show this help text
72
+ npx hypequery-generate-types --output=./src/types/db-schema.ts
73
+ npx hypequery-generate-types --host=https://your-instance.clickhouse.cloud:8443 --secure
74
+ npx hypequery-generate-types --host=http://localhost:8123 --username=default --password=password --database=my_db
75
+ npx hypequery-generate-types --include-tables=users,orders,products
58
76
  `);
59
77
  }
60
78
 
79
+ /**
80
+ * Parse command line arguments into a configuration object
81
+ */
82
+ function parseArguments(args) {
83
+ const config = {
84
+ output: './generated-schema.ts',
85
+ includeTables: [],
86
+ excludeTables: [],
87
+ secure: false
88
+ };
89
+
90
+ for (const arg of args) {
91
+ if (arg.startsWith('--output=')) {
92
+ config.output = arg.substring('--output='.length);
93
+ } else if (arg.startsWith('--host=')) {
94
+ config.host = arg.substring('--host='.length);
95
+ } else if (arg.startsWith('--username=')) {
96
+ config.username = arg.substring('--username='.length);
97
+ } else if (arg.startsWith('--password=')) {
98
+ config.password = arg.substring('--password='.length);
99
+ } else if (arg.startsWith('--database=')) {
100
+ config.database = arg.substring('--database='.length);
101
+ } else if (arg.startsWith('--include-tables=')) {
102
+ config.includeTables = arg.substring('--include-tables='.length).split(',');
103
+ } else if (arg.startsWith('--exclude-tables=')) {
104
+ config.excludeTables = arg.substring('--exclude-tables='.length).split(',');
105
+ } else if (arg === '--secure') {
106
+ config.secure = true;
107
+ } else if (arg === '--help' || arg === '-h') {
108
+ config.showHelp = true;
109
+ } else if (!arg.startsWith('-') && !config.output) {
110
+ // For backwards compatibility, treat the first non-flag argument as the output path
111
+ config.output = arg;
112
+ }
113
+ }
114
+
115
+ return config;
116
+ }
117
+
61
118
  /**
62
119
  * Main CLI function
63
120
  */
@@ -66,55 +123,82 @@ async function main() {
66
123
 
67
124
  // Process command line arguments
68
125
  const args = process.argv.slice(2);
126
+ const config = parseArguments(args);
69
127
 
70
128
  // Check for help flag
71
- if (args.includes('--help') || args.includes('-h')) {
129
+ if (config.showHelp) {
72
130
  showHelp();
73
131
  return;
74
132
  }
75
133
 
76
- // Get output path (default or from args)
77
- const outputPath = args.length > 0 && !args[0].startsWith('-')
78
- ? args[0]
79
- : './generated-schema.ts';
80
-
81
134
  try {
82
- // Display connection info
83
- const host = process.env.VITE_CLICKHOUSE_HOST || process.env.CLICKHOUSE_HOST || 'http://localhost:8123';
84
- const database = process.env.VITE_CLICKHOUSE_DATABASE || process.env.CLICKHOUSE_DATABASE || 'default';
135
+ // Get connection parameters from args and environment variables
136
+ const host = config.host ||
137
+ process.env.CLICKHOUSE_HOST ||
138
+ process.env.VITE_CLICKHOUSE_HOST ||
139
+ process.env.NEXT_PUBLIC_CLICKHOUSE_HOST ||
140
+ 'http://localhost:8123';
141
+
142
+ const username = config.username ||
143
+ process.env.CLICKHOUSE_USER ||
144
+ process.env.VITE_CLICKHOUSE_USER ||
145
+ process.env.NEXT_PUBLIC_CLICKHOUSE_USER ||
146
+ 'default';
147
+
148
+ const password = config.password ||
149
+ process.env.CLICKHOUSE_PASSWORD ||
150
+ process.env.VITE_CLICKHOUSE_PASSWORD ||
151
+ process.env.NEXT_PUBLIC_CLICKHOUSE_PASSWORD;
152
+
153
+ const database = config.database ||
154
+ process.env.CLICKHOUSE_DATABASE ||
155
+ process.env.VITE_CLICKHOUSE_DATABASE ||
156
+ process.env.NEXT_PUBLIC_CLICKHOUSE_DATABASE ||
157
+ 'default';
85
158
 
86
159
  console.log(`${colors.dim}Connecting to ClickHouse at ${colors.reset}${colors.bright}${host}${colors.reset}`);
87
160
  console.log(`${colors.dim}Database: ${colors.reset}${colors.bright}${database}${colors.reset}`);
88
161
 
89
- // Initialize connection from env vars
90
- ClickHouseConnection.initialize({
162
+ // Configure connection
163
+ const connectionConfig = {
91
164
  host,
92
- username: process.env.VITE_CLICKHOUSE_USER || process.env.CLICKHOUSE_USER || 'default',
93
- password: process.env.VITE_CLICKHOUSE_PASSWORD || process.env.CLICKHOUSE_PASSWORD,
165
+ username,
166
+ password,
94
167
  database,
95
- });
168
+ };
169
+
170
+ // Add secure connection options if needed
171
+ if (config.secure || host.startsWith('https://')) {
172
+ connectionConfig.secure = true;
173
+ }
174
+
175
+ // Initialize connection
176
+ ClickHouseConnection.initialize(connectionConfig);
96
177
 
97
178
  console.log(`${colors.dim}Generating TypeScript definitions...${colors.reset}`);
98
179
 
99
180
  // Ensure directory exists
100
- const dir = path.dirname(path.resolve(outputPath));
181
+ const dir = path.dirname(path.resolve(config.output));
101
182
  await fs.mkdir(dir, { recursive: true });
102
183
 
103
184
  // Generate types
104
- await generateTypes(outputPath);
185
+ await generateTypes(config.output, {
186
+ includeTables: config.includeTables.length > 0 ? config.includeTables : undefined,
187
+ excludeTables: config.excludeTables.length > 0 ? config.excludeTables : undefined
188
+ });
105
189
 
106
- console.log(`${colors.green}✓ Success! ${colors.reset}Types generated at ${colors.bright}${path.resolve(outputPath)}${colors.reset}`);
190
+ console.log(`${colors.green}✓ Success! ${colors.reset}Types generated at ${colors.bright}${path.resolve(config.output)}${colors.reset}`);
107
191
  console.log(`
108
192
  ${colors.dim}To use these types in your project:${colors.reset}
109
193
 
110
194
  import { createQueryBuilder } from '@hypequery/clickhouse';
111
- import { IntrospectedSchema } from '${outputPath.replace(/\.ts$/, '')}';
195
+ import { IntrospectedSchema } from '${config.output.replace(/\.ts$/, '')}';
112
196
 
113
197
  const db = createQueryBuilder<IntrospectedSchema>({
114
- host: process.env.CLICKHOUSE_HOST,
115
- username: process.env.CLICKHOUSE_USER,
116
- password: process.env.CLICKHOUSE_PASSWORD,
117
- database: process.env.CLICKHOUSE_DATABASE,
198
+ host: '${host}',
199
+ username: '${username}',
200
+ password: '********',
201
+ database: '${database}'
118
202
  });
119
203
  `);
120
204
  } catch (error) {
@@ -124,21 +208,29 @@ const db = createQueryBuilder<IntrospectedSchema>({
124
208
  if (error.message && error.message.includes('ECONNREFUSED')) {
125
209
  console.error(`
126
210
  ${colors.yellow}Connection refused.${colors.reset} Please check:
127
- - Is ClickHouse running at ${process.env.CLICKHOUSE_HOST || 'http://localhost:8123'}?
211
+ - Is ClickHouse running at the specified host?
128
212
  - Do you need to provide authentication credentials?
129
213
  - Are there any network/firewall restrictions?
214
+ - For cloud instances, did you include the port (usually 8443) and use HTTPS?
130
215
  `);
131
216
  } else if (error.message && error.message.includes('Authentication failed')) {
132
217
  console.error(`
133
218
  ${colors.yellow}Authentication failed.${colors.reset} Please check:
134
- - Are your CLICKHOUSE_USER and CLICKHOUSE_PASSWORD environment variables set correctly?
219
+ - Are your username and password correct?
220
+ - For ClickHouse Cloud, did you use the correct credentials from your cloud dashboard?
135
221
  - Does the user have sufficient permissions?
136
222
  `);
137
223
  } else if (error.message && error.message.includes('database does not exist')) {
138
224
  console.error(`
139
225
  ${colors.yellow}Database not found.${colors.reset} Please check:
140
- - Is the CLICKHOUSE_DATABASE environment variable set correctly?
226
+ - Is the database name correct?
141
227
  - Does the database exist in your ClickHouse instance?
228
+ `);
229
+ } else if (error.message && error.message.includes('certificate')) {
230
+ console.error(`
231
+ ${colors.yellow}SSL/TLS certificate issue.${colors.reset} For secure connections:
232
+ - Try adding the --secure flag
233
+ - For ClickHouse Cloud, make sure you're using https:// and port 8443
142
234
  `);
143
235
  }
144
236
 
@@ -12,6 +12,12 @@ dotenv.config();
12
12
  * @property {string} type - The ClickHouse type of the column
13
13
  */
14
14
 
15
+ /**
16
+ * @typedef {Object} GenerateTypesOptions
17
+ * @property {string[]} [includeTables] - List of tables to include
18
+ * @property {string[]} [excludeTables] - List of tables to exclude
19
+ */
20
+
15
21
  /**
16
22
  * Converts ClickHouse types to TypeScript types
17
23
  * @param {string} type - The ClickHouse type to convert
@@ -20,55 +26,92 @@ dotenv.config();
20
26
  const clickhouseToTsType = (type) => {
21
27
  if (type.startsWith('Array(')) {
22
28
  const innerType = type.slice(6, -1);
23
- return `Array(${clickhouseToTsType(innerType)})`;
29
+ return `Array<${clickhouseToTsType(innerType)}>`;
30
+ }
31
+
32
+ // Handle Nullable types
33
+ if (type.startsWith('Nullable(')) {
34
+ const innerType = type.slice(9, -1);
35
+ return `${clickhouseToTsType(innerType)} | null`;
24
36
  }
25
37
 
26
38
  switch (type.toLowerCase()) {
27
39
  case 'string':
28
40
  case 'fixedstring':
29
- return 'String';
41
+ return 'string';
30
42
  case 'int8':
31
43
  case 'int16':
32
44
  case 'int32':
33
- return 'Int32';
45
+ case 'uint8':
46
+ case 'uint16':
47
+ case 'uint32':
48
+ return 'number';
34
49
  case 'int64':
35
- return 'Int64';
50
+ case 'uint64':
51
+ return 'string'; // Use string for 64-bit integers to avoid precision loss
36
52
  case 'float32':
37
53
  case 'float64':
38
- return 'Float64';
54
+ case 'decimal':
55
+ return 'number';
39
56
  case 'datetime':
40
- return 'DateTime';
57
+ case 'datetime64':
58
+ return 'string'; // Use string for datetime
41
59
  case 'date':
42
- return 'Date';
60
+ case 'date32':
61
+ return 'string'; // Use string for date
62
+ case 'bool':
63
+ case 'boolean':
64
+ return 'boolean';
43
65
  default:
44
- return 'String';
66
+ // For complex types or unknown types, return string as a safe default
67
+ return 'string';
45
68
  }
46
69
  };
47
70
 
48
71
  /**
49
72
  * Generates TypeScript type definitions from the ClickHouse database schema
50
73
  * @param {string} outputPath - The file path where the type definitions will be written
74
+ * @param {GenerateTypesOptions} [options] - Options for type generation
51
75
  * @returns {Promise<void>}
52
76
  */
53
- export async function generateTypes(outputPath) {
77
+ export async function generateTypes(outputPath, options = {}) {
54
78
  const client = ClickHouseConnection.getClient();
79
+ const { includeTables = [], excludeTables = [] } = options;
55
80
 
56
81
  // Get all tables
57
82
  const tablesQuery = await client.query({
58
83
  query: 'SHOW TABLES',
59
84
  format: 'JSONEachRow'
60
85
  });
61
- const tables = await tablesQuery.json();
86
+ let tables = await tablesQuery.json();
87
+
88
+ // Filter tables if includeTables or excludeTables are specified
89
+ if (includeTables.length > 0) {
90
+ tables = tables.filter(table => includeTables.includes(table.name));
91
+ }
92
+
93
+ if (excludeTables.length > 0) {
94
+ tables = tables.filter(table => !excludeTables.includes(table.name));
95
+ }
96
+
97
+ // If no tables remain after filtering, log a warning
98
+ if (tables.length === 0) {
99
+ console.warn('Warning: No tables match the filter criteria. Check your include/exclude options.');
100
+ }
62
101
 
63
102
  let typeDefinitions = `// Generated by @hypequery/clickhouse
64
- import { ColumnType } from '@hypequery/clickhouse';
103
+ // This file defines TypeScript types based on your ClickHouse database schema
65
104
 
105
+ /**
106
+ * Schema interface for use with createQueryBuilder<IntrospectedSchema>()
107
+ * The string literals represent ClickHouse data types for each column
108
+ */
66
109
  export interface IntrospectedSchema {`;
67
110
 
68
111
  // Get columns for each table
69
112
  for (const table of tables) {
70
113
  const columnsQuery = await client.query({
71
- query: `DESCRIBE ${table.name}`,
114
+ query: `DESCRIBE TABLE ${table.name}`,
72
115
  format: 'JSONEachRow'
73
116
  });
74
117
  const columns = await columnsQuery.json();
@@ -82,10 +125,56 @@ export interface IntrospectedSchema {`;
82
125
 
83
126
  typeDefinitions += '\n}\n';
84
127
 
128
+ // Also generate a type-safe record type for each table
129
+ typeDefinitions += `\n// Type-safe record types for each table\n`;
130
+ for (const table of tables) {
131
+ const columnsQuery = await client.query({
132
+ query: `DESCRIBE TABLE ${table.name}`,
133
+ format: 'JSONEachRow'
134
+ });
135
+ const columns = await columnsQuery.json();
136
+
137
+ typeDefinitions += `export interface ${capitalizeFirstLetter(table.name)}Record {`;
138
+ for (const column of columns) {
139
+ const tsType = clickhouseToTsType(column.type).replace(/'/g, '');
140
+ typeDefinitions += `\n ${column.name}: ${tsType};`;
141
+ }
142
+ typeDefinitions += '\n}\n\n';
143
+ }
144
+
145
+ // Add a usage example
146
+ typeDefinitions += `
147
+ /**
148
+ * Usage example:
149
+ *
150
+ * import { createQueryBuilder } from '@hypequery/clickhouse';
151
+ * import { IntrospectedSchema } from './path-to-this-file';
152
+ *
153
+ * // Create a type-safe query builder
154
+ * const db = createQueryBuilder<IntrospectedSchema>();
155
+ *
156
+ * // Now you have full type safety and autocomplete
157
+ * const results = await db
158
+ * .from('${tables.length > 0 ? tables[0].name : 'table_name'}')
159
+ * .select(['column1', 'column2'])
160
+ * .where('column1', 'eq', 'value')
161
+ * .execute();
162
+ */
163
+ `;
164
+
85
165
  // Ensure the output directory exists
86
166
  const outputDir = path.dirname(path.resolve(outputPath));
87
167
  await fs.mkdir(outputDir, { recursive: true });
88
168
 
89
169
  // Write the file
90
170
  await fs.writeFile(path.resolve(outputPath), typeDefinitions);
171
+ }
172
+
173
+ /**
174
+ * Capitalize the first letter of a string
175
+ * @param {string} str - The string to capitalize
176
+ * @returns {string} - The capitalized string
177
+ */
178
+ function capitalizeFirstLetter(str) {
179
+ return str.charAt(0).toUpperCase() + str.slice(1);
91
180
  }
@@ -0,0 +1,145 @@
1
+ import { createClient } from '@clickhouse/client-web';
2
+ import type { ClickHouseSettings } from '@clickhouse/client-web';
3
+ /**
4
+ * Configuration options for the ClickHouse connection.
5
+ *
6
+ * @category Core
7
+ * @example
8
+ * ```typescript
9
+ * const config = {
10
+ * host: 'http://localhost:8123',
11
+ * username: 'default',
12
+ * password: 'password',
13
+ * database: 'my_database'
14
+ * };
15
+ * ```
16
+ */
17
+ export interface ClickHouseConnectionOptions {
18
+ /**
19
+ * The URL of the ClickHouse server, including protocol and port.
20
+ * Example: 'http://localhost:8123' or 'https://your-instance.clickhouse.cloud:8443'
21
+ */
22
+ host: string;
23
+ /**
24
+ * Username for authentication. Defaults to 'default' if not provided.
25
+ */
26
+ username?: string;
27
+ /**
28
+ * Password for authentication.
29
+ */
30
+ password?: string;
31
+ /**
32
+ * The database to connect to. Defaults to 'default' if not provided.
33
+ */
34
+ database?: string;
35
+ /**
36
+ * Enable secure connection (TLS/SSL).
37
+ * This is automatically set to true if the host URL starts with https://
38
+ */
39
+ secure?: boolean;
40
+ /**
41
+ * Custom HTTP headers to include with each request.
42
+ */
43
+ http_headers?: Record<string, string>;
44
+ /**
45
+ * Request timeout in milliseconds.
46
+ */
47
+ request_timeout?: number;
48
+ /**
49
+ * Compression options for the connection.
50
+ */
51
+ compression?: {
52
+ response?: boolean;
53
+ request?: boolean;
54
+ };
55
+ /**
56
+ * Application name to identify in ClickHouse server logs.
57
+ */
58
+ application?: string;
59
+ /**
60
+ * Keep-alive connection settings.
61
+ */
62
+ keep_alive?: {
63
+ enabled: boolean;
64
+ };
65
+ /**
66
+ * Logger configuration.
67
+ */
68
+ log?: any;
69
+ /**
70
+ * Additional ClickHouse-specific settings.
71
+ */
72
+ clickhouse_settings?: ClickHouseSettings;
73
+ }
74
+ /**
75
+ * The main entry point for connecting to a ClickHouse database.
76
+ * Provides static methods to initialize the connection and retrieve the client.
77
+ *
78
+ * @category Core
79
+ * @example
80
+ * ```typescript
81
+ * // Initialize the connection
82
+ * ClickHouseConnection.initialize({
83
+ * host: 'http://localhost:8123',
84
+ * username: 'default',
85
+ * password: 'password',
86
+ * database: 'my_database'
87
+ * });
88
+ *
89
+ * // Get the client to execute queries directly
90
+ * const client = ClickHouseConnection.getClient();
91
+ * const result = await client.query({
92
+ * query: 'SELECT * FROM my_table',
93
+ * format: 'JSONEachRow'
94
+ * });
95
+ * ```
96
+ */
97
+ export declare class ClickHouseConnection {
98
+ private static instance;
99
+ /**
100
+ * Initializes the ClickHouse connection with the provided configuration.
101
+ * This method must be called before any queries can be executed.
102
+ *
103
+ * @param config - The connection configuration options
104
+ * @returns The ClickHouseConnection class for method chaining
105
+ * @throws Will throw an error if the connection cannot be established
106
+ *
107
+ * @example
108
+ * ```typescript
109
+ * // For a local ClickHouse instance
110
+ * ClickHouseConnection.initialize({
111
+ * host: 'http://localhost:8123',
112
+ * username: 'default',
113
+ * password: 'password',
114
+ * database: 'my_database'
115
+ * });
116
+ *
117
+ * // For a ClickHouse Cloud instance
118
+ * ClickHouseConnection.initialize({
119
+ * host: 'https://your-instance.clickhouse.cloud:8443',
120
+ * username: 'default',
121
+ * password: 'your-password',
122
+ * database: 'my_database',
123
+ * secure: true
124
+ * });
125
+ * ```
126
+ */
127
+ static initialize(config: ClickHouseConnectionOptions): typeof ClickHouseConnection;
128
+ /**
129
+ * Retrieves the ClickHouse client instance for direct query execution.
130
+ *
131
+ * @returns The ClickHouse client instance
132
+ * @throws Will throw an error if the connection has not been initialized
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * const client = ClickHouseConnection.getClient();
137
+ * const result = await client.query({
138
+ * query: 'SELECT * FROM my_table',
139
+ * format: 'JSONEachRow'
140
+ * });
141
+ * ```
142
+ */
143
+ static getClient(): ReturnType<typeof createClient>;
144
+ }
145
+ //# sourceMappingURL=connection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/core/connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAWjE,MAAM,WAAW,2BAA2B;IAC1C,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE;QACZ,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;IACF,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,UAAU,CAAC,EAAE;QACX,OAAO,EAAE,OAAO,CAAC;KAClB,CAAC;IAEF,GAAG,CAAC,EAAE,GAAG,CAAC;IACV,mBAAmB,CAAC,EAAE,kBAAkB,CAAC;CAC1C;AAED,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAkC;IAEzD,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,2BAA2B,GAAG,IAAI;IAqB5D,MAAM,CAAC,SAAS,IAAI,UAAU,CAAC,OAAO,YAAY,CAAC;CAMpD"}
1
+ {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/core/connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AACtD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAGjE;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,2BAA2B;IAC1C;;;OAGG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;OAEG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB;;;OAGG;IACH,MAAM,CAAC,EAAE,OAAO,CAAC;IAEjB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAEtC;;OAEG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,WAAW,CAAC,EAAE;QACZ,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,OAAO,CAAC,EAAE,OAAO,CAAC;KACnB,CAAC;IAEF;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IAErB;;OAEG;IACH,UAAU,CAAC,EAAE;QACX,OAAO,EAAE,OAAO,CAAC;KAClB,CAAC;IAEF;;OAEG;IACH,GAAG,CAAC,EAAE,GAAG,CAAC;IAEV;;OAEG;IACH,mBAAmB,CAAC,EAAE,kBAAkB,CAAC;CAC1C;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,qBAAa,oBAAoB;IAC/B,OAAO,CAAC,MAAM,CAAC,QAAQ,CAAkC;IAEzD;;;;;;;;;;;;;;;;;;;;;;;;;;;OA2BG;IACH,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,2BAA2B,GAAG,OAAO,oBAAoB;IA+BnF;;;;;;;;;;;;;;OAcG;IACH,MAAM,CAAC,SAAS,IAAI,UAAU,CAAC,OAAO,YAAY,CAAC;CAMpD"}
@@ -1,5 +1,56 @@
1
1
  import { createClient } from '@clickhouse/client-web';
2
+ /**
3
+ * The main entry point for connecting to a ClickHouse database.
4
+ * Provides static methods to initialize the connection and retrieve the client.
5
+ *
6
+ * @category Core
7
+ * @example
8
+ * ```typescript
9
+ * // Initialize the connection
10
+ * ClickHouseConnection.initialize({
11
+ * host: 'http://localhost:8123',
12
+ * username: 'default',
13
+ * password: 'password',
14
+ * database: 'my_database'
15
+ * });
16
+ *
17
+ * // Get the client to execute queries directly
18
+ * const client = ClickHouseConnection.getClient();
19
+ * const result = await client.query({
20
+ * query: 'SELECT * FROM my_table',
21
+ * format: 'JSONEachRow'
22
+ * });
23
+ * ```
24
+ */
2
25
  export class ClickHouseConnection {
26
+ /**
27
+ * Initializes the ClickHouse connection with the provided configuration.
28
+ * This method must be called before any queries can be executed.
29
+ *
30
+ * @param config - The connection configuration options
31
+ * @returns The ClickHouseConnection class for method chaining
32
+ * @throws Will throw an error if the connection cannot be established
33
+ *
34
+ * @example
35
+ * ```typescript
36
+ * // For a local ClickHouse instance
37
+ * ClickHouseConnection.initialize({
38
+ * host: 'http://localhost:8123',
39
+ * username: 'default',
40
+ * password: 'password',
41
+ * database: 'my_database'
42
+ * });
43
+ *
44
+ * // For a ClickHouse Cloud instance
45
+ * ClickHouseConnection.initialize({
46
+ * host: 'https://your-instance.clickhouse.cloud:8443',
47
+ * username: 'default',
48
+ * password: 'your-password',
49
+ * database: 'my_database',
50
+ * secure: true
51
+ * });
52
+ * ```
53
+ */
3
54
  static initialize(config) {
4
55
  // Create a client config object with only the standard options
5
56
  const clientConfig = {
@@ -8,6 +59,14 @@ export class ClickHouseConnection {
8
59
  password: config.password,
9
60
  database: config.database,
10
61
  };
62
+ // Automatically enable secure mode for HTTPS URLs
63
+ const isSecure = config.secure || config.host.startsWith('https://');
64
+ if (isSecure) {
65
+ clientConfig.tls = {
66
+ ca_cert: undefined, // Use system CA certificates
67
+ verify: true,
68
+ };
69
+ }
11
70
  // Add the extended options if provided
12
71
  if (config.http_headers)
13
72
  clientConfig.http_headers = config.http_headers;
@@ -24,7 +83,23 @@ export class ClickHouseConnection {
24
83
  if (config.clickhouse_settings)
25
84
  clientConfig.clickhouse_settings = config.clickhouse_settings;
26
85
  this.instance = createClient(clientConfig);
86
+ return ClickHouseConnection;
27
87
  }
88
+ /**
89
+ * Retrieves the ClickHouse client instance for direct query execution.
90
+ *
91
+ * @returns The ClickHouse client instance
92
+ * @throws Will throw an error if the connection has not been initialized
93
+ *
94
+ * @example
95
+ * ```typescript
96
+ * const client = ClickHouseConnection.getClient();
97
+ * const result = await client.query({
98
+ * query: 'SELECT * FROM my_table',
99
+ * format: 'JSONEachRow'
100
+ * });
101
+ * ```
102
+ */
28
103
  static getClient() {
29
104
  if (!this.instance) {
30
105
  throw new Error('ClickHouse connection not initialized');