Skip to main content

CompiledSchema

Struct CompiledSchema 

Source
pub struct CompiledSchema {
Show 26 fields pub types: Vec<TypeDefinition>, pub enums: Vec<EnumDefinition>, pub input_types: Vec<InputObjectDefinition>, pub interfaces: Vec<InterfaceDefinition>, pub unions: Vec<UnionDefinition>, pub queries: Vec<QueryDefinition>, pub mutations: Vec<MutationDefinition>, pub subscriptions: Vec<SubscriptionDefinition>, pub directives: Vec<DirectiveDefinition>, pub fact_tables: HashMap<String, FactTableMetadata>, pub observers: Vec<ObserverDefinition>, pub federation: Option<FederationConfig>, pub security: Option<SecurityConfig>, pub observers_config: Option<ObserversConfig>, pub subscriptions_config: Option<SubscriptionsConfig>, pub validation_config: Option<ValidationConfig>, pub debug_config: Option<DebugConfig>, pub mcp_config: Option<McpConfig>, pub rest_config: Option<RestConfig>, pub grpc_config: Option<GrpcConfig>, pub schema_format_version: Option<u32>, pub schema_sdl: Option<String>, pub custom_scalars: CustomTypeRegistry, pub query_index: HashMap<String, usize>, pub mutation_index: HashMap<String, usize>, pub subscription_index: HashMap<String, usize>,
}
Expand description

Complete compiled schema - all type information for serving.

This is the central type that holds the entire GraphQL schema after compilation from any supported authoring language.

§Example

use fraiseql_core::schema::CompiledSchema;

let json = r#"{
    "types": [],
    "queries": [],
    "mutations": [],
    "subscriptions": []
}"#;

let schema = CompiledSchema::from_json(json).unwrap();
assert_eq!(schema.types.len(), 0);

Fields§

§types: Vec<TypeDefinition>

GraphQL object type definitions.

§enums: Vec<EnumDefinition>

GraphQL enum type definitions.

§input_types: Vec<InputObjectDefinition>

GraphQL input object type definitions.

§interfaces: Vec<InterfaceDefinition>

GraphQL interface type definitions.

§unions: Vec<UnionDefinition>

GraphQL union type definitions.

§queries: Vec<QueryDefinition>

GraphQL query definitions.

§mutations: Vec<MutationDefinition>

GraphQL mutation definitions.

§subscriptions: Vec<SubscriptionDefinition>

GraphQL subscription definitions.

§directives: Vec<DirectiveDefinition>

Custom directive definitions. These are user-defined directives beyond the built-in @skip, @include, @deprecated.

§fact_tables: HashMap<String, FactTableMetadata>

Fact table metadata (for analytics queries). Key: table name (e.g., tf_sales)

§observers: Vec<ObserverDefinition>

Observer definitions (database change event listeners).

§federation: Option<FederationConfig>

Federation metadata for Apollo Federation v2 support.

§security: Option<SecurityConfig>

Security configuration (from fraiseql.toml).

§observers_config: Option<ObserversConfig>

Observers/event system configuration (from fraiseql.toml).

Contains backend connection settings (redis_url, nats_url, etc.) and event handler definitions compiled from the [observers] TOML section.

§subscriptions_config: Option<SubscriptionsConfig>

WebSocket subscription configuration (hooks, limits). Compiled from the [subscriptions] TOML section.

§validation_config: Option<ValidationConfig>

Query validation config (depth/complexity limits). Compiled from the [validation] TOML section.

§debug_config: Option<DebugConfig>

Debug/development configuration. Compiled from the [debug] TOML section.

§mcp_config: Option<McpConfig>

MCP (Model Context Protocol) server configuration. Compiled from the [mcp] TOML section.

§rest_config: Option<RestConfig>

REST transport configuration. Compiled from the [rest] TOML section.

§grpc_config: Option<GrpcConfig>

gRPC transport configuration. Compiled from the [grpc] TOML section.

§schema_format_version: Option<u32>

Schema format version emitted by the compiler.

Used to detect runtime/compiler skew. If present and ≠ CURRENT_SCHEMA_FORMAT_VERSION, validate_format_version() returns an error.

§schema_sdl: Option<String>

Raw GraphQL schema as string (for SDL generation).

§custom_scalars: CustomTypeRegistry

Custom scalar type registry.

Contains definitions for custom scalar types defined in the schema. Built during code generation from IRScalar definitions. Not serialized - populated at runtime from ir.scalars.

§query_index: HashMap<String, usize>

O(1) lookup index: query name → index into self.queries. Built at construction time by build_indexes(); not serialized. Populated automatically by from_json(); call build_indexes() after direct mutation of self.queries.

§mutation_index: HashMap<String, usize>

O(1) lookup index: mutation name → index into self.mutations. Built at construction time by build_indexes(); not serialized. Populated automatically by from_json(); call build_indexes() after direct mutation of self.mutations.

§subscription_index: HashMap<String, usize>

O(1) lookup index: subscription name → index into self.subscriptions. Built at construction time by build_indexes(); not serialized. Populated automatically by from_json(); call build_indexes() after direct mutation of self.subscriptions.

Implementations§

Source§

impl CompiledSchema

Source

pub fn new() -> CompiledSchema

Create empty schema.

Source

pub fn validate_format_version(&self) -> Result<(), String>

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.

Source

pub fn build_indexes(&mut self)

Build O(1) lookup indexes for queries, mutations, and subscriptions.

Called automatically by from_json(). Must be called manually after any direct mutation of self.queries, self.mutations, or self.subscriptions.

Source

pub fn from_json(json: &str) -> Result<CompiledSchema, Error>

Deserialize from JSON string.

This is the primary way to create a schema from any authoring language. The authoring language emits schema.json; fraiseql-cli compile produces schema.compiled.json; Rust deserializes and owns the result.

§Integrity Checking

When fraiseql-cli compile embeds a _content_hash field in the compiled JSON, the runtime should verify it against content_hash() before accepting the schema. This guards against accidental corruption or tampering between compilation and deployment. The check is not performed here because _content_hash is not yet written by the CLI; once it is, add a post-deserialization step:

let schema = CompiledSchema::from_json(json)?;
if let Some(expected) = &schema._content_hash {
    let actual = schema.content_hash();
    if *expected != actual {
        return Err(IntegrityError::HashMismatch { expected, actual });
    }
}
§Errors

Returns error if JSON is malformed or doesn’t match schema structure.

§Example
use fraiseql_core::schema::CompiledSchema;

let json = r#"{"types": [], "queries": [], "mutations": [], "subscriptions": []}"#;
let schema = CompiledSchema::from_json(json).unwrap();
Source

pub fn to_json(&self) -> Result<String, Error>

Serialize to JSON string.

§Errors

Returns error if serialization fails (should not happen for valid schema).

Source

pub fn to_json_pretty(&self) -> Result<String, Error>

Serialize to pretty JSON string (for debugging/config files).

§Errors

Returns error if serialization fails.

Source

pub fn find_type(&self, name: &str) -> Option<&TypeDefinition>

Find a type definition by name.

Source

pub fn find_enum(&self, name: &str) -> Option<&EnumDefinition>

Find an enum definition by name.

Source

pub fn find_input_type(&self, name: &str) -> Option<&InputObjectDefinition>

Find an input object definition by name.

Source

pub fn find_interface(&self, name: &str) -> Option<&InterfaceDefinition>

Find an interface definition by name.

Source

pub fn find_implementors(&self, interface_name: &str) -> Vec<&TypeDefinition>

Find all types that implement a given interface.

Source

pub fn find_union(&self, name: &str) -> Option<&UnionDefinition>

Find a union definition by name.

Source

pub fn find_query(&self, name: &str) -> Option<&QueryDefinition>

Find a query definition by name.

Uses the O(1) pre-built index when available; falls back to O(n) linear scan for schemas built directly in tests without calling build_indexes().

Source

pub fn find_mutation(&self, name: &str) -> Option<&MutationDefinition>

Find a mutation definition by name.

Uses the O(1) pre-built index when available; falls back to O(n) linear scan for schemas built directly in tests without calling build_indexes().

Source

pub fn find_subscription(&self, name: &str) -> Option<&SubscriptionDefinition>

Find a subscription definition by name.

Uses the O(1) pre-built index when available; falls back to O(n) linear scan for schemas built directly in tests without calling build_indexes().

Source

pub fn find_directive(&self, name: &str) -> Option<&DirectiveDefinition>

Find a custom directive definition by name.

Source

pub const fn operation_count(&self) -> usize

Get total number of operations (queries + mutations + subscriptions).

Source

pub fn add_fact_table( &mut self, table_name: String, metadata: FactTableMetadata, )

Register fact table metadata.

§Arguments
  • table_name - Fact table name (e.g., tf_sales)
  • metadata - Typed FactTableMetadata
Source

pub fn get_fact_table(&self, name: &str) -> Option<&FactTableMetadata>

Get fact table metadata by name.

§Arguments
  • name - Fact table name
§Returns

Fact table metadata if found

Source

pub fn list_fact_tables(&self) -> Vec<&str>

List all fact table names.

§Returns

Vector of fact table names

Source

pub fn has_fact_tables(&self) -> bool

Check if schema contains any fact tables.

Source

pub fn find_observer(&self, name: &str) -> Option<&ObserverDefinition>

Find an observer definition by name.

Source

pub fn find_observers_for_entity( &self, entity: &str, ) -> Vec<&ObserverDefinition>

Get all observers for a specific entity type.

Source

pub fn find_observers_for_event(&self, event: &str) -> Vec<&ObserverDefinition>

Get all observers for a specific event type (INSERT, UPDATE, DELETE).

Source

pub const fn has_observers(&self) -> bool

Check if schema contains any observers.

Source

pub const fn observer_count(&self) -> usize

Get total number of observers.

Source

pub const fn federation_metadata(&self) -> Option<()>

Stub federation metadata when federation feature is disabled.

Source

pub const fn security_config(&self) -> Option<&SecurityConfig>

Get security configuration from schema.

§Returns

Security configuration if present (includes role definitions)

Source

pub fn is_multi_tenant(&self) -> bool

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.

Source

pub fn find_role(&self, role_name: &str) -> Option<RoleDefinition>

Find a role definition by name.

§Arguments
  • role_name - Name of the role to find
§Returns

Role definition if found

Source

pub fn get_role_scopes(&self, role_name: &str) -> Vec<String>

Get scopes for a role.

§Arguments
  • role_name - Name of the role
§Returns

Vector of scopes granted to the role

Source

pub fn role_has_scope(&self, role_name: &str, scope: &str) -> bool

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

Source

pub fn content_hash(&self) -> String

Returns a 32-character hex SHA-256 content hash of this schema’s canonical JSON.

Use as schema_version when constructing CachedDatabaseAdapter to guarantee cache invalidation on any schema change, regardless of whether the package version was bumped.

Two schemas that differ by even one field will produce different hashes. The same schema serialised twice always produces the same hash (stable).

§Panics

Does not panic — CompiledSchema always serialises to valid JSON.

§Example
use fraiseql_core::schema::CompiledSchema;

let schema = CompiledSchema::default();
let hash = schema.content_hash();
assert_eq!(hash.len(), 32); // 16 bytes → 32 hex chars
Source

pub fn has_rls_configured(&self) -> bool

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());
Source

pub fn raw_schema(&self) -> String

Get raw GraphQL schema SDL.

§Returns

Raw schema string if available, otherwise generates from type definitions

Source

pub fn validate(&self) -> Result<(), Vec<String>>

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.

Trait Implementations§

Source§

impl Clone for CompiledSchema

Source§

fn clone(&self) -> CompiledSchema

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for CompiledSchema

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for CompiledSchema

Source§

fn default() -> CompiledSchema

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for CompiledSchema

Source§

fn deserialize<__D>( __deserializer: __D, ) -> Result<CompiledSchema, <__D as Deserializer<'de>>::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl PartialEq for CompiledSchema

Source§

fn eq(&self, other: &CompiledSchema) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Serialize for CompiledSchema

Source§

fn serialize<__S>( &self, __serializer: __S, ) -> Result<<__S as Serializer>::Ok, <__S as Serializer>::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,