|
| 1 | +//! Logical SQL references extracted natively under one adapter's lexical rules. |
| 2 | +
|
| 3 | +use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult}; |
| 4 | +use pyo3::{pyclass, pymethods}; |
| 5 | +use sqlbuild_sqltext::sql_references::main::extract_sql_references::extract_sql_references; |
| 6 | +use sqlbuild_sqltext::sql_references::models::{ReferenceExtraction, SqlReference}; |
| 7 | +use sqlbuild_sqltext::sql_scan::models::LexicalSyntax; |
| 8 | + |
| 9 | +use crate::bindings::_helpers::boundary::panics::compiler_guard; |
| 10 | +use crate::bindings::_helpers::sqltext::lexical_syntax::LexicalSyntaxInput; |
| 11 | + |
| 12 | +/// `(kind, name, package, call_argument_count)` for one reference. |
| 13 | +type ReferenceRow = (&'static str, String, Option<String>, Option<usize>); |
| 14 | +/// The references, or Python's error message; `None` defers the text to Python. |
| 15 | +type ExtractionRow = Option<(Option<Vec<ReferenceRow>>, Option<String>)>; |
| 16 | + |
| 17 | +/// Extracts references under one adapter's lexical rules, read once per syntax. |
| 18 | +#[pyclass(module = "sqlbuild._native", frozen)] |
| 19 | +pub(crate) struct SqlReferenceScanner { |
| 20 | + syntax: LexicalSyntax, |
| 21 | +} |
| 22 | + |
| 23 | +#[pymethods] |
| 24 | +impl SqlReferenceScanner { |
| 25 | + #[new] |
| 26 | + fn new(syntax: LexicalSyntaxInput) -> Self { |
| 27 | + Self { |
| 28 | + syntax: syntax.into(), |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + /// Return `(references, None)`, `(None, message)` when Python raises, or `None` to defer. |
| 33 | + fn extract(&self, sql: &str) -> PyResult<ExtractionRow> { |
| 34 | + compiler_guard(|| { |
| 35 | + Ok(match extract_sql_references(sql, &self.syntax) { |
| 36 | + ReferenceExtraction::Extracted(references) => Some(( |
| 37 | + Some(references.into_iter().map(reference_row).collect()), |
| 38 | + None, |
| 39 | + )), |
| 40 | + ReferenceExtraction::Failed(message) => Some((None, Some(message))), |
| 41 | + ReferenceExtraction::Deferred => None, |
| 42 | + }) |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +fn reference_row(reference: SqlReference) -> ReferenceRow { |
| 48 | + ( |
| 49 | + reference.kind, |
| 50 | + reference.name, |
| 51 | + reference.package, |
| 52 | + reference.call_argument_count, |
| 53 | + ) |
| 54 | +} |
| 55 | + |
| 56 | +pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> { |
| 57 | + module.add_class::<SqlReferenceScanner>()?; |
| 58 | + Ok(()) |
| 59 | +} |
0 commit comments