no-mistakes-postgres-engine 0.109.130

PostgreSQL embedded SQL extraction, schema catalog, and replay-safety analysis for no-mistakes
Documentation
use std::collections::BTreeMap;

#[derive(Debug, Clone, Default)]
pub(super) struct CatalogLocations {
    pub(super) views: BTreeMap<String, usize>,
    pub(super) tables: BTreeMap<String, usize>,
    pub(super) columns: BTreeMap<(String, String), usize>,
}

pub(super) fn catalog_locations(
    value: &jsonc_parser::ast::Value<'_>,
    source: &str,
) -> CatalogLocations {
    let object = |key| {
        value
            .as_object()
            .and_then(|snapshot| snapshot.get(key))
            .and_then(|property| property.value.as_object())
    };
    let line_starts = source
        .bytes()
        .enumerate()
        .filter_map(|(index, byte)| (byte == b'\n').then_some(index + 1))
        .collect::<Vec<_>>();
    let mut locations = CatalogLocations::default();
    for table in object("tables")
        .into_iter()
        .flat_map(|tables| &tables.properties)
    {
        let table_name = table.name.as_str().to_string();
        let table_line = line_starts.partition_point(|start| *start <= table.range.start) + 1;
        locations.tables.insert(table_name.clone(), table_line);
        let Some(columns) = table
            .value
            .as_object()
            .and_then(|value| value.get("columns"))
            .and_then(|columns| columns.value.as_object())
        else {
            continue;
        };
        for column in &columns.properties {
            let line = line_starts.partition_point(|start| *start <= column.range.start) + 1;
            locations
                .columns
                .insert((table_name.clone(), column.name.as_str().to_string()), line);
        }
    }
    if let Some(views) = object("views") {
        for view in &views.properties {
            let line = line_starts.partition_point(|start| *start <= view.range.start) + 1;
            locations.views.insert(view.name.as_str().to_string(), line);
        }
    }
    locations
}
impl super::SchemaCatalog {
    pub fn table_line(&self, table: &str) -> usize {
        self.locations.tables.get(table).copied().unwrap_or(1)
    }

    pub fn column_line(&self, table: &str, column: &str) -> usize {
        self.locations
            .columns
            .get(&(table.to_string(), column.to_string()))
            .copied()
            .unwrap_or(1)
    }
}