dbml_rs/utils/
mod.rs

1use crate::analyzer::*;
2use crate::ast::*;
3
4/// Gets all relations associated with a table, including references to other tables, references from other tables, and self-references.
5///
6/// # Arguments
7///
8/// * `table_ident` - A reference to the table identifier for which relations are to be fetched.
9/// * `analyzed_indexer` - A reference to the analyzed indexer containing information about indexed references.
10///
11/// # Returns
12///
13/// A `TableRef` struct containing three vectors of `block::IndexedRefBlock` instances.
14///
15/// # Examples
16///
17/// ```rs
18/// use dbml_rs::{get_table_refs, TableIdent, AnalyzedIndexer};
19///
20/// let table_ident = TableIdent {
21///     span_range: 0..0,
22///     name: "users".to_string(),
23///     schema: Some("public".to_string()),
24///     alias: None,
25/// };
26///
27/// let analyzed_indexer = AnalyzedIndexer::default(); // Assuming some analyzed indexer is available
28///
29/// let table_refs = get_table_refs(&table_ident, &analyzed_indexer);
30/// // Now `table_refs` contains all relations associated with the specified table.
31/// ```
32pub fn get_table_refs(table_ident: &TableIdent, analyzed_indexer: &AnalyzedIndexer) -> TableRef {
33  let mut ref_to_blocks = vec![];
34  let mut ref_by_blocks = vec![];
35  let mut ref_self_blocks = vec![];
36
37  let eq = |table_ident: &TableIdent, ref_ident: &RefIdent| {
38    table_ident.schema.clone().map(|s| s.to_string) == ref_ident.schema.clone().map(|s| s.to_string)
39      && table_ident.name.to_string == ref_ident.table.to_string
40  };
41
42  for ref_block in analyzed_indexer.indexed_refs.iter() {
43    let lhs_ident = analyzed_indexer.indexer.resolve_ref_alias(&ref_block.lhs);
44    let rhs_ident = analyzed_indexer.indexer.resolve_ref_alias(&ref_block.rhs);
45
46    if eq(table_ident, &lhs_ident) && eq(table_ident, &rhs_ident) {
47      ref_self_blocks.push(ref_block.clone())
48    } else if eq(table_ident, &lhs_ident) {
49      ref_to_blocks.push(ref_block.clone())
50    } else if eq(table_ident, &rhs_ident) {
51      ref_by_blocks.push(ref_block.clone())
52    }
53  }
54
55  TableRef {
56    ref_to: ref_to_blocks,
57    ref_by: ref_by_blocks,
58    ref_self: ref_self_blocks,
59  }
60}