1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
//! Domain-specific methods for [`CompiledSchema`].
//!
//! Fact table management, observers, federation metadata, security configuration,
//! RLS, role scopes, tenancy, SDL generation, and schema validation.
#[cfg(feature = "federation")]
use std::collections::HashMap;
use std::fmt::Write as _;
use super::schema::{CURRENT_SCHEMA_FORMAT_VERSION, CompiledSchema};
use crate::{
compiler::fact_table::FactTableMetadata,
schema::{
observer_types::ObserverDefinition,
security_config::{RoleDefinition, SecurityConfig},
},
};
impl CompiledSchema {
/// Verify that the compiled schema was produced by a compatible compiler version.
///
/// Schemas without a `schema_format_version` field (produced before v2.1) are
/// accepted with a warning. Schemas with a mismatched version are rejected to
/// prevent silent data corruption from structural changes.
///
/// # Errors
///
/// Returns an error string if the version is present and incompatible.
pub fn validate_format_version(&self) -> Result<(), String> {
match self.schema_format_version {
None => {
// Pre-versioning schema — accept but callers may want to warn.
Ok(())
},
Some(v) if v == CURRENT_SCHEMA_FORMAT_VERSION => Ok(()),
Some(v) => Err(format!(
"Schema format version mismatch: compiled schema has version {v}, \
but this runtime expects version {CURRENT_SCHEMA_FORMAT_VERSION}. \
Please recompile your schema with the matching fraiseql-cli version."
)),
}
}
/// Register fact table metadata.
///
/// # Arguments
///
/// * `table_name` - Fact table name (e.g., `tf_sales`)
/// * `metadata` - Typed `FactTableMetadata`
pub fn add_fact_table(&mut self, table_name: String, metadata: FactTableMetadata) {
self.fact_tables.insert(table_name, metadata);
}
/// Get fact table metadata by name.
///
/// # Arguments
///
/// * `name` - Fact table name
///
/// # Returns
///
/// Fact table metadata if found
#[must_use]
pub fn get_fact_table(&self, name: &str) -> Option<&FactTableMetadata> {
self.fact_tables.get(name)
}
/// List all fact table names.
///
/// # Returns
///
/// Vector of fact table names
#[must_use]
pub fn list_fact_tables(&self) -> Vec<&str> {
self.fact_tables.keys().map(String::as_str).collect()
}
/// Check if schema contains any fact tables.
#[must_use]
pub fn has_fact_tables(&self) -> bool {
!self.fact_tables.is_empty()
}
/// Find an observer definition by name.
#[must_use]
pub fn find_observer(&self, name: &str) -> Option<&ObserverDefinition> {
self.observers.iter().find(|o| o.name == name)
}
/// Get all observers for a specific entity type.
#[must_use]
pub fn find_observers_for_entity(&self, entity: &str) -> Vec<&ObserverDefinition> {
self.observers.iter().filter(|o| o.entity == entity).collect()
}
/// Get all observers for a specific event type (INSERT, UPDATE, DELETE).
#[must_use]
pub fn find_observers_for_event(&self, event: &str) -> Vec<&ObserverDefinition> {
self.observers.iter().filter(|o| o.event == event).collect()
}
/// Check if schema contains any observers.
#[must_use]
pub const fn has_observers(&self) -> bool {
!self.observers.is_empty()
}
/// Get total number of observers.
#[must_use]
pub const fn observer_count(&self) -> usize {
self.observers.len()
}
/// Get federation metadata from schema.
///
/// # Returns
///
/// Federation metadata if configured in schema
#[cfg(feature = "federation")]
#[must_use]
pub fn federation_metadata(&self) -> Option<crate::federation::FederationMetadata> {
self.federation.as_ref().filter(|fed| fed.enabled).map(|fed| {
let types = fed
.entities
.iter()
.map(|e| crate::federation::types::FederatedType {
name: e.name.clone(),
keys: vec![crate::federation::types::KeyDirective {
fields: e.key_fields.clone(),
resolvable: true,
}],
is_extends: false,
external_fields: Vec::new(),
shareable_fields: Vec::new(),
inaccessible_fields: Vec::new(),
field_directives: std::collections::HashMap::new(),
type_shareable: false,
})
.collect();
crate::federation::FederationMetadata {
enabled: fed.enabled,
version: fed.version.clone().unwrap_or_else(|| "v2".to_string()),
types,
remote_subscription_fields: HashMap::new(),
}
})
}
/// Stub federation metadata when federation feature is disabled.
#[cfg(not(feature = "federation"))]
#[must_use]
pub const fn federation_metadata(&self) -> Option<()> {
None
}
/// Get security configuration from schema.
///
/// # Returns
///
/// Security configuration if present (includes role definitions)
#[must_use]
pub const fn security_config(&self) -> Option<&SecurityConfig> {
self.security.as_ref()
}
/// Returns `true` if this schema declares a multi-tenant deployment.
///
/// Multi-tenant schemas require Row-Level Security (RLS) to be active whenever
/// query result caching is enabled. Without RLS, all tenants sharing the same
/// query parameters would receive the same cached response.
///
/// Detection is based on `security.multi_tenant` in the compiled schema JSON.
#[must_use]
pub fn is_multi_tenant(&self) -> bool {
self.security.as_ref().is_some_and(|s| s.multi_tenant)
}
/// Returns the tenancy isolation mode configured for this schema.
///
/// Defaults to `TenancyMode::None` when no security or tenancy configuration
/// is present, meaning single-tenant operation with no isolation machinery.
#[must_use]
pub fn tenancy_mode(&self) -> crate::schema::TenancyMode {
self.security
.as_ref()
.map_or(crate::schema::TenancyMode::None, |s| s.tenancy.mode)
}
/// Returns the tenancy configuration, if present.
///
/// Returns `None` when no security configuration exists. Returns the
/// default `TenancyConfig` (mode=none) when security exists but tenancy
/// is not explicitly configured.
#[must_use]
pub fn tenancy_config(&self) -> Option<&crate::schema::TenancyConfig> {
self.security.as_ref().map(|s| &s.tenancy)
}
/// Find a role definition by name.
///
/// # Arguments
///
/// * `role_name` - Name of the role to find
///
/// # Returns
///
/// Role definition if found
#[must_use]
pub fn find_role(&self, role_name: &str) -> Option<RoleDefinition> {
self.security.as_ref().and_then(|config| config.find_role(role_name).cloned())
}
/// Get scopes for a role.
///
/// # Arguments
///
/// * `role_name` - Name of the role
///
/// # Returns
///
/// Vector of scopes granted to the role
#[must_use]
pub fn get_role_scopes(&self, role_name: &str) -> Vec<String> {
self.security
.as_ref()
.map(|config| config.get_role_scopes(role_name))
.unwrap_or_default()
}
/// Check if a role has a specific scope.
///
/// # Arguments
///
/// * `role_name` - Name of the role
/// * `scope` - Scope to check for
///
/// # Returns
///
/// true if role has the scope, false otherwise
#[must_use]
pub fn role_has_scope(&self, role_name: &str, scope: &str) -> bool {
self.security
.as_ref()
.is_some_and(|config| config.role_has_scope(role_name, scope))
}
/// Returns `true` if Row-Level Security policies are declared in this schema.
///
/// Used at server startup to validate that caching is safe for multi-tenant
/// deployments. When caching is enabled and no RLS policies are configured,
/// the server emits a startup warning about potential data leakage.
///
/// # Example
///
/// ```
/// use fraiseql_core::schema::CompiledSchema;
///
/// let schema = CompiledSchema::default();
/// assert!(!schema.has_rls_configured());
/// ```
#[must_use]
pub fn has_rls_configured(&self) -> bool {
self.security.as_ref().is_some_and(|s| {
!s.additional
.get("policies")
.and_then(|p: &serde_json::Value| p.as_array())
.is_none_or(|a| a.is_empty())
})
}
/// Get raw GraphQL schema SDL.
///
/// # Returns
///
/// Raw schema string if available, otherwise generates from type definitions
#[must_use]
pub fn raw_schema(&self) -> String {
self.schema_sdl.clone().unwrap_or_else(|| {
// Generate basic SDL from type definitions if not provided
let mut sdl = String::new();
// Add types
for type_def in &self.types {
let _ = writeln!(sdl, "type {} {{", type_def.name);
for field in &type_def.fields {
let _ = writeln!(sdl, " {}: {}", field.name, field.field_type);
}
sdl.push_str("}\n\n");
}
sdl
})
}
/// Validate the schema for internal consistency.
///
/// Checks:
/// - All type references resolve to defined types
/// - No duplicate type/operation names
/// - Required fields have valid types
///
/// # Errors
///
/// Returns list of validation errors if schema is invalid.
pub fn validate(&self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
// Check for duplicate type names
let mut type_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
for type_def in &self.types {
if !type_names.insert(type_def.name.as_str()) {
errors.push(format!("Duplicate type name: {}", type_def.name));
}
}
// Check for duplicate query names
let mut query_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
for query in &self.queries {
if !query_names.insert(&query.name) {
errors.push(format!("Duplicate query name: {}", query.name));
}
}
// Check for duplicate mutation names
let mut mutation_names: std::collections::HashSet<&str> = std::collections::HashSet::new();
for mutation in &self.mutations {
if !mutation_names.insert(&mutation.name) {
errors.push(format!("Duplicate mutation name: {}", mutation.name));
}
}
// Check type references in queries
for query in &self.queries {
if !type_names.contains(query.return_type.as_str())
&& !is_builtin_type(&query.return_type)
{
errors.push(format!(
"Query '{}' references undefined type '{}'",
query.name, query.return_type
));
}
}
// Check type references in mutations
for mutation in &self.mutations {
if !type_names.contains(mutation.return_type.as_str())
&& !is_builtin_type(&mutation.return_type)
{
errors.push(format!(
"Mutation '{}' references undefined type '{}'",
mutation.name, mutation.return_type
));
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
/// Check if a type name is a built-in scalar type.
fn is_builtin_type(name: &str) -> bool {
matches!(
name,
"String"
| "Int"
| "Float"
| "Boolean"
| "ID"
| "DateTime"
| "Date"
| "Time"
| "JSON"
| "UUID"
| "Decimal"
)
}