Skip to main content

dsl_hover/
render.rs

1//! Markdown renderers for hover bodies.
2//!
3//! Table hover ships both a column-list table AND a synthesised
4//! `CREATE TABLE` block so the user sees the source-level shape (types,
5//! NOT NULL, DEFAULT, FK targets) in one glance. Column / function /
6//! column-decl hovers each have their own renderer.
7
8use dsl_catalog::{Column, Constraint, ConstraintKind, Table, TableKind, Type, TypeKind, display_type};
9
10/// Render the table card + every catalog-wide attachment found via
11/// `cat` (inbound FKs from other tables, sequences owned by this
12/// table's columns). Used by the hover handler which has the full
13/// catalog in scope; resolver.rs (which doesn't) keeps calling
14/// `table()` for the bare card.
15pub fn table_with_catalog(t: &Table, cat: &dsl_catalog::Catalog) -> String {
16  let mut s = table(t);
17  let inbound = inbound_fks(t, cat);
18  if !inbound.is_empty() {
19    s.push_str("\n**Referenced by**\n\n");
20    s.push_str("```sql\n");
21    for line in inbound {
22      s.push_str(&line);
23      s.push('\n');
24    }
25    s.push_str("```\n");
26  }
27  let owned: Vec<&dsl_catalog::Sequence> = cat
28    .sequences
29    .iter()
30    .filter(|seq| {
31      let Some(owner) = &seq.owned_by_column else { return false };
32      let parts: Vec<&str> = owner.split('.').collect();
33      parts.len() >= 2 && parts[parts.len() - 2].eq_ignore_ascii_case(&t.name)
34    })
35    .collect();
36  if !owned.is_empty() {
37    s.push_str("\n**Sequences**\n\n");
38    s.push_str("```sql\n");
39    for seq in owned {
40      let cycle = if seq.cycle { " CYCLE" } else { "" };
41      s.push_str(&format!(
42        "CREATE SEQUENCE {}.{} AS {} START {} MIN {} MAX {} INCREMENT {}{};\n",
43        seq.schema, seq.name, seq.data_type, seq.start_value, seq.min_value, seq.max_value, seq.increment_by, cycle
44      ));
45      if let Some(o) = &seq.owned_by_column {
46        s.push_str(&format!("ALTER SEQUENCE {}.{} OWNED BY {};\n", seq.schema, seq.name, o));
47      }
48    }
49    s.push_str("```\n");
50  }
51  s
52}
53
54fn inbound_fks(t: &Table, cat: &dsl_catalog::Catalog) -> Vec<String> {
55  let mut out = Vec::new();
56  for other in cat.tables() {
57    if other.name.eq_ignore_ascii_case(&t.name) && other.schema.eq_ignore_ascii_case(&t.schema) {
58      continue;
59    }
60    for c in &other.constraints {
61      if !matches!(c.kind, ConstraintKind::ForeignKey) {
62        continue;
63      }
64      let Some(refs) = &c.references else { continue };
65      if !refs.table.eq_ignore_ascii_case(&t.name) {
66        continue;
67      }
68      let local = c.columns.join(", ");
69      let target = refs.columns.join(", ");
70      out.push(format!("-- FK: {}.{} ({}) -> {}.{} ({})", other.schema, other.name, local, t.schema, t.name, target));
71    }
72  }
73  out
74}
75
76pub fn table(t: &Table) -> String {
77  // Views render their defining query rather than a synthesised CREATE TABLE
78  // -- the SELECT is what a user hovering a view actually wants to see.
79  if matches!(t.kind, TableKind::View | TableKind::MaterializedView)
80    && let Some(def) = &t.definition
81    && !def.trim().is_empty()
82  {
83    return render_view(t, def);
84  }
85
86  // Compact view: skip the `# Table public.<name>` markdown title and
87  // emit the DDL block straight up. CREATE TABLE / CREATE VIEW already
88  // declares the kind + fully-qualified name on its first line, so the
89  // title was redundant noise.
90  if t.columns.is_empty() {
91    let fq = format!("{}.{}", t.schema, t.name);
92    let base = match t.kind {
93      TableKind::View => "View",
94      TableKind::MaterializedView => "Materialised View",
95      _ => "Table",
96    };
97    // WITHOUT ROWID and STRICT are independent SQLite table options.
98    let mut opts = Vec::new();
99    if matches!(t.kind, TableKind::WithoutRowid) {
100      opts.push("WITHOUT ROWID");
101    }
102    if t.strict {
103      opts.push("STRICT");
104    }
105    let kind = if opts.is_empty() { base.to_string() } else { format!("{base} ({})", opts.join(", ")) };
106    return format!("_{kind} `{fq}` -- no columns cached; run `:DBRefresh` after connecting._\n");
107  }
108
109  let mut s = String::new();
110  s.push_str("```sql\n");
111  s.push_str(&table_ddl(t));
112  s.push('\n');
113
114  // Owner: surface ownership on its own line right under the CREATE TABLE
115  // so a quick hover answers "who owns this." Mirrors how PG's
116  // `\d <table>` shows the owner in the metadata block.
117  if let Some(owner) = &t.owner
118    && !owner.is_empty()
119  {
120    s.push_str(&format!("ALTER TABLE {}.{} OWNER TO {};\n", t.schema, t.name, owner));
121  }
122
123  if !t.indexes.is_empty() {
124    s.push_str("\n-- Indexes\n");
125    for i in &t.indexes {
126      if let Some(def) = &i.definition {
127        s.push_str(def);
128        if !def.trim_end().ends_with(';') {
129          s.push(';');
130        }
131        s.push('\n');
132      } else {
133        let unique = if i.unique { "UNIQUE " } else { "" };
134        s.push_str(&format!(
135          "CREATE {unique}INDEX {} ON {}.{} ({});\n",
136          i.name,
137          t.schema,
138          t.name,
139          i.columns.join(", ")
140        ));
141      }
142    }
143  }
144
145  if !t.triggers.is_empty() {
146    s.push_str("\n-- Triggers\n");
147    for tg in &t.triggers {
148      s.push_str(&format!(
149        "CREATE TRIGGER {} {} {} ON {}.{} FOR EACH {} EXECUTE FUNCTION {}();\n",
150        tg.name, tg.timing, tg.event, t.schema, t.name, tg.granularity, tg.function
151      ));
152    }
153  }
154
155  if !t.policies.is_empty() {
156    s.push_str("\n-- Policies (Row-Level Security)\n");
157    for p in &t.policies {
158      s.push_str(&format!(
159        "CREATE POLICY {} ON {}.{} AS {} FOR {} TO {}",
160        p.name, t.schema, t.name, p.permissive, p.command, p.roles
161      ));
162      if let Some(u) = &p.using_expr {
163        s.push_str(&format!(" USING ({u})"));
164      }
165      if let Some(c) = &p.check_expr {
166        s.push_str(&format!(" WITH CHECK ({c})"));
167      }
168      s.push_str(";\n");
169    }
170  }
171
172  if let Some(comment) = &t.comment
173    && !comment.trim().is_empty()
174  {
175    s.push_str("\n-- Comment\n");
176    s.push_str("COMMENT ON TABLE ");
177    s.push_str(&t.schema);
178    s.push('.');
179    s.push_str(&t.name);
180    s.push_str(" IS ");
181    s.push('\'');
182    s.push_str(&comment.replace('\'', "''"));
183    s.push_str("';\n");
184  }
185
186  s.push_str("```\n");
187  s
188}
189
190/// Render a view / materialized view as its defining query, with the output
191/// columns listed as a trailing comment block. Keywords follow the active
192/// hover keyword case.
193fn render_view(t: &Table, def: &str) -> String {
194  let case = crate::current_keyword_case();
195  let kw = |k: &str| case.apply(k);
196  let create =
197    if matches!(t.kind, TableKind::MaterializedView) { kw("CREATE MATERIALIZED VIEW") } else { kw("CREATE VIEW") };
198
199  let mut s = String::new();
200  s.push_str("```sql\n");
201  s.push_str(&format!("{} {}.{} {}\n", create, t.schema, t.name, kw("AS")));
202  s.push_str(def.trim_end().trim_end_matches(';').trim_end());
203  s.push_str(";\n");
204
205  if !t.columns.is_empty() {
206    s.push_str("\n-- Columns\n");
207    for c in &t.columns {
208      // Offline-scanned views carry column names without types.
209      if c.data_type.is_empty() {
210        s.push_str(&format!("--   {}\n", c.name));
211      } else {
212        s.push_str(&format!("--   {} {}\n", c.name, case.apply(display_type(&c.data_type))));
213      }
214    }
215  }
216
217  if let Some(comment) = &t.comment
218    && !comment.trim().is_empty()
219  {
220    s.push_str(&format!("\n-- {}\n", comment.trim()));
221  }
222
223  s.push_str("```\n");
224  s
225}
226
227/// Synthesise a CREATE TABLE that mirrors the catalog. Columns first,
228/// then constraints. Aligned name + type columns for readability.
229/// Keywords are cased according to the active hover keyword case (set
230/// by `dsl_hover::hover_with`).
231pub fn table_ddl(t: &Table) -> String {
232  let case = crate::current_keyword_case();
233  let kw = |k: &str| case.apply(k);
234  let fq = format!("{}.{}", t.schema, t.name);
235  let mut lines: Vec<String> = Vec::new();
236  lines.push(format!("{} {} {fq} (", kw("CREATE"), kw("TABLE")));
237
238  // Inline-origin single-column constraints fold back onto the column
239  // row (`id int PRIMARY KEY`, `email text UNIQUE`,
240  // `parent_id int REFERENCES users(id)`). Anything table-level renders
241  // as a separate `CONSTRAINT ...` line below the columns.
242  let inline_by_col: std::collections::HashMap<String, Vec<&Constraint>> = {
243    let mut m: std::collections::HashMap<String, Vec<&Constraint>> = std::collections::HashMap::new();
244    for con in &t.constraints {
245      if con.inline && con.columns.len() == 1 {
246        m.entry(con.columns[0].to_ascii_lowercase()).or_default().push(con);
247      }
248    }
249    m
250  };
251
252  let name_w = t.columns.iter().map(|c| c.name.len()).max().unwrap_or(0);
253  let type_w = t.columns.iter().map(|c| display_type(&c.data_type).len()).max().unwrap_or(0);
254
255  let mut members: Vec<String> = Vec::new();
256  for c in &t.columns {
257    let inlines = inline_by_col.get(&c.name.to_ascii_lowercase());
258    let has_inline_pk = inlines.is_some_and(|v| v.iter().any(|c| matches!(c.kind, ConstraintKind::PrimaryKey)));
259    let mut row =
260      format!("    {:<nw$} {:<tw$}", c.name, case.apply(display_type(&c.data_type)), nw = name_w, tw = type_w);
261    // PRIMARY KEY already implies NOT NULL -- don't double up.
262    if !c.nullable && !has_inline_pk {
263      row.push(' ');
264      row.push_str(&kw("NOT NULL"));
265    }
266    if let Some(d) = &c.default {
267      row.push(' ');
268      row.push_str(&kw("DEFAULT"));
269      row.push(' ');
270      row.push_str(d);
271    }
272    if let Some(cons) = inlines {
273      // Stable order: PK, UNIQUE, FK, CHECK.
274      let order = |k: &ConstraintKind| match k {
275        ConstraintKind::PrimaryKey => 0,
276        ConstraintKind::Unique => 1,
277        ConstraintKind::ForeignKey => 2,
278        ConstraintKind::Check => 3,
279      };
280      let mut sorted: Vec<&&Constraint> = cons.iter().collect();
281      sorted.sort_by_key(|c| order(&c.kind));
282      for con in sorted {
283        row.push(' ');
284        match con.kind {
285          ConstraintKind::PrimaryKey => row.push_str(&kw("PRIMARY KEY")),
286          ConstraintKind::Unique => row.push_str(&kw("UNIQUE")),
287          ConstraintKind::ForeignKey => {
288            row.push_str(&kw("REFERENCES"));
289            if let Some(r) = &con.references {
290              let target_cols =
291                if r.columns.is_empty() { String::new() } else { format!(" ({})", r.columns.join(", ")) };
292              row.push(' ');
293              if r.schema.is_empty() || r.schema.eq_ignore_ascii_case("public") {
294                row.push_str(&format!("{}{target_cols}", r.table));
295              } else {
296                row.push_str(&format!("{}.{}{target_cols}", r.schema, r.table));
297              }
298            }
299          },
300          ConstraintKind::Check => {
301            row.push_str(&kw("CHECK"));
302            if let Some(def) = &con.definition {
303              row.push(' ');
304              row.push_str(def);
305            }
306          },
307        }
308      }
309    }
310    members.push(row);
311  }
312  // Table-level constraints get a blank line then a `CONSTRAINT ...` row each.
313  // Inline-origin constraints are already folded onto the column rows above.
314  let top_level: Vec<&Constraint> = t.constraints.iter().filter(|c| !c.inline).collect();
315  let inject_gap = !t.columns.is_empty() && !top_level.is_empty();
316  let columns_end_idx = members.len();
317  for con in top_level {
318    members.push(render_constraint(con));
319  }
320
321  let last_non_blank = members.len().saturating_sub(1);
322  for (i, m) in members.into_iter().enumerate() {
323    if inject_gap && i == columns_end_idx {
324      lines.push(String::new());
325    }
326    if i < last_non_blank {
327      lines.push(format!("{m},"));
328    } else {
329      lines.push(m);
330    }
331  }
332  // Trailing table-option clause after the column list. SQLite carries
333  // WITHOUT ROWID / STRICT (comma-joined, possibly both); MySQL carries a
334  // pre-rendered `ENGINE=... DEFAULT CHARSET=...` string in `options`. The
335  // two dialects never co-occur on one table.
336  let mut sqlite_opts: Vec<String> = Vec::new();
337  if matches!(t.kind, TableKind::WithoutRowid) {
338    sqlite_opts.push(kw("WITHOUT ROWID"));
339  }
340  if t.strict {
341    sqlite_opts.push(kw("STRICT"));
342  }
343  if !sqlite_opts.is_empty() {
344    lines.push(format!(") {};", sqlite_opts.join(", ")));
345  } else if let Some(opts) = t.options.as_deref().map(str::trim).filter(|o| !o.is_empty()) {
346    lines.push(format!(") {opts};"));
347  } else {
348    lines.push(");".into());
349  }
350  lines.join("\n")
351}
352
353fn render_constraint(c: &Constraint) -> String {
354  // Prefer the live `pg_get_constraintdef` output when introspection
355  // captured it -- it's the authoritative form straight from Postgres.
356  if let Some(def) = &c.definition {
357    return format!("    CONSTRAINT {} {def}", c.name);
358  }
359  let mut s = format!("    CONSTRAINT {} ", c.name);
360  match c.kind {
361    ConstraintKind::PrimaryKey => s.push_str(&format!("PRIMARY KEY ({})", c.columns.join(", "))),
362    ConstraintKind::Unique => s.push_str(&format!("UNIQUE ({})", c.columns.join(", "))),
363    ConstraintKind::Check => s.push_str("CHECK (...)"),
364    ConstraintKind::ForeignKey => {
365      s.push_str(&format!("FOREIGN KEY ({})", c.columns.join(", ")));
366      if let Some(r) = &c.references {
367        if r.schema.is_empty() || r.schema.eq_ignore_ascii_case("public") {
368          s.push_str(&format!(" REFERENCES {} ({})", r.table, r.columns.join(", ")));
369        } else {
370          s.push_str(&format!(" REFERENCES {}.{} ({})", r.schema, r.table, r.columns.join(", ")));
371        }
372      }
373    },
374  }
375  s
376}
377
378pub fn column(t: &Table, c: &Column) -> String {
379  // Blank lines around every paragraph and a bullet list so markdown
380  // renders the spec stack instead of collapsing onto one line. Long
381  // default expressions get wrapped at 72 cols so the hover float
382  // stays narrow.
383  let mut s = format!("# Column `{}.{}.{}`\n\n", t.schema, t.name, c.name);
384  s.push_str(&format!("- **type:** `{}`\n", display_type(&c.data_type)));
385  s.push_str(&format!("- **nullable:** `{}`\n", c.nullable));
386  if let Some(g) = &c.generated {
387    let wrapped = dsl_knowledge::wrap_paragraphs(g, 64);
388    s.push_str(&format!("- **generated:** `GENERATED ALWAYS AS ({wrapped}) STORED`\n"));
389  }
390  if let Some(d) = &c.default {
391    let wrapped = dsl_knowledge::wrap_paragraphs(d, 64);
392    s.push_str(&format!("- **default:** `{wrapped}`\n"));
393  }
394  // Mention every constraint on this column from its table.
395  let constraints_for_col: Vec<&Constraint> =
396    t.constraints.iter().filter(|con| con.columns.iter().any(|cn| cn.eq_ignore_ascii_case(&c.name))).collect();
397  if !constraints_for_col.is_empty() {
398    s.push_str("- **constraints:**\n");
399    for con in constraints_for_col {
400      let kind = match con.kind {
401        ConstraintKind::PrimaryKey => "PRIMARY KEY",
402        ConstraintKind::ForeignKey => "FOREIGN KEY",
403        ConstraintKind::Unique => "UNIQUE",
404        ConstraintKind::Check => "CHECK",
405      };
406      s.push_str(&format!("  - {kind} (`{}`)\n", con.name));
407    }
408  }
409  if let Some(cm) = &c.comment
410    && !cm.trim().is_empty()
411  {
412    s.push_str(&format!("\n{}\n", dsl_knowledge::wrap_paragraphs(cm, 72)));
413  }
414  s.push_str(&format!("\n_From table `{}.{}`_\n", t.schema, t.name));
415  s
416}
417
418/// Variant of [`column`] that also lists every FK in the catalog
419/// pointing at this column. The hover handler uses this when the
420/// catalog is in scope.
421pub fn column_with_catalog(t: &Table, c: &Column, cat: &dsl_catalog::Catalog) -> String {
422  let mut s = column(t, c);
423  let inbound: Vec<String> = cat
424    .tables()
425    .flat_map(|other| {
426      other.constraints.iter().filter_map(move |con| {
427        if !matches!(con.kind, ConstraintKind::ForeignKey) {
428          return None;
429        }
430        let refs = con.references.as_ref()?;
431        if !refs.table.eq_ignore_ascii_case(&t.name) {
432          return None;
433        }
434        if !refs.columns.iter().any(|x| x.eq_ignore_ascii_case(&c.name)) {
435          return None;
436        }
437        let local = con.columns.join(", ");
438        Some(format!("- `{}.{}` ({})", other.schema, other.name, local))
439      })
440    })
441    .collect();
442  if !inbound.is_empty() {
443    s.push_str("\n**Referenced by**\n\n");
444    for line in inbound {
445      s.push_str(&line);
446      s.push('\n');
447    }
448  }
449  s
450}
451
452pub fn column_in_tables(items: &[(&Table, &Column)]) -> String {
453  if items.len() == 1 {
454    return column(items[0].0, items[0].1);
455  }
456  let mut s = format!("# Column `{}` (in {} tables)\n\n", items[0].1.name, items.len());
457  let rows: Vec<Vec<String>> = items
458    .iter()
459    .map(|(t, c)| {
460      vec![
461        format!("{}.{}", t.schema, t.name),
462        display_type(&c.data_type).to_string(),
463        if c.nullable { "YES" } else { "NO" }.into(),
464      ]
465    })
466    .collect();
467  s.push_str(&crate::md_table::render(&["table", "type", "nullable"], &rows));
468  s
469}
470
471/// Render a column declaration with no implicit-spec data.
472pub fn column_decl(table_name: &str, col: &dsl_parse::ColumnDef) -> String {
473  column_decl_with_implicit(table_name, col, &crate::implicit::Implicit::default())
474}
475
476/// Render a column declaration plus every implicit spec derived from
477/// the parent table (PRIMARY KEY -> NOT NULL + UNIQUE, FOREIGN KEY,
478/// SERIAL / IDENTITY -> NOT NULL + auto-increment). The result is the
479/// "full spec view" -- declared + implicit, in one table.
480pub fn column_decl_with_implicit(
481  table_name: &str,
482  col: &dsl_parse::ColumnDef,
483  implicit: &crate::implicit::Implicit,
484) -> String {
485  // Compute effective values.
486  let nullable_effective = col.nullable && !implicit.primary_key && !implicit.auto_increment;
487  let unique_effective = implicit.unique || implicit.primary_key;
488
489  let mut s = format!("# Column `{}.{}`\n\n_DDL definition (current buffer)_\n\n", table_name, col.name);
490
491  let mut rows: Vec<Vec<String>> = Vec::new();
492  let push = |rows: &mut Vec<Vec<String>>, spec: &str, value: &str, declared: bool| {
493    rows.push(vec![spec.into(), value.into(), (if declared { "declared" } else { "implicit" }).into()]);
494  };
495  push(&mut rows, "type", &col.type_name, true);
496  push(
497    &mut rows,
498    "nullable",
499    if nullable_effective { "YES" } else { "NO" },
500    !implicit.primary_key && !implicit.auto_increment,
501  );
502  if implicit.primary_key {
503    push(&mut rows, "primary key", "yes", false);
504  }
505  if unique_effective && !implicit.primary_key {
506    push(&mut rows, "unique", "yes", !implicit.unique);
507  }
508  if implicit.auto_increment {
509    push(&mut rows, "auto-increment", "yes (SERIAL / IDENTITY)", false);
510  }
511  if let Some(fk) = &implicit.foreign_key {
512    push(&mut rows, "references", &fk.references, false);
513  }
514  if implicit.check_count > 0 {
515    push(&mut rows, "check constraints", &format!("{}", implicit.check_count), false);
516  }
517  if let Some(d) = &col.default {
518    push(&mut rows, "default", d, true);
519  } else if implicit.auto_increment {
520    push(&mut rows, "default", "nextval(...) (implicit via SERIAL / IDENTITY)", false);
521  }
522  s.push_str(&crate::md_table::render(&["spec", "value", "source"], &rows));
523
524  s.push_str("\n```sql\n");
525  s.push_str(&col.name);
526  s.push(' ');
527  s.push_str(&col.type_name);
528  if !nullable_effective {
529    s.push_str(" NOT NULL");
530  }
531  if let Some(d) = &col.default {
532    s.push_str(" DEFAULT ");
533    s.push_str(d);
534  }
535  if implicit.primary_key {
536    s.push_str(" PRIMARY KEY");
537  }
538  s.push_str("\n```\n");
539
540  if implicit.primary_key || implicit.auto_increment || implicit.foreign_key.is_some() || implicit.unique {
541    s.push_str(
542      "\n_Implicit specs come from table-level constraints \
543             (PRIMARY KEY, UNIQUE, FOREIGN KEY) or the column type \
544             (SERIAL, IDENTITY)._\n",
545    );
546  }
547  s
548}
549
550/// Render a DB-side function with signature + return type + body when
551/// available. Body is taken from the `comment` field, where introspection
552/// stashes the `pg_get_functiondef()` output.
553pub fn function_full(f: &dsl_catalog::Function) -> String {
554  let args = f
555    .arguments
556    .iter()
557    .map(|a| match &a.name {
558      Some(n) => format!("{n} {}", display_type(&a.data_type)),
559      None => display_type(&a.data_type).to_string(),
560    })
561    .collect::<Vec<_>>()
562    .join(", ");
563  let mut s = format!("# Function `{}.{}`\n\n_DB function_\n\n", f.schema, f.name);
564  s.push_str("```sql\n");
565  // Break the signature across lines when it grows past 72 cols --
566  // long argument lists are otherwise unreadable inside the hover.
567  let sig = format!("{}.{}({}) -> {}", f.schema, f.name, args, display_type(&f.return_type));
568  if sig.len() > 72 && !args.is_empty() {
569    s.push_str(&format!("{}.{} (\n", f.schema, f.name));
570    for (i, a) in f.arguments.iter().enumerate() {
571      let arg_str = match &a.name {
572        Some(n) => format!("    {n} {}", display_type(&a.data_type)),
573        None => format!("    {}", display_type(&a.data_type)),
574      };
575      s.push_str(&arg_str);
576      if i + 1 < f.arguments.len() {
577        s.push(',');
578      }
579      s.push('\n');
580    }
581    s.push_str(&format!(") -> {}", display_type(&f.return_type)));
582  } else {
583    s.push_str(&sig);
584  }
585  s.push_str("\n```\n\n");
586  if let Some(body) = function_body(f) {
587    s.push_str("**Source**\n\n```sql\n");
588    s.push_str(&body);
589    s.push_str("\n```\n");
590  }
591  s
592}
593
594fn function_body(f: &dsl_catalog::Function) -> Option<String> {
595  let c = f.comment.as_ref()?;
596  let trimmed = c.trim_start().to_ascii_uppercase();
597  if trimmed.starts_with("CREATE") { Some(c.clone()) } else { None }
598}
599
600pub fn user_type(t: &Type) -> String {
601  let fq = format!("{}.{}", t.schema, t.name);
602  let kind = match t.kind {
603    TypeKind::Enum => "enum",
604    TypeKind::Domain => "domain",
605    TypeKind::Composite => "composite type",
606  };
607  format!("# `{fq}`\n_{kind}_\n")
608}
609
610#[cfg(test)]
611mod tests {
612  use super::*;
613
614  fn view(kind: TableKind, definition: Option<&str>, columns: Vec<Column>) -> Table {
615    Table {
616      schema: "public".into(),
617      name: "v".into(),
618      kind,
619      columns,
620      constraints: Vec::new(),
621      indexes: Vec::new(),
622      triggers: Vec::new(),
623      policies: Vec::new(),
624      comment: None,
625      row_estimate: None,
626      owner: None,
627      definition: definition.map(str::to_string),
628      strict: false,
629      options: None,
630    }
631  }
632
633  #[test]
634  fn view_renders_defining_query() {
635    let out = table(&view(TableKind::View, Some("SELECT id FROM t"), Vec::new()));
636    assert!(out.contains("CREATE VIEW public.v AS"), "{out}");
637    assert!(out.contains("SELECT id FROM t;"), "{out}");
638  }
639
640  #[test]
641  fn materialized_view_label() {
642    let out = table(&view(TableKind::MaterializedView, Some("SELECT 1"), Vec::new()));
643    assert!(out.contains("CREATE MATERIALIZED VIEW public.v AS"), "{out}");
644  }
645
646  #[test]
647  fn view_without_definition_falls_back() {
648    // No definition cached -> keep the legacy "no columns" rendering path
649    // rather than emitting an empty CREATE VIEW.
650    let out = table(&view(TableKind::View, None, Vec::new()));
651    assert!(out.contains("View `public.v`"), "{out}");
652  }
653
654  fn col(name: &str) -> Column {
655    Column {
656      name: name.into(),
657      data_type: "int".into(),
658      nullable: true,
659      default: None,
660      comment: None,
661      generated: None,
662      json_keys: None,
663    }
664  }
665
666  fn sqlite_table(kind: TableKind, strict: bool) -> Table {
667    let mut t = view(kind, None, vec![col("a")]);
668    t.strict = strict;
669    t
670  }
671
672  #[test]
673  fn strict_table_ddl_trailer() {
674    let out = table_ddl(&sqlite_table(TableKind::Table, true));
675    assert!(out.trim_end().ends_with(") STRICT;"), "{out}");
676  }
677
678  #[test]
679  fn without_rowid_and_strict_combine_in_ddl() {
680    let out = table_ddl(&sqlite_table(TableKind::WithoutRowid, true));
681    assert!(out.trim_end().ends_with(") WITHOUT ROWID, STRICT;"), "{out}");
682  }
683
684  #[test]
685  fn mysql_options_render_in_ddl_trailer() {
686    let mut t = sqlite_table(TableKind::Table, false);
687    t.options = Some("ENGINE=InnoDB DEFAULT CHARSET=utf8mb4".into());
688    let out = table_ddl(&t);
689    assert!(out.trim_end().ends_with(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"), "{out}");
690  }
691
692  #[test]
693  fn sqlite_options_take_precedence_over_generic_options() {
694    // A STRICT SQLite table never also has MySQL `options`, but guard the
695    // precedence anyway: the kind/flag trailer wins.
696    let mut t = sqlite_table(TableKind::WithoutRowid, true);
697    t.options = Some("ENGINE=InnoDB".into());
698    let out = table_ddl(&t);
699    assert!(out.trim_end().ends_with(") WITHOUT ROWID, STRICT;"), "{out}");
700  }
701
702  #[test]
703  fn empty_strict_table_label() {
704    // No columns -> the compact label reflects the option.
705    let out = table(&sqlite_table(TableKind::Table, true));
706    // sqlite_table has a column, so drop it to hit the empty-label path.
707    let mut empty = sqlite_table(TableKind::Table, true);
708    empty.columns.clear();
709    let label = table(&empty);
710    assert!(label.contains("Table (STRICT)"), "{label}");
711    // With columns it renders the DDL trailer instead.
712    assert!(out.contains("STRICT"), "{out}");
713  }
714}