Skip to main content

postgres_mcp/
typeinfo.rs

1//! Resolves column type OIDs: built-ins from the static table, other types from pg_type, cached per OID.
2// WireError holds DbError by value, which is large (fixed by the wire interface).
3#![allow(clippy::result_large_err)]
4
5use std::collections::{HashMap, HashSet};
6use std::sync::Mutex;
7use std::sync::atomic::{AtomicU64, Ordering};
8
9use crate::encode::{TypeInfo, TypeKind, builtin_type};
10use crate::pg::wire::{Connection, WireError};
11
12/// Depth limit for element, domain-base and range-subtype chains; deeper types decode as Text.
13const MAX_DEPTH: usize = 8;
14
15/// Non-built-in types already looked up in pg_type. Unresolvable OIDs are never stored.
16pub struct TypeCache {
17    entries: Mutex<HashMap<u32, TypeInfo>>,
18    lookups: AtomicU64,
19}
20
21impl TypeCache {
22    pub fn new() -> TypeCache {
23        TypeCache {
24            entries: Mutex::new(HashMap::new()),
25            lookups: AtomicU64::new(0),
26        }
27    }
28
29    /// Number of pg_type queries sent on behalf of this cache.
30    pub fn lookups(&self) -> u64 {
31        self.lookups.load(Ordering::Relaxed)
32    }
33
34    /// TypeInfo for each OID, in order. Unknown OIDs become name "unknown" with kind Text, uncached.
35    pub async fn resolve(
36        &self,
37        conn: &mut Connection,
38        oids: &[u32],
39    ) -> Result<Vec<TypeInfo>, WireError> {
40        let mut found: HashMap<u32, TypeInfo> = HashMap::new();
41        let mut pending: Vec<u32> = Vec::new();
42        {
43            let entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
44            let mut seen = HashSet::new();
45            for &oid in oids {
46                if builtin_type(oid).is_some() || !seen.insert(oid) {
47                    continue;
48                }
49                match entries.get(&oid) {
50                    Some(info) => {
51                        found.insert(oid, info.clone());
52                    }
53                    None => pending.push(oid),
54                }
55            }
56        }
57        if !pending.is_empty() {
58            let rows = self.load_catalog(conn, &pending).await?;
59            let mut entries = self.entries.lock().unwrap_or_else(|e| e.into_inner());
60            for &oid in &pending {
61                if let Some(info) = build(oid, 0, &rows) {
62                    entries.insert(oid, info.clone());
63                    found.insert(oid, info);
64                }
65            }
66        }
67        Ok(oids
68            .iter()
69            .map(|&oid| {
70                builtin_type(oid)
71                    .or_else(|| found.get(&oid).cloned())
72                    .unwrap_or_else(|| unknown(oid))
73            })
74            .collect())
75    }
76
77    /// One pg_type query per batch; follow-up batches fetch the element, base and subtype OIDs.
78    async fn load_catalog(
79        &self,
80        conn: &mut Connection,
81        pending: &[u32],
82    ) -> Result<HashMap<u32, CatalogRow>, WireError> {
83        let mut rows = HashMap::new();
84        let mut asked: HashSet<u32> = pending.iter().copied().collect();
85        let mut batch: Vec<u32> = pending.to_vec();
86        for _ in 0..=MAX_DEPTH {
87            if batch.is_empty() {
88                break;
89            }
90            self.lookups.fetch_add(1, Ordering::Relaxed);
91            let fetched = query_catalog(conn, &batch).await?;
92            let mut next = Vec::new();
93            for row in fetched {
94                for child in row.children() {
95                    if builtin_type(child).is_none() && asked.insert(child) {
96                        next.push(child);
97                    }
98                }
99                rows.insert(row.oid, row);
100            }
101            batch = next;
102        }
103        Ok(rows)
104    }
105}
106
107impl Default for TypeCache {
108    fn default() -> Self {
109        Self::new()
110    }
111}
112
113/// One pg_type row with the fields the mapping needs.
114struct CatalogRow {
115    oid: u32,
116    name: String,
117    typtype: char,
118    elem: u32,
119    delim: char,
120    base: u32,
121    array_in: bool,
122    range_sub: Option<u32>,
123}
124
125impl CatalogRow {
126    /// OIDs this row's mapping refers to, zero excluded.
127    fn children(&self) -> Vec<u32> {
128        let refs = if self.array_in && self.elem != 0 {
129            vec![self.elem]
130        } else {
131            match self.typtype {
132                'd' => vec![self.base],
133                'r' | 'm' => self.range_sub.into_iter().collect(),
134                _ => Vec::new(),
135            }
136        };
137        refs.into_iter().filter(|&oid| oid != 0).collect()
138    }
139}
140
141fn unknown(oid: u32) -> TypeInfo {
142    TypeInfo {
143        oid,
144        name: "unknown".into(),
145        kind: TypeKind::Text,
146    }
147}
148
149/// Maps one catalog-backed OID. None when pg_type has no row for it.
150fn build(oid: u32, depth: usize, rows: &HashMap<u32, CatalogRow>) -> Option<TypeInfo> {
151    if let Some(info) = builtin_type(oid) {
152        return Some(info);
153    }
154    let row = rows.get(&oid)?;
155    if depth >= MAX_DEPTH {
156        return Some(TypeInfo {
157            oid,
158            name: row.name.clone(),
159            kind: TypeKind::Text,
160        });
161    }
162    if row.array_in && row.elem != 0 {
163        let elem = child(row.elem, depth, rows);
164        return Some(TypeInfo {
165            oid,
166            name: format!("{}[]", elem.name),
167            kind: TypeKind::Array {
168                elem: Box::new(elem),
169                delim: row.delim,
170            },
171        });
172    }
173    let kind = match row.typtype {
174        'd' => {
175            let base = child(row.base, depth, rows);
176            return Some(TypeInfo {
177                oid,
178                name: row.name.clone(),
179                kind: base.kind,
180            });
181        }
182        'r' => TypeKind::Range {
183            sub: Box::new(child(row.range_sub.unwrap_or(0), depth, rows)),
184        },
185        'm' => TypeKind::Multirange {
186            sub: Box::new(child(row.range_sub.unwrap_or(0), depth, rows)),
187        },
188        _ => TypeKind::Text,
189    };
190    Some(TypeInfo {
191        oid,
192        name: row.name.clone(),
193        kind,
194    })
195}
196
197/// A referenced type one level deeper; an OID that cannot be resolved becomes unknown.
198fn child(oid: u32, depth: usize, rows: &HashMap<u32, CatalogRow>) -> TypeInfo {
199    build(oid, depth + 1, rows).unwrap_or_else(|| unknown(oid))
200}
201
202/// Schema-qualified unless the schema is pg_catalog or public.
203fn display_name(schema: &str, typname: &str) -> String {
204    if schema == "pg_catalog" || schema == "public" {
205        typname.to_string()
206    } else {
207        format!("{schema}.{typname}")
208    }
209}
210
211async fn query_catalog(conn: &mut Connection, oids: &[u32]) -> Result<Vec<CatalogRow>, WireError> {
212    let list: Vec<String> = oids.iter().map(u32::to_string).collect();
213    let sql = format!(
214        "SELECT t.oid::text, t.typname::text, n.nspname::text, t.typtype::text, t.typelem::text, \
215         t.typdelim::text, t.typbasetype::text, \
216         (t.typinput = 'pg_catalog.array_in'::pg_catalog.regproc)::text, \
217         (SELECT r.rngsubtype::text FROM pg_catalog.pg_range r \
218          WHERE r.rngtypid = t.oid OR r.rngmultitypid = t.oid LIMIT 1) \
219         FROM pg_catalog.pg_type t JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace \
220         WHERE t.oid IN ({})",
221        list.join(",")
222    );
223    let result = conn.simple_query(&sql).await?;
224    result.rows.iter().map(|row| parse_row(row)).collect()
225}
226
227fn parse_row(row: &[Option<String>]) -> Result<CatalogRow, WireError> {
228    let oid = parse_oid(field(row, 0)?)?;
229    let typname = field(row, 1)?;
230    let schema = field(row, 2)?;
231    let typtype = single_char(field(row, 3)?)?;
232    let elem = parse_oid(field(row, 4)?)?;
233    let delim = single_char(field(row, 5)?)?;
234    let base = parse_oid(field(row, 6)?)?;
235    let array_in = field(row, 7)? == "true";
236    let range_sub = row
237        .get(8)
238        .and_then(|v| v.as_deref())
239        .map(parse_oid)
240        .transpose()?;
241    Ok(CatalogRow {
242        oid,
243        name: display_name(schema, typname),
244        typtype,
245        elem,
246        delim,
247        base,
248        array_in,
249        range_sub,
250    })
251}
252
253fn field(row: &[Option<String>], index: usize) -> Result<&str, WireError> {
254    row.get(index)
255        .and_then(|v| v.as_deref())
256        .ok_or_else(malformed)
257}
258
259fn parse_oid(text: &str) -> Result<u32, WireError> {
260    text.parse().map_err(|_| malformed())
261}
262
263fn single_char(text: &str) -> Result<char, WireError> {
264    let mut chars = text.chars();
265    match (chars.next(), chars.next()) {
266        (Some(c), None) => Ok(c),
267        _ => Err(malformed()),
268    }
269}
270
271fn malformed() -> WireError {
272    WireError::Protocol("unexpected pg_type row".into())
273}