sqlmesh icon indicating copy to clipboard operation
sqlmesh copied to clipboard

@SCHEMA_NAME.model_name is not rendered in python models

Open lafirm opened this issue 1 year ago • 3 comments

I've a variable called schema_name defined in sqlmesh config yaml, I use this in all my sql models and its working fine.

I recently created a python model using the below config, but the name is actually not rendered and gives me the error

@model(
    name="@schema_name.model_name",
    description="model",
    kind={"name": ModelKindName.FULL},
    columns={..},
)
def execute(...

Error: KeyError: '"iceberg".@schema_name."model_name"'

did I use them correctly in the model decorator args? or do we not yet have an option to use sqlmesh vars in the name parameter?

lafirm avatar Jan 14 '25 06:01 lafirm

Hey @lafirm, can you share a fully reproducible example? I don't see the behavior you described:

import pandas as pd

from sqlmesh import model


@model(
    "@schema_name.test_model",
    kind="FULL",
    columns={"id": "INT"},
)
def execute(*args, **kwargs):
    return pd.DataFrame([{"id": 1}])


# The config.yaml file looks like this:
#
# gateways:
#   local:
#     connection:
#       type: duckdb
#       database: db.db
#
# default_gateway: local
#
# model_defaults:
#   dialect: duckdb
#   start: 2025-01-13
#
# variables:
#   schema_name: foo

georgesittas avatar Jan 14 '25 17:01 georgesittas

Hey @lafirm, can you share a fully reproducible example? I don't see the behavior you described:

apologies @georgesittas, I over looked that the error doesn't raise because of the variables in the name parameter but in resolve_table method

This is an example which throws KeyError:

import pandas as pd
from sqlglot import exp

from sqlmesh import model


@model(
    "@schema_name.test_model2",
    kind="FULL",
    columns={"id": "INT"},
    tags=["test"]
)
def execute(context, **kwargs):
    table = context.resolve_table("@schema_name.test_model1")
    select_query = exp.select("*").from_(table)
    return context.fetchdf(select_query)

I tried fetching variables instead like this, but this gives me the below error

from sqlglot import exp

from sqlmesh import model

variable_name = "schema_name"

@model(
    "@schema_name.test_model2",
    kind="FULL",
    columns={"id": "INT"},
    tags=["test"]
)
def execute(context, **kwargs):
    table_name = f"{context.var(variable_name)}.test_model1"
    table = context.resolve_table(table_name)
    select_query = exp.select("*").from_(table)
    return context.fetchdf(select_query)

Error: Error resolving dependencies for 'models/test_model2.py'. Argument 'table_name' must be resolvable at parse time.

lafirm avatar Jan 15 '25 06:01 lafirm

I see, yeah this may not be supported at the moment. Let me take a look.

georgesittas avatar Jan 15 '25 16:01 georgesittas