1use crate::compiler::ir::{JoinType, QueryBuilderFn};
2
3#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5pub enum ChainGroup {
6 Evm,
8 Solana,
10 Trading,
12}
13
14#[derive(Debug, Clone, PartialEq, Eq)]
15pub enum DimType {
16 String,
17 Int,
18 Float,
19 DateTime,
20 Bool,
21}
22
23#[derive(Debug, Clone)]
24pub struct Dimension {
25 pub graphql_name: String,
26 pub column: String,
27 pub dim_type: DimType,
28 pub description: Option<String>,
29}
30
31#[derive(Debug, Clone)]
32pub enum DimensionNode {
33 Leaf(Dimension),
34 Group {
35 graphql_name: String,
36 description: Option<String>,
37 children: Vec<DimensionNode>,
38 },
39 Array {
42 graphql_name: String,
43 description: Option<String>,
44 children: Vec<ArrayFieldDef>,
45 },
46}
47
48#[derive(Debug, Clone)]
50pub struct ArrayFieldDef {
51 pub graphql_name: String,
52 pub column: String,
53 pub field_type: ArrayFieldType,
54 pub description: Option<String>,
55}
56
57#[derive(Debug, Clone)]
59pub enum ArrayFieldType {
60 Scalar(DimType),
61 Union(Vec<UnionVariant>),
62}
63
64#[derive(Debug, Clone)]
66pub struct UnionVariant {
67 pub type_name: String,
69 pub field_name: String,
71 pub source_type: DimType,
73}
74
75#[derive(Debug, Clone)]
79pub struct SelectorDef {
80 pub graphql_name: String,
81 pub column: String,
82 pub dim_type: DimType,
83}
84
85pub fn selector(graphql_name: &str, column: &str, dim_type: DimType) -> SelectorDef {
86 SelectorDef {
87 graphql_name: graphql_name.to_string(),
88 column: column.to_string(),
89 dim_type,
90 }
91}
92
93#[derive(Debug, Clone)]
95pub struct MetricDef {
96 pub name: String,
97 pub expression_template: Option<String>,
101 pub return_type: DimType,
102 pub description: Option<String>,
103 pub supports_where: bool,
105}
106
107impl MetricDef {
108 pub fn standard(name: &str) -> Self {
109 Self {
110 name: name.to_string(),
111 expression_template: None,
112 return_type: DimType::Float,
113 description: None,
114 supports_where: true,
115 }
116 }
117
118 pub fn custom(name: &str, expression: &str) -> Self {
119 Self {
120 name: name.to_string(),
121 expression_template: Some(expression.to_string()),
122 return_type: DimType::Float,
123 description: None,
124 supports_where: false,
125 }
126 }
127
128 pub fn with_description(mut self, desc: &str) -> Self {
129 self.description = Some(desc.to_string());
130 self
131 }
132
133 pub fn with_return_type(mut self, rt: DimType) -> Self {
134 self.return_type = rt;
135 self
136 }
137}
138
139pub fn standard_metrics(names: &[&str]) -> Vec<MetricDef> {
141 names.iter().map(|n| MetricDef::standard(n)).collect()
142}
143
144#[derive(Debug, Clone)]
147pub struct TableRoute {
148 pub schema: String,
149 pub table_pattern: String,
150 pub available_columns: Vec<String>,
152 pub priority: u32,
154}
155
156#[derive(Debug, Clone)]
158pub struct JoinDef {
159 pub field_name: String,
161 pub target_cube: String,
163 pub conditions: Vec<(String, String)>,
165 pub description: Option<String>,
166 pub join_type: JoinType,
168}
169
170pub fn join_def(field_name: &str, target_cube: &str, conditions: &[(&str, &str)]) -> JoinDef {
171 JoinDef {
172 field_name: field_name.to_string(),
173 target_cube: target_cube.to_string(),
174 conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
175 description: None,
176 join_type: JoinType::Left,
177 }
178}
179
180pub fn join_def_desc(field_name: &str, target_cube: &str, conditions: &[(&str, &str)], desc: &str) -> JoinDef {
181 JoinDef {
182 field_name: field_name.to_string(),
183 target_cube: target_cube.to_string(),
184 conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
185 description: Some(desc.to_string()),
186 join_type: JoinType::Left,
187 }
188}
189
190pub fn join_def_typed(
191 field_name: &str, target_cube: &str,
192 conditions: &[(&str, &str)],
193 join_type: JoinType,
194) -> JoinDef {
195 JoinDef {
196 field_name: field_name.to_string(),
197 target_cube: target_cube.to_string(),
198 conditions: conditions.iter().map(|(l, r)| (l.to_string(), r.to_string())).collect(),
199 description: None,
200 join_type,
201 }
202}
203
204#[derive(Debug, Clone)]
205pub struct CubeDefinition {
206 pub name: String,
207 pub schema: String,
208 pub table_pattern: String,
213 pub chain_column: Option<String>,
217 pub dimensions: Vec<DimensionNode>,
218 pub metrics: Vec<MetricDef>,
219 pub selectors: Vec<SelectorDef>,
220 pub default_filters: Vec<(String, String)>,
221 pub default_limit: u32,
222 pub max_limit: u32,
223 pub use_final: bool,
225 pub description: String,
227 pub joins: Vec<JoinDef>,
229 pub table_routes: Vec<TableRoute>,
232 pub custom_query_builder: Option<QueryBuilderFn>,
235 pub from_subquery: Option<String>,
239 pub chain_groups: Vec<ChainGroup>,
241}
242
243impl CubeDefinition {
244 pub fn table_for_chain(&self, chain: &str) -> String {
245 self.table_pattern.replace("{chain}", chain)
246 }
247
248 pub fn qualified_table(&self, chain: &str) -> String {
249 format!("{}.{}", self.schema, self.table_for_chain(chain))
250 }
251
252 pub fn resolve_table(&self, chain: &str, requested_columns: &[String]) -> (String, String) {
255 if self.table_routes.is_empty() {
256 return (self.schema.clone(), self.table_for_chain(chain));
257 }
258
259 let mut candidates: Vec<&TableRoute> = self.table_routes.iter()
260 .filter(|r| {
261 r.available_columns.is_empty()
262 || requested_columns.iter().all(|c| r.available_columns.contains(c))
263 })
264 .collect();
265
266 candidates.sort_by_key(|r| r.priority);
267
268 if let Some(best) = candidates.first() {
269 (best.schema.clone(), best.table_pattern.replace("{chain}", chain))
270 } else {
271 (self.schema.clone(), self.table_for_chain(chain))
272 }
273 }
274
275 pub fn flat_dimensions(&self) -> Vec<(String, Dimension)> {
276 let mut out = Vec::new();
277 for node in &self.dimensions {
278 collect_leaves(node, "", &mut out);
279 }
280 out
281 }
282
283 pub fn has_metric(&self, name: &str) -> bool {
285 self.metrics.iter().any(|m| m.name == name)
286 }
287
288 pub fn find_metric(&self, name: &str) -> Option<&MetricDef> {
290 self.metrics.iter().find(|m| m.name == name)
291 }
292}
293
294fn collect_leaves(node: &DimensionNode, prefix: &str, out: &mut Vec<(String, Dimension)>) {
295 match node {
296 DimensionNode::Leaf(dim) => {
297 let path = if prefix.is_empty() {
298 dim.graphql_name.clone()
299 } else {
300 format!("{}_{}", prefix, dim.graphql_name)
301 };
302 out.push((path, dim.clone()));
303 }
304 DimensionNode::Group { graphql_name, children, .. } => {
305 let new_prefix = if prefix.is_empty() {
306 graphql_name.clone()
307 } else {
308 format!("{prefix}_{graphql_name}")
309 };
310 for child in children {
311 collect_leaves(child, &new_prefix, out);
312 }
313 }
314 DimensionNode::Array { .. } => {
315 }
318 }
319}
320
321pub struct CubeBuilder {
326 def: CubeDefinition,
327}
328
329impl CubeBuilder {
330 pub fn new(name: &str) -> Self {
331 Self {
332 def: CubeDefinition {
333 name: name.to_string(),
334 schema: String::new(),
335 table_pattern: String::new(),
336 chain_column: None,
337 dimensions: Vec::new(),
338 metrics: Vec::new(),
339 selectors: Vec::new(),
340 default_filters: Vec::new(),
341 default_limit: 25,
342 max_limit: 10000,
343 use_final: false,
344 description: String::new(),
345 joins: Vec::new(),
346 table_routes: Vec::new(),
347 custom_query_builder: None,
348 from_subquery: None,
349 chain_groups: Vec::new(),
350 },
351 }
352 }
353
354 pub fn schema(mut self, schema: &str) -> Self {
355 self.def.schema = schema.to_string();
356 self
357 }
358
359 pub fn table(mut self, pattern: &str) -> Self {
360 self.def.table_pattern = pattern.to_string();
361 self
362 }
363
364 pub fn chain_column(mut self, column: &str) -> Self {
365 self.def.chain_column = Some(column.to_string());
366 self
367 }
368
369 pub fn dimension(mut self, node: DimensionNode) -> Self {
370 self.def.dimensions.push(node);
371 self
372 }
373
374 pub fn metric(mut self, name: &str) -> Self {
376 self.def.metrics.push(MetricDef::standard(name));
377 self
378 }
379
380 pub fn metrics(mut self, names: &[&str]) -> Self {
382 self.def.metrics.extend(names.iter().map(|s| MetricDef::standard(s)));
383 self
384 }
385
386 pub fn custom_metric(mut self, def: MetricDef) -> Self {
388 self.def.metrics.push(def);
389 self
390 }
391
392 pub fn selector(mut self, sel: SelectorDef) -> Self {
393 self.def.selectors.push(sel);
394 self
395 }
396
397 pub fn default_filter(mut self, column: &str, value: &str) -> Self {
398 self.def.default_filters.push((column.to_string(), value.to_string()));
399 self
400 }
401
402 pub fn default_limit(mut self, limit: u32) -> Self {
403 self.def.default_limit = limit;
404 self
405 }
406
407 pub fn max_limit(mut self, limit: u32) -> Self {
408 self.def.max_limit = limit;
409 self
410 }
411
412 pub fn use_final(mut self, val: bool) -> Self {
413 self.def.use_final = val;
414 self
415 }
416
417 pub fn description(mut self, desc: &str) -> Self {
418 self.def.description = desc.to_string();
419 self
420 }
421
422 pub fn join(mut self, j: JoinDef) -> Self {
423 self.def.joins.push(j);
424 self
425 }
426
427 pub fn joins(mut self, js: Vec<JoinDef>) -> Self {
428 self.def.joins.extend(js);
429 self
430 }
431
432 pub fn table_route(mut self, route: TableRoute) -> Self {
433 self.def.table_routes.push(route);
434 self
435 }
436
437 pub fn custom_query_builder(mut self, builder: QueryBuilderFn) -> Self {
438 self.def.custom_query_builder = Some(builder);
439 self
440 }
441
442 pub fn from_subquery(mut self, subquery_sql: &str) -> Self {
443 self.def.from_subquery = Some(subquery_sql.to_string());
444 self
445 }
446
447 pub fn chain_groups(mut self, groups: Vec<ChainGroup>) -> Self {
448 self.def.chain_groups = groups;
449 self
450 }
451
452 pub fn build(self) -> CubeDefinition {
453 self.def
454 }
455}
456
457pub fn dim(graphql_name: &str, column: &str, dim_type: DimType) -> DimensionNode {
462 DimensionNode::Leaf(Dimension {
463 graphql_name: graphql_name.to_string(),
464 column: column.to_string(),
465 dim_type,
466 description: None,
467 })
468}
469
470pub fn dim_desc(graphql_name: &str, column: &str, dim_type: DimType, desc: &str) -> DimensionNode {
471 DimensionNode::Leaf(Dimension {
472 graphql_name: graphql_name.to_string(),
473 column: column.to_string(),
474 dim_type,
475 description: Some(desc.to_string()),
476 })
477}
478
479pub fn dim_group(graphql_name: &str, children: Vec<DimensionNode>) -> DimensionNode {
480 DimensionNode::Group {
481 graphql_name: graphql_name.to_string(),
482 description: None,
483 children,
484 }
485}
486
487pub fn dim_group_desc(graphql_name: &str, desc: &str, children: Vec<DimensionNode>) -> DimensionNode {
488 DimensionNode::Group {
489 graphql_name: graphql_name.to_string(),
490 description: Some(desc.to_string()),
491 children,
492 }
493}
494
495pub fn dim_array(graphql_name: &str, children: Vec<ArrayFieldDef>) -> DimensionNode {
496 DimensionNode::Array {
497 graphql_name: graphql_name.to_string(),
498 description: None,
499 children,
500 }
501}
502
503pub fn dim_array_desc(graphql_name: &str, desc: &str, children: Vec<ArrayFieldDef>) -> DimensionNode {
504 DimensionNode::Array {
505 graphql_name: graphql_name.to_string(),
506 description: Some(desc.to_string()),
507 children,
508 }
509}
510
511pub fn array_field(graphql_name: &str, column: &str, field_type: ArrayFieldType) -> ArrayFieldDef {
512 ArrayFieldDef {
513 graphql_name: graphql_name.to_string(),
514 column: column.to_string(),
515 field_type,
516 description: None,
517 }
518}
519
520pub fn array_field_desc(graphql_name: &str, column: &str, field_type: ArrayFieldType, desc: &str) -> ArrayFieldDef {
521 ArrayFieldDef {
522 graphql_name: graphql_name.to_string(),
523 column: column.to_string(),
524 field_type,
525 description: Some(desc.to_string()),
526 }
527}
528
529pub fn variant(type_name: &str, field_name: &str, source_type: DimType) -> UnionVariant {
530 UnionVariant {
531 type_name: type_name.to_string(),
532 field_name: field_name.to_string(),
533 source_type,
534 }
535}