activecube-rs 0.1.16

A generic GraphQL-to-SQL OLAP query engine library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
use crate::compiler::ir::{JoinType, QueryBuilderFn};

/// Which top-level chain wrapper(s) a cube appears under.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ChainGroup {
    /// EVM chains (eth, bsc, ...) — wrapper carries a `network` argument.
    Evm,
    /// Solana — implicit `sol` chain, no network argument needed.
    Solana,
    /// Cross-chain aggregated cubes (OHLC, TokenStats, ...).
    Trading,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DimType {
    String,
    Int,
    Float,
    /// High-precision decimal — GraphQL filter/output uses String to preserve precision
    Decimal,
    /// Date string (YYYY-MM-DD) with range operators (since/till/after/before)
    Date,
    DateTime,
    Bool,
}

#[derive(Debug, Clone)]
pub struct Dimension {
    pub graphql_name: String,
    pub column: String,
    pub dim_type: DimType,
    pub description: Option<String>,
}

#[derive(Debug, Clone)]
pub enum DimensionNode {
    Leaf(Dimension),
    Group {
        graphql_name: String,
        description: Option<String>,
        children: Vec<DimensionNode>,
    },
    /// Array dimension: maps to parallel ClickHouse Array columns.
    /// Each element is a structured object with fields from aligned arrays.
    Array {
        graphql_name: String,
        description: Option<String>,
        children: Vec<ArrayFieldDef>,
    },
}

/// One field inside an Array dimension, backed by a ClickHouse Array(String) column.
#[derive(Debug, Clone)]
pub struct ArrayFieldDef {
    pub graphql_name: String,
    pub column: String,
    pub field_type: ArrayFieldType,
    pub description: Option<String>,
}

/// Type of an array field: scalar or polymorphic Union.
#[derive(Debug, Clone)]
pub enum ArrayFieldType {
    Scalar(DimType),
    Union(Vec<UnionVariant>),
}

/// One variant of a GraphQL Union type.
#[derive(Debug, Clone)]
pub struct UnionVariant {
    /// GraphQL type name, e.g. "Solana_ABI_Integer_Value_Arg"
    pub type_name: String,
    /// GraphQL field name inside the variant, e.g. "integer"
    pub field_name: String,
    /// Scalar type of the value, e.g. DimType::Int
    pub source_type: DimType,
    /// Source type strings that resolve to this variant (e.g. ["u8", "u16", "u32"]).
    /// Empty means this is the fallback variant (matched when no other variant matches).
    pub source_type_names: Vec<String>,
}

/// A named selector defines a filterable field on a Cube.
/// Each selector maps a GraphQL argument name to a column + type,
/// enabling `eq`, `gt`, `in`, `any` etc.
#[derive(Debug, Clone)]
pub struct SelectorDef {
    pub graphql_name: String,
    pub column: String,
    pub dim_type: DimType,
}

pub fn selector(graphql_name: &str, column: &str, dim_type: DimType) -> SelectorDef {
    SelectorDef {
        graphql_name: graphql_name.to_string(),
        column: column.to_string(),
        dim_type,
    }
}

/// Metric definition — standard SQL aggregate or custom expression.
#[derive(Debug, Clone)]
pub struct MetricDef {
    pub name: String,
    /// If None, uses the standard SQL function (COUNT/SUM/AVG/...).
    /// If Some, uses this SQL template with `{column}` as placeholder.
    /// Example: `"sumIf({column}, direction='in') - sumIf({column}, direction='out')"`
    pub expression_template: Option<String>,
    pub return_type: DimType,
    pub description: Option<String>,
    /// Whether this metric supports conditional aggregation (countIf/sumIf).
    pub supports_where: bool,
}

impl MetricDef {
    pub fn standard(name: &str) -> Self {
        Self {
            name: name.to_string(),
            expression_template: None,
            return_type: DimType::Float,
            description: None,
            supports_where: true,
        }
    }

    pub fn custom(name: &str, expression: &str) -> Self {
        Self {
            name: name.to_string(),
            expression_template: Some(expression.to_string()),
            return_type: DimType::Float,
            description: None,
            supports_where: false,
        }
    }

    pub fn with_description(mut self, desc: &str) -> Self {
        self.description = Some(desc.to_string());
        self
    }

    pub fn with_return_type(mut self, rt: DimType) -> Self {
        self.return_type = rt;
        self
    }
}

/// Helper to create a list of standard metrics from names.
pub fn standard_metrics(names: &[&str]) -> Vec<MetricDef> {
    names.iter().map(|n| MetricDef::standard(n)).collect()
}

/// Multi-table routing: a single Cube can map to different physical tables
/// depending on which columns the query requests.
#[derive(Debug, Clone)]
pub struct TableRoute {
    pub schema: String,
    pub table_pattern: String,
    /// Columns available in this table. If empty, this route serves all queries.
    pub available_columns: Vec<String>,
    /// Lower priority = preferred. The primary table (schema/table_pattern) has implicit priority 0.
    pub priority: u32,
}

/// Declares a JOIN relationship from this cube to another cube.
#[derive(Debug, Clone)]
pub struct JoinDef {
    /// GraphQL field name on the source record, e.g. "joinTransfers"
    pub field_name: String,
    /// Target cube name as registered in the CubeRegistry, e.g. "Transfers"
    pub target_cube: String,
    /// (local_column, remote_column) pairs for the ON clause.
    pub conditions: Vec<(String, String)>,
    pub description: Option<String>,
    /// JOIN type — defaults to Left.
    pub join_type: JoinType,
}

pub fn join_def(field_name: &str, target_cube: &str, conditions: &[(&str, &str)]) -> JoinDef {
    JoinDef {
        field_name: field_name.to_string(),
        target_cube: target_cube.to_string(),
        conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
        description: None,
        join_type: JoinType::Left,
    }
}

pub fn join_def_desc(field_name: &str, target_cube: &str, conditions: &[(&str, &str)], desc: &str) -> JoinDef {
    JoinDef {
        field_name: field_name.to_string(),
        target_cube: target_cube.to_string(),
        conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
        description: Some(desc.to_string()),
        join_type: JoinType::Left,
    }
}

pub fn join_def_typed(
    field_name: &str, target_cube: &str,
    conditions: &[(&str, &str)],
    join_type: JoinType,
) -> JoinDef {
    JoinDef {
        field_name: field_name.to_string(),
        target_cube: target_cube.to_string(),
        conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
        description: None,
        join_type,
    }
}

#[derive(Debug, Clone)]
pub struct CubeDefinition {
    pub name: String,
    pub schema: String,
    /// Table name pattern. Use `{chain}` as placeholder for chain-prefixed tables
    /// (e.g. `{chain}_trades` → `sol_trades`). For tables without chain prefix
    /// (e.g. `dex_pool_liquidities`), use the literal table name and set
    /// `chain_column` instead.
    pub table_pattern: String,
    /// If set, the table doesn't use a `{chain}` prefix in its name. Instead,
    /// the chain is filtered via `WHERE <chain_column> = ?`. Example:
    /// `dex_pool_liquidities` has a `chain` column rather than `sol_dex_pool_liquidities`.
    pub chain_column: Option<String>,
    pub dimensions: Vec<DimensionNode>,
    pub metrics: Vec<MetricDef>,
    pub selectors: Vec<SelectorDef>,
    pub default_filters: Vec<(String, String)>,
    pub default_limit: u32,
    pub max_limit: u32,
    /// Append FINAL to FROM clause for ReplacingMergeTree tables in ClickHouse.
    pub use_final: bool,
    /// Human-readable description of the cube's purpose, exposed via _cubeMetadata.
    pub description: String,
    /// Declarative JOIN relationships to other cubes.
    pub joins: Vec<JoinDef>,
    /// Alternative tables that can serve subsets of this cube's columns.
    /// When non-empty, `resolve_table` picks the best match by requested columns.
    pub table_routes: Vec<TableRoute>,
    /// Custom query builder that bypasses the standard IR → SQL compilation.
    /// Used for cubes requiring window functions, CTEs, or multi-step subqueries.
    pub custom_query_builder: Option<QueryBuilderFn>,
    /// SQL subquery used as the FROM source instead of `schema.table`.
    /// Supports `{schema}` and `{chain}` placeholders expanded at query time.
    /// When set, the compiler generates `FROM ({expanded}) AS _t`.
    pub from_subquery: Option<String>,
    /// Which chain wrapper(s) this cube appears under. Empty = legacy flat mode.
    pub chain_groups: Vec<ChainGroup>,
}

impl CubeDefinition {
    pub fn table_for_chain(&self, chain: &str) -> String {
        self.table_pattern.replace("{chain}", chain)
    }

    pub fn qualified_table(&self, chain: &str) -> String {
        format!("{}.{}", self.schema, self.table_for_chain(chain))
    }

    /// Pick the optimal (schema, table) for a given chain and set of requested columns.
    /// Falls back to the primary schema/table_pattern when no route matches.
    pub fn resolve_table(&self, chain: &str, requested_columns: &[String]) -> (String, String) {
        if self.table_routes.is_empty() {
            return (self.schema.clone(), self.table_for_chain(chain));
        }

        let mut candidates: Vec<&TableRoute> = self.table_routes.iter()
            .filter(|r| {
                r.available_columns.is_empty()
                    || (!requested_columns.is_empty()
                        && requested_columns.iter().all(|c| r.available_columns.contains(c)))
            })
            .collect();

        candidates.sort_by_key(|r| r.priority);

        if let Some(best) = candidates.first() {
            (best.schema.clone(), best.table_pattern.replace("{chain}", chain))
        } else {
            (self.schema.clone(), self.table_for_chain(chain))
        }
    }

    pub fn flat_dimensions(&self) -> Vec<(String, Dimension)> {
        let mut out = Vec::new();
        for node in &self.dimensions {
            collect_leaves(node, "", &mut out);
        }
        out
    }

    /// Check if a metric name exists in this cube's metrics.
    pub fn has_metric(&self, name: &str) -> bool {
        self.metrics.iter().any(|m| m.name == name)
    }

    /// Find a metric definition by name.
    pub fn find_metric(&self, name: &str) -> Option<&MetricDef> {
        self.metrics.iter().find(|m| m.name == name)
    }

    /// Collect all columns used by Array dimensions (parallel arrays).
    /// Returns `(graphql_path, column)` pairs for every array child field.
    pub fn array_columns(&self) -> Vec<(String, String)> {
        let mut out = Vec::new();
        for node in &self.dimensions {
            collect_array_columns(node, "", &mut out);
        }
        out
    }
}

fn collect_array_columns(node: &DimensionNode, prefix: &str, out: &mut Vec<(String, String)>) {
    match node {
        DimensionNode::Leaf(_) => {}
        DimensionNode::Group { graphql_name, children, .. } => {
            let new_prefix = if prefix.is_empty() {
                graphql_name.clone()
            } else {
                format!("{prefix}_{graphql_name}")
            };
            for child in children {
                collect_array_columns(child, &new_prefix, out);
            }
        }
        DimensionNode::Array { graphql_name, children, .. } => {
            let arr_prefix = if prefix.is_empty() {
                graphql_name.clone()
            } else {
                format!("{prefix}_{graphql_name}")
            };
            for af in children {
                out.push((
                    format!("{}_{}", arr_prefix, af.graphql_name),
                    af.column.clone(),
                ));
            }
        }
    }
}

fn collect_leaves(node: &DimensionNode, prefix: &str, out: &mut Vec<(String, Dimension)>) {
    match node {
        DimensionNode::Leaf(dim) => {
            let path = if prefix.is_empty() {
                dim.graphql_name.clone()
            } else {
                format!("{}_{}", prefix, dim.graphql_name)
            };
            out.push((path, dim.clone()));
        }
        DimensionNode::Group { graphql_name, children, .. } => {
            let new_prefix = if prefix.is_empty() {
                graphql_name.clone()
            } else {
                format!("{prefix}_{graphql_name}")
            };
            for child in children {
                collect_leaves(child, &new_prefix, out);
            }
        }
        DimensionNode::Array { .. } => {
            // Array dimensions are not flat leaves; they are resolved
            // via parallel array columns and handled separately in schema generation.
        }
    }
}

// ---------------------------------------------------------------------------
// CubeBuilder — ergonomic builder pattern for CubeDefinition
// ---------------------------------------------------------------------------

pub struct CubeBuilder {
    def: CubeDefinition,
}

impl CubeBuilder {
    pub fn new(name: &str) -> Self {
        Self {
            def: CubeDefinition {
                name: name.to_string(),
                schema: String::new(),
                table_pattern: String::new(),
                chain_column: None,
                dimensions: Vec::new(),
                metrics: Vec::new(),
                selectors: Vec::new(),
                default_filters: Vec::new(),
                default_limit: 25,
                max_limit: 10000,
                use_final: false,
                description: String::new(),
                joins: Vec::new(),
                table_routes: Vec::new(),
                custom_query_builder: None,
                from_subquery: None,
                chain_groups: Vec::new(),
            },
        }
    }

    pub fn schema(mut self, schema: &str) -> Self {
        self.def.schema = schema.to_string();
        self
    }

    pub fn table(mut self, pattern: &str) -> Self {
        self.def.table_pattern = pattern.to_string();
        self
    }

    pub fn chain_column(mut self, column: &str) -> Self {
        self.def.chain_column = Some(column.to_string());
        self
    }

    pub fn dimension(mut self, node: DimensionNode) -> Self {
        self.def.dimensions.push(node);
        self
    }

    /// Add a standard metric (count, sum, avg, min, max, uniq).
    pub fn metric(mut self, name: &str) -> Self {
        self.def.metrics.push(MetricDef::standard(name));
        self
    }

    /// Add multiple standard metrics by name.
    pub fn metrics(mut self, names: &[&str]) -> Self {
        self.def.metrics.extend(names.iter().map(|s| MetricDef::standard(s)));
        self
    }

    /// Add a custom metric with an SQL expression template.
    pub fn custom_metric(mut self, def: MetricDef) -> Self {
        self.def.metrics.push(def);
        self
    }

    pub fn selector(mut self, sel: SelectorDef) -> Self {
        self.def.selectors.push(sel);
        self
    }

    pub fn default_filter(mut self, column: &str, value: &str) -> Self {
        self.def.default_filters.push((column.to_string(), value.to_string()));
        self
    }

    pub fn default_limit(mut self, limit: u32) -> Self {
        self.def.default_limit = limit;
        self
    }

    pub fn max_limit(mut self, limit: u32) -> Self {
        self.def.max_limit = limit;
        self
    }

    pub fn use_final(mut self, val: bool) -> Self {
        self.def.use_final = val;
        self
    }

    pub fn description(mut self, desc: &str) -> Self {
        self.def.description = desc.to_string();
        self
    }

    pub fn join(mut self, j: JoinDef) -> Self {
        self.def.joins.push(j);
        self
    }

    pub fn joins(mut self, js: Vec<JoinDef>) -> Self {
        self.def.joins.extend(js);
        self
    }

    pub fn table_route(mut self, route: TableRoute) -> Self {
        self.def.table_routes.push(route);
        self
    }

    pub fn custom_query_builder(mut self, builder: QueryBuilderFn) -> Self {
        self.def.custom_query_builder = Some(builder);
        self
    }

    pub fn from_subquery(mut self, subquery_sql: &str) -> Self {
        self.def.from_subquery = Some(subquery_sql.to_string());
        self
    }

    pub fn chain_groups(mut self, groups: Vec<ChainGroup>) -> Self {
        self.def.chain_groups = groups;
        self
    }

    pub fn build(self) -> CubeDefinition {
        self.def
    }
}

// ---------------------------------------------------------------------------
// Helper functions for concise dimension/selector construction
// ---------------------------------------------------------------------------

pub fn dim(graphql_name: &str, column: &str, dim_type: DimType) -> DimensionNode {
    DimensionNode::Leaf(Dimension {
        graphql_name: graphql_name.to_string(),
        column: column.to_string(),
        dim_type,
        description: None,
    })
}

pub fn dim_desc(graphql_name: &str, column: &str, dim_type: DimType, desc: &str) -> DimensionNode {
    DimensionNode::Leaf(Dimension {
        graphql_name: graphql_name.to_string(),
        column: column.to_string(),
        dim_type,
        description: Some(desc.to_string()),
    })
}

pub fn dim_group(graphql_name: &str, children: Vec<DimensionNode>) -> DimensionNode {
    DimensionNode::Group {
        graphql_name: graphql_name.to_string(),
        description: None,
        children,
    }
}

pub fn dim_group_desc(graphql_name: &str, desc: &str, children: Vec<DimensionNode>) -> DimensionNode {
    DimensionNode::Group {
        graphql_name: graphql_name.to_string(),
        description: Some(desc.to_string()),
        children,
    }
}

pub fn dim_array(graphql_name: &str, children: Vec<ArrayFieldDef>) -> DimensionNode {
    DimensionNode::Array {
        graphql_name: graphql_name.to_string(),
        description: None,
        children,
    }
}

pub fn dim_array_desc(graphql_name: &str, desc: &str, children: Vec<ArrayFieldDef>) -> DimensionNode {
    DimensionNode::Array {
        graphql_name: graphql_name.to_string(),
        description: Some(desc.to_string()),
        children,
    }
}

pub fn array_field(graphql_name: &str, column: &str, field_type: ArrayFieldType) -> ArrayFieldDef {
    ArrayFieldDef {
        graphql_name: graphql_name.to_string(),
        column: column.to_string(),
        field_type,
        description: None,
    }
}

pub fn array_field_desc(graphql_name: &str, column: &str, field_type: ArrayFieldType, desc: &str) -> ArrayFieldDef {
    ArrayFieldDef {
        graphql_name: graphql_name.to_string(),
        column: column.to_string(),
        field_type,
        description: Some(desc.to_string()),
    }
}

/// Create a Union variant without explicit source-type matching (fallback-only).
pub fn variant(type_name: &str, field_name: &str, source_type: DimType) -> UnionVariant {
    UnionVariant {
        type_name: type_name.to_string(),
        field_name: field_name.to_string(),
        source_type,
        source_type_names: vec![],
    }
}

/// Create a Union variant with explicit source-type string matching.
/// When the discriminator column value matches any of `source_names`,
/// this variant is selected.
pub fn variant_matching(
    type_name: &str,
    field_name: &str,
    source_type: DimType,
    source_names: &[&str],
) -> UnionVariant {
    UnionVariant {
        type_name: type_name.to_string(),
        field_name: field_name.to_string(),
        source_type,
        source_type_names: source_names.iter().map(|s| s.to_string()).collect(),
    }
}