@hypequery/clickhouse 1.5.0 → 1.6.1

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 (118) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -14
  3. package/dist/cli/generate-types.js +5 -12
  4. package/dist/core/adapters/clickhouse-adapter.d.ts +14 -0
  5. package/dist/core/adapters/clickhouse-adapter.d.ts.map +1 -0
  6. package/dist/core/adapters/clickhouse-adapter.js +58 -0
  7. package/dist/core/adapters/database-adapter.d.ts +13 -0
  8. package/dist/core/adapters/database-adapter.d.ts.map +1 -0
  9. package/dist/core/adapters/database-adapter.js +1 -0
  10. package/dist/core/cache/cache-manager.d.ts.map +1 -1
  11. package/dist/core/cache/cache-manager.js +6 -5
  12. package/dist/core/dialects/clickhouse-dialect.d.ts +10 -0
  13. package/dist/core/dialects/clickhouse-dialect.d.ts.map +1 -0
  14. package/dist/core/dialects/clickhouse-dialect.js +47 -0
  15. package/dist/core/dialects/sql-dialect.d.ts +11 -0
  16. package/dist/core/dialects/sql-dialect.d.ts.map +1 -0
  17. package/dist/core/dialects/sql-dialect.js +1 -0
  18. package/dist/core/features/aggregations.d.ts +5 -5
  19. package/dist/core/features/analytics.d.ts +822 -4
  20. package/dist/core/features/analytics.d.ts.map +1 -1
  21. package/dist/core/features/analytics.js +15 -9
  22. package/dist/core/features/executor.d.ts.map +1 -1
  23. package/dist/core/features/executor.js +26 -53
  24. package/dist/core/features/filtering.d.ts +5 -5
  25. package/dist/core/features/joins.d.ts +1 -1
  26. package/dist/core/features/query-modifiers.d.ts +6 -6
  27. package/dist/core/query-builder.d.ts +20 -7
  28. package/dist/core/query-builder.d.ts.map +1 -1
  29. package/dist/core/query-builder.js +45 -32
  30. package/dist/core/tests/integration/setup.d.ts +3 -1
  31. package/dist/core/tests/integration/setup.d.ts.map +1 -1
  32. package/dist/core/tests/test-utils.d.ts.map +1 -1
  33. package/dist/core/tests/test-utils.js +16 -4
  34. package/dist/core/types/builder-state.d.ts +7 -5
  35. package/dist/core/types/builder-state.d.ts.map +1 -1
  36. package/dist/core/types/select-types.d.ts +4 -3
  37. package/dist/core/types/select-types.d.ts.map +1 -1
  38. package/dist/core/utils/predicate-builder.d.ts +4 -0
  39. package/dist/core/utils/predicate-builder.d.ts.map +1 -1
  40. package/dist/core/utils/predicate-builder.js +4 -1
  41. package/dist/core/utils/streaming-helpers.d.ts.map +1 -1
  42. package/dist/core/utils/streaming-helpers.js +8 -0
  43. package/dist/core/utils.d.ts.map +1 -1
  44. package/dist/core/utils.js +3 -0
  45. package/dist/dataset/definition.d.ts +135 -0
  46. package/dist/dataset/definition.d.ts.map +1 -0
  47. package/dist/dataset/definition.js +265 -0
  48. package/dist/dataset/helpers.d.ts +136 -0
  49. package/dist/dataset/helpers.d.ts.map +1 -0
  50. package/dist/dataset/helpers.js +189 -0
  51. package/dist/dataset/index.d.ts +51 -0
  52. package/dist/dataset/index.d.ts.map +1 -0
  53. package/dist/dataset/index.js +59 -0
  54. package/dist/dataset/introspection.d.ts +133 -0
  55. package/dist/dataset/introspection.d.ts.map +1 -0
  56. package/dist/dataset/introspection.js +239 -0
  57. package/dist/dataset/sql-tag.d.ts +51 -0
  58. package/dist/dataset/sql-tag.d.ts.map +1 -0
  59. package/dist/dataset/sql-tag.js +86 -0
  60. package/dist/dataset/types.d.ts +300 -0
  61. package/dist/dataset/types.d.ts.map +1 -0
  62. package/dist/dataset/types.js +11 -0
  63. package/dist/index.d.ts +21 -0
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +25 -15
  66. package/dist/migrations/config/index.d.ts +3 -0
  67. package/dist/migrations/config/index.d.ts.map +1 -0
  68. package/dist/migrations/config/index.js +1 -0
  69. package/dist/migrations/config/types.d.ts +45 -0
  70. package/dist/migrations/config/types.d.ts.map +1 -0
  71. package/dist/migrations/config/types.js +28 -0
  72. package/dist/migrations/diff/diff.d.ts +11 -0
  73. package/dist/migrations/diff/diff.d.ts.map +1 -0
  74. package/dist/migrations/diff/diff.js +240 -0
  75. package/dist/migrations/diff/index.d.ts +3 -0
  76. package/dist/migrations/diff/index.d.ts.map +1 -0
  77. package/dist/migrations/diff/index.js +1 -0
  78. package/dist/migrations/diff/types.d.ts +74 -0
  79. package/dist/migrations/diff/types.d.ts.map +1 -0
  80. package/dist/migrations/diff/types.js +1 -0
  81. package/dist/migrations/schema/column.d.ts +71 -0
  82. package/dist/migrations/schema/column.d.ts.map +1 -0
  83. package/dist/migrations/schema/column.js +123 -0
  84. package/dist/migrations/schema/define.d.ts +24 -0
  85. package/dist/migrations/schema/define.d.ts.map +1 -0
  86. package/dist/migrations/schema/define.js +47 -0
  87. package/dist/migrations/schema/index.d.ts +4 -0
  88. package/dist/migrations/schema/index.d.ts.map +1 -0
  89. package/dist/migrations/schema/index.js +2 -0
  90. package/dist/migrations/schema/types.d.ts +74 -0
  91. package/dist/migrations/schema/types.d.ts.map +1 -0
  92. package/dist/migrations/schema/types.js +1 -0
  93. package/dist/migrations/snapshot/index.d.ts +3 -0
  94. package/dist/migrations/snapshot/index.d.ts.map +1 -0
  95. package/dist/migrations/snapshot/index.js +1 -0
  96. package/dist/migrations/snapshot/serialize.d.ts +21 -0
  97. package/dist/migrations/snapshot/serialize.d.ts.map +1 -0
  98. package/dist/migrations/snapshot/serialize.js +127 -0
  99. package/dist/migrations/snapshot/types.d.ts +47 -0
  100. package/dist/migrations/snapshot/types.d.ts.map +1 -0
  101. package/dist/migrations/snapshot/types.js +1 -0
  102. package/dist/migrations/sql/index.d.ts +4 -0
  103. package/dist/migrations/sql/index.d.ts.map +1 -0
  104. package/dist/migrations/sql/index.js +2 -0
  105. package/dist/migrations/sql/render.d.ts +11 -0
  106. package/dist/migrations/sql/render.d.ts.map +1 -0
  107. package/dist/migrations/sql/render.js +334 -0
  108. package/dist/migrations/sql/types.d.ts +48 -0
  109. package/dist/migrations/sql/types.d.ts.map +1 -0
  110. package/dist/migrations/sql/types.js +1 -0
  111. package/dist/migrations/sql/write.d.ts +9 -0
  112. package/dist/migrations/sql/write.d.ts.map +1 -0
  113. package/dist/migrations/sql/write.js +31 -0
  114. package/dist/types/base.d.ts +2 -1
  115. package/dist/types/base.d.ts.map +1 -1
  116. package/dist/types/clickhouse-types.d.ts +3 -1
  117. package/dist/types/clickhouse-types.d.ts.map +1 -1
  118. package/package.json +20 -20
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Dataset Introspection API
3
+ *
4
+ * Provides introspection capabilities for datasets, enabling AI agents
5
+ * and other tools to understand the structure and metadata of datasets.
6
+ *
7
+ * Key functions:
8
+ * - getDatasetSchema(): Get full schema for a dataset
9
+ * - listDatasets(): List all available datasets
10
+ * - introspectDimension(): Get metadata for a specific dimension
11
+ * - introspectMetric(): Get metadata for a specific metric
12
+ */
13
+ import { getDataset, listDatasets as listDatasetNames, normalizeDimension, getDimensionSQL, getMetricSQL, } from './definition.js';
14
+ // =============================================================================
15
+ // DIMENSION INTROSPECTION
16
+ // =============================================================================
17
+ /**
18
+ * Introspect a dimension definition to extract metadata
19
+ *
20
+ * @param dimension - Dimension definition (any format)
21
+ * @returns Introspected dimension metadata
22
+ */
23
+ export function introspectDimension(dimension) {
24
+ const normalized = normalizeDimension(dimension);
25
+ return {
26
+ type: normalized.type,
27
+ description: normalized.description || undefined,
28
+ examples: normalized.examples,
29
+ sql: getDimensionSQL(dimension),
30
+ };
31
+ }
32
+ // =============================================================================
33
+ // METRIC INTROSPECTION
34
+ // =============================================================================
35
+ /**
36
+ * Introspect a metric definition to extract metadata
37
+ *
38
+ * @param metric - Metric definition
39
+ * @returns Introspected metric metadata
40
+ */
41
+ export function introspectMetric(metric) {
42
+ return {
43
+ type: 'number',
44
+ aggregationType: metric.type,
45
+ description: metric.description,
46
+ format: metric.format,
47
+ sql: getMetricSQL(metric),
48
+ };
49
+ }
50
+ // =============================================================================
51
+ // DATASET INTROSPECTION
52
+ // =============================================================================
53
+ /**
54
+ * Get the complete schema for a dataset (for AI agents)
55
+ *
56
+ * @param datasets - Map of all dataset definitions
57
+ * @param datasetName - Name of the dataset to introspect
58
+ * @returns Introspected dataset schema
59
+ * @throws Error if dataset not found
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const schema = getDatasetSchema(datasets, 'orders');
64
+ * console.log(schema.dimensions.region.description);
65
+ * console.log(schema.metrics.revenue.format);
66
+ * ```
67
+ */
68
+ export function getDatasetSchema(datasets, datasetName) {
69
+ const dataset = getDataset(datasets, datasetName);
70
+ // Introspect all dimensions
71
+ const dimensions = {};
72
+ for (const [name, dimension] of Object.entries(dataset.dimensions)) {
73
+ dimensions[name] = introspectDimension(dimension);
74
+ }
75
+ // Introspect all metrics
76
+ const metrics = {};
77
+ for (const [name, metric] of Object.entries(dataset.metrics)) {
78
+ metrics[name] = introspectMetric(metric);
79
+ }
80
+ return {
81
+ name: dataset.name,
82
+ description: dataset.description,
83
+ table: dataset.table,
84
+ dimensions,
85
+ metrics,
86
+ tenantRequired: dataset.tenant?.required,
87
+ limits: dataset.limits,
88
+ };
89
+ }
90
+ /**
91
+ * List all available datasets
92
+ *
93
+ * @param datasets - Map of all dataset definitions
94
+ * @returns Array of dataset names
95
+ *
96
+ * @example
97
+ * ```typescript
98
+ * const allDatasets = listDatasets(datasets);
99
+ * // ['orders', 'customers', 'products']
100
+ * ```
101
+ */
102
+ export function listDatasets(datasets) {
103
+ return listDatasetNames(datasets);
104
+ }
105
+ /**
106
+ * Get introspected schemas for all datasets
107
+ *
108
+ * @param datasets - Map of all dataset definitions
109
+ * @returns Map of dataset names to introspected schemas
110
+ *
111
+ * @example
112
+ * ```typescript
113
+ * const allSchemas = getAllDatasetSchemas(datasets);
114
+ * for (const [name, schema] of Object.entries(allSchemas)) {
115
+ * console.log(`Dataset: ${name}`);
116
+ * console.log(`Description: ${schema.description}`);
117
+ * }
118
+ * ```
119
+ */
120
+ export function getAllDatasetSchemas(datasets) {
121
+ const schemas = {};
122
+ for (const name of listDatasetNames(datasets)) {
123
+ schemas[name] = getDatasetSchema(datasets, name);
124
+ }
125
+ return schemas;
126
+ }
127
+ /**
128
+ * Generate a human-readable summary of a dataset (for LLMs)
129
+ *
130
+ * @param datasets - Map of all dataset definitions
131
+ * @param datasetName - Name of the dataset to summarize
132
+ * @returns Markdown-formatted summary
133
+ *
134
+ * @example
135
+ * ```typescript
136
+ * const summary = summarizeDataset(datasets, 'orders');
137
+ * console.log(summary);
138
+ * // # Dataset: orders
139
+ * // Customer orders and revenue data
140
+ * //
141
+ * // ## Dimensions
142
+ * // - region (string): Geographic region
143
+ * // Examples: US, EU, APAC
144
+ * // ...
145
+ * ```
146
+ */
147
+ export function summarizeDataset(datasets, datasetName) {
148
+ const schema = getDatasetSchema(datasets, datasetName);
149
+ const lines = [];
150
+ // Header
151
+ lines.push(`# Dataset: ${schema.name}`);
152
+ lines.push(schema.description);
153
+ lines.push('');
154
+ // Dimensions
155
+ lines.push('## Dimensions');
156
+ for (const [name, dimension] of Object.entries(schema.dimensions)) {
157
+ lines.push(`- ${name} (${dimension.type})${dimension.description ? `: ${dimension.description}` : ''}`);
158
+ if (dimension.examples && dimension.examples.length > 0) {
159
+ lines.push(` Examples: ${dimension.examples.join(', ')}`);
160
+ }
161
+ }
162
+ lines.push('');
163
+ // Metrics
164
+ lines.push('## Metrics');
165
+ for (const [name, metric] of Object.entries(schema.metrics)) {
166
+ lines.push(`- ${name} (${metric.aggregationType})${metric.description ? `: ${metric.description}` : ''}`);
167
+ if (metric.format) {
168
+ lines.push(` Format: ${metric.format}`);
169
+ }
170
+ }
171
+ lines.push('');
172
+ // Constraints
173
+ if (schema.tenantRequired || schema.limits) {
174
+ lines.push('## Constraints');
175
+ if (schema.tenantRequired) {
176
+ lines.push('- Multi-tenancy: Required');
177
+ }
178
+ if (schema.limits) {
179
+ if (schema.limits.maxDimensions) {
180
+ lines.push(`- Max dimensions: ${schema.limits.maxDimensions}`);
181
+ }
182
+ if (schema.limits.maxMetrics) {
183
+ lines.push(`- Max metrics: ${schema.limits.maxMetrics}`);
184
+ }
185
+ if (schema.limits.maxFilters) {
186
+ lines.push(`- Max filters: ${schema.limits.maxFilters}`);
187
+ }
188
+ }
189
+ lines.push('');
190
+ }
191
+ return lines.join('\n');
192
+ }
193
+ /**
194
+ * Generate a JSON representation of all datasets (for AI context)
195
+ *
196
+ * @param datasets - Map of all dataset definitions
197
+ * @returns JSON string with all dataset schemas
198
+ *
199
+ * @example
200
+ * ```typescript
201
+ * const json = datasetsToJSON(datasets);
202
+ * // Send to LLM as context for query generation
203
+ * ```
204
+ */
205
+ export function datasetsToJSON(datasets) {
206
+ const schemas = getAllDatasetSchemas(datasets);
207
+ return JSON.stringify(schemas, null, 2);
208
+ }
209
+ /**
210
+ * Get a concise summary of all datasets (for LLM context)
211
+ *
212
+ * @param datasets - Map of all dataset definitions
213
+ * @returns Array of dataset summaries
214
+ *
215
+ * @example
216
+ * ```typescript
217
+ * const summaries = summarizeAllDatasets(datasets);
218
+ * // [
219
+ * // {
220
+ * // name: 'orders',
221
+ * // description: 'Customer orders and revenue data',
222
+ * // dimensionCount: 5,
223
+ * // metricCount: 4
224
+ * // },
225
+ * // ...
226
+ * // ]
227
+ * ```
228
+ */
229
+ export function summarizeAllDatasets(datasets) {
230
+ return listDatasetNames(datasets).map((name) => {
231
+ const schema = getDatasetSchema(datasets, name);
232
+ return {
233
+ name: schema.name,
234
+ description: schema.description,
235
+ dimensionCount: Object.keys(schema.dimensions).length,
236
+ metricCount: Object.keys(schema.metrics).length,
237
+ };
238
+ });
239
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * SQL Tagged Template Literal
3
+ *
4
+ * Marks a string as a SQL expression rather than a column reference.
5
+ * Used to distinguish between:
6
+ * - Simple column: 'region' (string)
7
+ * - SQL expression: sql`DATE(created_at)` (SQLExpression)
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * dimensions: {
12
+ * region: 'region', // Simple column reference
13
+ * date: sql`DATE(created_at)`, // SQL expression
14
+ * hour: sql`toHour(created_at)` // SQL expression
15
+ * }
16
+ * ```
17
+ */
18
+ /**
19
+ * Represents a SQL expression with metadata
20
+ */
21
+ export interface SQLExpression {
22
+ readonly __brand: 'SQLExpression';
23
+ readonly sql: string;
24
+ readonly raw: boolean;
25
+ }
26
+ /**
27
+ * Tagged template literal for SQL expressions
28
+ *
29
+ * @param strings - Template string array
30
+ * @param values - Interpolated values
31
+ * @returns SQLExpression object
32
+ */
33
+ export declare function sql(strings: TemplateStringsArray, ...values: unknown[]): SQLExpression;
34
+ /**
35
+ * Type guard to check if a value is a SQLExpression
36
+ *
37
+ * @param value - Value to check
38
+ * @returns True if value is a SQLExpression
39
+ */
40
+ export declare function isSQLExpression(value: unknown): value is SQLExpression;
41
+ /**
42
+ * Convert a value to a SQL string
43
+ * - If it's a SQLExpression, return the sql property
44
+ * - If it's a string, return it as-is (assumed to be a column name)
45
+ * - Otherwise, throw an error
46
+ *
47
+ * @param value - Value to convert
48
+ * @returns SQL string
49
+ */
50
+ export declare function toSQLString(value: string | SQLExpression): string;
51
+ //# sourceMappingURL=sql-tag.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql-tag.d.ts","sourceRoot":"","sources":["../../src/dataset/sql-tag.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,OAAO,EAAE,eAAe,CAAC;IAClC,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,GAAG,EAAE,OAAO,CAAC;CACvB;AAED;;;;;;GAMG;AACH,wBAAgB,GAAG,CACjB,OAAO,EAAE,oBAAoB,EAC7B,GAAG,MAAM,EAAE,OAAO,EAAE,GACnB,aAAa,CA+Bf;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAOtE;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,GAAG,MAAM,CAYjE"}
@@ -0,0 +1,86 @@
1
+ /**
2
+ * SQL Tagged Template Literal
3
+ *
4
+ * Marks a string as a SQL expression rather than a column reference.
5
+ * Used to distinguish between:
6
+ * - Simple column: 'region' (string)
7
+ * - SQL expression: sql`DATE(created_at)` (SQLExpression)
8
+ *
9
+ * @example
10
+ * ```typescript
11
+ * dimensions: {
12
+ * region: 'region', // Simple column reference
13
+ * date: sql`DATE(created_at)`, // SQL expression
14
+ * hour: sql`toHour(created_at)` // SQL expression
15
+ * }
16
+ * ```
17
+ */
18
+ /**
19
+ * Tagged template literal for SQL expressions
20
+ *
21
+ * @param strings - Template string array
22
+ * @param values - Interpolated values
23
+ * @returns SQLExpression object
24
+ */
25
+ export function sql(strings, ...values) {
26
+ // Build the SQL string by interleaving strings and values
27
+ let result = strings[0];
28
+ for (let i = 0; i < values.length; i++) {
29
+ const value = values[i];
30
+ // Handle nested SQL expressions
31
+ if (isSQLExpression(value)) {
32
+ result += value.sql;
33
+ }
34
+ else if (typeof value === 'string') {
35
+ // For security, we should escape string values
36
+ // In production, this would use proper escaping
37
+ result += value;
38
+ }
39
+ else if (typeof value === 'number') {
40
+ result += String(value);
41
+ }
42
+ else if (value === null || value === undefined) {
43
+ result += 'NULL';
44
+ }
45
+ else {
46
+ // For other types, convert to string
47
+ result += String(value);
48
+ }
49
+ result += strings[i + 1];
50
+ }
51
+ return {
52
+ __brand: 'SQLExpression',
53
+ sql: result,
54
+ raw: true,
55
+ };
56
+ }
57
+ /**
58
+ * Type guard to check if a value is a SQLExpression
59
+ *
60
+ * @param value - Value to check
61
+ * @returns True if value is a SQLExpression
62
+ */
63
+ export function isSQLExpression(value) {
64
+ return (typeof value === 'object' &&
65
+ value !== null &&
66
+ '__brand' in value &&
67
+ value.__brand === 'SQLExpression');
68
+ }
69
+ /**
70
+ * Convert a value to a SQL string
71
+ * - If it's a SQLExpression, return the sql property
72
+ * - If it's a string, return it as-is (assumed to be a column name)
73
+ * - Otherwise, throw an error
74
+ *
75
+ * @param value - Value to convert
76
+ * @returns SQL string
77
+ */
78
+ export function toSQLString(value) {
79
+ if (typeof value === 'string') {
80
+ return value;
81
+ }
82
+ if (isSQLExpression(value)) {
83
+ return value.sql;
84
+ }
85
+ throw new Error(`Expected string or SQLExpression, got ${typeof value}`);
86
+ }
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Dataset API Type Definitions
3
+ *
4
+ * Comprehensive type system for the dataset API, including:
5
+ * - Dataset definitions
6
+ * - Dimension and metric types
7
+ * - Filter operators and types
8
+ * - Query execution types
9
+ * - Type inference utilities
10
+ */
11
+ import type { SQLExpression } from './sql-tag.js';
12
+ /**
13
+ * Dimension value types
14
+ */
15
+ export type DimensionType = 'string' | 'number' | 'date' | 'boolean';
16
+ /**
17
+ * Simple dimension definition (column name as string)
18
+ */
19
+ export type SimpleDimension = string;
20
+ /**
21
+ * Complex dimension definition with metadata
22
+ */
23
+ export interface DimensionDefinition {
24
+ /** SQL expression or column name */
25
+ sql: string | SQLExpression;
26
+ /** Data type of the dimension */
27
+ type: DimensionType;
28
+ /** Human-readable description (for AI agents) */
29
+ description: string;
30
+ /** Example values (for AI context) */
31
+ examples?: string[];
32
+ /** Whether this dimension requires a join */
33
+ join?: string;
34
+ }
35
+ /**
36
+ * Dimension definition (simple or complex)
37
+ */
38
+ export type Dimension = SimpleDimension | SQLExpression | DimensionDefinition;
39
+ /**
40
+ * Map of dimension names to definitions
41
+ */
42
+ export type DimensionsMap = Record<string, Dimension>;
43
+ /**
44
+ * Supported metric aggregation types
45
+ */
46
+ export type MetricAggregationType = 'count' | 'sum' | 'avg' | 'min' | 'max' | 'countDistinct' | 'custom';
47
+ /**
48
+ * Metric format hints
49
+ */
50
+ export type MetricFormat = 'currency' | 'percent' | 'number' | 'bytes';
51
+ /**
52
+ * Metric definition
53
+ */
54
+ export interface MetricDefinition {
55
+ /** Aggregation type */
56
+ type: MetricAggregationType;
57
+ /** SQL expression or column name */
58
+ sql: string | SQLExpression;
59
+ /** Human-readable description (for AI agents) */
60
+ description: string;
61
+ /** Format hint for display */
62
+ format?: MetricFormat;
63
+ /** Whether this metric requires a join */
64
+ join?: string;
65
+ /** Allow fan-out (for oneToMany joins) - advanced use only */
66
+ allowFanout?: boolean;
67
+ }
68
+ /**
69
+ * Map of metric names to definitions
70
+ */
71
+ export type MetricsMap = Record<string, MetricDefinition>;
72
+ /**
73
+ * Multi-tenancy configuration
74
+ */
75
+ export interface TenantConfig {
76
+ /** Column name for tenant isolation */
77
+ column: string;
78
+ /** Whether tenant filtering is required */
79
+ required?: boolean;
80
+ }
81
+ /**
82
+ * Complexity limits to prevent expensive queries
83
+ */
84
+ export interface DatasetLimits {
85
+ /** Maximum number of dimensions in a query */
86
+ maxDimensions?: number;
87
+ /** Maximum number of metrics in a query */
88
+ maxMetrics?: number;
89
+ /** Maximum number of filters in a query */
90
+ maxFilters?: number;
91
+ /** Maximum result set size */
92
+ maxResultSize?: number;
93
+ }
94
+ /**
95
+ * Complete dataset definition
96
+ */
97
+ export interface DatasetDefinition<TDimensions extends DimensionsMap = DimensionsMap, TMetrics extends MetricsMap = MetricsMap> {
98
+ /** Unique dataset name */
99
+ name: string;
100
+ /** Human-readable description (for AI agents) */
101
+ description: string;
102
+ /** Source table name */
103
+ table: string;
104
+ /** Schema type (for type inference) */
105
+ schema?: unknown;
106
+ /** Dimension definitions */
107
+ dimensions: TDimensions;
108
+ /** Metric definitions */
109
+ metrics: TMetrics;
110
+ /** Multi-tenancy configuration */
111
+ tenant?: TenantConfig;
112
+ /** Complexity guardrails */
113
+ limits?: DatasetLimits;
114
+ }
115
+ /**
116
+ * Map of dataset names to definitions
117
+ */
118
+ export type DatasetsMap = Record<string, DatasetDefinition>;
119
+ /**
120
+ * Filter operator types
121
+ */
122
+ export type FilterOperator = 'eq' | 'ne' | 'gt' | 'lt' | 'gte' | 'lte' | 'in' | 'notIn' | 'between' | 'like' | 'notLike' | 'isNull' | 'isNotNull' | 'inDateRange';
123
+ /**
124
+ * Date range helper values
125
+ */
126
+ export type DateRangeValue = 'today' | 'yesterday' | 'last_7_days' | 'last_30_days' | 'this_week' | 'last_week' | 'this_month' | 'last_month' | 'this_quarter' | 'last_quarter' | 'this_year' | 'last_year' | {
127
+ start: string;
128
+ end: string;
129
+ };
130
+ /**
131
+ * Filter value type based on operator
132
+ */
133
+ export type FilterValue<TOperator extends FilterOperator = FilterOperator> = TOperator extends 'in' | 'notIn' ? unknown[] : TOperator extends 'between' ? [unknown, unknown] : TOperator extends 'isNull' | 'isNotNull' ? never : TOperator extends 'inDateRange' ? DateRangeValue : unknown;
134
+ /**
135
+ * Filter definition
136
+ */
137
+ export interface FilterDefinition<TOperator extends FilterOperator = FilterOperator> {
138
+ /** Dimension to filter on */
139
+ dimension: string;
140
+ /** Filter operator */
141
+ operator: TOperator;
142
+ /** Filter value (type depends on operator) */
143
+ value?: FilterValue<TOperator>;
144
+ }
145
+ /**
146
+ * Array of filters
147
+ */
148
+ export type Filters = FilterDefinition[];
149
+ /**
150
+ * Sort direction
151
+ */
152
+ export type SortDirection = 'asc' | 'desc';
153
+ /**
154
+ * Order by dimension
155
+ */
156
+ export interface OrderByDimension {
157
+ dimension: string;
158
+ direction: SortDirection;
159
+ }
160
+ /**
161
+ * Order by metric
162
+ */
163
+ export interface OrderByMetric {
164
+ metric: string;
165
+ direction: SortDirection;
166
+ }
167
+ /**
168
+ * Order definition (dimension or metric)
169
+ */
170
+ export type OrderBy = OrderByDimension | OrderByMetric;
171
+ /**
172
+ * Cache options for query results
173
+ */
174
+ export interface CacheOptions {
175
+ /** Time-to-live in seconds */
176
+ ttl?: number;
177
+ /** Custom cache key */
178
+ key?: string;
179
+ }
180
+ /**
181
+ * Dataset query definition
182
+ */
183
+ export interface DatasetQuery<TDataset extends DatasetDefinition = DatasetDefinition> {
184
+ /** Dimensions to include in the query */
185
+ dimensions: Array<keyof TDataset['dimensions'] & string>;
186
+ /** Metrics to include in the query */
187
+ metrics: Array<keyof TDataset['metrics'] & string>;
188
+ /** Filters to apply */
189
+ filters?: Filters;
190
+ /** Ordering */
191
+ order?: OrderBy[];
192
+ /** Result limit */
193
+ limit?: number;
194
+ /** Result offset (for pagination) */
195
+ offset?: number;
196
+ /** Cache options */
197
+ cache?: CacheOptions;
198
+ }
199
+ /**
200
+ * Query execution context (for multi-tenancy)
201
+ */
202
+ export interface QueryContext {
203
+ /** Tenant ID for multi-tenant isolation */
204
+ tenantId?: string;
205
+ }
206
+ /**
207
+ * Query result metadata
208
+ */
209
+ export interface QueryResultMetadata {
210
+ /** Dimensions included in the result */
211
+ dimensions: string[];
212
+ /** Metrics included in the result */
213
+ metrics: string[];
214
+ /** Number of rows returned */
215
+ rowCount: number;
216
+ /** Whether the result was served from cache */
217
+ cached: boolean;
218
+ /** Execution time in milliseconds */
219
+ executionTime?: number;
220
+ /** Generated SQL query */
221
+ sql?: string;
222
+ }
223
+ /**
224
+ * Query result
225
+ */
226
+ export interface QueryResult<TRow = Record<string, unknown>> {
227
+ /** Result data */
228
+ data: TRow[];
229
+ /** Result metadata */
230
+ metadata: QueryResultMetadata;
231
+ }
232
+ /**
233
+ * Infer the TypeScript type from a dimension definition
234
+ */
235
+ export type InferDimensionType<T> = T extends string ? string : T extends SQLExpression ? unknown : T extends DimensionDefinition ? T['type'] extends 'string' ? string : T['type'] extends 'number' ? number : T['type'] extends 'date' ? Date : T['type'] extends 'boolean' ? boolean : unknown : unknown;
236
+ /**
237
+ * Infer the TypeScript type from a metric definition
238
+ * All metrics return numbers
239
+ */
240
+ export type InferMetricType<T> = T extends MetricDefinition ? number : number;
241
+ /**
242
+ * Infer the row type from a dataset query
243
+ */
244
+ export type InferQueryRowType<TDataset extends DatasetDefinition, TDimensions extends Array<keyof TDataset['dimensions'] & string>, TMetrics extends Array<keyof TDataset['metrics'] & string>> = {
245
+ [K in TDimensions[number]]: InferDimensionType<TDataset['dimensions'][K]>;
246
+ } & {
247
+ [K in TMetrics[number]]: InferMetricType<TDataset['metrics'][K]>;
248
+ };
249
+ /**
250
+ * Infer the complete result type from a dataset query
251
+ */
252
+ export type InferQueryResult<TDataset extends DatasetDefinition, TQuery extends DatasetQuery<TDataset>> = QueryResult<InferQueryRowType<TDataset, TQuery['dimensions'], TQuery['metrics']>>;
253
+ /**
254
+ * Introspected dimension schema (for AI agents)
255
+ */
256
+ export interface IntrospectedDimension {
257
+ /** Dimension type */
258
+ type: DimensionType;
259
+ /** Human-readable description */
260
+ description?: string;
261
+ /** Example values */
262
+ examples?: string[];
263
+ /** SQL expression */
264
+ sql: string;
265
+ }
266
+ /**
267
+ * Introspected metric schema (for AI agents)
268
+ */
269
+ export interface IntrospectedMetric {
270
+ /** Always 'number' for metrics */
271
+ type: 'number';
272
+ /** Aggregation type */
273
+ aggregationType: MetricAggregationType;
274
+ /** Human-readable description */
275
+ description: string;
276
+ /** Format hint */
277
+ format?: MetricFormat;
278
+ /** SQL expression */
279
+ sql: string;
280
+ }
281
+ /**
282
+ * Introspected dataset schema (for AI agents)
283
+ */
284
+ export interface IntrospectedDataset {
285
+ /** Dataset name */
286
+ name: string;
287
+ /** Dataset description */
288
+ description: string;
289
+ /** Source table */
290
+ table: string;
291
+ /** Introspected dimensions */
292
+ dimensions: Record<string, IntrospectedDimension>;
293
+ /** Introspected metrics */
294
+ metrics: Record<string, IntrospectedMetric>;
295
+ /** Whether multi-tenancy is required */
296
+ tenantRequired?: boolean;
297
+ /** Complexity limits */
298
+ limits?: DatasetLimits;
299
+ }
300
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/dataset/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAMlD;;GAEG;AACH,MAAM,MAAM,aAAa,GAAG,QAAQ,GAAG,QAAQ,GAAG,MAAM,GAAG,SAAS,CAAC;AAErE;;GAEG;AACH,MAAM,MAAM,eAAe,GAAG,M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