Skip to main content

sql_splitter/
json_schema.rs

1//! JSON Schema generation for CLI output types.
2//!
3//! This module provides schema generation for all commands that support --json output,
4//! plus the editor-facing `generate-config.schema.json` for the `generate` command's
5//! YAML input (see [`generate_config_schema`]). Schemas are generated using the
6//! schemars crate and can be exported via the `schema` subcommand.
7
8use schemars::{generate::SchemaSettings, transform::RestrictFormats, JsonSchema, Schema};
9use serde_json::{json, Map, Value};
10use std::collections::BTreeMap;
11
12use crate::generate::registry::{ArgumentSpec, ExtensionRegistry};
13
14/// Returns all JSON schemas for commands that support --json output.
15/// Uses BTreeMap for deterministic ordering (important for diffable output).
16pub fn all_schemas() -> BTreeMap<&'static str, Schema> {
17    let mut schemas = schemars_schemas();
18    schemas.insert("generate-config", generate_config_schema());
19    schemas
20}
21
22/// The schemars-derived `--json` output schemas. Kept separate from the
23/// hand-built `generate-config` schema so requesting any one command's schema
24/// does not eagerly build (and depend on the schemars-shape assumptions of)
25/// the generate-config schema.
26fn schemars_schemas() -> BTreeMap<&'static str, Schema> {
27    let settings = SchemaSettings::default().with_transform(RestrictFormats::default());
28    let generator = settings.into_generator();
29
30    let mut schemas = BTreeMap::new();
31
32    schemas.insert(
33        "analyze",
34        generator
35            .clone()
36            .into_root_schema_for::<crate::cmd::analyze::AnalyzeJsonOutput>(),
37    );
38
39    schemas.insert(
40        "convert",
41        generator
42            .clone()
43            .into_root_schema_for::<crate::cmd::convert::ConvertJsonOutput>(),
44    );
45
46    schemas.insert(
47        "graph",
48        generator
49            .clone()
50            .into_root_schema_for::<crate::graph::format::json::ErdJson>(),
51    );
52
53    schemas.insert(
54        "merge",
55        generator
56            .clone()
57            .into_root_schema_for::<crate::cmd::merge::MergeJsonOutput>(),
58    );
59
60    schemas.insert(
61        "redact",
62        generator
63            .clone()
64            .into_root_schema_for::<crate::redactor::RedactStats>(),
65    );
66
67    schemas.insert(
68        "sample",
69        generator
70            .clone()
71            .into_root_schema_for::<crate::cmd::sample::SampleJsonOutput>(),
72    );
73
74    schemas.insert(
75        "shard",
76        generator
77            .clone()
78            .into_root_schema_for::<crate::cmd::shard::ShardJsonOutput>(),
79    );
80
81    schemas.insert(
82        "split",
83        generator
84            .clone()
85            .into_root_schema_for::<crate::cmd::split::SplitJsonOutput>(),
86    );
87
88    schemas.insert(
89        "validate",
90        generator.into_root_schema_for::<crate::validate::ValidationSummary>(),
91    );
92
93    schemas
94}
95
96/// Generate a single schema by command name.
97pub fn get_schema(command: &str) -> Option<Schema> {
98    // Build only what was asked for: `generate-config` is expensive and carries
99    // schemars-shape assumptions, so requesting another command's schema must
100    // not build it.
101    if command == "generate-config" {
102        return Some(generate_config_schema());
103    }
104    schemars_schemas().remove(command)
105}
106
107/// Schema-only view of the `generate` YAML root: either a `kind: model` or a
108/// `kind: overrides` document. `#[schemars(untagged)]` makes schemars emit a
109/// bare `oneOf` over the two variants' own schemas, rather than wrapping them
110/// in an externally-tagged envelope — each variant's `kind` field already
111/// discriminates. This type exists purely for schema generation; the real
112/// parse path is [`crate::synthetic::model::SyntheticFile::parse_value`].
113#[derive(JsonSchema)]
114#[schemars(untagged)]
115#[allow(dead_code)] // constructed only through the derive, never at runtime
116enum GenerateConfigRoot {
117    Model(crate::synthetic::model::SyntheticModel),
118    Overrides(crate::synthetic::overrides::SyntheticOverrides),
119}
120
121/// Build the editor-facing JSON Schema for the `generate` command's `kind:
122/// model` / `kind: overrides` YAML configs.
123///
124/// The structural shape (tables, columns, rows, relationships, ...) comes
125/// straight from `schemars` deriving over [`GenerateConfigRoot`]. The one
126/// part `schemars` cannot see is what a `generator:`/`modifiers:`/`planners:`
127/// entry's `{ kind, ...args }` shape actually accepts: `args` is a
128/// registry-resolved `BTreeMap<String, serde_yaml_ng::Value>` (see
129/// [`crate::synthetic::model::GeneratorConfig`]), so on its own schemars can
130/// only describe it as "any object". This function replaces that permissive
131/// placeholder with a `oneOf` composed from [`ExtensionRegistry::standard`]'s
132/// descriptors — one branch per registered generator/modifier/planner,
133/// keying on `kind` (primary name and aliases) and listing that operator's
134/// declared [`ArgumentSpec`]s, with required arguments enforced.
135///
136/// This documents the *standard* registry only: a statically-linked custom
137/// registry (extra generators/modifiers/planners compiled in by a
138/// downstream embedder) is validated at runtime by the compiler, not by this
139/// shipped schema.
140///
141/// Argument-strictness depth: each branch enumerates its `kind`, requires any
142/// argument [`ArgumentSpec`] marks `required`, and rejects unrecognized
143/// top-level argument names (`additionalProperties: false`). Per-argument
144/// value types and nested object shapes are still checked by each factory's
145/// compiler because [`ArgumentSpec`] deliberately carries no value schema.
146pub fn generate_config_schema() -> Schema {
147    let settings = SchemaSettings::default().with_transform(RestrictFormats::default());
148    let generator = settings.into_generator();
149    let mut schema = generator.into_root_schema_for::<GenerateConfigRoot>();
150
151    let registry = ExtensionRegistry::standard();
152
153    let generator_branches: Vec<Value> = registry
154        .generators()
155        .map(|factory| {
156            let d = factory.descriptor();
157            operator_branch(d.kind, d.aliases, d.arguments, true)
158        })
159        .collect();
160    let modifier_branches: Vec<Value> = registry
161        .modifiers()
162        .map(|factory| {
163            let d = factory.descriptor();
164            operator_branch(d.kind, d.aliases, d.arguments, true)
165        })
166        .collect();
167    let planner_branches: Vec<Value> = registry
168        .planners()
169        .map(|factory| {
170            let d = factory.descriptor();
171            operator_branch(d.kind, d.aliases, d.arguments, true)
172        })
173        .collect();
174
175    let obj = schema.ensure_object();
176    obj.insert(
177        "$id".to_string(),
178        json!("https://sql-splitter.dev/schemas/generate-config.schema.json"),
179    );
180    obj.insert("title".to_string(), json!("sql-splitter generate config"));
181    obj.insert(
182        "description".to_string(),
183        json!(
184            "Schema for the `sql-splitter generate` command's `kind: model` and \
185             `kind: overrides` YAML documents. Add `# yaml-language-server: \
186             $schema=https://sql-splitter.dev/schemas/generate-config.schema.json` \
187             as the first line of a config file for editor validation and completion."
188        ),
189    );
190
191    let defs = obj
192        .get_mut("$defs")
193        .and_then(Value::as_object_mut)
194        .expect("schemars always emits a $defs object for a type with nested definitions");
195
196    replace_def(defs, "GeneratorConfig", generator_branches);
197    replace_def(defs, "ModifierConfig", modifier_branches);
198    replace_def(defs, "PlannerConfig", planner_branches);
199
200    schema
201}
202
203/// Replace `defs[name]` with `{"oneOf": branches}`, keeping any existing
204/// `$defs`-level metadata (there is none today, but this avoids clobbering a
205/// future schemars addition such as `"description"`).
206fn replace_def(defs: &mut Map<String, Value>, name: &str, branches: Vec<Value>) {
207    defs.insert(name.to_string(), json!({ "oneOf": branches }));
208}
209
210/// One `oneOf` branch for a single registered operator: `kind` is restricted
211/// to the operator's primary name and aliases, each declared argument is
212/// accepted (required arguments are required). When `closed` is `true`, no
213/// other property is allowed (`additionalProperties: false`); `closed` exists
214/// for callers that build extension schemas with intentionally open maps.
215fn operator_branch(
216    kind: &str,
217    aliases: &[&str],
218    arguments: &[ArgumentSpec],
219    closed: bool,
220) -> Value {
221    let mut kinds = vec![Value::String(kind.to_string())];
222    kinds.extend(aliases.iter().map(|alias| Value::String(alias.to_string())));
223
224    let mut properties = Map::new();
225    properties.insert("kind".to_string(), json!({ "enum": kinds }));
226
227    let mut required = vec!["kind".to_string()];
228    for arg in arguments {
229        properties.insert(arg.name.to_string(), json!({ "description": arg.summary }));
230        if arg.required {
231            required.push(arg.name.to_string());
232        }
233    }
234
235    json!({
236        "type": "object",
237        "properties": properties,
238        "required": required,
239        "additionalProperties": !closed,
240    })
241}