-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathtest_model.py
More file actions
12160 lines (10318 loc) · 358 KB
/
test_model.py
File metadata and controls
12160 lines (10318 loc) · 358 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ruff: noqa: F811
import json
import typing as t
import re
from datetime import date, datetime
from pathlib import Path
from unittest.mock import patch, PropertyMock
import time_machine
import pandas as pd # noqa: TID253
import pytest
from pytest_mock.plugin import MockerFixture
from sqlglot import exp, parse_one
from sqlglot.errors import ParseError
from sqlglot.schema import MappingSchema
from sqlmesh.cli.project_init import init_example_project, ProjectTemplate
from sqlmesh.core.environment import EnvironmentNamingInfo
from sqlmesh.core.model.kind import TimeColumn, ModelKindName, SeedKind
from sqlmesh import CustomMaterialization, CustomKind
from pydantic import model_validator, ValidationError
from sqlmesh.core import constants as c
from sqlmesh.core import dialect as d
from sqlmesh.core.console import get_console
from sqlmesh.core.audit import ModelAudit, load_audit
from sqlmesh.core.model.common import ParsableSql
from sqlmesh.core.config import (
Config,
DuckDBConnectionConfig,
GatewayConfig,
NameInferenceConfig,
ModelDefaultsConfig,
LinterConfig,
)
from sqlmesh.core import constants as c
from sqlmesh.core.context import Context, ExecutionContext
from sqlmesh.core.dialect import parse
from sqlmesh.core.engine_adapter.base import MERGE_SOURCE_ALIAS, MERGE_TARGET_ALIAS
from sqlmesh.core.engine_adapter.duckdb import DuckDBEngineAdapter
from sqlmesh.core.engine_adapter.shared import DataObjectType
from sqlmesh.core.macros import MacroEvaluator, macro
from sqlmesh.core.model import (
CustomKind,
PythonModel,
FullKind,
IncrementalByTimeRangeKind,
IncrementalUnmanagedKind,
IncrementalByUniqueKeyKind,
ModelCache,
ModelMeta,
SeedKind,
SqlModel,
TimeColumn,
ExternalKind,
ViewKind,
EmbeddedKind,
SCDType2ByTimeKind,
create_external_model,
create_seed_model,
create_sql_model,
load_sql_based_model,
load_sql_based_models,
model,
)
from sqlmesh.core.model.common import parse_expression
from sqlmesh.core.model.kind import _ModelKind, ModelKindName, _model_kind_validator
from sqlmesh.core.model.seed import CsvSettings
from sqlmesh.core.node import IntervalUnit, _Node, DbtNodeInfo
from sqlmesh.core.signal import signal
from sqlmesh.core.snapshot import Snapshot, SnapshotChangeCategory
from sqlmesh.utils.date import TimeLike, to_datetime, to_ds, to_timestamp
from sqlmesh.utils.errors import ConfigError, SQLMeshError, LinterError
from sqlmesh.utils.jinja import JinjaMacroRegistry, MacroInfo, MacroExtractor
from sqlmesh.utils.metaprogramming import Executable, SqlValue
from sqlmesh.core.macros import RuntimeStage
from tests.utils.test_helpers import use_terminal_console
def missing_schema_warning_msg(model, deps):
deps = ", ".join(f"'{dep}'" for dep in sorted(deps))
return (
f"SELECT * cannot be expanded due to missing schema(s) for model(s): {deps}. "
f"Run `sqlmesh create_external_models` and / or make sure that the model '{model}' "
"can be rendered at parse time."
)
def test_load(assert_exp_eq):
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name,
storage_format iceberg,
partitioned_by d,
clustered_by e,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a,
),
tags [tag_foo, tag_bar],
grain [a, b],
references (
f,
g
),
);
@DEF(x, 1);
@DEF(y, @x + 1);
CACHE TABLE x AS SELECT 1;
ADD JAR 's3://my_jar.jar';
SELECT
1::int AS a,
CAST(2 AS double) AS b,
c::bool,
1::int AS d, -- d
CAST(2 AS double) AS e, --e
f::bool, --f
@y::int AS g,
FROM
db.other_table t1
LEFT JOIN
db.table t2
ON
t1.a = t2.a;
DROP TABLE x;
"""
)
model = load_sql_based_model(expressions)
assert model.name == "db.table"
assert model.owner == "owner_name"
assert model.dialect == "spark"
assert model.table_format is None
assert model.storage_format == "iceberg"
assert [col.sql() for col in model.partitioned_by] == ['"a"', '"d"']
assert [col.sql() for col in model.clustered_by] == ['"e"']
assert model.columns_to_types == {
"a": exp.DataType.build("int"),
"b": exp.DataType.build("double"),
"c": exp.DataType.build("boolean"),
"d": exp.DataType.build("int"),
"e": exp.DataType.build("double"),
"f": exp.DataType.build("boolean"),
"g": exp.DataType.build("int"),
}
assert model.annotated
assert model.view_name == "table"
assert model.macro_definitions == [d.parse_one("@DEF(x, 1)"), d.parse_one("@DEF(y, @x + 1)")]
assert list(model.pre_statements) == [
d.parse_one("@DEF(x, 1)"),
d.parse_one("@DEF(y, @x + 1)"),
d.parse_one("CACHE TABLE x AS SELECT 1"),
d.parse_one("ADD JAR 's3://my_jar.jar'", dialect="spark"),
]
assert list(model.post_statements) == [
d.parse_one("DROP TABLE x"),
]
assert model.depends_on == {'"db"."other_table"'}
assert (
model.render_query().sql(pretty=True, dialect="spark")
== """SELECT
CAST(1 AS INT) AS `a`,
CAST(2 AS DOUBLE) AS `b`,
CAST(`c` AS BOOLEAN) AS `c`,
CAST(1 AS INT) AS `d`, /* d */
CAST(2 AS DOUBLE) AS `e`, /* e */
CAST(`f` AS BOOLEAN) AS `f`, /* f */
CAST(1 + 1 AS INT) AS `g`
FROM `db`.`other_table` AS `t1`
LEFT JOIN `db`.`table` AS `t2`
ON `t1`.`a` = `t2`.`a`"""
)
assert model.tags == ["tag_foo", "tag_bar"]
assert [r.dict() for r in model.all_references] == [
{"model_name": "db.table", "expression": d.parse_one("[a, b]"), "unique": True},
{"model_name": "db.table", "expression": d.parse_one("f"), "unique": True},
{"model_name": "db.table", "expression": d.parse_one("g"), "unique": True},
]
def test_model_multiple_select_statements():
# Make sure the load_model raises an exception for model with multiple select statements.
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name,
);
SELECT 1, ds;
SELECT 2, ds;
"""
)
with pytest.raises(ConfigError, match=r"^Only one SELECT.*"):
load_sql_based_model(expressions)
def test_model_validation(tmp_path):
expressions = d.parse(
f"""
MODEL (
name db.table,
kind FULL,
);
SELECT
y::int,
x::int AS y
FROM db.ext
"""
)
ctx = Context(
config=Config(linter=LinterConfig(enabled=True, rules=["noambiguousprojections"])),
paths=tmp_path,
)
ctx.upsert_model(load_sql_based_model(expressions, default_catalog="memory"))
errors = ctx.lint_models(["db.table"], raise_on_error=False)
assert errors, "Expected NoAmbiguousProjections violation"
assert errors[0].violation_msg == "Found duplicate outer select name 'y'"
expressions = d.parse(
"""
MODEL (
name db.table,
kind FULL,
);
SELECT a, a UNION SELECT c, c
"""
)
ctx.upsert_model(load_sql_based_model(expressions, default_catalog="memory"))
errors = ctx.lint_models(["db.table"], raise_on_error=False)
assert errors, "Expected NoAmbiguousProjections violation"
assert errors[0].violation_msg == "Found duplicate outer select name 'a'"
expressions = d.parse(
f"""
MODEL (
name db.table,
kind FULL,
);
SELECT * FROM db.table
"""
)
model = load_sql_based_model(expressions)
with pytest.raises(ConfigError) as ex:
model.validate_definition()
assert "require inferrable column types" in str(ex.value)
def test_model_union_query(sushi_context, assert_exp_eq):
expressions = d.parse(
"""
MODEL (
name db.table,
kind FULL,
);
SELECT a, b UNION SELECT c, c
"""
)
load_sql_based_model(expressions)
expressions = d.parse(
"""
MODEL (
name sushi.test,
kind FULL,
);
@union('all', sushi.marketing, sushi.marketing)
"""
)
sushi_context.upsert_model(load_sql_based_model(expressions, default_catalog="memory"))
assert_exp_eq(
sushi_context.get_model("sushi.test").render_query(),
"""SELECT
CAST("marketing"."customer_id" AS INT) AS "customer_id",
CAST("marketing"."status" AS TEXT) AS "status",
CAST("marketing"."updated_at" AS TIMESTAMPNTZ) AS "updated_at",
CAST("marketing"."valid_from" AS TIMESTAMP) AS "valid_from",
CAST("marketing"."valid_to" AS TIMESTAMP) AS "valid_to"
FROM "memory"."sushi"."marketing" AS "marketing"
UNION ALL
SELECT
CAST("marketing"."customer_id" AS INT) AS "customer_id",
CAST("marketing"."status" AS TEXT) AS "status",
CAST("marketing"."updated_at" AS TIMESTAMPNTZ) AS "updated_at",
CAST("marketing"."valid_from" AS TIMESTAMP) AS "valid_from",
CAST("marketing"."valid_to" AS TIMESTAMP) AS "valid_to"
FROM "memory"."sushi"."marketing" AS "marketing"
""",
)
@time_machine.travel("1996-02-10 00:00:00 UTC")
@pytest.mark.parametrize(
"test_id, condition, union_type, table_count, expected_result",
[
# Test case 1: Basic conditional union - True condition
(
"test_1",
"@get_date() == '1996-02-10'",
"'all'",
2,
lambda expected_select: f"{expected_select}\nUNION ALL\n{expected_select}\n",
),
# Test case 2: False condition - should return just first table
(
"test_2",
"@get_date() > '1996-02-10'",
"'all'",
2,
lambda expected_select: f"{expected_select}\n",
),
# Test case 3: Multiple tables in union
(
"test_3",
"@get_date() == '1996-02-10'",
"'all'",
3,
lambda expected_select: f"{expected_select}\nUNION ALL\n{expected_select}\nUNION ALL\n{expected_select}\n",
),
# Test case 4: DISTINCT type
(
"test_4",
"@get_date() == '1996-02-10'",
"'distinct'",
2,
lambda expected_select: f"{expected_select}\nUNION\n{expected_select}\n",
),
# Test case 5: Complex condition
(
"test_5",
"@get_date() = '1996-02-10' and 1=1 or @get_date() > '1996-02-10'",
"'distinct'",
2,
lambda expected_select: f"{expected_select}\nUNION\n{expected_select}\n",
),
# Test case 6: Missing union type (defaults to ALL)
(
"test_6",
"@get_date() == '1996-02-10'",
"",
2,
lambda expected_select: f"{expected_select}\nUNION ALL\n{expected_select}\n",
),
# Test case 7: Missing union type AND condition
(
"test_7",
"",
"",
2,
lambda expected_select: f"{expected_select}\nUNION ALL\n{expected_select}\n",
),
# Test case 8: Missing union type AND condition multiple tables
(
"test_8",
"",
"",
3,
lambda expected_select: f"{expected_select}\nUNION ALL\n{expected_select}\n\nUNION ALL\n{expected_select}\n",
),
# Test case 9: Missing union type AND condition one table
(
"test_9",
"",
"",
1,
lambda expected_select: f"{expected_select}",
),
# Test case 10: Union type with one table
(
"test_10",
"",
"'distinct'",
1,
lambda expected_select: f"{expected_select}",
),
# Test case 11: Condition with one table
(
"test_9",
"True",
"",
1,
lambda expected_select: f"{expected_select}",
),
],
)
def test_model_union_conditional(
sushi_context, assert_exp_eq, test_id, condition, union_type, table_count, expected_result
):
@macro()
def get_date(evaluator):
from sqlmesh.utils.date import now
return f"'{now().date()}'"
expected_select = """SELECT
CAST("marketing"."customer_id" AS INT) AS "customer_id",
CAST("marketing"."status" AS TEXT) AS "status",
CAST("marketing"."updated_at" AS TIMESTAMPNTZ) AS "updated_at",
CAST("marketing"."valid_from" AS TIMESTAMP) AS "valid_from",
CAST("marketing"."valid_to" AS TIMESTAMP) AS "valid_to"
FROM "memory"."sushi"."marketing" AS "marketing"
"""
# Create tables argument list based on table_count
tables = ", ".join(["sushi.marketing"] * table_count)
# Handle the missing union_type case
union_type_arg = f", {union_type}" if union_type else ""
expressions = d.parse(
f"""
MODEL (
name sushi.{test_id},
kind FULL,
);
@union({condition}{union_type_arg}, {tables})
"""
)
sushi_context.upsert_model(load_sql_based_model(expressions, default_catalog="memory"))
assert_exp_eq(
sushi_context.get_model(f"sushi.{test_id}").render_query(),
expected_result(expected_select),
)
@use_terminal_console
def test_model_qualification(tmp_path: Path):
with patch.object(get_console(), "log_warning") as mock_logger:
expressions = d.parse(
"""
MODEL (
name db.table,
kind FULL,
);
SELECT a
"""
)
ctx = Context(
config=Config(linter=LinterConfig(enabled=True, warn_rules=["ALL"])), paths=tmp_path
)
ctx.upsert_model(load_sql_based_model(expressions))
ctx.plan_builder("dev")
assert (
"""Column '"a"' could not be resolved for model '"db"."table"', the column may not exist or is ambiguous."""
in mock_logger.call_args[0][0]
)
@use_terminal_console
def test_model_missing_audits(tmp_path: Path):
with patch.object(get_console(), "log_warning") as mock_logger:
expressions = d.parse(
"""
MODEL (
name db.table,
kind FULL,
);
SELECT a
"""
)
ctx = Context(
config=Config(linter=LinterConfig(enabled=True, warn_rules=["nomissingaudits"])),
paths=tmp_path,
)
ctx.upsert_model(load_sql_based_model(expressions))
ctx.plan_builder("plan")
assert (
"""Model `audits` must be configured to test data quality."""
in mock_logger.call_args[0][0]
)
def test_project_is_set_in_standalone_audit(tmp_path: Path) -> None:
init_example_project(tmp_path, engine_type="duckdb", template=ProjectTemplate.EMPTY)
db_path = str(tmp_path / "db.db")
db_connection = DuckDBConnectionConfig(database=db_path)
config = Config(
project="test",
gateways={"gw": GatewayConfig(connection=db_connection)},
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
)
model = tmp_path / "models" / "some_model.sql"
model.parent.mkdir(parents=True, exist_ok=True)
model.write_text("MODEL (name m); SELECT 1 AS c")
audit = tmp_path / "audits" / "a_standalone_audit.sql"
audit.parent.mkdir(parents=True, exist_ok=True)
audit.write_text("AUDIT (name a, standalone true); SELECT * FROM m WHERE c <= 0")
context = Context(paths=tmp_path, config=config)
context.plan(no_prompts=True, auto_apply=True)
model = tmp_path / "models" / "some_model.sql"
model.parent.mkdir(parents=True, exist_ok=True)
model.write_text("MODEL (name m); SELECT 2 AS c")
assert context.fetchdf(
"select snapshot -> 'node' -> 'project' AS standalone_audit_project "
"""from sqlmesh._snapshots where (snapshot -> 'node' -> 'source_type')::text = '"audit"'"""
).to_dict()["standalone_audit_project"] == {0: '"test"'}
assert context.load().standalone_audits["a"].project == "test"
@pytest.mark.parametrize(
"partition_by_input, partition_by_output, output_dialect, expected_exception",
[
("a", ["`a`"], "bigquery", None),
("(a, b)", ["`a`", "`b`"], "bigquery", None),
("TIMESTAMP_TRUNC(`a`, DAY)", ["TIMESTAMP_TRUNC(`a`, DAY)"], "bigquery", None),
("e", "", "bigquery", ConfigError),
("(a, e)", "", "bigquery", ConfigError),
("(a, a)", "", "bigquery", ConfigError),
("(day(a),b)", ['DAY("a")', '"b"'], "trino", None),
],
)
def test_partitioned_by(
partition_by_input, partition_by_output, output_dialect, expected_exception
):
expressions = d.parse(
f"""
MODEL (
name db.table,
dialect bigquery,
owner owner_name,
partitioned_by {partition_by_input},
clustered_by (c, d),
kind INCREMENTAL_BY_TIME_RANGE(
time_column a,
),
);
SELECT 1::int AS a, 2::int AS b, 3 AS c, 4 as d;
"""
)
model = load_sql_based_model(expressions)
assert model.clustered_by == [exp.to_column('"c"'), exp.to_column('"d"')]
if expected_exception:
with pytest.raises(expected_exception):
model.validate_definition()
else:
model.validate_definition()
assert [
col.sql(dialect=output_dialect) for col in model.partitioned_by
] == partition_by_output
def test_opt_out_of_time_column_in_partitioned_by():
expressions = d.parse(
"""
MODEL (
name db.table,
dialect bigquery,
partitioned_by b,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a,
partition_by_time_column false
),
);
SELECT 1::int AS a, 2::int AS b;
"""
)
model = load_sql_based_model(expressions)
assert model.partitioned_by == [exp.to_column('"b"')]
def test_model_no_name():
expressions = d.parse(
"""
MODEL (
dialect bigquery,
);
SELECT 1::int AS a, 2::int AS b;
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
assert (
str(ex.value)
== "Please add the required 'name' field to the MODEL block at the top of the file.\n\nLearn more at https://sqlmesh.readthedocs.io/en/stable/concepts/models/overview"
)
def test_model_field_name_suggestions():
# top-level field
expressions = d.parse(
"""
MODEL (
name db.table,
dialects bigquery,
);
SELECT 1::int AS a, 2::int AS b;
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
assert (
str(ex.value)
== "Invalid field name present in the MODEL block: 'dialects'. Did you mean 'dialect'?"
)
# kind field
expressions = d.parse(
"""
MODEL (
name db.table,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a,
batch_sizes 1
),
);
SELECT 1::int AS a, 2::int AS b;
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
assert (
str(ex.value)
== "Invalid field name present in the MODEL block 'kind INCREMENTAL_BY_TIME_RANGE' field: 'batch_sizes'. Did you mean 'batch_size'?"
)
# multiple fields
expressions = d.parse(
"""
MODEL (
name db.table,
dialects bigquery,
descriptions 'a',
asdfasdf true
);
SELECT 1::int AS a, 2::int AS b;
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
ex_str = str(ex.value)
# field order is non-deterministic, so we can't test the output string directly
assert "Invalid field names present in the MODEL block: " in ex_str
assert "'descriptions'" in ex_str
assert "'dialects'" in ex_str
assert "'asdfasdf'" in ex_str
assert "- descriptions: Did you mean 'description'?" in ex_str
assert "- dialects: Did you mean 'dialect'?" in ex_str
assert "- asdfasdf: Did you mean " not in ex_str
def test_model_required_field_missing():
expressions = d.parse(
"""
MODEL (
name db.table,
kind INCREMENTAL_BY_TIME_RANGE (),
);
SELECT 1::int AS a, 2::int AS b;
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
assert (
str(ex.value)
== "Please add required field 'time_column' to the MODEL block 'kind INCREMENTAL_BY_TIME_RANGE' field."
)
def test_no_model_statement(tmp_path: Path):
# No name inference => MODEL (...) is required
expressions = d.parse("SELECT 1 AS x")
with pytest.raises(
ConfigError,
match="Please add a MODEL block at the top of the file. Example:",
):
load_sql_based_model(expressions)
# Name inference is enabled => MODEL (...) not required
init_example_project(tmp_path, engine_type="duckdb")
test_sql_file = tmp_path / "models/test_schema/test_model.sql"
test_sql_file.parent.mkdir(parents=True, exist_ok=True)
test_sql_file.write_text("SELECT 1 AS c")
config = Config(
model_defaults=ModelDefaultsConfig(dialect="duckdb"),
model_naming=NameInferenceConfig(infer_names=True),
)
context = Context(paths=tmp_path, config=config)
model = context.get_model("test_schema.test_model")
assert isinstance(model, SqlModel)
assert model.name == "test_schema.test_model"
def test_unordered_model_statements():
expressions = d.parse(
"""
SELECT 1 AS x;
MODEL (
name db.table,
dialect spark,
owner owner_name
);
"""
)
with pytest.raises(ConfigError) as ex:
load_sql_based_model(expressions)
assert "Please add a MODEL block at the top of the file. Example:" in str(ex.value)
def test_no_query():
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name
);
@DEF(x, 1)
"""
)
with pytest.raises(ConfigError) as ex:
model = load_sql_based_model(expressions, path=Path("test_location"))
model.validate_definition()
assert "Model query needs to be a SELECT or a UNION, got @DEF(x, 1)." in str(ex.value)
def test_single_macro_as_query(assert_exp_eq):
@macro()
def select_query(evaluator, *projections):
return exp.select(*[f'{p} AS "{p}"' for p in projections])
expressions = d.parse(
"""
MODEL (
name test
);
@SELECT_QUERY(1, 2, 3)
"""
)
model = load_sql_based_model(expressions)
assert_exp_eq(
model.render_query(),
"""
SELECT
1 AS "1",
2 AS "2",
3 AS "3"
""",
)
def test_partition_key_is_missing_in_query():
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a
),
partitioned_by (b, c, d)
);
SELECT 1::int AS a, 2::int AS b;
"""
)
model = load_sql_based_model(expressions)
with pytest.raises(ConfigError) as ex:
model.validate_definition()
assert "['c', 'd'] are missing" in str(ex.value)
def test_cluster_key_is_missing_in_query():
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a
),
clustered_by (b, c, d)
);
SELECT 1::int AS a, 2::int AS b;
"""
)
model = load_sql_based_model(expressions)
with pytest.raises(ConfigError) as ex:
model.validate_definition()
assert "['c', 'd'] are missing" in str(ex.value)
def test_partition_key_and_select_star():
expressions = d.parse(
"""
MODEL (
name db.table,
dialect spark,
owner owner_name,
kind INCREMENTAL_BY_TIME_RANGE(
time_column a
),
partitioned_by (b, c, d)
);
SELECT * FROM tbl;
"""
)
load_sql_based_model(expressions)
def test_json_serde():
expressions = parse(
"""
MODEL (
name test_model,
kind INCREMENTAL_BY_TIME_RANGE(
time_column ds
),
owner test_owner,
dialect spark,
cron '@daily',
storage_format parquet,
partitioned_by a,
physical_properties (
key_a = 'value_a',
'key_b' = 1,
key_c = true,
"key_d" = 2.0,
),
);
@DEF(key, 'value');
SELECT a, ds FROM `tbl`
"""
)
model = load_sql_based_model(expressions)
model_json = model.json()
model_json_parsed = json.loads(model.json())
assert model_json_parsed["kind"]["dialect"] == "spark"
assert model_json_parsed["kind"]["time_column"]["column"] == "`ds`"
assert model_json_parsed["partitioned_by"] == ["`a`"]
deserialized_model = SqlModel.parse_raw(model_json)
assert deserialized_model.dict() == model.dict()
expressions = parse(
"""
MODEL (
name test_model,
kind FULL,
dialect duckdb,
);
SELECT
x ~ y AS c
"""
)
model = load_sql_based_model(expressions)
model_json = model.json()
model_json_parsed = json.loads(model.json())
assert (
SqlModel.parse_obj(model_json_parsed).render_query().sql("duckdb")
== 'SELECT REGEXP_FULL_MATCH("x", "y") AS "c"'
)
def test_scd_type_2_by_col_serde():
expressions = parse(
"""
MODEL(
name test_model,
KIND SCD_TYPE_2_BY_COLUMN (
unique_key a,
columns *,
),
cron '@daily',
owner 'reakman',
grain a,
dialect bigquery
);
SELECT a, ds FROM `tbl`
""",
default_dialect="bigquery",
)
model = load_sql_based_model(expressions)
model_json = model.json()
model_json_parsed = json.loads(model.json())
assert model_json_parsed["kind"]["dialect"] == "bigquery"
assert model_json_parsed["kind"]["unique_key"] == ["`a`"]
assert model_json_parsed["kind"]["columns"] == ["*"]
# Bigquery converts TIMESTAMP -> DATETIME
assert model_json_parsed["kind"]["time_data_type"] == "DATETIME"
deserialized_model = SqlModel.parse_raw(model_json)
assert deserialized_model.dict() == model.dict()
def test_column_descriptions(sushi_context, assert_exp_eq):
assert sushi_context.models[
'"memory"."sushi"."customer_revenue_by_day"'
].column_descriptions == {
"customer_id": "Customer id",
"country code": "Customer country code, used for testing spaces",
"revenue": "Revenue from orders made by this customer",
"event_date": "Date",
}
expressions = d.parse(
"""
MODEL (
name db.table,
kind FULL,
);
SELECT
-- this is the id column, used in ...
id::int, -- primary key
foo::int, -- bar
FROM table
"""
)
model = load_sql_based_model(expressions, default_catalog="memory")
assert_exp_eq(
model.query,
"""
SELECT
-- this is the id column, used in ...
id::int, -- primary key
foo::int, -- bar
FROM table
""",
)
assert model.column_descriptions == {"id": "primary key", "foo": "bar"}
def test_model_jinja_macro_reference_extraction():
@macro()