Skip to content

Commit 543aba5

Browse files
committed
fix: expand grants_config parsing to support more complex expressions
1 parent 0fe5759 commit 543aba5

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
@@ -527,30 +527,62 @@ def custom_materialization_properties(self) -> CustomMaterializationProperties:
527527
def grants(self) -> t.Optional[GrantsConfig]:
528528
"""A dictionary of grants mapping permission names to lists of grantees."""
529529

530-
if not self.grants_:
530+
if self.grants_ is None:
531531
return None
532532

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

540573
grants_dict = {}
541574
for eq_expr in self.grants_.expressions:
542-
permission_name = parse_exp_to_str(eq_expr.this) # left hand side
543-
grantees_expr = eq_expr.expression # right hand side
544-
if isinstance(grantees_expr, exp.Array):
545-
grantee_list = []
546-
for grantee_expr in grantees_expr.expressions:
547-
grantee = parse_exp_to_str(grantee_expr)
548-
if grantee: # skip empty strings
549-
grantee_list.append(grantee)
550-
551-
grants_dict[permission_name.strip()] = grantee_list
552-
553-
return grants_dict
575+
try:
576+
permission_name = expr_to_string(eq_expr.left, "permission name")
577+
grantee_list = normalize_to_string_list(eq_expr.expression)
578+
grants_dict[permission_name] = grantee_list
579+
except ConfigError as e:
580+
permission_name = (
581+
eq_expr.left.name if hasattr(eq_expr.left, "name") else str(eq_expr.left)
582+
)
583+
raise ConfigError(f"Invalid grants configuration for '{permission_name}': {e}")
584+
585+
return grants_dict if grants_dict else None
554586

555587
@property
556588
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
@@ -11737,90 +11737,235 @@ def test_use_original_sql():
1173711737
assert model.post_statements_[0].sql == "CREATE TABLE post (b INT)"
1173811738

1173911739

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

1174911759

11750-
def test_grants_validation_embedded_model_error():
11751-
with pytest.raises(ValidationError, match=r".*grants cannot be set for EMBEDDED.*"):
11760+
@pytest.mark.parametrize(
11761+
"kind",
11762+
[
11763+
"EXTERNAL",
11764+
"EMBEDDED",
11765+
],
11766+
)
11767+
def test_grants_invalid_model_kind_errors(kind: str):
11768+
with pytest.raises(ValidationError, match=rf".*grants cannot be set for {kind}.*"):
1175211769
create_sql_model(
1175311770
"db.table",
1175411771
parse_one("SELECT 1 AS id"),
11755-
kind="EMBEDDED",
11772+
kind=kind,
1175611773
grants={"select": ["user1"], "insert": ["admin_user"]},
1175711774
)
1175811775

1175911776

11760-
def test_grants_validation_valid_seed_model():
11777+
def test_grants_validation_no_grants():
11778+
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11779+
assert model.grants is None
11780+
11781+
11782+
def test_grants_validation_empty_grantees():
1176111783
model = create_sql_model(
11762-
"db.table",
11763-
parse_one("SELECT 1 AS id"),
11764-
kind=SeedKind(path="test.csv"),
11765-
grants={"select": ["user1"], "insert": ["admin_user"]},
11784+
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1176611785
)
11767-
assert model.grants == {"select": ["user1"], "insert": ["admin_user"]}
11786+
assert model.grants == {"select": []}
1176811787

1176911788

11770-
def test_grants_validation_valid_materialized_model():
11789+
def test_grants_single_value_conversions():
11790+
expressions = d.parse(f"""
11791+
MODEL (
11792+
name test.nested_arrays,
11793+
kind FULL,
11794+
grants (
11795+
'select' = "user1", update = user2
11796+
)
11797+
);
11798+
SELECT 1 as id
11799+
""")
11800+
model = load_sql_based_model(expressions)
11801+
assert model.grants == {"select": ["user1"], "update": ["user2"]}
11802+
1177111803
model = create_sql_model(
1177211804
"db.table",
1177311805
parse_one("SELECT 1 AS id"),
1177411806
kind="FULL",
11775-
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11807+
grants={"select": "user1", "insert": 123},
1177611808
)
11777-
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin_user"]}
11809+
assert model.grants == {"select": ["user1"], "insert": ["123"]}
1177811810

1177911811

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

1178611856

11787-
def test_grants_validation_valid_incremental_model():
11788-
model = create_sql_model(
11789-
"db.table",
11790-
parse_one("SELECT 1 AS id, CURRENT_TIMESTAMP AS ts"),
11791-
kind=IncrementalByTimeRangeKind(time_column="ts"),
11792-
grants={"select": ["user1"], "update": ["admin_user"]},
11857+
def test_grants_macro_var_in_array_flattening():
11858+
expressions = d.parse("""
11859+
MODEL (
11860+
name test.macro_in_array,
11861+
kind FULL,
11862+
grants (
11863+
'select' = ['user1', @VAR('admins'), 'user3']
11864+
)
11865+
);
11866+
SELECT 1 as id
11867+
""")
11868+
11869+
model = load_sql_based_model(expressions, variables={"admins": ["admin1", "admin2"]})
11870+
assert model.grants == {"select": ["user1", "admin1", "admin2", "user3"]}
11871+
11872+
model2 = load_sql_based_model(expressions, variables={"admins": "super_admin"})
11873+
assert model2.grants == {"select": ["user1", "super_admin", "user3"]}
11874+
11875+
11876+
def test_grants_dynamic_permission_names():
11877+
expressions = d.parse("""
11878+
MODEL (
11879+
name test.dynamic_keys,
11880+
kind FULL,
11881+
grants (
11882+
@VAR('read_perm') = ['user1', 'user2'],
11883+
@VAR('write_perm') = ['admin']
11884+
)
11885+
);
11886+
SELECT 1 as id
11887+
""")
11888+
model = load_sql_based_model(
11889+
expressions, variables={"read_perm": "select", "write_perm": "insert"}
1179311890
)
11794-
assert model.grants == {"select": ["user1"], "update": ["admin_user"]}
11891+
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin"]}
1179511892

1179611893

11797-
def test_grants_validation_no_grants():
11798-
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11799-
assert model.grants is None
11894+
def test_grants_unresolved_macro_errors():
11895+
expressions1 = d.parse("""
11896+
MODEL (name test.bad1, kind FULL, grants ('select' = @VAR('undefined')));
11897+
SELECT 1 as id
11898+
""")
11899+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11900+
load_sql_based_model(expressions1)
1180011901

11902+
expressions2 = d.parse("""
11903+
MODEL (name test.bad2, kind FULL, grants (@VAR('undefined') = ['user']));
11904+
SELECT 1 as id
11905+
""")
11906+
with pytest.raises(ConfigError, match=r"Invalid grants configuration.*NULL value"):
11907+
load_sql_based_model(expressions2)
1180111908

11802-
def test_grants_validation_empty_grantees():
11803-
model = create_sql_model(
11909+
expressions3 = d.parse("""
11910+
MODEL (name test.bad3, kind FULL, grants ('select' = ['user', @VAR('undefined')]));
11911+
SELECT 1 as id
11912+
""")
11913+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11914+
load_sql_based_model(expressions3)
11915+
11916+
11917+
def test_grants_mixed_types_conversion():
11918+
expressions = d.parse("""
11919+
MODEL (
11920+
name test.mixed_types,
11921+
kind FULL,
11922+
grants (
11923+
'select' = ['user1', 123, admin_role, 'user2']
11924+
)
11925+
);
11926+
SELECT 1 as id
11927+
""")
11928+
model = load_sql_based_model(expressions)
11929+
assert model.grants == {"select": ["user1", "123", "admin_role", "user2"]}
11930+
11931+
11932+
def test_grants_empty_values():
11933+
model1 = create_sql_model(
1180411934
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1180511935
)
11806-
assert model.grants == {"select": []}
11936+
assert model1.grants == {"select": []}
1180711937

11938+
model2 = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11939+
assert model2.grants is None
1180811940

11809-
def test_grants_table_type_view():
11810-
model = create_sql_model("test_view", parse_one("SELECT 1 as id"), kind="VIEW")
11811-
assert model.grants_table_type == DataObjectType.VIEW
1181211941

11942+
def test_grants_backward_compatibility():
1181311943
model = create_sql_model(
11814-
"test_mv", parse_one("SELECT 1 as id"), kind=ViewKind(materialized=True)
11944+
"db.table",
11945+
parse_one("SELECT 1 AS id"),
11946+
kind="FULL",
11947+
grants={
11948+
"select": ["user1", "user2"],
11949+
"insert": ["admin"],
11950+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
11951+
},
1181511952
)
11816-
assert model.grants_table_type == DataObjectType.MATERIALIZED_VIEW
11817-
11818-
11819-
def test_grants_table_type_table():
11820-
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind="FULL")
11821-
assert model.grants_table_type == DataObjectType.TABLE
11953+
assert model.grants == {
11954+
"select": ["user1", "user2"],
11955+
"insert": ["admin"],
11956+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
11957+
}
1182211958

1182311959

11824-
def test_grants_table_type_managed():
11825-
model = create_sql_model("test_managed", parse_one("SELECT 1 as id"), kind="MANAGED")
11826-
assert model.grants_table_type == DataObjectType.MANAGED_TABLE
11960+
@pytest.mark.parametrize(
11961+
"kind, expected",
11962+
[
11963+
("VIEW", DataObjectType.VIEW),
11964+
("FULL", DataObjectType.TABLE),
11965+
("MANAGED", DataObjectType.MANAGED_TABLE),
11966+
(ViewKind(materialized=True), DataObjectType.MATERIALIZED_VIEW),
11967+
],
11968+
)
11969+
def test_grants_table_type(kind: t.Union[str, _ModelKind], expected: DataObjectType):
11970+
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind=kind)
11971+
assert model.grants_table_type == expected

0 commit comments

Comments
 (0)