Skip to content

Commit 53784e0

Browse files
committed
fix: expand grants_config parsing to support more complex expressions
1 parent 3f57d37 commit 53784e0

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
@@ -11804,90 +11804,235 @@ def my_macro(evaluator):
1180411804
assert model.render_query_or_raise().sql() == 'SELECT 3 AS "c"'
1180511805

1180611806

11807-
def test_grants_validation_symbolic_model_error():
11808-
with pytest.raises(ValidationError, match=r".*grants cannot be set for EXTERNAL.*"):
11809-
create_sql_model(
11810-
"db.table",
11811-
parse_one("SELECT 1 AS id"),
11812-
kind="EXTERNAL",
11813-
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11814-
)
11807+
@pytest.mark.parametrize(
11808+
"kind",
11809+
[
11810+
"FULL",
11811+
"VIEW",
11812+
SeedKind(path="test.csv"),
11813+
IncrementalByTimeRangeKind(time_column="ds"),
11814+
IncrementalByUniqueKeyKind(unique_key="id"),
11815+
],
11816+
)
11817+
def test_grants_valid_model_kinds(kind: t.Union[str, _ModelKind]):
11818+
model = create_sql_model(
11819+
"db.table",
11820+
parse_one("SELECT 1 AS id"),
11821+
kind=kind,
11822+
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11823+
)
11824+
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin_user"]}
1181511825

1181611826

11817-
def test_grants_validation_embedded_model_error():
11818-
with pytest.raises(ValidationError, match=r".*grants cannot be set for EMBEDDED.*"):
11827+
@pytest.mark.parametrize(
11828+
"kind",
11829+
[
11830+
"EXTERNAL",
11831+
"EMBEDDED",
11832+
],
11833+
)
11834+
def test_grants_invalid_model_kind_errors(kind: str):
11835+
with pytest.raises(ValidationError, match=rf".*grants cannot be set for {kind}.*"):
1181911836
create_sql_model(
1182011837
"db.table",
1182111838
parse_one("SELECT 1 AS id"),
11822-
kind="EMBEDDED",
11839+
kind=kind,
1182311840
grants={"select": ["user1"], "insert": ["admin_user"]},
1182411841
)
1182511842

1182611843

11827-
def test_grants_validation_valid_seed_model():
11844+
def test_grants_validation_no_grants():
11845+
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11846+
assert model.grants is None
11847+
11848+
11849+
def test_grants_validation_empty_grantees():
1182811850
model = create_sql_model(
11829-
"db.table",
11830-
parse_one("SELECT 1 AS id"),
11831-
kind=SeedKind(path="test.csv"),
11832-
grants={"select": ["user1"], "insert": ["admin_user"]},
11851+
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1183311852
)
11834-
assert model.grants == {"select": ["user1"], "insert": ["admin_user"]}
11853+
assert model.grants == {"select": []}
1183511854

1183611855

11837-
def test_grants_validation_valid_materialized_model():
11856+
def test_grants_single_value_conversions():
11857+
expressions = d.parse(f"""
11858+
MODEL (
11859+
name test.nested_arrays,
11860+
kind FULL,
11861+
grants (
11862+
'select' = "user1", update = user2
11863+
)
11864+
);
11865+
SELECT 1 as id
11866+
""")
11867+
model = load_sql_based_model(expressions)
11868+
assert model.grants == {"select": ["user1"], "update": ["user2"]}
11869+
1183811870
model = create_sql_model(
1183911871
"db.table",
1184011872
parse_one("SELECT 1 AS id"),
1184111873
kind="FULL",
11842-
grants={"select": ["user1", "user2"], "insert": ["admin_user"]},
11874+
grants={"select": "user1", "insert": 123},
1184311875
)
11844-
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin_user"]}
11876+
assert model.grants == {"select": ["user1"], "insert": ["123"]}
1184511877

1184611878

11847-
def test_grants_validation_valid_view_model():
11848-
model = create_sql_model(
11849-
"db.table", parse_one("SELECT 1 AS id"), kind="VIEW", grants={"select": ["user1", "user2"]}
11879+
@pytest.mark.parametrize(
11880+
"grantees",
11881+
[
11882+
"('user1', ('user2', 'user3'), 'user4')",
11883+
"('user1', ['user2', 'user3'], user4)",
11884+
"['user1', ['user2', user3], 'user4']",
11885+
"[user1, ('user2', \"user3\"), 'user4']",
11886+
],
11887+
)
11888+
def test_grants_array_flattening(grantees: str):
11889+
expressions = d.parse(f"""
11890+
MODEL (
11891+
name test.nested_arrays,
11892+
kind FULL,
11893+
grants (
11894+
'select' = {grantees}
11895+
)
11896+
);
11897+
SELECT 1 as id
11898+
""")
11899+
model = load_sql_based_model(expressions)
11900+
assert model.grants == {"select": ["user1", "user2", "user3", "user4"]}
11901+
11902+
11903+
def test_grants_macro_var_resolved():
11904+
expressions = d.parse("""
11905+
MODEL (
11906+
name test.macro_grants,
11907+
kind FULL,
11908+
grants (
11909+
'select' = @VAR('readers'),
11910+
'insert' = @VAR('writers')
11911+
)
11912+
);
11913+
SELECT 1 as id
11914+
""")
11915+
model = load_sql_based_model(
11916+
expressions, variables={"readers": ["user1", "user2"], "writers": "admin"}
1185011917
)
11851-
assert model.grants == {"select": ["user1", "user2"]}
11918+
assert model.grants == {
11919+
"select": ["user1", "user2"],
11920+
"insert": ["admin"],
11921+
}
1185211922

1185311923

11854-
def test_grants_validation_valid_incremental_model():
11855-
model = create_sql_model(
11856-
"db.table",
11857-
parse_one("SELECT 1 AS id, CURRENT_TIMESTAMP AS ts"),
11858-
kind=IncrementalByTimeRangeKind(time_column="ts"),
11859-
grants={"select": ["user1"], "update": ["admin_user"]},
11924+
def test_grants_macro_var_in_array_flattening():
11925+
expressions = d.parse("""
11926+
MODEL (
11927+
name test.macro_in_array,
11928+
kind FULL,
11929+
grants (
11930+
'select' = ['user1', @VAR('admins'), 'user3']
11931+
)
11932+
);
11933+
SELECT 1 as id
11934+
""")
11935+
11936+
model = load_sql_based_model(expressions, variables={"admins": ["admin1", "admin2"]})
11937+
assert model.grants == {"select": ["user1", "admin1", "admin2", "user3"]}
11938+
11939+
model2 = load_sql_based_model(expressions, variables={"admins": "super_admin"})
11940+
assert model2.grants == {"select": ["user1", "super_admin", "user3"]}
11941+
11942+
11943+
def test_grants_dynamic_permission_names():
11944+
expressions = d.parse("""
11945+
MODEL (
11946+
name test.dynamic_keys,
11947+
kind FULL,
11948+
grants (
11949+
@VAR('read_perm') = ['user1', 'user2'],
11950+
@VAR('write_perm') = ['admin']
11951+
)
11952+
);
11953+
SELECT 1 as id
11954+
""")
11955+
model = load_sql_based_model(
11956+
expressions, variables={"read_perm": "select", "write_perm": "insert"}
1186011957
)
11861-
assert model.grants == {"select": ["user1"], "update": ["admin_user"]}
11958+
assert model.grants == {"select": ["user1", "user2"], "insert": ["admin"]}
1186211959

1186311960

11864-
def test_grants_validation_no_grants():
11865-
model = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
11866-
assert model.grants is None
11961+
def test_grants_unresolved_macro_errors():
11962+
expressions1 = d.parse("""
11963+
MODEL (name test.bad1, kind FULL, grants ('select' = @VAR('undefined')));
11964+
SELECT 1 as id
11965+
""")
11966+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11967+
load_sql_based_model(expressions1)
1186711968

11969+
expressions2 = d.parse("""
11970+
MODEL (name test.bad2, kind FULL, grants (@VAR('undefined') = ['user']));
11971+
SELECT 1 as id
11972+
""")
11973+
with pytest.raises(ConfigError, match=r"Invalid grants configuration.*NULL value"):
11974+
load_sql_based_model(expressions2)
1186811975

11869-
def test_grants_validation_empty_grantees():
11870-
model = create_sql_model(
11976+
expressions3 = d.parse("""
11977+
MODEL (name test.bad3, kind FULL, grants ('select' = ['user', @VAR('undefined')]));
11978+
SELECT 1 as id
11979+
""")
11980+
with pytest.raises(ConfigError, match=r"Invalid grants configuration for 'select': NULL value"):
11981+
load_sql_based_model(expressions3)
11982+
11983+
11984+
def test_grants_mixed_types_conversion():
11985+
expressions = d.parse("""
11986+
MODEL (
11987+
name test.mixed_types,
11988+
kind FULL,
11989+
grants (
11990+
'select' = ['user1', 123, admin_role, 'user2']
11991+
)
11992+
);
11993+
SELECT 1 as id
11994+
""")
11995+
model = load_sql_based_model(expressions)
11996+
assert model.grants == {"select": ["user1", "123", "admin_role", "user2"]}
11997+
11998+
11999+
def test_grants_empty_values():
12000+
model1 = create_sql_model(
1187112001
"db.table", parse_one("SELECT 1 AS id"), kind="FULL", grants={"select": []}
1187212002
)
11873-
assert model.grants == {"select": []}
12003+
assert model1.grants == {"select": []}
1187412004

12005+
model2 = create_sql_model("db.table", parse_one("SELECT 1 AS id"), kind="FULL")
12006+
assert model2.grants is None
1187512007

11876-
def test_grants_table_type_view():
11877-
model = create_sql_model("test_view", parse_one("SELECT 1 as id"), kind="VIEW")
11878-
assert model.grants_table_type == DataObjectType.VIEW
1187912008

12009+
def test_grants_backward_compatibility():
1188012010
model = create_sql_model(
11881-
"test_mv", parse_one("SELECT 1 as id"), kind=ViewKind(materialized=True)
12011+
"db.table",
12012+
parse_one("SELECT 1 AS id"),
12013+
kind="FULL",
12014+
grants={
12015+
"select": ["user1", "user2"],
12016+
"insert": ["admin"],
12017+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
12018+
},
1188212019
)
11883-
assert model.grants_table_type == DataObjectType.MATERIALIZED_VIEW
11884-
11885-
11886-
def test_grants_table_type_table():
11887-
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind="FULL")
11888-
assert model.grants_table_type == DataObjectType.TABLE
12020+
assert model.grants == {
12021+
"select": ["user1", "user2"],
12022+
"insert": ["admin"],
12023+
"roles/bigquery.dataViewer": ["user:data_eng@company.com"],
12024+
}
1188912025

1189012026

11891-
def test_grants_table_type_managed():
11892-
model = create_sql_model("test_managed", parse_one("SELECT 1 as id"), kind="MANAGED")
11893-
assert model.grants_table_type == DataObjectType.MANAGED_TABLE
12027+
@pytest.mark.parametrize(
12028+
"kind, expected",
12029+
[
12030+
("VIEW", DataObjectType.VIEW),
12031+
("FULL", DataObjectType.TABLE),
12032+
("MANAGED", DataObjectType.MANAGED_TABLE),
12033+
(ViewKind(materialized=True), DataObjectType.MATERIALIZED_VIEW),
12034+
],
12035+
)
12036+
def test_grants_table_type(kind: t.Union[str, _ModelKind], expected: DataObjectType):
12037+
model = create_sql_model("test_table", parse_one("SELECT 1 as id"), kind=kind)
12038+
assert model.grants_table_type == expected

0 commit comments

Comments
 (0)