Config

Struct Config 

Source
pub struct Config {
    pub url: String,
    pub orm: OrmType,
    pub db: DatabaseType,
    pub output_dir: PathBuf,
    pub headers: HashMap<String, String>,
    pub type_mappings: HashMap<String, String>,
    pub scalar_mappings: HashMap<String, String>,
    pub table_naming: TableNamingConvention,
    pub generate_migrations: bool,
    pub generate_entities: bool,
}
Expand description

Configuration for GraphQL code generation.

The Config struct defines all parameters needed to generate Rust ORM code from a GraphQL schema. It supports both programmatic creation and loading from configuration files (TOML or YAML).

§Required Fields

  • url: GraphQL endpoint URL that supports introspection
  • orm: ORM to generate code for (Diesel or Sea-ORM)
  • db: Target database (SQLite, PostgreSQL, or MySQL)
  • output_dir: Directory where generated code will be written

§Optional Fields

All other fields have sensible defaults and are typically configured through configuration files rather than programmatically.

§Configuration Files

§TOML Format (graphql-codegen-rust.toml)

url = "https://api.example.com/graphql"
orm = "Diesel"
db = "Postgres"
output_dir = "./generated"

[headers]
Authorization = "Bearer token"

[type_mappings]
"MyCustomType" = "String"

§YAML Format (codegen.yml) - Requires yaml-codegen-config feature

schema:
  url: https://api.example.com/graphql
  headers:
    Authorization: Bearer token

rust_codegen:
  orm: Diesel
  db: Postgres
  output_dir: ./generated

§Example

use graphql_codegen_rust::{Config, cli::{OrmType, DatabaseType}};
use std::collections::HashMap;

let config = Config {
    url: "https://api.example.com/graphql".to_string(),
    orm: OrmType::Diesel,
    db: DatabaseType::Postgres,
    output_dir: "./generated".into(),
    headers: HashMap::from([
        ("Authorization".to_string(), "Bearer token".to_string())
    ]),
    ..Default::default()
};

Fields§

§url: String

URL of the GraphQL endpoint that supports introspection.

This must be a GraphQL API that responds to introspection queries. The endpoint should be accessible and may require authentication headers.

§Examples

  • "https://api.github.com/graphql" (GitHub’s public API)
  • "https://api.example.com/graphql" (your custom API)
  • "http://localhost:4000/graphql" (local development)
§orm: OrmType

ORM framework to generate code for.

Determines the structure and style of generated code:

  • OrmType::Diesel: Generates table schemas and Queryable structs
  • OrmType::SeaOrm: Generates Entity models and ActiveModel structs
§db: DatabaseType

Target database backend.

Affects type mappings and SQL generation:

  • DatabaseType::Sqlite: Uses INTEGER for IDs, TEXT for strings
  • DatabaseType::Postgres: Uses UUID for IDs, native JSON support
  • DatabaseType::Mysql: Uses INT for IDs, MEDIUMTEXT for large content
§output_dir: PathBuf

Directory where generated code will be written.

The directory will be created if it doesn’t exist. Generated files include:

  • src/schema.rs (Diesel table definitions)
  • src/entities/*.rs (Entity structs)
  • src/mod.rs (Sea-ORM module definitions)
  • migrations/ (Database migration files)
§headers: HashMap<String, String>

Additional HTTP headers to send with GraphQL requests.

Common headers include authentication tokens, API keys, or content-type specifications. Headers are sent with both introspection queries and any follow-up requests.

§Examples

use std::collections::HashMap;

let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), "Bearer token123".to_string());
headers.insert("X-API-Key".to_string(), "key456".to_string());
§type_mappings: HashMap<String, String>

Custom type mappings for GraphQL types to Rust types.

Maps GraphQL type names to custom Rust types. Useful for:

  • Custom scalar types (DateTime, UUID, etc.)
  • Domain-specific types
  • Third-party library types

If a GraphQL type is not found in this map, default mappings are used based on the database type and built-in GraphQL scalars.

§Examples

[type_mappings]
"DateTime" = "chrono::DateTime<chrono::Utc>"
"UUID" = "uuid::Uuid"
"Email" = "String"  # Simple string wrapper
§scalar_mappings: HashMap<String, String>

Custom scalar type mappings for GraphQL scalars.

Similar to type_mappings but specifically for GraphQL scalar types. These are applied before the built-in scalar mappings.

§Examples

[scalar_mappings]
"Date" = "chrono::NaiveDate"
"Timestamp" = "i64"
§table_naming: TableNamingConvention

Naming convention for database tables and columns.

Controls how GraphQL type/field names are converted to database identifiers.

  • TableNamingConvention::SnakeCase: UserProfileuser_profile
  • TableNamingConvention::PascalCase: UserProfileUserProfile

SnakeCase is recommended for most databases.

§generate_migrations: bool

Whether to generate database migration files.

When enabled, creates SQL migration files in the migrations/ directory that can be applied to set up the database schema. Each GraphQL type gets its own migration with CREATE TABLE statements.

Default: true

§generate_entities: bool

Whether to generate Rust entity/model structs.

When enabled, creates Rust structs that represent the GraphQL types:

  • Diesel: Queryable structs for reading data
  • Sea-ORM: Model structs with relationships

Default: true

Implementations§

Source§

impl Config

Source

pub fn from_file(path: &PathBuf) -> Result<Self>

Load config from a file (auto-detects YAML or TOML)

Source

pub fn from_toml_str(contents: &str) -> Result<Self>

Load config from TOML string

Source

pub fn save_to_file(&self, path: &PathBuf) -> Result<()>

Save config to a TOML file

Source

pub fn config_path(output_dir: &Path) -> PathBuf

Get the config file path for a given output directory

Source

pub fn auto_detect_config() -> Result<PathBuf>

Auto-detect config file in current directory

Trait Implementations§

Source§

impl Clone for Config

Source§

fn clone(&self) -> Config

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 Config

Source§

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

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

impl Default for Config

Source§

fn default() -> Config

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

impl<'de> Deserialize<'de> for Config

Source§

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

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

impl From<&Commands> for Config

Source§

fn from(cmd: &Commands) -> Self

Converts to this type from the input type.
Source§

impl Serialize for Config

Source§

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

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

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> 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> 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> 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<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<T> ErasedDestructor for T
where T: 'static,