Skip to main content

postrust_core/schema_cache/
mod.rs

1//! PostgreSQL schema introspection and caching.
2//!
3//! This module provides functionality to discover and cache database schema
4//! metadata including tables, columns, relationships, and functions.
5
6mod queries;
7mod relationship;
8mod routine;
9mod table;
10
11pub use relationship::{
12    Cardinality, Junction, MediaHandler, MediaHandlerMap, Relationship, RelationshipsMap,
13};
14pub use routine::{FuncVolatility, RetType, Routine, RoutineMap, RoutineParam};
15
16#[cfg(feature = "sqlx")]
17pub use queries::enum_values;
18pub use table::{Column, ColumnMap, ComputedColumn, Table, TablesMap};
19
20use crate::api_request::QualifiedIdentifier;
21use crate::db::{Db, Tx};
22use crate::error::{Error, Result};
23use serde::{Deserialize, Serialize};
24use std::collections::{HashMap, HashSet};
25use std::sync::Arc;
26use tracing::info;
27
28/// Cached PostgreSQL schema metadata.
29///
30/// Serializable, so a host that cannot afford to load it on every cold start
31/// -- a Cloudflare Worker -- can keep a copy elsewhere. The maps keyed by more
32/// than a string are written as lists of `[key, value]` pairs, since a JSON
33/// object can only be keyed by a string.
34#[derive(Clone, Debug, Serialize, Deserialize)]
35pub struct SchemaCache {
36    /// Tables and views by qualified identifier.
37    #[serde(with = "pairs")]
38    pub tables: TablesMap,
39    /// Relationships between tables.
40    #[serde(with = "pairs")]
41    pub relationships: RelationshipsMap,
42    /// Stored functions/procedures.
43    #[serde(with = "pairs")]
44    pub routines: RoutineMap,
45    /// Valid timezone names.
46    pub timezones: HashSet<String>,
47    /// PostgreSQL version.
48    pub pg_version: i32,
49    /// User-defined renderers for media types, by (schema, media type).
50    #[serde(with = "pairs")]
51    pub media_handlers: MediaHandlerMap,
52    /// Casts between a domain and `json`/`text`, by (source, target) type.
53    ///
54    /// A schema uses these to decide how a value of one of its domains is
55    /// written on the wire and how one written by a client is read back.
56    #[serde(with = "pairs")]
57    pub representations: std::collections::HashMap<(String, String), String>,
58}
59
60/// A map written as a list of `[key, value]` pairs, for keys a JSON object
61/// cannot have.
62mod pairs {
63    use serde::{Deserialize, Deserializer, Serialize, Serializer};
64    use std::collections::HashMap;
65    use std::hash::Hash;
66
67    pub fn serialize<K, V, S>(map: &HashMap<K, V>, serializer: S) -> Result<S::Ok, S::Error>
68    where
69        K: Serialize,
70        V: Serialize,
71        S: Serializer,
72    {
73        serializer.collect_seq(map.iter())
74    }
75
76    pub fn deserialize<'de, K, V, D>(deserializer: D) -> Result<HashMap<K, V>, D::Error>
77    where
78        K: Deserialize<'de> + Eq + Hash,
79        V: Deserialize<'de>,
80        D: Deserializer<'de>,
81    {
82        Ok(Vec::<(K, V)>::deserialize(deserializer)?
83            .into_iter()
84            .collect())
85    }
86}
87
88impl SchemaCache {
89    /// Load schema cache from the database.
90    #[cfg(feature = "sqlx")]
91    pub async fn load(pool: &sqlx::PgPool, schemas: &[String]) -> Result<Self> {
92        Self::load_from(pool, schemas).await
93    }
94
95    /// Load the cache, resolving functions along `extra_search_path` as well.
96    /// See [`Self::load_with_search_path_from`].
97    #[cfg(feature = "sqlx")]
98    pub async fn load_with_search_path(
99        pool: &sqlx::PgPool,
100        schemas: &[String],
101        extra_search_path: &[String],
102    ) -> Result<Self> {
103        Self::load_with_search_path_from(pool, schemas, extra_search_path).await
104    }
105
106    /// Load schema cache through any [`Db`] -- a sqlx pool, or the socket
107    /// driver a Cloudflare Worker uses.
108    pub async fn load_from<D: Db>(db: &D, schemas: &[String]) -> Result<Self> {
109        Self::load_with_search_path_from(db, schemas, &[]).await
110    }
111
112    /// Load the cache, resolving functions along `extra_search_path` as well.
113    ///
114    /// A computed column's function is reached the way the database reaches
115    /// it, which is along the search path -- so it may live in a schema the
116    /// API does not expose. The table it reads must still be exposed.
117    ///
118    /// Every catalog query runs on one transaction, through the same
119    /// interface a request uses, so any driver that can serve requests can
120    /// load the cache.
121    pub async fn load_with_search_path_from<D: Db>(
122        db: &D,
123        schemas: &[String],
124        extra_search_path: &[String],
125    ) -> Result<Self> {
126        info!("Loading schema cache for schemas: {:?}", schemas);
127
128        let function_schemas: Vec<String> = schemas
129            .iter()
130            .chain(extra_search_path)
131            .cloned()
132            .collect::<std::collections::BTreeSet<_>>()
133            .into_iter()
134            .collect();
135
136        let failed = |e: crate::db::DbError| Error::SchemaCacheLoadFailed(e.to_string());
137        let mut tx = db.begin().await.map_err(failed)?;
138
139        // Get PostgreSQL version
140        let pg_version = queries::get_pg_version(&mut tx).await?;
141        info!("PostgreSQL version: {}", pg_version);
142
143        // Load tables and columns
144        let mut tables = queries::load_tables(&mut tx, schemas).await?;
145        info!("Loaded {} tables/views", tables.len());
146
147        // Which base-table columns each view carries. Loaded before the
148        // relationships, because a view's base table may live in a schema
149        // that is not itself exposed -- `private.articles` behind a public
150        // view -- and its foreign keys are needed all the same.
151        let view_columns = queries::load_view_columns(&mut tx, schemas).await?;
152
153        // Functions that read as columns. Attached to the tables they belong
154        // to, so resolving a field name has one place to look.
155        for computed in queries::load_computed_columns(&mut tx, schemas, &function_schemas).await? {
156            if let Some(table) = tables.get_mut(&computed.table) {
157                table.computed_columns.insert(
158                    computed.name,
159                    ComputedColumn {
160                        function: computed.function,
161                        data_type: computed.return_type,
162                        description: computed.description,
163                        row_argument: computed.row_argument,
164                        session_argument: computed.session_argument,
165                        takes_arguments: computed.takes_arguments,
166                    },
167                );
168            }
169        }
170
171        let mut relationship_schemas: Vec<String> = schemas.to_vec();
172        for column in &view_columns {
173            if !relationship_schemas.contains(&column.base.schema) {
174                relationship_schemas.push(column.base.schema.clone());
175            }
176        }
177
178        // Load relationships
179        let relationships = queries::load_relationships(&mut tx, &relationship_schemas).await?;
180        info!("Loaded {} relationship sets", relationships.len());
181
182        // Load routines
183        let routines = queries::load_routines(&mut tx, schemas).await?;
184        info!("Loaded {} routines", routines.len());
185
186        // Load timezone names
187        let timezones = queries::load_timezones(&mut tx).await?;
188        info!("Loaded {} timezones", timezones.len());
189
190        // Junctions first, then views: a many-to-many derived from a
191        // junction is itself a relationship a view can carry, and the
192        // junction may live in a schema that is not exposed.
193        let primary_keys = queries::load_primary_keys(&mut tx, &relationship_schemas).await?;
194
195        // Which uniqueness an upsert resolves against has to be named, and a
196        // table may have several.
197        let mut tables = tables;
198        for (qi, constraints) in queries::load_unique_constraints(&mut tx, schemas).await? {
199            if let Some(table) = tables.get_mut(&qi) {
200                table.unique_constraints = constraints;
201            }
202        }
203
204        let mut relationships = relationships;
205        add_junction_relationships(&primary_keys, &mut relationships);
206        substitute_hidden_junctions(&tables, &view_columns, &mut relationships);
207        add_view_relationships(&tables, &view_columns, &mut relationships);
208
209        // A view over a junction is a junction. It has no key of its own, so
210        // this runs only once the view's own relationships exist -- which is
211        // why the pass is here and not with the first one.
212        let view_keys = view_primary_keys(&primary_keys, &view_columns);
213        add_junction_relationships(&view_keys, &mut relationships);
214        dedupe_relationships(&mut relationships);
215
216        // A view has no key of its own in `pg_index`; it has the one it
217        // inherits, and everything that asks a table for its key -- the
218        // `Location` of a created row, whether PUT is allowed, an upsert --
219        // should find it there.
220        for (view, key) in &view_keys {
221            if let Some(table) = tables.get_mut(view).filter(|table| table.is_view) {
222                for column in table.columns.values_mut() {
223                    column.is_pk = key.contains(&column.name);
224                }
225                table.pk_cols = key.clone();
226            }
227        }
228
229        let media_handlers = queries::load_media_handlers(&mut tx, schemas).await?;
230        info!("Loaded {} media type handlers", media_handlers.len());
231
232        let representations = queries::load_representations(&mut tx).await?;
233        info!("Loaded {} data representations", representations.len());
234
235        tx.commit().await.map_err(failed)?;
236
237        Ok(Self {
238            tables,
239            relationships,
240            routines,
241            timezones,
242            pg_version,
243            media_handlers,
244            representations,
245        })
246    }
247
248    /// Get a table by qualified identifier.
249    pub fn get_table(&self, qi: &QualifiedIdentifier) -> Option<&Table> {
250        self.tables.get(qi)
251    }
252
253    /// Get a table, returning an error if not found.
254    pub fn require_table(&self, qi: &QualifiedIdentifier) -> Result<&Table> {
255        self.get_table(qi).ok_or_else(|| Error::TableNotFound {
256            name: qi.to_string(),
257            suggestion: self.similar_table(qi),
258        })
259    }
260
261    /// The exposed table whose name is closest to one that does not exist.
262    ///
263    /// PostgREST answers a schema-cache miss with a suggestion where there is
264    /// an obviously intended table -- `projectx` for `projects` -- and with
265    /// nothing where there is not, which is what the similarity floor decides.
266    /// Below it the "suggestion" would be noise, and would also say more about
267    /// the schema than the client asked.
268    fn similar_table(&self, qi: &QualifiedIdentifier) -> Option<String> {
269        // PostgREST's tableNotFoundHint asks fuzzyset for the nearest name
270        // with a minimum score of 0.75 (Error.hs, getFuzzyHint HintTable).
271        const MIN_RATIO: f64 = 0.75;
272        // The 3-gram prefilter, kept from before: it rules out names that
273        // share no runs of letters with the one asked for.
274        const MIN_GRAM_SIMILARITY: f64 = 0.5;
275
276        // Candidates must clear both bars. Of those, the Levenshtein ratio
277        // decides; a tie there (`itemsx` is one edit from both `items` and
278        // `items3`) goes to the 3-gram cosine, which notices that `items` is
279        // the query's own length and `items3` is not.
280        let asked = grams(&qi.name, 3);
281
282        self.tables
283            .keys()
284            .filter(|candidate| candidate.schema == qi.schema)
285            .map(|candidate| {
286                (
287                    similarity(&candidate.name, &qi.name),
288                    cosine(&asked, &grams(&candidate.name, 3)),
289                    candidate,
290                )
291            })
292            .filter(|(ratio, gram, _)| *ratio >= MIN_RATIO && *gram >= MIN_GRAM_SIMILARITY)
293            // Ties go to the shorter name, and then to the earlier one, so
294            // that the suggestion does not depend on iteration order.
295            .max_by(|(ra, a, left), (rb, b, right)| {
296                ra.total_cmp(rb)
297                    .then_with(|| a.total_cmp(b))
298                    .then_with(|| right.name.len().cmp(&left.name.len()))
299                    .then_with(|| right.name.cmp(&left.name))
300            })
301            .map(|(_, _, candidate)| candidate.to_string())
302    }
303
304    /// Get relationships for a table.
305    pub fn get_relationships(
306        &self,
307        qi: &QualifiedIdentifier,
308        schema: &str,
309    ) -> Option<&Vec<Relationship>> {
310        self.relationships.get(&(qi.clone(), schema.to_string()))
311    }
312
313    /// Get a routine by qualified identifier.
314    pub fn get_routines(&self, qi: &QualifiedIdentifier) -> Option<&Vec<Routine>> {
315        self.routines.get(qi)
316    }
317
318    /// Check if a timezone is valid.
319    pub fn is_valid_timezone(&self, tz: &str) -> bool {
320        self.timezones.contains(tz)
321    }
322
323    /// Get a summary of the cached schema.
324    pub fn summary(&self) -> String {
325        format!(
326            "SchemaCache: {} tables, {} relationship sets, {} routines, PG {}",
327            self.tables.len(),
328            self.relationships.len(),
329            self.routines.len(),
330            self.pg_version
331        )
332    }
333
334    /// The table whose rows a function returns, if it returns rows of one.
335    ///
336    /// This is what makes a function behave like a table for everything after
337    /// the call: its result can be selected from, filtered, ordered, paged and
338    /// embedded on, all of which need a table to resolve columns against.
339    ///
340    /// `format_type` may or may not qualify the name, depending on the search
341    /// path it was rendered against, so both spellings are tried -- and an
342    /// unqualified one is looked for in the function's own schema.
343    pub fn routine_returned_table(&self, qi: &QualifiedIdentifier) -> Option<&Table> {
344        self.returned_table(self.get_routines(qi)?.first()?)
345    }
346
347    /// The same, for a routine already chosen.
348    ///
349    /// A name may carry several signatures returning different things, so
350    /// which overload was selected decides which table the result is shaped
351    /// by -- and only the caller knows that.
352    pub fn returned_table(&self, routine: &Routine) -> Option<&Table> {
353        // Only a row type names a table. Without this, a function returning
354        // `xml` is shaped by whatever relation happens to be called `xml` --
355        // and the fixtures have one, so this is not hypothetical.
356        if !routine.returns_composite {
357            return None;
358        }
359        let type_name = routine.return_type.type_name()?;
360        let candidate = match type_name.split_once('.') {
361            Some((schema, name)) => QualifiedIdentifier::new(schema, name),
362            None => QualifiedIdentifier::new(&routine.schema, type_name),
363        };
364        self.get_table(&candidate)
365    }
366
367    /// The function that renders a value of `pg_type` as `target`, if the
368    /// schema declared one.
369    pub fn representation(&self, pg_type: &str, target: &str) -> Option<&str> {
370        self.representations
371            .get(&(pg_type.to_string(), target.to_string()))
372            .map(String::as_str)
373    }
374
375    /// Find a user-defined renderer for a media type on a given table.
376    ///
377    /// A handler declared for the table itself wins over one taking
378    /// `anyelement`, which is the schema-wide fallback.
379    /// A schema may also declare a handler for `*/*`, which renders whatever
380    /// was asked for. What comes back is the handler and the media type the
381    /// response should be labelled with -- not always the one requested, since
382    /// `*/*` is not a type a response can claim to be. PostgREST resolves it
383    /// to `application/octet-stream`, which is what a body of unnamed bytes
384    /// is, and this follows it.
385    /// A handler declared for one table renders that table as it is, so it
386    /// only applies to a request that asked for the table as it is:
387    /// `?select=id` is a different shape from the one the handler was written
388    /// against, and running it over that shape produces either nonsense or an
389    /// error. PostgREST guards both table-specific lookups on the selection
390    /// being the default one, and `default_select` is that guard.
391    pub fn media_handler<'a>(
392        &'a self,
393        schema: &str,
394        media_type: &'a str,
395        table: &QualifiedIdentifier,
396        default_select: bool,
397    ) -> Option<(&'a MediaHandler, &'a str)> {
398        let named = |media: &str| {
399            let candidates = self
400                .media_handlers
401                .get(&(schema.to_string(), media.to_string()))?;
402            candidates
403                .iter()
404                .find(|h| default_select && h.table.as_ref() == Some(table))
405                .or_else(|| candidates.iter().find(|h| h.table.is_none()))
406        };
407
408        match named(media_type) {
409            // A handler for `*/*` produces bytes of no stated type, which is
410            // reported as `application/octet-stream`, never as the wildcard.
411            Some(handler) if media_type == "*/*" => Some((handler, "application/octet-stream")),
412            Some(handler) => Some((handler, media_type)),
413            // `*/*` is declared on a table, so it is a table lookup too.
414            None if default_select => {
415                named("*/*").map(|handler| (handler, "application/octet-stream"))
416            }
417            None => None,
418        }
419    }
420
421    /// The error to report when no relationship connects two resources.
422    ///
423    /// Built here rather than at the call site because the suggestion needs
424    /// the relationships the origin actually has, which is what the client
425    /// most likely meant to name.
426    pub fn relationship_not_found(
427        &self,
428        from: &QualifiedIdentifier,
429        to_name: &str,
430        hint: Option<&str>,
431        schema: &str,
432    ) -> Error {
433        // Looser than the table suggestion: a relationship is named by the far
434        // table, and a client that got it wrong tends to have got it wrong by
435        // a whole word -- `car_model_sales_202101` for `car_model_sales`.
436        const MIN_SIMILARITY: f64 = 0.4;
437
438        let related: Vec<&str> = self
439            .get_relationships(from, schema)
440            .into_iter()
441            .flatten()
442            .map(|rel| rel.foreign_table().name.as_str())
443            .collect();
444
445        // A relationship of exactly that name exists, so the name is not what
446        // went wrong -- the hint is, and there is nothing to suggest. Dropping
447        // only the exact match and then offering the next-nearest name told a
448        // client that asked for `person!space` that it had perhaps meant
449        // `person_detail`, when what it had meant was `person` all along.
450        let suggestion = match related.contains(&to_name) {
451            true => None,
452            false => related
453                .iter()
454                .map(|name| (similarity(name, to_name), *name))
455                .filter(|(score, _)| *score >= MIN_SIMILARITY)
456                .max_by(|(a, _), (b, _)| a.total_cmp(b))
457                .map(|(_, name)| name.to_string()),
458        };
459
460        Error::RelationshipNotFound {
461            origin: from.name.clone(),
462            target: to_name.to_string(),
463            hint: hint.map(str::to_string),
464            schema: schema.to_string(),
465            suggestion,
466        }
467    }
468
469    /// The exposed function whose name is closest to one that does not exist.
470    ///
471    /// Only when the name itself is wrong: an existing name whose arguments do
472    /// not match is a different mistake, and the overloads answer it better.
473    pub fn similar_routine(&self, qi: &QualifiedIdentifier) -> Option<String> {
474        const MIN_SIMILARITY: f64 = 0.75;
475
476        self.routines
477            .keys()
478            .filter(|candidate| candidate.schema == qi.schema)
479            .map(|candidate| (similarity(&candidate.name, &qi.name), candidate))
480            .filter(|(score, _)| *score >= MIN_SIMILARITY)
481            .max_by(|(a, _), (b, _)| a.total_cmp(b))
482            .map(|(_, candidate)| candidate.to_string())
483    }
484
485    /// Find a relationship between two tables by name.
486    ///
487    /// `hint` is the `!hint` of `person_detail!message_sender_fkey(name)`,
488    /// which names the relationship when the two resources are connected by
489    /// more than one.
490    ///
491    /// Returns `Ok(None)` when nothing matches, and an error when several do
492    /// and no hint told them apart -- picking one arbitrarily would answer a
493    /// question the client did not ask.
494    pub fn find_relationship(
495        &self,
496        from: &QualifiedIdentifier,
497        to_name: &str,
498        hint: Option<&str>,
499        schema: &str,
500    ) -> Result<Option<&Relationship>> {
501        let Some(candidates) = self.get_relationships(from, schema) else {
502            return Ok(None);
503        };
504
505        // An embedding may be named three ways, and they are tried in the
506        // order of how specifically they identify one relationship.
507        //
508        // The target table's name is the usual spelling, but it stops
509        // identifying anything as soon as two foreign keys point at the same
510        // table. The foreign key constraint names exactly one relationship,
511        // and so does the column that joins them -- `/messages?select=*,
512        // sender(*)` embeds through the `sender` column, and
513        // `/projects?select=*,client(*)` through the constraint called
514        // `client`.
515        let by_target: Vec<&Relationship> = candidates
516            .iter()
517            .filter(|r| match r {
518                // A computed relationship is named by its function. Two
519                // functions may return the same table, so the table's name
520                // would not tell them apart.
521                Relationship::Computed { function, .. } => function.name == to_name,
522                // One foreign key pointing at its own table is two
523                // relationships, and the table's name alone cannot tell them
524                // apart. The convention is PostgREST's: the table's name means
525                // the rows that point here -- the children -- and the key's own
526                // column means the row this one points at. A hint names the
527                // column the children point with, and so always means children.
528                r if r.is_self_referential() => match hint {
529                    None => {
530                        (r.foreign_table().name == to_name && r.is_one_to_many())
531                            || (r.single_local_column() == Some(to_name) && !r.is_one_to_many())
532                    }
533                    Some(hint) => {
534                        r.foreign_table().name == to_name
535                            && r.is_one_to_many()
536                            && r.single_foreign_column() == Some(hint)
537                    }
538                },
539                Relationship::ForeignKey { foreign_table, .. } => foreign_table.name == to_name,
540            })
541            .collect();
542
543        // A relationship projected onto a view carries the constraint and
544        // columns of the base one it came from, so naming either of those
545        // would match both. Only the view's own name selects the projection;
546        // the constraint and the column mean the relationship they belong to.
547        // PostgreSQL cannot point a foreign key at a view, so a view on the
548        // far side is exactly what marks a projection.
549        let declared = |r: &&Relationship| !matches!(r, Relationship::ForeignKey { foreign_table_is_view, .. } if *foreign_table_is_view);
550
551        // A computed relationship declared under a name overrides whatever the
552        // catalogue found under it. That is deliberate on the schema author's
553        // part -- naming the function after the table is how a schema replaces
554        // the derived relationship with one of its own -- so the two are not
555        // an ambiguity to report back.
556        let by_target = match by_target
557            .iter()
558            .any(|r| matches!(r, Relationship::Computed { .. }))
559        {
560            true => by_target
561                .into_iter()
562                .filter(|r| matches!(r, Relationship::Computed { .. }))
563                .collect(),
564            false => by_target,
565        };
566
567        let mut matches = match by_target.is_empty() {
568            false => by_target,
569            true => {
570                let by_constraint: Vec<&Relationship> = candidates
571                    .iter()
572                    .filter(declared)
573                    .filter(|r| r.constraint_name() == to_name)
574                    .collect();
575                match by_constraint.is_empty() {
576                    false => by_constraint,
577                    true => candidates
578                        .iter()
579                        .filter(declared)
580                        .filter(|r| r.join_columns().iter().any(|(local, _)| local == to_name))
581                        .collect(),
582                }
583            }
584        };
585
586        // A self-referential match has already accounted for the hint, and the
587        // general rule would reject it: both directions join on the same pair
588        // of columns, so the hint names them both.
589        if let Some(hint) = hint {
590            matches.retain(|r| r.is_self_referential() || r.matches_hint(hint));
591        }
592
593        // The order the candidates are reported in is part of the answer: it
594        // is what `details` lists and what the `hint` names as alternatives.
595        // Loading them in a fixed order makes it reproducible; this makes it
596        // PostgREST's.
597        //
598        // Inferred from every ambiguity its own suite covers, which agree on
599        // cardinality first and the relationship's own name to break a tie --
600        // `/agents?select=*,departments(*)` reports the one-to-many before the
601        // many-to-one, and `/sites?select=*,big_projects(*)` the many-to-one
602        // before the many-to-many. Where one-to-one sorts against the others
603        // no case says, and this is a guess: no ambiguity in the corpus mixes
604        // it with another cardinality.
605        matches.sort_by(|a, b| {
606            fn rank(name: &str) -> u8 {
607                match name {
608                    "one-to-many" => 0,
609                    "one-to-one" => 1,
610                    "many-to-one" => 2,
611                    _ => 3,
612                }
613            }
614            rank(a.cardinality_name())
615                .cmp(&rank(b.cardinality_name()))
616                .then_with(|| a.describe().cmp(&b.describe()))
617        });
618
619        match matches.len() {
620            0 => Ok(None),
621            1 => Ok(Some(matches[0])),
622            _ => Err(Error::AmbiguousRelationship {
623                origin: from.name.clone(),
624                target: to_name.to_string(),
625                candidates: matches
626                    .iter()
627                    .map(|r| (r.cardinality_name().to_string(), r.describe()))
628                    .collect(),
629                // What the client would have to write instead. The details
630                // say which relationships were found; this says how to ask for
631                // one of them, which is the part it can act on.
632                disambiguated: matches
633                    .iter()
634                    .map(|r| format!("{}!{}", to_name, r.disambiguator()))
635                    .collect(),
636            }),
637        }
638    }
639}
640
641/// How alike two names are, from 0 (nothing in common) to 1 (identical).
642///
643/// Edit distance over the longer of the two, which is enough to tell a typo
644/// from a different word.
645pub(crate) fn similarity(a: &str, b: &str) -> f64 {
646    let longest = a.chars().count().max(b.chars().count());
647    if longest == 0 {
648        return 1.0;
649    }
650    1.0 - edit_distance(a, b) as f64 / longest as f64
651}
652
653/// The closest of `candidates` to `query`, or `None` if none is close enough.
654///
655/// Scored the way PostgREST scores its hints: cosine similarity over the
656/// character n-grams of both strings, three at a time and falling back to two
657/// where three finds nothing, with the ends marked so that a shared prefix
658/// counts for something. A Levenshtein ratio, which is the obvious thing to
659/// reach for, answers differently on the cases that matter -- it calls
660/// `(any_arg)` and `(name)` a third alike, because they are both short, where
661/// sharing no letter sequence at all is what a client needs to be told.
662///
663/// The floor is strict, and applies to the similarity; among what clears it,
664/// the nearest by edit distance wins. A floor of zero therefore means "shares
665/// any sequence of characters at all", which is a real filter -- two strings
666/// with no run of two characters in common score nothing and never reach the
667/// ranking.
668pub(crate) fn closest<'a>(
669    candidates: impl IntoIterator<Item = &'a str> + Clone,
670    query: &str,
671    min_score: f64,
672) -> Option<&'a str> {
673    for size in [3usize, 2] {
674        let asked = grams(query, size);
675        let mut fitting: Vec<&str> = candidates
676            .clone()
677            .into_iter()
678            .filter(|candidate| cosine(&asked, &grams(candidate, size)) > min_score)
679            .collect();
680
681        // Ranked by edit distance only among those the similarity admitted,
682        // which is why a short unrelated name never surfaces: it never got
683        // this far.
684        fitting.sort_by(|a, b| {
685            similarity(&normalize(b), &normalize(query))
686                .total_cmp(&similarity(&normalize(a), &normalize(query)))
687        });
688        if let Some(best) = fitting.first() {
689            return Some(best);
690        }
691    }
692    None
693}
694
695/// A string reduced to what a comparison should see.
696///
697/// Punctuation is dropped, so `(name)` and `name` are the same word; commas
698/// and spaces are kept, because a parameter list is compared as the list it
699/// is written as.
700fn normalize(value: &str) -> String {
701    value
702        .chars()
703        .flat_map(char::to_lowercase)
704        .filter(|c| c.is_alphanumeric() || *c == ',' || *c == ' ')
705        .collect()
706}
707
708/// How many times each run of `size` characters occurs, ends marked.
709fn grams(value: &str, size: usize) -> HashMap<String, usize> {
710    let mut padded: Vec<char> = std::iter::once('-')
711        .chain(normalize(value).chars())
712        .chain(std::iter::once('-'))
713        .collect();
714    while padded.len() < size {
715        padded.push('-');
716    }
717
718    let mut counts: HashMap<String, usize> = HashMap::new();
719    for window in padded.windows(size) {
720        *counts.entry(window.iter().collect()).or_insert(0) += 1;
721    }
722    counts
723}
724
725/// The cosine of the angle between two gram counts.
726fn cosine(a: &HashMap<String, usize>, b: &HashMap<String, usize>) -> f64 {
727    let magnitude = |counts: &HashMap<String, usize>| -> f64 {
728        counts.values().map(|n| (n * n) as f64).sum::<f64>().sqrt()
729    };
730    let (a_size, b_size) = (magnitude(a), magnitude(b));
731    if a_size == 0.0 || b_size == 0.0 {
732        return 0.0;
733    }
734    let shared: f64 = a
735        .iter()
736        .map(|(gram, count)| (count * b.get(gram).copied().unwrap_or(0)) as f64)
737        .sum();
738    shared / (a_size * b_size)
739}
740
741/// Levenshtein distance, computed one row at a time.
742fn edit_distance(a: &str, b: &str) -> usize {
743    let b: Vec<char> = b.chars().collect();
744    let mut previous: Vec<usize> = (0..=b.len()).collect();
745    let mut current = vec![0; b.len() + 1];
746
747    for (i, a_char) in a.chars().enumerate() {
748        current[0] = i + 1;
749        for (j, b_char) in b.iter().enumerate() {
750            let substitution = previous[j] + usize::from(a_char != *b_char);
751            current[j + 1] = substitution.min(previous[j + 1] + 1).min(current[j] + 1);
752        }
753        std::mem::swap(&mut previous, &mut current);
754    }
755
756    previous[b.len()]
757}
758
759/// Route a many-to-many through the exposed view of its junction.
760///
761/// The junction is often the one table of the three that the API does not
762/// expose -- `private.personnages` behind `test.personnages` -- and joining
763/// through the base table is a `permission denied for schema private` at
764/// request time even though the relationship itself is real. Where a view over
765/// it is exposed and carries both keys, that view is joined through instead.
766fn substitute_hidden_junctions(
767    tables: &TablesMap,
768    view_columns: &[queries::ViewColumn],
769    relationships: &mut RelationshipsMap,
770) {
771    use std::collections::HashMap;
772
773    // Which name an exposed view gives each of a base table's columns.
774    type ColumnRenames<'a> = HashMap<&'a str, &'a str>;
775    /// The exposed views over one base table, each with its renames.
776    type ExposedViews<'a> = Vec<(&'a QualifiedIdentifier, ColumnRenames<'a>)>;
777
778    let mut views_over: HashMap<&QualifiedIdentifier, ExposedViews<'_>> = HashMap::new();
779    for column in view_columns {
780        if !tables.contains_key(&column.view) {
781            continue;
782        }
783        let entry = views_over.entry(&column.base).or_default();
784        match entry.iter_mut().find(|(view, _)| *view == &column.view) {
785            Some((_, mapping)) => {
786                mapping.insert(&column.base_column, &column.view_column);
787            }
788            None => {
789                let mut mapping = HashMap::new();
790                mapping.insert(column.base_column.as_str(), column.view_column.as_str());
791                entry.push((&column.view, mapping));
792            }
793        }
794    }
795
796    for rel in relationships.values_mut().flatten() {
797        let Relationship::ForeignKey {
798            cardinality: Cardinality::M2M(junction),
799            ..
800        } = rel
801        else {
802            continue;
803        };
804        if tables.contains_key(&junction.table) {
805            continue;
806        }
807
808        let needed: Vec<&str> = junction
809            .source_columns
810            .iter()
811            .map(|(_, through)| through.as_str())
812            .chain(
813                junction
814                    .target_columns
815                    .iter()
816                    .map(|(through, _)| through.as_str()),
817            )
818            .collect();
819
820        let Some((view, mapping)) = views_over.get(&junction.table).and_then(|views| {
821            views
822                .iter()
823                .find(|(_, mapping)| needed.iter().all(|name| mapping.contains_key(name)))
824        }) else {
825            // Nothing exposes the junction, so nothing can join through it.
826            // Marked rather than removed here, since the relationship is being
827            // iterated; the sweep below drops them.
828            junction.table = QualifiedIdentifier::new("", "");
829            continue;
830        };
831
832        junction.table = (*view).clone();
833        for (_, through) in junction.source_columns.iter_mut() {
834            if let Some(renamed) = mapping.get(through.as_str()) {
835                *through = (*renamed).to_string();
836            }
837        }
838        for (through, _) in junction.target_columns.iter_mut() {
839            if let Some(renamed) = mapping.get(through.as_str()) {
840                *through = (*renamed).to_string();
841            }
842        }
843    }
844
845    // Offering an unreachable relationship would answer `permission denied for
846    // schema private` where PostgREST answers that no relationship was found,
847    // which is both the truer answer and the one that says nothing about a
848    // schema the client was never shown.
849    for rels in relationships.values_mut() {
850        rels.retain(|rel| {
851            !matches!(
852                rel,
853                Relationship::ForeignKey {
854                    cardinality: Cardinality::M2M(junction),
855                    ..
856                } if junction.table.name.is_empty()
857            )
858        });
859    }
860    relationships.retain(|_, rels| !rels.is_empty());
861}
862
863/// Project relationships from base tables onto the views that select them.
864///
865/// A view carrying both ends of a foreign key can stand in for either side of
866/// it, so `/articleStars?select=*,articles(*)` embeds through the key on
867/// `private.article_stars` without the client ever naming the private table.
868///
869/// The join columns are rewritten to the names the view gives them: a view is
870/// free to rename what it selects, and the projected relationship has to join
871/// on the names the client can actually see. Where a view selects one base
872/// column twice under different names, each spelling is a relationship of its
873/// own -- they are genuinely different joins, and `!t1_id1` is how a client
874/// tells them apart.
875fn add_view_relationships(
876    tables: &TablesMap,
877    view_columns: &[queries::ViewColumn],
878    relationships: &mut RelationshipsMap,
879) {
880    use std::collections::HashMap;
881
882    // base table -> view -> base column -> the names that view gives it
883    type ColumnNames = HashMap<String, Vec<String>>;
884    let mut views_over: HashMap<&QualifiedIdentifier, HashMap<&QualifiedIdentifier, ColumnNames>> =
885        HashMap::new();
886    for column in view_columns {
887        views_over
888            .entry(&column.base)
889            .or_default()
890            .entry(&column.view)
891            .or_default()
892            .entry(column.base_column.clone())
893            .or_default()
894            .push(column.view_column.clone());
895    }
896
897    let existing: Vec<((QualifiedIdentifier, String), Relationship)> = relationships
898        .iter()
899        .flat_map(|(key, rels)| rels.iter().map(move |rel| (key.clone(), rel.clone())))
900        .collect();
901
902    let mut derived: Vec<((QualifiedIdentifier, String), Relationship)> = Vec::new();
903
904    for ((source, _), rel) in &existing {
905        let Relationship::ForeignKey {
906            foreign_table,
907            cardinality,
908            table_is_view,
909            foreign_table_is_view,
910            constraint_name,
911            ..
912        } = rel
913        else {
914            continue;
915        };
916
917        // Which columns each end has to carry for the view to stand in for
918        // it. A many-to-many joins through a junction, so the two ends are
919        // described by different halves of it -- the near side by the columns
920        // going into the junction, the far side by the ones coming out.
921        let (near_needs, far_needs): (Vec<String>, Vec<String>) = match cardinality {
922            Cardinality::M2M(junction) => (
923                junction
924                    .source_columns
925                    .iter()
926                    .map(|(near, _)| near.clone())
927                    .collect(),
928                junction
929                    .target_columns
930                    .iter()
931                    .map(|(_, far)| far.clone())
932                    .collect(),
933            ),
934            _ => {
935                let columns = cardinality.columns();
936                (
937                    columns.iter().map(|(near, _)| near.clone()).collect(),
938                    columns.iter().map(|(_, far)| far.clone()).collect(),
939                )
940            }
941        };
942
943        // Every way the view can spell the columns this end joins on. Empty
944        // when it does not carry all of them, which is what disqualifies it
945        // from standing in at all.
946        let spellings = |view_cols: &ColumnNames, needed: &[String]| -> Vec<Vec<String>> {
947            let mut combinations: Vec<Vec<String>> = vec![vec![]];
948            for name in needed {
949                let Some(candidates) = view_cols.get(name) else {
950                    return vec![];
951                };
952                combinations = combinations
953                    .into_iter()
954                    .flat_map(|prefix| {
955                        candidates.iter().map(move |candidate| {
956                            let mut extended = prefix.clone();
957                            extended.push(candidate.clone());
958                            extended
959                        })
960                    })
961                    .collect();
962            }
963            combinations
964        };
965
966        // The view stands in for the near side.
967        if let Some(views) = views_over.get(source) {
968            for (view, view_cols) in views {
969                for near in spellings(view_cols, &near_needs) {
970                    derived.push((
971                        ((*view).clone(), view.schema.clone()),
972                        Relationship::ForeignKey {
973                            table: (*view).clone(),
974                            foreign_table: foreign_table.clone(),
975                            is_self: *view == foreign_table,
976                            cardinality: rename_cardinality(cardinality, Some(&near), None),
977                            table_is_view: true,
978                            foreign_table_is_view: *foreign_table_is_view,
979                            constraint_name: constraint_name.clone(),
980                        },
981                    ));
982                }
983            }
984        }
985
986        // The view stands in for the far side, and likewise.
987        if let Some(views) = views_over.get(foreign_table) {
988            for (view, view_cols) in views {
989                for far in spellings(view_cols, &far_needs) {
990                    derived.push((
991                        (source.clone(), source.schema.clone()),
992                        Relationship::ForeignKey {
993                            table: source.clone(),
994                            foreign_table: (*view).clone(),
995                            is_self: source == *view,
996                            cardinality: rename_cardinality(cardinality, None, Some(&far)),
997                            table_is_view: *table_is_view,
998                            foreign_table_is_view: true,
999                            constraint_name: constraint_name.clone(),
1000                        },
1001                    ));
1002                }
1003            }
1004        }
1005
1006        // Both sides are views. Neither of the cases above covers it: each
1007        // replaces one end and leaves the other as the base table.
1008        if let (Some(near_views), Some(far_views)) =
1009            (views_over.get(source), views_over.get(foreign_table))
1010        {
1011            for (near_view, near_cols) in near_views {
1012                for near in spellings(near_cols, &near_needs) {
1013                    for (far_view, far_cols) in far_views {
1014                        for far in spellings(far_cols, &far_needs) {
1015                            derived.push((
1016                                ((*near_view).clone(), near_view.schema.clone()),
1017                                Relationship::ForeignKey {
1018                                    table: (*near_view).clone(),
1019                                    foreign_table: (*far_view).clone(),
1020                                    is_self: near_view == far_view,
1021                                    cardinality: rename_cardinality(
1022                                        cardinality,
1023                                        Some(&near),
1024                                        Some(&far),
1025                                    ),
1026                                    table_is_view: true,
1027                                    foreign_table_is_view: true,
1028                                    constraint_name: constraint_name.clone(),
1029                                },
1030                            ));
1031                        }
1032                    }
1033                }
1034            }
1035        }
1036    }
1037
1038    // A projection is only useful if the client can name both ends. The base
1039    // table behind a view is often in a schema that is not exposed, and
1040    // offering it as a target would produce a relationship that resolves to a
1041    // table the request has no permission to read.
1042    for (key, rel) in derived {
1043        if !tables.contains_key(&key.0) || !tables.contains_key(rel.foreign_table()) {
1044            continue;
1045        }
1046        relationships.entry(key).or_default().push(rel);
1047    }
1048}
1049
1050/// A cardinality with one or both ends' columns renamed.
1051///
1052/// `near` and `far` are given in the order the cardinality lists them, so the
1053/// nth name replaces the nth column. `None` leaves that end alone.
1054fn rename_cardinality(
1055    cardinality: &Cardinality,
1056    near: Option<&[String]>,
1057    far: Option<&[String]>,
1058) -> Cardinality {
1059    let rename_pairs = |columns: &[(String, String)]| -> Vec<(String, String)> {
1060        columns
1061            .iter()
1062            .enumerate()
1063            .map(|(i, (local, foreign))| {
1064                (
1065                    near.and_then(|names| names.get(i)).unwrap_or(local).clone(),
1066                    far.and_then(|names| names.get(i))
1067                        .unwrap_or(foreign)
1068                        .clone(),
1069                )
1070            })
1071            .collect()
1072    };
1073
1074    match cardinality {
1075        Cardinality::O2M {
1076            constraint,
1077            columns,
1078        } => Cardinality::O2M {
1079            constraint: constraint.clone(),
1080            columns: rename_pairs(columns),
1081        },
1082        Cardinality::M2O {
1083            constraint,
1084            columns,
1085        } => Cardinality::M2O {
1086            constraint: constraint.clone(),
1087            columns: rename_pairs(columns),
1088        },
1089        Cardinality::O2O {
1090            constraint,
1091            columns,
1092            is_parent,
1093        } => Cardinality::O2O {
1094            constraint: constraint.clone(),
1095            columns: rename_pairs(columns),
1096            is_parent: *is_parent,
1097        },
1098        // Only the outer ends move: the junction keeps its own column names,
1099        // since the view stands in for a side of the join and not for the
1100        // table doing the joining.
1101        Cardinality::M2M(junction) => {
1102            let mut junction = junction.clone();
1103            if let Some(names) = near {
1104                for (i, (source, _)) in junction.source_columns.iter_mut().enumerate() {
1105                    if let Some(name) = names.get(i) {
1106                        *source = name.clone();
1107                    }
1108                }
1109            }
1110            if let Some(names) = far {
1111                for (i, (_, target)) in junction.target_columns.iter_mut().enumerate() {
1112                    if let Some(name) = names.get(i) {
1113                        *target = name.clone();
1114                    }
1115                }
1116            }
1117            Cardinality::M2M(junction)
1118        }
1119    }
1120}
1121
1122/// The key a view inherits from the tables it selects from.
1123///
1124/// A view over a junction is a junction: `main_jobs` selects the columns of
1125/// `jobs` that make it one, and PostgREST embeds `sites` through it and
1126/// through `jobs` alike -- reporting both as candidates when the two cannot be
1127/// told apart. A view has no key of its own, so each base table's is mapped
1128/// through the names the view gives those columns.
1129///
1130/// PostgREST's `addViewPrimaryKeys`: for every base table's key column, the
1131/// first view column that selects it, and the keys of all the base tables
1132/// concatenated -- `select * from with_pk1, with_pk2` is keyed on both. A key
1133/// column the view does not select is simply left out. The bases come in the
1134/// order the view first uses them.
1135fn view_primary_keys(
1136    primary_keys: &std::collections::HashMap<QualifiedIdentifier, Vec<String>>,
1137    view_columns: &[queries::ViewColumn],
1138) -> std::collections::HashMap<QualifiedIdentifier, Vec<String>> {
1139    use std::collections::HashMap;
1140
1141    let mut ordered: Vec<&queries::ViewColumn> = view_columns.iter().collect();
1142    ordered.sort_by_key(|column| column.view_ordinal);
1143
1144    // view -> bases in order of first use, each with base column -> view column
1145    #[allow(clippy::type_complexity)]
1146    let mut by_view: HashMap<
1147        &QualifiedIdentifier,
1148        Vec<(&QualifiedIdentifier, HashMap<&str, &str>)>,
1149    > = HashMap::new();
1150    for column in ordered {
1151        let bases = by_view.entry(&column.view).or_default();
1152        let position = match bases.iter().position(|(base, _)| *base == &column.base) {
1153            Some(position) => position,
1154            None => {
1155                bases.push((&column.base, HashMap::new()));
1156                bases.len() - 1
1157            }
1158        };
1159        bases[position]
1160            .1
1161            .entry(column.base_column.as_str())
1162            .or_insert(column.view_column.as_str());
1163    }
1164
1165    let mut keys = HashMap::new();
1166    for (view, bases) in by_view {
1167        let mut key: Vec<String> = Vec::new();
1168        for (base, columns) in bases {
1169            let Some(base_key) = primary_keys.get(base) else {
1170                continue;
1171            };
1172            for column in base_key {
1173                if let Some(name) = columns.get(column.as_str()) {
1174                    if !key.iter().any(|existing| existing == name) {
1175                        key.push(name.to_string());
1176                    }
1177                }
1178            }
1179        }
1180        if !key.is_empty() {
1181            keys.insert(view.clone(), key);
1182        }
1183    }
1184
1185    keys
1186}
1187
1188/// Drop a relationship derived twice.
1189///
1190/// The same many-to-many through a view over an unexposed junction is found by
1191/// the first junction pass (then substituted onto the view) and again by the
1192/// second, once the view has a key. Left alone, the two read as two
1193/// candidates and a plain embed answers 300. Two relationships are the same
1194/// when they join the same tables through the same junction, by the same
1195/// constraints, over the same columns; the junction is part of that, because
1196/// `jobs` and `main_jobs` are rightly two ways to the same table.
1197fn dedupe_relationships(relationships: &mut RelationshipsMap) {
1198    for rels in relationships.values_mut() {
1199        let mut seen = std::collections::HashSet::new();
1200        rels.retain(|rel| match rel {
1201            Relationship::ForeignKey {
1202                foreign_table,
1203                cardinality: Cardinality::M2M(junction),
1204                ..
1205            } => seen.insert((
1206                foreign_table.clone(),
1207                junction.table.clone(),
1208                junction.constraint1.clone(),
1209                junction.constraint2.clone(),
1210                junction.source_columns.clone(),
1211                junction.target_columns.clone(),
1212            )),
1213            _ => true,
1214        });
1215    }
1216}
1217
1218/// Derive many-to-many relationships from junction tables.
1219///
1220/// A junction is a table that exists only to join two others: it has exactly
1221/// two foreign keys, to two different tables, and its primary key is precisely
1222/// the columns of those keys. That last condition is what separates a junction
1223/// from an ordinary table that happens to reference two others, which would
1224/// otherwise sprout a relationship it has no business having.
1225///
1226/// Both sides get the relationship, named after the table across the junction,
1227/// so `/users?select=name,tasks(name)` works from either end.
1228fn add_junction_relationships(
1229    primary_keys: &std::collections::HashMap<QualifiedIdentifier, Vec<String>>,
1230    relationships: &mut RelationshipsMap,
1231) {
1232    let mut derived: Vec<((QualifiedIdentifier, String), Relationship)> = Vec::new();
1233
1234    for (junction_qi, junction_pk) in primary_keys {
1235        let key = (junction_qi.clone(), junction_qi.schema.clone());
1236        let Some(rels) = relationships.get(&key) else {
1237            continue;
1238        };
1239
1240        // The keys out of the junction, however many columns each is written
1241        // over. Requiring one column apiece looked like what separates a
1242        // junction from a table that merely references two others, but it is
1243        // not: `touched_files` joins `files(project_id, filename)` to
1244        // `users_tasks(user_id, task_id)` and is as much a junction as any
1245        // other. What separates them is the primary-key test below, which this
1246        // duplicated and then over-applied -- so a composite junction was
1247        // answered "no relationship" for a relationship that is plainly there.
1248        let outgoing: Vec<(&Relationship, Vec<(String, String)>)> = rels
1249            .iter()
1250            .filter(|r| matches!(r, Relationship::ForeignKey { table, .. } if table == junction_qi))
1251            .filter(|r| r.is_to_one())
1252            .filter_map(|r| {
1253                let mut columns = r.join_columns();
1254                columns.dedup();
1255                match columns.is_empty() {
1256                    true => None,
1257                    false => Some((r, columns)),
1258                }
1259            })
1260            .collect();
1261
1262        let pk: Vec<&str> = junction_pk.iter().map(String::as_str).collect();
1263
1264        // The pair whose columns are part of the primary key is what makes
1265        // this a junction: keying on both of them is what says a row of it is
1266        // one pairing. A junction may carry more in its key than the pair --
1267        // `group_yard` keys on `(id, group_id, yard_id)` -- and requiring the
1268        // key to be exactly the two columns missed those.
1269        for near in 0..outgoing.len() {
1270            for far in 0..outgoing.len() {
1271                if near == far {
1272                    continue;
1273                }
1274                let (near_rel, near_columns) = &outgoing[near];
1275                let (far_rel, far_columns) = &outgoing[far];
1276                if near_rel.foreign_table() == far_rel.foreign_table() {
1277                    continue;
1278                }
1279                // Every column either key is written over has to be part of
1280                // the junction's own key: that is what says a row of it is one
1281                // pairing and nothing more.
1282                if !near_columns
1283                    .iter()
1284                    .chain(far_columns)
1285                    .all(|(local, _)| pk.contains(&local.as_str()))
1286                {
1287                    continue;
1288                }
1289
1290                let source = near_rel.foreign_table().clone();
1291                let target = far_rel.foreign_table().clone();
1292
1293                derived.push((
1294                    (source.clone(), source.schema.clone()),
1295                    Relationship::ForeignKey {
1296                        table: source,
1297                        foreign_table: target,
1298                        is_self: false,
1299                        cardinality: Cardinality::M2M(Junction {
1300                            table: junction_qi.clone(),
1301                            constraint1: near_rel.constraint_name().to_string(),
1302                            constraint2: far_rel.constraint_name().to_string(),
1303                            // Source to junction, then junction to target,
1304                            // each in the order the constraint declares so a
1305                            // composite key joins column for column.
1306                            source_columns: near_columns
1307                                .iter()
1308                                .map(|(local, foreign)| (foreign.clone(), local.clone()))
1309                                .collect(),
1310                            target_columns: far_columns
1311                                .iter()
1312                                .map(|(local, foreign)| (local.clone(), foreign.clone()))
1313                                .collect(),
1314                        }),
1315                        table_is_view: false,
1316                        foreign_table_is_view: false,
1317                        constraint_name: String::new(),
1318                    },
1319                ));
1320            }
1321        }
1322    }
1323
1324    for (key, rel) in derived {
1325        relationships.entry(key).or_default().push(rel);
1326    }
1327}
1328
1329/// Thread-safe schema cache wrapper.
1330#[derive(Clone)]
1331pub struct SchemaCacheRef(Arc<tokio::sync::RwLock<Option<SchemaCache>>>);
1332
1333impl SchemaCacheRef {
1334    /// Create a new empty schema cache reference.
1335    pub fn new() -> Self {
1336        Self(Arc::new(tokio::sync::RwLock::new(None)))
1337    }
1338
1339    /// Create a schema cache reference from a static cache.
1340    pub fn from_static(cache: SchemaCache) -> Self {
1341        Self(Arc::new(tokio::sync::RwLock::new(Some(cache))))
1342    }
1343
1344    /// Load or reload the schema cache.
1345    #[cfg(feature = "sqlx")]
1346    pub async fn load(&self, pool: &sqlx::PgPool, schemas: &[String]) -> Result<()> {
1347        let cache = SchemaCache::load(pool, schemas).await?;
1348        let mut guard = self.0.write().await;
1349        *guard = Some(cache);
1350        Ok(())
1351    }
1352
1353    /// Get a read reference to the schema cache.
1354    pub async fn get(&self) -> Result<tokio::sync::RwLockReadGuard<'_, Option<SchemaCache>>> {
1355        let guard = self.0.read().await;
1356        if guard.is_none() {
1357            return Err(Error::SchemaCacheNotLoaded);
1358        }
1359        Ok(guard)
1360    }
1361
1362    /// Check if the cache is loaded.
1363    pub async fn is_loaded(&self) -> bool {
1364        self.0.read().await.is_some()
1365    }
1366}
1367
1368impl Default for SchemaCacheRef {
1369    fn default() -> Self {
1370        Self::new()
1371    }
1372}
1373
1374#[cfg(test)]
1375mod key_and_hint_tests {
1376    use super::*;
1377    use crate::schema_cache::{Cardinality, Junction, Relationship};
1378
1379    fn qi(name: &str) -> QualifiedIdentifier {
1380        QualifiedIdentifier::new("api", name)
1381    }
1382
1383    fn table(name: &str) -> Table {
1384        Table {
1385            schema: "api".into(),
1386            name: name.into(),
1387            description: None,
1388            is_view: false,
1389            is_partitioned: false,
1390            insertable: true,
1391            updatable: true,
1392            deletable: true,
1393            pk_cols: Vec::new(),
1394            unique_constraints: Vec::new(),
1395            columns: Default::default(),
1396            computed_columns: Default::default(),
1397        }
1398    }
1399
1400    fn cache(names: &[&str]) -> SchemaCache {
1401        SchemaCache {
1402            tables: names.iter().map(|n| (qi(n), table(n))).collect(),
1403            relationships: Default::default(),
1404            routines: Default::default(),
1405            timezones: Default::default(),
1406            pg_version: 160000,
1407            media_handlers: Default::default(),
1408            representations: Default::default(),
1409        }
1410    }
1411
1412    #[test]
1413    fn a_table_hint_needs_a_levenshtein_ratio_of_three_quarters() {
1414        let cache = cache(&["items", "items3", "car_model_sales", "car_models"]);
1415        // One edit in six: close enough, and the nearer of two ties wins.
1416        assert_eq!(
1417            cache.similar_table(&qi("itemsx")).as_deref(),
1418            Some("api.items")
1419        );
1420        // A partition's name is seven characters past its parent: 15/22.
1421        assert_eq!(cache.similar_table(&qi("car_model_sales_202101")), None);
1422        assert_eq!(cache.similar_table(&qi("car_models_default")), None);
1423    }
1424
1425    fn view_column(
1426        view: &str,
1427        base: &str,
1428        base_column: &str,
1429        name: &str,
1430        at: i32,
1431    ) -> queries::ViewColumn {
1432        queries::ViewColumn {
1433            view: qi(view),
1434            base: qi(base),
1435            base_column: base_column.into(),
1436            view_column: name.into(),
1437            view_ordinal: at,
1438        }
1439    }
1440
1441    #[test]
1442    fn a_view_key_concatenates_the_keys_of_its_bases() {
1443        let keys: std::collections::HashMap<_, _> = [
1444            (qi("with_pk1"), vec!["pk1".to_string()]),
1445            (qi("with_pk2"), vec!["pk2".to_string()]),
1446        ]
1447        .into();
1448        // `select * from with_pk1, with_pk2`, plus a second reference to pk1.
1449        let columns = vec![
1450            view_column("v", "with_pk2", "pk2", "pk2", 2),
1451            view_column("v", "with_pk1", "pk1", "pk1", 1),
1452            view_column("v", "with_pk1", "pk1", "again", 3),
1453        ];
1454        let view_keys = view_primary_keys(&keys, &columns);
1455        assert_eq!(view_keys[&qi("v")], ["pk1", "pk2"]);
1456    }
1457
1458    fn m2m(foreign: &str, junction: &str) -> Relationship {
1459        Relationship::ForeignKey {
1460            table: qi("a"),
1461            foreign_table: qi(foreign),
1462            is_self: false,
1463            cardinality: Cardinality::M2M(Junction {
1464                table: qi(junction),
1465                constraint1: "c1".into(),
1466                constraint2: "c2".into(),
1467                source_columns: vec![("id".into(), "a_id".into())],
1468                target_columns: vec![("b_id".into(), "id".into())],
1469            }),
1470            table_is_view: false,
1471            foreign_table_is_view: false,
1472            constraint_name: String::new(),
1473        }
1474    }
1475
1476    #[test]
1477    fn a_many_to_many_derived_twice_is_one_but_two_junctions_are_two() {
1478        let mut map = RelationshipsMap::new();
1479        map.insert(
1480            (qi("a"), "api".into()),
1481            vec![m2m("b", "jobs"), m2m("b", "jobs"), m2m("b", "main_jobs")],
1482        );
1483        dedupe_relationships(&mut map);
1484        assert_eq!(map[&(qi("a"), "api".to_string())].len(), 2);
1485    }
1486}