-
Notifications
You must be signed in to change notification settings - Fork 373
Expand file tree
/
Copy pathtest_integration.py
More file actions
3836 lines (3402 loc) · 141 KB
/
test_integration.py
File metadata and controls
3836 lines (3402 loc) · 141 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
# type: ignore
from __future__ import annotations
import pathlib
import re
import sys
import typing as t
import shutil
from datetime import datetime, timedelta, date
from unittest import mock
from unittest.mock import patch
import logging
import numpy as np # noqa: TID253
import pandas as pd # noqa: TID253
import pytest
import pytz
import time_machine
from sqlglot import exp, parse_one
from sqlglot.optimizer.normalize_identifiers import normalize_identifiers
from sqlglot.optimizer.qualify_columns import quote_identifiers
from sqlmesh import Config, Context
from sqlmesh.cli.project_init import init_example_project
from sqlmesh.core.config.common import VirtualEnvironmentMode
from sqlmesh.core.config.connection import ConnectionConfig
import sqlmesh.core.dialect as d
from sqlmesh.core.environment import EnvironmentSuffixTarget
from sqlmesh.core.dialect import select_from_values
from sqlmesh.core.model import Model, load_sql_based_model
from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType
from sqlmesh.core.engine_adapter.mixins import RowDiffMixin, LogicalMergeMixin
from sqlmesh.core.model.definition import create_sql_model
from sqlmesh.core.plan import Plan
from sqlmesh.core.state_sync.db import EngineAdapterStateSync
from sqlmesh.core.snapshot import Snapshot, SnapshotChangeCategory
from sqlmesh.utils.date import now, to_date, to_time_column
from sqlmesh.core.table_diff import TableDiff
from sqlmesh.utils.errors import SQLMeshError
from sqlmesh.utils.pydantic import PydanticModel
from tests.conftest import SushiDataValidator
from tests.core.engine_adapter.integration import (
TestContext,
MetadataResults,
TEST_SCHEMA,
wait_until,
)
DATA_TYPE = exp.DataType.Type
VARCHAR_100 = exp.DataType.build("varchar(100)")
class PlanResults(PydanticModel):
plan: Plan
ctx: TestContext
schema_metadata: MetadataResults
internal_schema_metadata: MetadataResults
@classmethod
def create(cls, plan: Plan, ctx: TestContext, schema_name: str):
schema_metadata = ctx.get_metadata_results(schema_name)
internal_schema_metadata = ctx.get_metadata_results(f"sqlmesh__{schema_name}")
return PlanResults(
plan=plan,
ctx=ctx,
schema_metadata=schema_metadata,
internal_schema_metadata=internal_schema_metadata,
)
def snapshot_for(self, model: Model) -> Snapshot:
return next((s for s in list(self.plan.snapshots.values()) if s.name == model.fqn))
def modified_snapshot_for(self, model: Model) -> Snapshot:
return next((s for s in list(self.plan.modified_snapshots.values()) if s.name == model.fqn))
def table_name_for(
self, snapshot_or_model: Snapshot | Model, is_deployable: bool = True
) -> str:
snapshot = (
snapshot_or_model
if isinstance(snapshot_or_model, Snapshot)
else self.snapshot_for(snapshot_or_model)
)
table_name = snapshot.table_name(is_deployable)
return exp.to_table(table_name).this.sql(dialect=self.ctx.dialect)
def dev_table_name_for(self, snapshot: Snapshot) -> str:
return self.table_name_for(snapshot, is_deployable=False)
def test_connection(ctx: TestContext):
cursor_from_connection = ctx.engine_adapter.connection.cursor()
cursor_from_connection.execute("SELECT 1")
assert cursor_from_connection.fetchone()[0] == 1
def test_catalog_operations(ctx: TestContext):
if (
ctx.engine_adapter.catalog_support.is_unsupported
or ctx.engine_adapter.catalog_support.is_single_catalog_only
):
pytest.skip(
f"Engine adapter {ctx.engine_adapter.dialect} doesn't support catalog operations"
)
# use a unique name so that integration tests on cloud databases can run in parallel
catalog_name = "testing" if not ctx.is_remote else ctx.add_test_suffix("testing")
ctx.create_catalog(catalog_name)
current_catalog = ctx.engine_adapter.get_current_catalog().lower()
ctx.engine_adapter.set_current_catalog(catalog_name)
assert ctx.engine_adapter.get_current_catalog().lower() == catalog_name
ctx.engine_adapter.set_current_catalog(current_catalog)
assert ctx.engine_adapter.get_current_catalog().lower() == current_catalog
# cleanup cloud databases since they persist between runs
if ctx.is_remote:
ctx.drop_catalog(catalog_name)
def test_drop_schema_catalog(ctx: TestContext, caplog):
def drop_schema_and_validate(schema_name: str):
ctx.engine_adapter.drop_schema(schema_name, cascade=True)
results = ctx.get_metadata_results(schema_name)
assert (
len(results.tables)
== len(results.views)
== len(results.materialized_views)
== len(results.non_temp_tables)
== 0
)
def create_objects_and_validate(schema_name: str):
ctx.engine_adapter.create_schema(schema_name)
ctx.engine_adapter.create_view(f"{schema_name}.test_view", parse_one("SELECT 1 as col"))
ctx.engine_adapter.create_table(
f"{schema_name}.test_table", {"col": exp.DataType.build("int")}
)
ctx.engine_adapter.create_table(
f"{schema_name}.replace_table", {"col": exp.DataType.build("int")}
)
ctx.engine_adapter.replace_query(
f"{schema_name}.replace_table",
parse_one("SELECT 1 as col"),
{"col": exp.DataType.build("int")},
)
results = ctx.get_metadata_results(schema_name)
assert len(results.tables) == 2
assert len(results.views) == 1
assert len(results.materialized_views) == 0
assert len(results.non_temp_tables) == 2
if ctx.engine_adapter.catalog_support.is_unsupported:
pytest.skip(
f"Engine adapter {ctx.engine_adapter.dialect} doesn't support catalog operations"
)
if ctx.dialect == "spark":
pytest.skip(
"Currently local spark is configured to have iceberg be the testing catalog and drop cascade doesn't work on iceberg. Skipping until we have time to fix."
)
catalog_name = "testing" if not ctx.is_remote else ctx.add_test_suffix("testing")
if ctx.dialect == "bigquery":
catalog_name = ctx.engine_adapter.get_current_catalog()
catalog_name = normalize_identifiers(catalog_name, dialect=ctx.dialect).sql(dialect=ctx.dialect)
ctx.create_catalog(catalog_name)
schema = ctx.schema("drop_schema_catalog_test", catalog_name)
if ctx.engine_adapter.catalog_support.is_single_catalog_only:
with pytest.raises(
SQLMeshError, match="requires that all catalog operations be against a single catalog"
):
drop_schema_and_validate(schema)
create_objects_and_validate(schema)
return
drop_schema_and_validate(schema)
create_objects_and_validate(schema)
if ctx.is_remote:
ctx.drop_catalog(catalog_name)
def test_temp_table(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
table = ctx.table("example")
with ctx.engine_adapter.temp_table(
ctx.input_data(input_data), table.sql(), table_format=ctx.default_table_format
) as table_name:
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.tables) == 1
assert len(results.non_temp_tables) == 0
assert len(results.materialized_views) == 0
ctx.compare_with_current(table_name, input_data)
results = ctx.get_metadata_results()
assert len(results.views) == len(results.tables) == len(results.non_temp_tables) == 0
def test_create_table(ctx: TestContext):
table = ctx.table("test_table")
ctx.engine_adapter.create_table(
table,
{"id": exp.DataType.build("int")},
table_description="test table description",
column_descriptions={"id": "test id column description"},
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results()
assert len(results.tables) == 1
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert results.tables[0] == table.name
if ctx.engine_adapter.COMMENT_CREATION_TABLE.is_supported:
table_description = ctx.get_table_comment(table.db, "test_table")
column_comments = ctx.get_column_comments(table.db, "test_table")
assert table_description == "test table description"
assert column_comments == {"id": "test id column description"}
def test_ctas(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
table = ctx.table("test_table")
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
ctx.engine_adapter.ctas(
table,
ctx.input_data(input_data),
table_description="test table description",
column_descriptions={"id": "test id column description"},
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results(schema=table.db)
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
if ctx.engine_adapter.COMMENT_CREATION_TABLE.is_supported:
table_description = ctx.get_table_comment(table.db, table.name)
column_comments = ctx.get_column_comments(table.db, table.name)
assert table_description == "test table description"
assert column_comments == {"id": "test id column description"}
# ensure we don't hit clickhouse INSERT with LIMIT 0 bug on CTAS
if ctx.dialect == "clickhouse":
ctx.engine_adapter.ctas(table, exp.select("1").limit(0))
def test_ctas_source_columns(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
table = ctx.table("test_table")
columns_to_types = ctx.columns_to_types.copy()
columns_to_types["ignored_column"] = exp.DataType.build("int")
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01", "ignored_source": "ignored_value"},
{"id": 2, "ds": "2022-01-02", "ignored_source": "ignored_value"},
{"id": 3, "ds": "2022-01-03", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.ctas(
table,
ctx.input_data(input_data),
table_description="test table description",
column_descriptions={"id": "test id column description"},
table_format=ctx.default_table_format,
target_columns_to_types=columns_to_types,
source_columns=["id", "ds", "ignored_source"],
)
expected_data = input_data.copy()
expected_data["ignored_column"] = pd.Series()
expected_data = expected_data.drop(columns=["ignored_source"])
results = ctx.get_metadata_results(schema=table.db)
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, expected_data)
if ctx.engine_adapter.COMMENT_CREATION_TABLE.is_supported:
table_description = ctx.get_table_comment(table.db, table.name)
column_comments = ctx.get_column_comments(table.db, table.name)
assert table_description == "test table description"
assert column_comments == {"id": "test id column description"}
# ensure we don't hit clickhouse INSERT with LIMIT 0 bug on CTAS
if ctx.dialect == "clickhouse":
ctx.engine_adapter.ctas(table, exp.select("1").limit(0))
def test_create_view(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
view = ctx.table("test_view")
ctx.engine_adapter.create_view(
view,
ctx.input_data(input_data),
table_description="test view description",
column_descriptions={"id": "test id column description"},
)
results = ctx.get_metadata_results()
assert len(results.tables) == 0
assert len(results.views) == 1
assert len(results.materialized_views) == 0
assert results.views[0] == view.name
ctx.compare_with_current(view, input_data)
if ctx.engine_adapter.COMMENT_CREATION_VIEW.is_supported:
table_description = ctx.get_table_comment(view.db, "test_view", table_kind="VIEW")
column_comments = ctx.get_column_comments(view.db, "test_view", table_kind="VIEW")
# Query:
# In the query test, columns_to_types are not available when the view is created. Since we
# can only register column comments in the CREATE VIEW schema expression with columns_to_types
# available, the column comments must be registered via post-creation commands. Some engines,
# such as Spark and Snowflake, do not support view column comments via post-creation commands.
assert table_description == "test view description"
assert column_comments == (
{}
if (
ctx.test_type == "query"
and not ctx.engine_adapter.COMMENT_CREATION_VIEW.supports_column_comment_commands
)
else {"id": "test id column description"}
)
def test_create_view_source_columns(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
columns_to_types = ctx.columns_to_types.copy()
columns_to_types["ignored_column"] = exp.DataType.build("int")
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01", "ignored_source": "ignored_value"},
{"id": 2, "ds": "2022-01-02", "ignored_source": "ignored_value"},
{"id": 3, "ds": "2022-01-03", "ignored_source": "ignored_value"},
]
)
view = ctx.table("test_view")
ctx.engine_adapter.create_view(
view,
ctx.input_data(input_data),
table_description="test view description",
column_descriptions={"id": "test id column description"},
source_columns=["id", "ds", "ignored_source"],
target_columns_to_types=columns_to_types,
)
expected_data = input_data.copy()
expected_data["ignored_column"] = pd.Series()
expected_data = expected_data.drop(columns=["ignored_source"])
results = ctx.get_metadata_results()
assert len(results.tables) == 0
assert len(results.views) == 1
assert len(results.materialized_views) == 0
assert results.views[0] == view.name
ctx.compare_with_current(view, expected_data)
if ctx.engine_adapter.COMMENT_CREATION_VIEW.is_supported:
table_description = ctx.get_table_comment(view.db, "test_view", table_kind="VIEW")
column_comments = ctx.get_column_comments(view.db, "test_view", table_kind="VIEW")
assert table_description == "test view description"
assert column_comments == {"id": "test id column description"}
def test_materialized_view(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
if not ctx.engine_adapter.SUPPORTS_MATERIALIZED_VIEWS:
pytest.skip(f"Engine adapter {ctx.engine_adapter} doesn't support materialized views")
if ctx.engine_adapter.dialect == "databricks":
pytest.skip(
"Databricks requires DBSQL Serverless or Pro warehouse to test materialized views which we do not have setup"
)
if ctx.engine_adapter.dialect == "snowflake":
pytest.skip("Snowflake requires enterprise edition which we do not have setup")
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
source_table = ctx.table("source_table")
ctx.engine_adapter.ctas(source_table, ctx.input_data(input_data), ctx.columns_to_types)
view = ctx.table("test_view")
view_query = exp.select(*ctx.columns_to_types).from_(source_table)
ctx.engine_adapter.create_view(view, view_query, materialized=True)
results = ctx.get_metadata_results()
# Redshift considers the underlying dataset supporting materialized views as a table therefore we get 2
# tables in the result
if ctx.engine_adapter.dialect == "redshift":
assert len(results.tables) == 2
else:
assert len(results.tables) == 1
assert len(results.views) == 0
assert len(results.materialized_views) == 1
assert results.materialized_views[0] == view.name
ctx.compare_with_current(view, input_data)
# Make sure that dropping a materialized view also works
ctx.engine_adapter.drop_view(view, materialized=True)
results = ctx.get_metadata_results()
assert len(results.materialized_views) == 0
def test_drop_schema(ctx: TestContext):
ctx.columns_to_types = {"one": "int"}
schema = ctx.schema(TEST_SCHEMA)
ctx.engine_adapter.drop_schema(schema, cascade=True)
results = ctx.get_metadata_results()
assert len(results.tables) == 0
assert len(results.views) == 0
ctx.engine_adapter.create_schema(schema)
view = ctx.table("test_view")
view_query = exp.Select().select(exp.Literal.number(1).as_("one"))
ctx.engine_adapter.create_view(view, view_query, ctx.columns_to_types)
results = ctx.get_metadata_results()
assert len(results.tables) == 0
assert len(results.views) == 1
ctx.engine_adapter.drop_schema(schema, cascade=True)
results = ctx.get_metadata_results()
assert len(results.tables) == 0
assert len(results.views) == 0
def test_nan_roundtrip(ctx_df: TestContext):
ctx = ctx_df
ctx.engine_adapter.DEFAULT_BATCH_SIZE = sys.maxsize
table = ctx.table("test_table")
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": np.nan, "ds": np.nan},
]
)
ctx.engine_adapter.create_table(table, ctx.columns_to_types)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(input_data),
target_columns_to_types=ctx.columns_to_types,
)
results = ctx.get_metadata_results()
assert not results.views
assert not results.materialized_views
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
def test_replace_query(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
ctx.engine_adapter.DEFAULT_BATCH_SIZE = sys.maxsize
table = ctx.table("test_table")
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
ctx.engine_adapter.create_table(
table, ctx.columns_to_types, table_format=ctx.default_table_format
)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(input_data),
# Spark based engines do a create table -> insert overwrite instead of replace. If columns to types aren't
# provided then it checks the table itself for types. This is fine within SQLMesh since we always know the tables
# exist prior to evaluation but when running these tests that isn't the case. As a result we just pass in
# columns_to_types for these two engines so we can still test inference on the other ones
target_columns_to_types=ctx.columns_to_types
if ctx.dialect in ["spark", "databricks"]
else None,
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
# Replace that we only need to run once
if type == "df":
replace_data = pd.DataFrame(
[
{"id": 4, "ds": "2022-01-04"},
{"id": 5, "ds": "2022-01-05"},
{"id": 6, "ds": "2022-01-06"},
]
)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(replace_data),
target_columns_to_types=(
ctx.columns_to_types if ctx.dialect in ["spark", "databricks"] else None
),
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, replace_data)
def test_replace_query_source_columns(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
ctx.engine_adapter.DEFAULT_BATCH_SIZE = sys.maxsize
table = ctx.table("test_table")
columns_to_types = ctx.columns_to_types.copy()
columns_to_types["ignored_column"] = exp.DataType.build("int")
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01", "ignored_source": "ignored_value"},
{"id": 2, "ds": "2022-01-02", "ignored_source": "ignored_value"},
{"id": 3, "ds": "2022-01-03", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.create_table(table, columns_to_types, table_format=ctx.default_table_format)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(input_data),
table_format=ctx.default_table_format,
source_columns=["id", "ds", "ignored_source"],
target_columns_to_types=columns_to_types,
)
expected_data = input_data.copy()
expected_data["ignored_column"] = pd.Series()
expected_data = expected_data.drop(columns=["ignored_source"])
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, expected_data)
# Replace that we only need to run once
if type == "df":
replace_data = pd.DataFrame(
[
{"id": 4, "ds": "2022-01-04"},
{"id": 5, "ds": "2022-01-05"},
{"id": 6, "ds": "2022-01-06"},
]
)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(replace_data),
table_format=ctx.default_table_format,
source_columns=["id", "ds"],
target_columns_to_types=columns_to_types,
)
expected_data = replace_data.copy()
expected_data["ignored_column"] = pd.Series()
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, expected_data)
def test_replace_query_batched(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
ctx.engine_adapter.DEFAULT_BATCH_SIZE = 1
table = ctx.table("test_table")
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
ctx.engine_adapter.create_table(
table, ctx.columns_to_types, table_format=ctx.default_table_format
)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(input_data),
# Spark based engines do a create table -> insert overwrite instead of replace. If columns to types aren't
# provided then it checks the table itself for types. This is fine within SQLMesh since we always know the tables
# exist prior to evaluation but when running these tests that isn't the case. As a result we just pass in
# columns_to_types for these two engines so we can still test inference on the other ones
target_columns_to_types=ctx.columns_to_types
if ctx.dialect in ["spark", "databricks"]
else None,
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
# Replace that we only need to run once
if ctx.test_type == "df":
replace_data = pd.DataFrame(
[
{"id": 4, "ds": "2022-01-04"},
{"id": 5, "ds": "2022-01-05"},
{"id": 6, "ds": "2022-01-06"},
]
)
ctx.engine_adapter.replace_query(
table,
ctx.input_data(replace_data),
target_columns_to_types=(
ctx.columns_to_types if ctx.dialect in ["spark", "databricks"] else None
),
table_format=ctx.default_table_format,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, replace_data)
def test_insert_append(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
table = ctx.table("test_table")
ctx.engine_adapter.create_table(
table, ctx.columns_to_types, table_format=ctx.default_table_format
)
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
ctx.engine_adapter.insert_append(table, ctx.input_data(input_data))
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
# Replace that we only need to run once
if ctx.test_type == "df":
append_data = pd.DataFrame(
[
{"id": 4, "ds": "2022-01-04"},
{"id": 5, "ds": "2022-01-05"},
{"id": 6, "ds": "2022-01-06"},
]
)
ctx.engine_adapter.insert_append(table, ctx.input_data(append_data))
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) in [1, 2, 3]
assert len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, pd.concat([input_data, append_data]))
def test_insert_append_source_columns(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
table = ctx.table("test_table")
columns_to_types = ctx.columns_to_types.copy()
columns_to_types["ignored_column"] = exp.DataType.build("int")
ctx.engine_adapter.create_table(table, columns_to_types, table_format=ctx.default_table_format)
# Initial Load
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01", "ignored_source": "ignored_value"},
{"id": 2, "ds": "2022-01-02", "ignored_source": "ignored_value"},
{"id": 3, "ds": "2022-01-03", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.insert_append(
table,
ctx.input_data(input_data),
source_columns=["id", "ds", "ignored_source"],
target_columns_to_types=columns_to_types,
)
expected_data = input_data.copy()
expected_data["ignored_column"] = pd.Series()
expected_data = expected_data.drop(columns=["ignored_source"])
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, expected_data)
# Replace that we only need to run once
if ctx.test_type == "df":
append_data = pd.DataFrame(
[
{"id": 4, "ds": "2022-01-04", "ignored_source": "ignored_value"},
{"id": 5, "ds": "2022-01-05", "ignored_source": "ignored_value"},
{"id": 6, "ds": "2022-01-06", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.insert_append(
table,
ctx.input_data(append_data),
source_columns=["id", "ds", "ignored_source"],
target_columns_to_types=columns_to_types,
)
append_expected_data = append_data.copy()
append_expected_data["ignored_column"] = pd.Series()
append_expected_data = append_expected_data.drop(columns=["ignored_source"])
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) in [1, 2, 3]
assert len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, pd.concat([expected_data, append_expected_data]))
def test_insert_overwrite_by_time_partition(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
ds_type = "string"
if ctx.dialect == "bigquery":
ds_type = "datetime"
if ctx.dialect == "tsql":
ds_type = "varchar(max)"
ctx.columns_to_types = {"id": "int", "ds": ds_type}
table = ctx.table("test_table")
if ctx.dialect == "bigquery":
partitioned_by = ["DATE(ds)"]
else:
partitioned_by = ctx.partitioned_by # type: ignore
ctx.engine_adapter.create_table(
table,
ctx.columns_to_types,
partitioned_by=partitioned_by,
partition_interval_unit="DAY",
table_format=ctx.default_table_format,
)
input_data = pd.DataFrame(
[
{"id": 1, ctx.time_column: "2022-01-01"},
{"id": 2, ctx.time_column: "2022-01-02"},
{"id": 3, ctx.time_column: "2022-01-03"},
]
)
ctx.engine_adapter.insert_overwrite_by_time_partition(
table,
ctx.input_data(input_data),
start="2022-01-02",
end="2022-01-03",
time_formatter=ctx.time_formatter,
time_column=ctx.time_column,
target_columns_to_types=ctx.columns_to_types,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
if ctx.dialect == "trino":
# trino has some lag between partitions being registered and data showing up
wait_until(lambda: len(ctx.get_current_data(table)) > 0)
ctx.compare_with_current(table, input_data.iloc[1:])
if ctx.test_type == "df":
overwrite_data = pd.DataFrame(
[
{"id": 10, ctx.time_column: "2022-01-03"},
{"id": 4, ctx.time_column: "2022-01-04"},
{"id": 5, ctx.time_column: "2022-01-05"},
]
)
ctx.engine_adapter.insert_overwrite_by_time_partition(
table,
ctx.input_data(overwrite_data),
start="2022-01-03",
end="2022-01-05",
time_formatter=ctx.time_formatter,
time_column=ctx.time_column,
target_columns_to_types=ctx.columns_to_types,
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
if ctx.dialect == "trino":
wait_until(lambda: len(ctx.get_current_data(table)) > 2)
ctx.compare_with_current(
table,
pd.DataFrame(
[
{"id": 2, ctx.time_column: "2022-01-02"},
{"id": 10, ctx.time_column: "2022-01-03"},
{"id": 4, ctx.time_column: "2022-01-04"},
{"id": 5, ctx.time_column: "2022-01-05"},
]
),
)
def test_insert_overwrite_by_time_partition_source_columns(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
ds_type = "string"
if ctx.dialect == "bigquery":
ds_type = "datetime"
if ctx.dialect == "tsql":
ds_type = "varchar(max)"
ctx.columns_to_types = {"id": "int", "ds": ds_type}
columns_to_types = {
"id": exp.DataType.build("int"),
"ignored_column": exp.DataType.build("int"),
"ds": exp.DataType.build(ds_type),
}
table = ctx.table("test_table")
if ctx.dialect == "bigquery":
partitioned_by = ["DATE(ds)"]
else:
partitioned_by = ctx.partitioned_by # type: ignore
ctx.engine_adapter.create_table(
table,
columns_to_types,
partitioned_by=partitioned_by,
partition_interval_unit="DAY",
table_format=ctx.default_table_format,
)
input_data = pd.DataFrame(
[
{"id": 1, ctx.time_column: "2022-01-01", "ignored_source": "ignored_value"},
{"id": 2, ctx.time_column: "2022-01-02", "ignored_source": "ignored_value"},
{"id": 3, ctx.time_column: "2022-01-03", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.insert_overwrite_by_time_partition(
table,
ctx.input_data(input_data),
start="2022-01-02",
end="2022-01-03",
time_formatter=ctx.time_formatter,
time_column=ctx.time_column,
target_columns_to_types=columns_to_types,
source_columns=["id", "ds", "ignored_source"],
)
expected_data = input_data.copy()
expected_data = expected_data.drop(columns=["ignored_source"])
expected_data.insert(len(expected_data.columns) - 1, "ignored_column", pd.Series())
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
if ctx.dialect == "trino":
# trino has some lag between partitions being registered and data showing up
wait_until(lambda: len(ctx.get_current_data(table)) > 0)
ctx.compare_with_current(table, expected_data.iloc[1:])
if ctx.test_type == "df":
overwrite_data = pd.DataFrame(
[
{"id": 10, ctx.time_column: "2022-01-03", "ignored_source": "ignored_value"},
{"id": 4, ctx.time_column: "2022-01-04", "ignored_source": "ignored_value"},
{"id": 5, ctx.time_column: "2022-01-05", "ignored_source": "ignored_value"},
]
)
ctx.engine_adapter.insert_overwrite_by_time_partition(
table,
ctx.input_data(overwrite_data),
start="2022-01-03",
end="2022-01-05",
time_formatter=ctx.time_formatter,
time_column=ctx.time_column,
target_columns_to_types=columns_to_types,
source_columns=["id", "ds", "ignored_source"],
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
if ctx.dialect == "trino":
wait_until(lambda: len(ctx.get_current_data(table)) > 2)
ctx.compare_with_current(
table,
pd.DataFrame(
[
{"id": 2, "ignored_column": None, ctx.time_column: "2022-01-02"},
{"id": 10, "ignored_column": None, ctx.time_column: "2022-01-03"},
{"id": 4, "ignored_column": None, ctx.time_column: "2022-01-04"},
{"id": 5, "ignored_column": None, ctx.time_column: "2022-01-05"},
]
),
)
def test_merge(ctx_query_and_df: TestContext):
ctx = ctx_query_and_df
if not ctx.supports_merge:
pytest.skip(f"{ctx.dialect} doesn't support merge")
table = ctx.table("test_table")
# Athena only supports MERGE on Iceberg tables
# And it cant fall back to a logical merge on Hive tables because it cant delete records
table_format = "iceberg" if ctx.dialect == "athena" else None
ctx.engine_adapter.create_table(table, ctx.columns_to_types, table_format=table_format)
input_data = pd.DataFrame(
[
{"id": 1, "ds": "2022-01-01"},
{"id": 2, "ds": "2022-01-02"},
{"id": 3, "ds": "2022-01-03"},
]
)
ctx.engine_adapter.merge(
table,
ctx.input_data(input_data),
target_columns_to_types=None,
unique_key=[exp.to_identifier("id")],
)
results = ctx.get_metadata_results()
assert len(results.views) == 0
assert len(results.materialized_views) == 0
assert len(results.tables) == len(results.non_temp_tables) == 1
assert len(results.non_temp_tables) == 1
assert results.non_temp_tables[0] == table.name
ctx.compare_with_current(table, input_data)
if ctx.test_type == "df":
merge_data = pd.DataFrame(
[
{"id": 2, "ds": "2022-01-10"},
{"id": 4, "ds": "2022-01-04"},
{"id": 5, "ds": "2022-01-05"},
]
)
ctx.engine_adapter.merge(
table,