Skip to main content

dsl_hover/
constraint_id.rs

1//! Hover for constraint / index / trigger identifiers.
2//!
3//! Conventional Postgres style prefixes object names with a 2-3 letter
4//! tag indicating their kind:
5//!
6//!   pk_   primary key
7//!   fk_   foreign key
8//!   uq_   unique constraint
9//!   uidx_ unique index
10//!   idx_  index
11//!   ix_   index (alt)
12//!   ch_   check constraint
13//!   chk_  check (alt)
14//!   tg_   trigger
15//!   tr_   trigger (alt)
16//!   trg_  trigger (alt)
17//!
18//! We use the prefix as a quick classifier, then try to look up the
19//! actual object in the catalog (constraints + indexes + triggers
20//! attached to each table). When we find a match we render its real
21//! definition; otherwise we still render an "expected to be a <kind>"
22//! card so the user gets useful context.
23
24use dsl_catalog::{Catalog, Constraint, ConstraintKind, IndexDef, Table, Trigger};
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum Kind {
28  PrimaryKey,
29  ForeignKey,
30  Unique,
31  UniqueIndex,
32  Index,
33  Check,
34  Trigger,
35}
36
37impl Kind {
38  fn label(self) -> &'static str {
39    match self {
40      Kind::PrimaryKey => "Primary key",
41      Kind::ForeignKey => "Foreign key",
42      Kind::Unique => "Unique constraint",
43      Kind::UniqueIndex => "Unique index",
44      Kind::Index => "Index",
45      Kind::Check => "Check constraint",
46      Kind::Trigger => "Trigger",
47    }
48  }
49}
50
51/// Classify a token by its conventional prefix. Order matters --
52/// `uidx_` must be checked before `idx_`.
53pub fn classify(token: &str) -> Option<Kind> {
54  let t = token.to_ascii_lowercase();
55  for (prefix, kind) in [
56    ("uidx_", Kind::UniqueIndex),
57    ("idx_", Kind::Index),
58    ("ix_", Kind::Index),
59    ("pk_", Kind::PrimaryKey),
60    ("fk_", Kind::ForeignKey),
61    ("uq_", Kind::Unique),
62    ("ch_", Kind::Check),
63    ("chk_", Kind::Check),
64    ("tg_", Kind::Trigger),
65    ("tr_", Kind::Trigger),
66    ("trg_", Kind::Trigger),
67  ] {
68    if t.starts_with(prefix) {
69      return Some(kind);
70    }
71  }
72  None
73}
74
75/// Look the identifier up in the catalog and render a card. Returns None
76/// when the token does not match the constraint-identifier convention.
77pub fn render_for(token: &str, catalog: &Catalog) -> Option<String> {
78  let kind = classify(token)?;
79  if let Some(found) = find_in_catalog(token, catalog) {
80    return Some(render_known(token, kind, found));
81  }
82  Some(render_unknown(token, kind))
83}
84
85enum Found<'a> {
86  Constraint(&'a Table, &'a Constraint),
87  Index(&'a Table, &'a IndexDef),
88  Trigger(&'a Table, &'a Trigger),
89}
90
91fn find_in_catalog<'a>(token: &str, catalog: &'a Catalog) -> Option<Found<'a>> {
92  for t in catalog.tables() {
93    for c in &t.constraints {
94      if c.name.eq_ignore_ascii_case(token) {
95        return Some(Found::Constraint(t, c));
96      }
97    }
98    for i in &t.indexes {
99      if i.name.eq_ignore_ascii_case(token) {
100        return Some(Found::Index(t, i));
101      }
102    }
103    for tg in &t.triggers {
104      if tg.name.eq_ignore_ascii_case(token) {
105        return Some(Found::Trigger(t, tg));
106      }
107    }
108  }
109  None
110}
111
112fn render_known(token: &str, kind: Kind, found: Found<'_>) -> String {
113  // Pure-SQL output: one fenced code block, header lines as SQL
114  // comments. The server splits this at the fence and ships the
115  // body as `LanguageString { language: "sql", value: ... }` so
116  // nvim's stock hover handler colors EVERY line with sql.vim
117  // syntax -- including the comment header. No markdown italic /
118  // bold / heading styling can leak through.
119  let mut s = String::new();
120  s.push_str("```sql\n");
121  s.push_str(&format!("-- {}: {}\n", kind.label(), token));
122  match found {
123    Found::Constraint(t, c) => {
124      s.push_str(&format!("-- on {}.{}\n", t.schema, t.name));
125      s.push('\n');
126      s.push_str(&render_constraint(c));
127    },
128    Found::Index(t, i) => {
129      s.push_str(&format!("-- on {}.{}\n", t.schema, t.name));
130      s.push('\n');
131      if let Some(def) = &i.definition {
132        s.push_str(def);
133        if !def.trim_end().ends_with(';') {
134          s.push(';');
135        }
136      } else {
137        let unique = if i.unique { "UNIQUE " } else { "" };
138        s.push_str(&format!("CREATE {unique}INDEX {} ON {}.{} ({});", i.name, t.schema, t.name, i.columns.join(", ")));
139      }
140    },
141    Found::Trigger(t, tg) => {
142      s.push_str(&format!("-- on {}.{}\n", t.schema, t.name));
143      s.push('\n');
144      s.push_str(&format!(
145        "CREATE TRIGGER {} {} {} ON {}.{} FOR EACH {} EXECUTE FUNCTION {}();",
146        tg.name, tg.timing, tg.event, t.schema, t.name, tg.granularity, tg.function
147      ));
148    },
149  }
150  s.push_str("\n```\n");
151  s
152}
153
154fn render_unknown(token: &str, kind: Kind) -> String {
155  let hint = match kind {
156    Kind::PrimaryKey => "pk_<table>_<columns>",
157    Kind::ForeignKey => "fk_<table>_<column>_<ref_table>",
158    Kind::Unique => "uq_<table>_<columns>",
159    Kind::UniqueIndex => "uidx_<table>_<columns>",
160    Kind::Index => "idx_<table>_<columns>",
161    Kind::Check => "ch_<table>_<rule>",
162    Kind::Trigger => "tg_<table>_<event>",
163  };
164  format!(
165    "```sql\n-- {kind_label} (identifier): {token}\n-- No matching object in the catalog yet.\n-- Convention: {hint}\n```\n",
166    kind_label = kind.label(),
167  )
168}
169
170fn render_constraint(c: &Constraint) -> String {
171  if let Some(def) = &c.definition {
172    return format!("CONSTRAINT {} {def}", c.name);
173  }
174  let mut s = format!("CONSTRAINT {} ", c.name);
175  match c.kind {
176    ConstraintKind::PrimaryKey => s.push_str(&format!("PRIMARY KEY ({})", c.columns.join(", "))),
177    ConstraintKind::Unique => s.push_str(&format!("UNIQUE ({})", c.columns.join(", "))),
178    ConstraintKind::Check => s.push_str("CHECK (...)"),
179    ConstraintKind::ForeignKey => {
180      s.push_str(&format!("FOREIGN KEY ({})", c.columns.join(", ")));
181      if let Some(r) = &c.references {
182        s.push_str(&format!(" REFERENCES {}.{} ({})", r.schema, r.table, r.columns.join(", ")));
183      }
184    },
185  }
186  s
187}