sqlmesh icon indicating copy to clipboard operation
sqlmesh copied to clipboard

Feature request: Blueprinted names for the columns with a Python data frame model.

Open samcunliffe opened this issue 7 months ago • 5 comments

Hello devs! 👋 Hopefully, I'm allowed to simply open a feature request here. Please tell me if I'm missing something.


With SQL model blueprints, it's possible to use a blueprint variable in the column names.

With a Python model that uses the decorated def execute(...) -> pd.DataFrame: ... function, the docs say

Because SQLMesh creates tables before evaluating models, the schema of the output DataFrame is a required argument. The @model argument columns contains a dictionary of column names to types.

So I need to declare the columns in the @model decorator, but they can't be blueprinted.

Here's an minimum not-working example:

@model(
    "schema.@{name}",   # blueprinting works here!
    kind="full",
    columns={
        "@{column_name}": "text",             # ... but not here
        "TRANSFORMED_@{column_name}": "text",
    },
    blueprints=[
        {"name": "FirstTable", "column_name": "FIRSTCOLUMN"},
        {"name": "SecondTable", "column_name": "SECONDCOLUMN"},
    ],
)
def execute(
    context: ExecutionContext,
    start: datetime,
    end: datetime, 
    execution_time: datetime, 
    **kwargs: t.Any, 
) -> pd.DataFrame:
    """Execute the model."""
    # Get hold of blueprint variables for the column name
    name = context.blueprint_var("name")
    column_name = context.blueprint_var("column_name")

    source_table = f"{name}Source"
    select_statement = f"SELECT {column_name} FROM {source_table};" 
    output_column_name = f"TRANSFORMED_{column_name}"

    df = context.fetchdf(select_statement)
    df[output_column_name] = df[column_name].apply(some_fancy_transformation)
    return df

Is it possible/easy to support this pattern?

samcunliffe avatar Apr 17 '26 09:04 samcunliffe

I don't know off the top of my head, so I'll let others jump in on this

yuki-kakegawa avatar May 30 '26 05:05 yuki-kakegawa

I don't know off the top of my head, so I'll let others jump in on this

I'm happy to implement this feature, please let me know if you’re okay with me working on it

lafirm avatar Jun 15 '26 08:06 lafirm

Sorry, I went ahead and opened this PR, thinking it would be fine with you. Please review when you get a chance and let me know what you think @StuffbyYuki

lafirm avatar Jun 17 '26 05:06 lafirm

@samcunliffe @StuffbyYuki I think this can be closed now

lafirm avatar Jun 19 '26 12:06 lafirm

From a totally non-expert skim read of your PR and the very nice...

def test_python_model_blueprint_column_names(tmp_path: Path) -> None:
    ...

... I agree this is solved! Thanks so much for the fast feature implementation!!

samcunliffe avatar Jun 19 '26 13:06 samcunliffe