Skip to main content

no_mistakes_postgres_engine/catalog/
locations.rs

1use std::collections::BTreeMap;
2
3#[derive(Debug, Clone, Default)]
4pub(super) struct CatalogLocations {
5    pub(super) views: BTreeMap<String, usize>,
6    pub(super) tables: BTreeMap<String, usize>,
7    pub(super) columns: BTreeMap<(String, String), usize>,
8}
9
10pub(super) fn catalog_locations(
11    value: &jsonc_parser::ast::Value<'_>,
12    source: &str,
13) -> CatalogLocations {
14    let object = |key| {
15        value
16            .as_object()
17            .and_then(|snapshot| snapshot.get(key))
18            .and_then(|property| property.value.as_object())
19    };
20    let line_starts = source
21        .bytes()
22        .enumerate()
23        .filter_map(|(index, byte)| (byte == b'\n').then_some(index + 1))
24        .collect::<Vec<_>>();
25    let mut locations = CatalogLocations::default();
26    for table in object("tables")
27        .into_iter()
28        .flat_map(|tables| &tables.properties)
29    {
30        let table_name = table.name.as_str().to_string();
31        let table_line = line_starts.partition_point(|start| *start <= table.range.start) + 1;
32        locations.tables.insert(table_name.clone(), table_line);
33        let Some(columns) = table
34            .value
35            .as_object()
36            .and_then(|value| value.get("columns"))
37            .and_then(|columns| columns.value.as_object())
38        else {
39            continue;
40        };
41        for column in &columns.properties {
42            let line = line_starts.partition_point(|start| *start <= column.range.start) + 1;
43            locations
44                .columns
45                .insert((table_name.clone(), column.name.as_str().to_string()), line);
46        }
47    }
48    if let Some(views) = object("views") {
49        for view in &views.properties {
50            let line = line_starts.partition_point(|start| *start <= view.range.start) + 1;
51            locations.views.insert(view.name.as_str().to_string(), line);
52        }
53    }
54    locations
55}
56impl super::SchemaCatalog {
57    pub fn table_line(&self, table: &str) -> usize {
58        self.locations.tables.get(table).copied().unwrap_or(1)
59    }
60
61    pub fn column_line(&self, table: &str, column: &str) -> usize {
62        self.locations
63            .columns
64            .get(&(table.to_string(), column.to_string()))
65            .copied()
66            .unwrap_or(1)
67    }
68}