Skip to content

Commit d36830d

Browse files
committed
fix: expand grants_config parsing to support more complex expressions
1 parent 58be5c8 commit d36830d

2 files changed

Lines changed: 247 additions & 70 deletions

File tree

sqlmesh/core/model/meta.py

Lines changed: 51 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -523,30 +523,62 @@ def custom_materialization_properties(self) -> CustomMaterializationProperties:
523523
def grants(self) -> t.Optional[GrantsConfig]:
524524
"""A dictionary of grants mapping permission names to lists of grantees."""
525525

526-
if not self.grants_:
526+
if self.grants_ is None:
527527
return None
528528

529-
def parse_exp_to_str(e: exp.Expression) -> str:
530-
if isinstance(e, exp.Literal) and e.is_string:
531-
return e.this.strip()
532-
if isinstance(e, exp.Identifier):
533-
return e.name
534-
return e.sql(dialect=self.dialect).strip()
529+
if not self.grants_.expressions:
530+
return {}
531+
532+
def expr_to_string(expr: exp.Expression, context: str) -> str:
533+
if isinstance(expr, (d.MacroFunc, d.MacroVar)):
534+
raise ConfigError(
535+
f"Unresolved macro in {context}: {expr.sql(dialect=self.dialect)}"
536+
)
537+
538+
if isinstance(expr, exp.Null):
539+
raise ConfigError(f"NULL value in {context}")
540+
541+
if isinstance(expr, exp.Literal):
542+
return str(expr.this).strip()
543+
if isinstance(expr, exp.Identifier):
544+
return expr.name
545+
if isinstance(expr, exp.Column):
546+
return expr.name
547+
return expr.sql(dialect=self.dialect).strip()
548+
549+
def normalize_to_string_list(value_expr: exp.Expression) -> t.List[str]:
550+
result = []
551+
552+
def process_expression(expr: exp.Expression) -> None:
553+
if isinstance(expr, exp.Array):
554+
for elem in expr.expressions:
555+
process_expression(elem)
556+
557+
elif isinstance(expr, (exp.Tuple, exp.Paren)):
558+
expressions = (
559+
[expr.unnest()] if isinstance(expr, exp.Paren) else expr.expressions
560+
)
561+
for elem in expressions:
562+
process_expression(elem)
563+
else:
564+
result.append(expr_to_string(expr, "grant value"))
565+
566+
process_expression(value_expr)
567+
return result
535568

536569
grants_dict = {}
537570
for eq_expr in self.grants_.expressions:
538-
permission_name = parse_exp_to_str(eq_expr.this) # left hand side
539-
grantees_expr = eq_expr.expression # right hand side
540-
if isinstance(grantees_expr, exp.Array):
541-
grantee_list = []
542-
for grantee_expr in grantees_expr.expressions:
543-
grantee = parse_exp_to_str(grantee_expr)
544-
if grantee: # skip empty strings
545-
grantee_list.append(grantee)
546-
547-
grants_dict[permission_name.strip()] = grantee_list
548-
549-
return grants_dict
571+
try:
572+
permission_name = expr_to_string(eq_expr.left, "permission name")
573+
grantee_list = normalize_to_string_list(eq_expr.expression)
574+
grants_dict[permission_name] = grantee_list
575+
except ConfigError as e:
576+
permission_name = (
577+
eq_expr.left.name if hasattr(eq_expr.left, "name") else str(eq_expr.left)
578+
)
579+
raise ConfigError(f"Invalid grants configuration for '{permission_name}': {e}")
580+
581+
return grants_dict if grants_dict else None
550582

551583
@property
552584
def all_references(self) -> t.List[Reference]:

tests/core/test_model.py

Lines changed: 196 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@
6161
model,
6262
)
6363
from sqlmesh.core.model.common import parse_expression
64-
from sqlmesh.core.model.kind import ModelKindName, _model_kind_validator
64+
from sqlmesh.core.model.kind import _ModelKind, ModelKindName, _model_kind_validator
6565
from sqlmesh.core.model.seed import CsvSettings
6666
from sqlmesh.core.node import IntervalUnit, _Node
6767
from sqlmesh.core.signal import signal
@@ -11732,90 +11732,235 @@ def test_use_original_sql():
1173211732
assert model.post_statements_[0].sql == "CREATE TABLE post (b INT)"
1173311733

1173411734

11735-
def test_grants_validation_symbolic_model_error():
11736-
with pytest.raises(ValidationError, match=r".*grants cannot be set for EXTERNAL.*"):
11737-
create_sql_model(
11738-
"db.table",
11739-
parse_one("SELECT 1 AS id"),
11740-
kind="EXTERNAL",
11741-
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11742-
)
11735+
@pytest.mark.parametrize(
11736+
"kind",
11737+
[
11738+
"FULL",
11739+
"VIEW",
11740+
SeedKind(path="test.csv"),
11741+
IncrementalByTimeRangeKind(time_column="ds"),
11742+
IncrementalByUniqueKeyKind(unique_key="id"),
11743+
],
11744+
)
11745+
def test_grants_valid_model_kinds(kind: t.Union[str, _ModelKind]):
11746+
model = create_sql_model(
11747+
"db.table",
11748+
parse_one("SELECT 1 AS id"),
11749+
kind=kind,
11750+
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11751+
)
11752+
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin_user"]}
1174311753

1174411754

11745-
def test_grants_validation_embedded_model_error():
11746-
with pytest.raises(ValidationError, match=r".*grants cannot be set for EMBEDDED.*"):
11755+
@pytest.mark.parametrize(
11756+
"kind",
11757+
[
11758+
"EXTERNAL",
11759+
"EMBEDDED",
11760+
],
11761+
)
11762+
def test_grants_invalid_model_kind_errors(kind: str):
11763+
with pytest.raises(ValidationError, match=rf".*grants cannot be set for {kind}.*"):
1174711764
create_sql_model(
1174811765
"db.table",
1174911766
parse_one("SELECT 1 AS id"),
11750-
kind="EMBEDDED",
11767+
kind=kind,
1175111768
grants={"select": ["user1"], "insert": ["admin_user"]},
1175211769
)
1175311770

1175411771

11755-
def test_grants_validation_valid_seed_model():
11772+
def test_grants_validation_no_grants():
11773+
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11774+
assert model.grants is None
11775+
11776+
11777+
def test_grants_validation_empty_grantees():
1175611778
model = create_sql_model(
11757-
"db.table",
11758-
parse_one("SELECT 1 AS id"),
11759-
kind=SeedKind(path="test.csv"),
11760-
grants={"select": ["user1"], "insert": ["admin_user"]},
11779+
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1176111780
)
11762-
assert model.grants == {"select": ["user1"], "insert": ["admin_user"]}
11781+
assert model.grants == {"select": []}
1176311782

1176411783

11765-
def test_grants_validation_valid_materialized_model():
11784+
def test_grants_single_value_conversions():
11785+
expressions = d.parse(f"""
11786+
MODEL (
11787+
name test.nested_arrays,
11788+
kind FULL,
11789+
grants (
11790+
'select' = "user1", update = user2
11791+
)
11792+
);
11793+
SELECT 1 as id
11794+
""")
11795+
model = load_sql_based_model(expressions)
11796+
assert model.grants == {"select": ["user1"], "update": ["user2"]}
11797+
1176611798
model = create_sql_model(
1176711799
"db.table",
1176811800
parse_one("SELECT 1 AS id"),
1176911801
kind="FULL",
11770-
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11802+
grants={"select": "user1", "insert": 123},
1177111803
)
11772-
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin_user"]}
11804+
assert model.grants == {"select": ["user1"], "insert": ["123"]}
1177311805

1177411806

11775-
def test_grants_validation_valid_view_model():
11776-
model = create_sql_model(
11777-
"db.table", parse_one("SELECT 1 AS id"), kind="VIEW", grants={"select": ["user1", "user2"]}
11807+
@pytest.mark.parametrize(
11808+
"grantees",
11809+
[
11810+
"('user1', ('user2', 'user3'), 'user4')",
11811+
"('user1', ['user2', 'user3'], user4)",
11812+
"['user1', ['user2', user3], 'user4']",
11813+
"[user1, ('user2', \"user3\"), 'user4']",
11814+
],
11815+
)
11816+
def test_grants_array_flattening(grantees: str):
11817+
expressions = d.parse(f"""
11818+
MODEL (
11819+
name test.nested_arrays,
11820+
kind FULL,
11821+
grants (
11822+
'select' = {grantees}
11823+
)
11824+
);
11825+
SELECT 1 as id
11826+
""")
11827+
model = load_sql_based_model(expressions)
11828+
assert model.grants == {"select": ["user1", "user2", "user3", "user4"]}
11829+
11830+
11831+
def test_grants_macro_var_resolved():
11832+
expressions = d.parse("""
11833+
MODEL (
11834+
name test.macro_grants,
11835+
kind FULL,
11836+
grants (
11837+
'select' = @VAR('readers'),
11838+
'insert' = @VAR('writers')
11839+
)
11840+
);
11841+
SELECT 1 as id
11842+
""")
11843+
model = load_sql_based_model(
11844+
expressions, variables={"readers": ["user1", "user2"], "writers": "admin"}
1177811845
)
11779-
assert model.grants == {"select": ["user1", "user2"]}
11846+
assert model.grants == {
11847+
"select": ["user1", "user2"],
11848+
"insert": ["admin"],
11849+
}
1178011850

1178111851

11782-
def test_grants_validation_valid_incremental_model():
11783-
model = create_sql_model(
11784-
"db.table",
11785-
parse_one("SELECT 1 AS id, CURRENT_TIMESTAMP AS ts"),
11786-
kind=IncrementalByTimeRangeKind(time_column="ts"),
11787-
grants={"select": ["user1"], "update": ["admin_user"]},
11852+
def test_grants_macro_var_in_array_flattening():
11853+
expressions = d.parse("""
11854+
MODEL (
11855+
name test.macro_in_array,
11856+
kind FULL,
11857+
grants (
11858+
'select' = ['user1', @VAR('admins'), 'user3']
11859+
)
11860+
);
11861+
SELECT 1 as id
11862+
""")
11863+
11864+
model = load_sql_based_model(expressions, variables={"admins": ["admin1", "admin2"]})
11865+
assert model.grants == {"select": ["user1", "admin1", "admin2", "user3"]}
11866+
11867+
model2 = load_sql_based_model(expressions, variables={"admins": "super_admin"})
11868+
assert model2.grants == {"select": ["user1", "super_admin", "user3"]}
11869+
11870+
11871+
def test_grants_dynamic_permission_names():
11872+
expressions = d.parse("""
11873+
MODEL (
11874+
name test.dynamic_keys,
11875+
kind FULL,
11876+
grants (
11877+
@VAR('read_perm') = ['user1', 'user2'],
11878+
@VAR('write_perm') = ['admin']
11879+
)
11880+
);
11881+
SELECT 1 as id
11882+
""")
11883+
model = load_sql_based_model(
11884+
expressions, variables={"read_perm": "select", "write_perm": "insert"}
1178811885
)
11789-
assert model.grants == {"select": ["user1"], "update": ["admin_user"]}
11886+
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin"]}
1179011887

1179111888

11792-
def test_grants_validation_no_grants():
11793-
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11794-
assert model.grants is None
11889+
def test_grants_unresolved_macro_errors():
11890+
expressions1 = d.parse("""
11891+
MODEL (name test.bad1, kind FULL, grants ('select' = @VAR('undefined')));
11892+
SELECT 1 as id
11893+
""")
11894+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11895+
load_sql_based_model(expressions1)
1179511896

11897+
expressions2 = d.parse("""
11898+
MODEL (name test.bad2, kind FULL, grants (@VAR('undefined') = ['user']));
11899+
SELECT 1 as id
11900+
""")
11901+
with pytest.raises(ConfigError, match=r"Invalid grants configuration.*NULL value"):
11902+
load_sql_based_model(expressions2)
1179611903

11797-
def test_grants_validation_empty_grantees():
11798-
model = create_sql_model(
11904+
expressions3 = d.parse("""
11905+
MODEL (name test.bad3, kind FULL, grants ('select' = ['user', @VAR('undefined')]));
11906+
SELECT 1 as id
11907+
""")
11908+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11909+
load_sql_based_model(expressions3)
11910+
11911+
11912+
def test_grants_mixed_types_conversion():
11913+
expressions = d.parse("""
11914+
MODEL (
11915+
name test.mixed_types,
11916+
kind FULL,
11917+
grants (
11918+
'select' = ['user1', 123, admin_role, 'user2']
11919+
)
11920+
);
11921+
SELECT 1 as id
11922+
""")
11923+
model = load_sql_based_model(expressions)
11924+
assert model.grants == {"select": ["user1", "123", "admin_role", "user2"]}
11925+
11926+
11927+
def test_grants_empty_values():
11928+
model1 = create_sql_model(
1179911929
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1180011930
)
11801-
assert model.grants == {"select": []}
11931+
assert model1.grants == {"select": []}
1180211932

11933+
model2 = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11934+
assert model2.grants is None
1180311935

11804-
def test_grants_table_type_view():
11805-
model = create_sql_model("test_view", parse_one("SELECT 1 as id"), kind="VIEW")
11806-
assert model.grants_table_type == DataObjectType.VIEW
1180711936

11937+
def test_grants_backward_compatibility():
1180811938
model = create_sql_model(
11809-
"test_mv", parse_one("SELECT 1 as id"), kind=ViewKind(materialized=True)
11939+
"db.table",
11940+
parse_one("SELECT 1 AS id"),
11941+
kind="FULL",
11942+
grants={
11943+
"select": ["user1", "user2"],
11944+
"insert": ["admin"],
11945+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
11946+
},
1181011947
)
11811-
assert model.grants_table_type == DataObjectType.MATERIALIZED_VIEW
11812-
11813-
11814-
def test_grants_table_type_table():
11815-
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind="FULL")
11816-
assert model.grants_table_type == DataObjectType.TABLE
11948+
assert model.grants == {
11949+
"select": ["user1", "user2"],
11950+
"insert": ["admin"],
11951+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
11952+
}
1181711953

1181811954

11819-
def test_grants_table_type_managed():
11820-
model = create_sql_model("test_managed", parse_one("SELECT 1 as id"), kind="MANAGED")
11821-
assert model.grants_table_type == DataObjectType.MANAGED_TABLE
11955+
@pytest.mark.parametrize(
11956+
"kind, expected",
11957+
[
11958+
("VIEW", DataObjectType.VIEW),
11959+
("FULL", DataObjectType.TABLE),
11960+
("MANAGED", DataObjectType.MANAGED_TABLE),
11961+
(ViewKind(materialized=True), DataObjectType.MATERIALIZED_VIEW),
11962+
],
11963+
)
11964+
def test_grants_table_type(kind: t.Union[str, _ModelKind], expected: DataObjectType):
11965+
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind=kind)
11966+
assert model.grants_table_type == expected

0 commit comments

Comments
 (0)