Skip to main content

Organize SQL files

In Bauplan you can express transformations in Python, in SQL, or in a combination of both. A .py file can define several models, while each .sql file defines exactly one, named after the file by default. A project with many SQL models therefore has many files, and two questions come up quickly, namely how to group them into folders and how to keep their names from colliding.

Group SQL files into subfolders as you like, and list every subfolder under include_paths in bauplan_project.yaml. Give each model a unique name, one that isn't already used by another model or by a table the pipeline reads.

List the SQL subfolders in the project file

Group SQL files into subfolders, and declare every subfolder in include_paths. Any .sql file not in the root of the Bauplan project needs to be included. For a project laid out like this one

    • bauplan_project.yaml
    • pyproject.toml
    • schemas.py
      • stg_users.sql
      • stg_products.sql
        • active_users.sql
        • user_signups_daily.sql
        • top_products.sql
        • product_sales_daily.sql

the project file lists both folders.

bauplan_project.yaml
project:
id: 7f1d3c2a-5b8e-4c1f-9a6d-2e4b8c0f1a3d
name: my_pipeline
include_paths:
- staging/*.sql
- marts/**/*.sql

The patterns follow a few rules:

  1. Each pattern must be an explicit .sql glob. staging/*.sql is accepted, staging/* is not.
  2. Paths are relative to the project directory, and absolute paths are rejected.
  3. Upward traversal, such as ../common/*.sql, is not allowed.
  4. Files ignored by Git are excluded even if they match a pattern.
  5. Symbolic links that point outside the project directory are rejected.

Give every model a unique name

The model name is the file name, so staging/stg_users.sql defines the model stg_users, and can read the users table without clashing with it.

When the file name can't be the model name, for example because two subfolders each have a file with the same name, set the name with a header. As with any SQL model, the output schema is defined as a class in a top-level Python file:

schemas.py
import bauplan

class NewUsers(bauplan.TableSchema):
"""Users who signed up in the last day."""

id: bauplan.Int64
created_at: bauplan.TimestampMicroUTC
staging/latest_signups.sql
-- bauplan: name = new_users
-- bauplan: output_schema = NewUsers
SELECT id, created_at
FROM users
WHERE created_at > NOW() - INTERVAL '24 hours'

This file defines the model new_users, whatever the file is called.