vlorql_core/schema/snapshot.rs
1//! Database schema snapshots and indexed lookup helpers.
2
3use super::types::DataType;
4use schemars::JsonSchema;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use std::sync::{Arc, OnceLock};
8
9/// Shared ownership type for schema snapshots used by validators and builders.
10pub type ArcSchemaSnapshot = Arc<SchemaSnapshot>;
11
12type TableIndex = HashMap<String, usize>;
13
14fn new_table_index() -> Arc<OnceLock<TableIndex>> {
15 Arc::new(OnceLock::new())
16}
17
18/// A database schema snapshot used for plan validation and prompt construction.
19///
20/// The snapshot owns the table list and lazily builds an internal
21/// `HashMap<name, position>` for O(1) table lookups. The index is
22/// `#[serde(skip)]`'d so it never appears in serialized output and
23/// is rebuilt on demand after deserialization.
24///
25/// # Examples
26///
27/// ```
28/// use vlorql_core::schema::{SchemaSnapshot, TableSchema, ColumnSchema, DataType, SchemaMetadata};
29///
30/// let snapshot = SchemaSnapshot::new(
31/// vec![TableSchema {
32/// name: "users".to_owned(),
33/// columns: vec![ColumnSchema {
34/// name: "id".to_owned(),
35/// data_type: DataType::Int,
36/// nullable: false,
37/// description: None,
38/// is_primary_key: true,
39/// foreign_key: None,
40/// }],
41/// description: None,
42/// primary_key: Some(vec!["id".to_owned()]),
43/// }],
44/// SchemaMetadata::default(),
45/// );
46/// assert_eq!(snapshot.table_count(), 1);
47/// assert!(snapshot.get_table("users").is_some());
48/// assert!(snapshot.get_column("users", "id").is_some());
49/// ```
50#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
51#[serde(deny_unknown_fields)]
52pub struct SchemaSnapshot {
53 /// The serializable representation remains a vector for stable API output.
54 pub tables: Vec<TableSchema>,
55 /// Free-form metadata describing the snapshot's source.
56 #[serde(default)]
57 pub metadata: SchemaMetadata,
58 /// Runtime-only lookup index. It is rebuilt lazily after deserialization.
59 #[serde(skip, default = "new_table_index")]
60 #[schemars(skip)]
61 table_index: Arc<OnceLock<TableIndex>>,
62}
63
64impl Default for SchemaSnapshot {
65 fn default() -> Self {
66 Self::new(Vec::new(), SchemaMetadata::default())
67 }
68}
69
70impl PartialEq for SchemaSnapshot {
71 fn eq(&self, other: &Self) -> bool {
72 self.tables == other.tables && self.metadata == other.metadata
73 }
74}
75
76impl Eq for SchemaSnapshot {}
77
78impl SchemaSnapshot {
79 /// Creates a snapshot and builds its table-name index immediately.
80 pub fn new(tables: Vec<TableSchema>, metadata: SchemaMetadata) -> Self {
81 let snapshot = Self {
82 tables,
83 metadata,
84 table_index: new_table_index(),
85 };
86 snapshot.initialize_index();
87 snapshot
88 }
89
90 /// Replaces the table list and rebuilds the runtime lookup index.
91 pub fn set_tables(&mut self, tables: Vec<TableSchema>) {
92 self.tables = tables;
93 self.table_index = new_table_index();
94 self.initialize_index();
95 }
96
97 /// Rebuilds the runtime lookup index after direct changes to `tables`.
98 pub fn rebuild_index(&mut self) {
99 self.table_index = new_table_index();
100 self.initialize_index();
101 }
102
103 /// Looks up a table by its exact schema name.
104 pub fn get_table(&self, name: &str) -> Option<&TableSchema> {
105 let index = self
106 .table_index
107 .get_or_init(|| build_table_index(&self.tables));
108 index
109 .get(name)
110 .and_then(|position| self.tables.get(*position))
111 }
112
113 /// Looks up a column by table and exact column name.
114 pub fn get_column(&self, table: &str, column: &str) -> Option<&ColumnSchema> {
115 self.get_table(table)?
116 .columns
117 .iter()
118 .find(|candidate| candidate.name == column)
119 }
120
121 /// Returns the number of tables in this snapshot.
122 pub fn table_count(&self) -> usize {
123 self.tables.len()
124 }
125
126 fn initialize_index(&self) {
127 let _ = self.table_index.set(build_table_index(&self.tables));
128 }
129}
130
131fn build_table_index(tables: &[TableSchema]) -> TableIndex {
132 let mut index = HashMap::with_capacity(tables.len());
133 for (position, table) in tables.iter().enumerate() {
134 index.insert(table.name.clone(), position);
135 }
136 index
137}
138
139/// Metadata describing where and when a schema snapshot was produced.
140///
141/// All fields are optional so a deserialized payload may omit any of
142/// them; they exist to help operators audit the source of a snapshot
143/// and are surfaced verbatim in the system prompt.
144#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
145#[serde(deny_unknown_fields)]
146pub struct SchemaMetadata {
147 /// Schema version string (e.g. `"v3"`).
148 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub version: Option<String>,
150 /// Origin of the schema (e.g. the introspection job that produced it).
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub source: Option<String>,
153 /// ISO-8601 timestamp at which the snapshot was generated.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub generated_at: Option<String>,
156}
157
158/// A table and its columns in a schema snapshot.
159#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
160#[serde(deny_unknown_fields)]
161pub struct TableSchema {
162 /// Table name as it appears in the database.
163 pub name: String,
164 /// The column definitions, in the order they should be exposed to the LLM.
165 pub columns: Vec<ColumnSchema>,
166 /// Optional human-readable description of the table's purpose.
167 pub description: Option<String>,
168 /// Optional list of column names that form the primary key.
169 pub primary_key: Option<Vec<String>>,
170}
171
172/// A column and its database-level type and constraints.
173#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
174#[serde(deny_unknown_fields)]
175pub struct ColumnSchema {
176 /// Column name as it appears in the database.
177 pub name: String,
178 /// The SQL data type of the column.
179 pub data_type: DataType,
180 /// Whether the column allows `NULL` values.
181 pub nullable: bool,
182 /// Optional human-readable description of the column's purpose.
183 pub description: Option<String>,
184 /// Whether the column participates in the table's primary key.
185 pub is_primary_key: bool,
186 /// Optional foreign-key reference to another table and column.
187 pub foreign_key: Option<ForeignKey>,
188}
189
190/// A foreign-key reference from one column to another table and column.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
192#[serde(deny_unknown_fields)]
193pub struct ForeignKey {
194 /// The referenced table name.
195 pub foreign_table: String,
196 /// The referenced column name.
197 pub foreign_column: String,
198}