dbt Custom Schemas: Routing Models to Snowflake Databases

9 minutes to read
Get free consultation

 

Data engineering at the enterprise level requires strict governance. When we architect Snowflake environments for our clients, we prioritize predictability. Your data pipeline operates as a highway. Proper lanes keep traffic flowing smoothly.

By default, dbt structures database paths to protect local development. It concatenates schema names. This creates isolated environments for individual engineers. Scaling effectively requires adjusting this default behavior. Managing this configuration keeps production environments clean and organized. It eliminates redundant names like prod_prod_marts. It also streamlines role-based access control.

Enterprise Analytics Engineers need total control over data routing. Proper routing ensures error-free reporting. It enforces strict security boundaries. We achieve this by overriding the default dbt target schema configuration.

In this guide, we explore dbt custom schemas. We detail how to override the generate_schema_name macro. We also share our architectural best practices for aligning your Snowflake database structure with dbt. Our goal is your growth. We build well-oiled data machines that accelerate business decisions. Clients report significantly faster insights post-implementation. They reclaim valuable time by navigating highly organized data environments.

Understanding dbt’s Default Schema Naming Behavior

Mastering the baseline allows you to customize your deployment effectively. The default dbt target schema configuration prioritizes developer safety. It ensures that analytics engineers cannot accidentally overwrite production data.

How generate_schema_name Calculates Schema Names

Every dbt project uses a hidden internal macro. This macro is called generate_schema_name. When you define a custom schema in your dbt_project.yml, dbt passes it through this macro.

By default, dbt concatenates two variables. It takes your target schema (defined in your profiles.yml). It then appends your custom schema (defined in your model configuration).

Consider a standard local development setup. Your target schema is dev_vitaly. Your model configures a custom schema named marts.

The default macro outputs: dev_vitaly_marts.

This output routes the model to a highly specific schema in Snowflake. The logic provides a simple and effective structure.

Why the Default Exists

This default behavior solves a major problem for growing teams. It safeguards against accidental data overwrites.

Imagine a team of ten analytics engineers. They all develop locally. They all run dbt build against a shared Snowflake development database. Using a concatenated schema name prevents immediate collisions. Each engineer maintains their own tested tables securely.

The default macro protects shared schemas during local development. It creates a sandbox for every developer. It allows engineers to test complex transformations safely. Adapting this safety mechanism prepares your project for production deployments. When your deployment target is prod, the default macro creates prod_marts. If your custom schema is prod_marts, it creates prod_prod_marts.

Customization resolves these clunky schema prefixes. Business intelligence tools perform better with a streamlined structure. Data discovery becomes intuitive and fast. We improve this structure through strategic customization.

How to Override the generate_schema_name Macro

We empower data teams to take control of their architecture. You achieve this by creating a custom macro, as outlined in the dbt guide to customizing database, schema, and alias. You place this file directly in your dbt project.

The Risks of Removing Default Prefixes Globally

Developers must proceed carefully during this step. Overriding the macro to return only the custom schema name strips away the target schema logic.

Retaining the target schema logic safeguards your environment from accidental data overwrites. A robust approach maintains developer isolation. This alignment strengthens your entire Snowflake database structure.

Maintaining target schema logic keeps local development running smoothly. Implementing environment-aware routing ensures developers route their data to distinct schemas. This strategy keeps your data highway organized.

Example: A Production-Aware Macro Override

We streamline data transformations by writing intelligent macros. You can override the default behavior safely. You create a file named generate_schema_name.sql in your macros directory.

This macro evaluates the current environment. If the environment is production, it drops the target prefix. It outputs clean schema names. If the environment is development, it retains the developer prefix. It preserves isolation.

Here is the exact macro code we use for enterprise clients:

{% macro generate_schema_name(custom_schema_name, node) -%}

    {%- set default_schema = target.schema -%}

    {%- if custom_schema_name is none -%}

        {{ default_schema }}

    {%- elif target.name == 'prod' -%}

        {{ custom_schema_name | trim }}

    {%- else -%}

        {{ default_schema }}_{{ custom_schema_name | trim }}

    {%- endif -%}

{%- endmacro %}

Let us break down the business impact of this logic:

Snowflake Database Structure and dbt Environment Separation

Macro overrides provide the crucial first half of the solution. True enterprise governance requires structural separation. We design Snowflake environments to map perfectly to dbt deployment strategies.

Database Routing vs. Schema Routing

Schema routing manages folders within a database. Database routing manages the entire building. Understanding this difference empowers better architectural design.

While generate_schema_name routes models to specific schemas, dbt also provides generate_database_name. Separating environments at the database level provides superior security. Housing development and production schemas in entirely separate databases maximizes governance.

Dedicated databases simplify Snowflake access controls. They also reduce the risk of human error significantly. We optimize this by implementing strict database boundaries.

Best Practices for Development, Staging, and Production

We structure Snowflake databases for dbt deployments using three distinct environments, in line with Snowflake’s best practices for dbt Projects on Snowflake. This methodology guarantees stability.

  1. The Development Database (ANALYTICS_DEV): This database houses isolated developer sandboxes. It handles high-churn data. The generate_schema_name macro appends developer prefixes here. Engineers can experiment freely.
  2. The Staging/CI Database (ANALYTICS_STAGING): This environment acts as the gatekeeper. Continuous Integration tools deploy here. We run automated tests in this database. It ensures code quality before production merges.
  3. The Production Database (ANALYTICS_PROD): This is the gold standard environment. It contains pure, prefix-free schemas. System configurations restrict write access to automated service accounts exclusively.

Security, Roles, and Loose Schema Permissions

Strict schema permissions prevent massive security vulnerabilities. When dbt creates custom schemas, it must inherit proper Snowflake roles.

We map the Snowflake role hierarchy directly to these customized schemas.

Snowflake future grants automate this security model. When your dbt macro generates a new custom schema, Snowflake automatically applies permissions.

-- Example of securing a routed schema
GRANT USAGE ON FUTURE SCHEMAS IN DATABASE ANALYTICS_PROD TO ROLE bi_reporting_role;
GRANT SELECT ON FUTURE TABLES IN DATABASE ANALYTICS_PROD TO ROLE bi_reporting_role;

This alignment guarantees compliance. Your reporting tools experience seamless data access. Your production data stays fully secured against unauthorized users.

Managing CI/CD Pipelines and Schema Cleanup

Enterprise data workflows rely heavily on Continuous Integration (CI). CI platforms automatically test every pull request. They generate temporary dbt custom schemas to validate transformations.

Avoiding Orphan CI Schemas

CI pipelines introduce a specific operational consideration. A pull request triggers a dbt run. The macro generates a unique schema (e.g., ci_pr_123_marts). The tests pass. The code merges.

These temporary schemas often remain in Snowflake after completion. Over time, these schemas accumulate. Proactive management prevents significant storage bloat. It keeps the database UI clean and organized.

We streamline this process with automated cleanup jobs. Including a teardown step in your CI pipeline optimizes your environment.

When a pull request closes, a script efficiently executes a drop command.

DROP SCHEMA IF EXISTS ANALYTICS_STAGING.ci_pr_123_marts CASCADE;

Alternatively, we use Snowflake tasks to drop schemas older than seven days. This proactive governance keeps your Snowflake environment pristine. It optimizes storage costs. It ensures your staging database perfectly reflects active development.

Integrating Fivetran, Snowflake, and dbt

Your transformation layer relies deeply on robust integration. It benefits directly from your data ingestion pipeline. We heavily integrate Fivetran to populate Snowflake.

Aligning Ingestion and Transformation

Fivetran utilizes its own dedicated governance model. We keep Fivetran raw ingestion databases structurally independent from dbt transform databases.

We typically create a dedicated database named RAW_FIVETRAN. Fivetran holds exclusive ownership over this database. It automatically creates schemas based on your source systems (e.g., salesforce, stripe).

Your dbt project references this data using the {{ source() }} macro. The dbt custom schemas then route the transformed outputs into ANALYTICS_PROD.

This clear boundary ensures smooth tool interoperability. Fivetran handles extraction and loading. dbt handles transformation. Snowflake manages the compute layer. This framework creates the foundation of a modern, resilient data stack.

If your organization seeks to optimize data pipelines, we offer specialized data integration with Fivetran and Snowflake. We design ingestion strategies that perfectly align with custom dbt routing.

Conclusion: Build a Governed Data Machine

Mastering dbt custom schemas requires intentional architectural design.

By replacing the generate_schema_name macro, you streamline your environment by removing clunky schema prefixes. You secure local development against accidental data overwrites. By routing models to distinct Snowflake databases, you enforce strict role-based access control.

These technical configurations drive massive business impact. They streamline reporting. They optimize compute costs by efficiently processing data. They empower your analytics team to deploy code with total confidence.

At Stellans, we turn complex data into actionable insights. We build scalable systems that fuel growth and innovation. If you want to transform your analytics infrastructure, partner with our data engineering experts. We will work with you to unlock your data potential.

Frequently Asked Questions

How does dbt generate a model’s schema name?

By default, dbt concatenates the target schema and the model’s custom schema using the generate_schema_name macro. This creates highly specific names to prevent data collisions during local development.

How can I override the generate_schema_name macro in dbt?

You can override this behavior by creating a file named generate_schema_name.sql in your macros directory and defining environment-aware routing logic. This allows you to remove developer prefixes in production while maintaining isolation in development.

Why should I separate my dbt development and production databases?

Separating environments prevents accidental data overwrites and simplifies Snowflake role-based access control. It ensures that business intelligence tools only query stable, fully validated data sets.

How do I prevent CI schemas from cluttering Snowflake?

You should implement an automated teardown step in your CI/CD pipeline. This step drops the temporary schemas created during testing once the pull request merges.

References

Article By:

https://stellans.io/wp-content/uploads/2024/08/Vitaly_Lilich.jpg
Vitaly Lilich

Co-founder and CEO