Repository navigation
Expand file tree
/
Copy pathsql_references.rs
More file actions
85 lines (76 loc) · 2.82 KB
/
Copy pathsql_references.rs
File metadata and controls
85 lines (76 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//! Logical SQL references extracted natively under one adapter's lexical rules.
use pyo3::prelude::{Bound, PyModule, PyModuleMethods, PyResult};
use pyo3::{pyclass, pymethods};
use sqlbuild_sqltext::sql_references::main::extract_sql_references::extract_sql_references;
use sqlbuild_sqltext::sql_references::models::{
InvalidReferenceCall, ReferenceExtraction, SqlReference,
};
use sqlbuild_sqltext::sql_scan::models::LexicalSyntax;
use crate::bindings::_helpers::boundary::panics::compiler_guard;
use crate::bindings::_helpers::sqltext::lexical_syntax::LexicalSyntaxInput;
/// `(kind, name, package, call_argument_count)` for one reference.
type ReferenceRow = (&'static str, String, Option<String>, Option<usize>);
/// `(kind, call, start, message, help, corrected_call)` for one rejected call.
type InvalidCallRow = (&'static str, String, usize, String, String, String);
/// The references and rejected calls, or Python's error and its start; `None` defers.
type ExtractionRow = Option<(
Option<(Vec<ReferenceRow>, Vec<InvalidCallRow>)>,
Option<(String, usize)>,
)>;
/// Extracts references under one adapter's lexical rules, read once per syntax.
#[pyclass(module = "sqlbuild._native", frozen)]
pub(crate) struct SqlReferenceScanner {
syntax: LexicalSyntax,
}
#[pymethods]
impl SqlReferenceScanner {
#[new]
fn new(syntax: LexicalSyntaxInput) -> Self {
Self {
syntax: syntax.into(),
}
}
/// Return `((references, rejected calls), None)`, `(None, (message, start))`, or `None`.
fn extract(&self, sql: &str) -> PyResult<ExtractionRow> {
compiler_guard(|| {
Ok(match extract_sql_references(sql, &self.syntax) {
ReferenceExtraction::Extracted(scan) => Some((
Some((
scan.references.into_iter().map(reference_row).collect(),
scan.invalid_calls
.into_iter()
.map(invalid_call_row)
.collect(),
)),
None,
)),
ReferenceExtraction::Failed(failure) => {
Some((None, Some((failure.message, failure.start))))
}
ReferenceExtraction::Deferred => None,
})
})
}
}
fn reference_row(reference: SqlReference) -> ReferenceRow {
(
reference.kind,
reference.name,
reference.package,
reference.call_argument_count,
)
}
fn invalid_call_row(call: InvalidReferenceCall) -> InvalidCallRow {
(
call.kind,
call.call,
call.start,
call.message,
call.help,
call.corrected_call,
)
}
pub(crate) fn register(module: &Bound<'_, PyModule>) -> PyResult<()> {
module.add_class::<SqlReferenceScanner>()?;
Ok(())
}