-
Notifications
You must be signed in to change notification settings - Fork 375
Expand file tree
/
Copy pathtest_snowflake.py
More file actions
838 lines (692 loc) · 29.3 KB
/
test_snowflake.py
File metadata and controls
838 lines (692 loc) · 29.3 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
import typing as t
import pandas as pd # noqa: TID253
import pytest
from pytest_mock.plugin import MockerFixture
from sqlglot import exp, parse_one
import sqlmesh.core.dialect as d
from sqlmesh.core.dialect import normalize_model_name
from sqlmesh.core.engine_adapter.base import EngineAdapter
from sqlmesh.core.model import load_sql_based_model
from sqlmesh.core.engine_adapter import SnowflakeEngineAdapter
from sqlmesh.core.model.definition import SqlModel
from sqlmesh.core.node import IntervalUnit
from sqlmesh.utils.errors import SQLMeshError
from sqlmesh.utils import optional_import
from tests.core.engine_adapter import to_sql_calls
from sqlmesh.core.model.kind import ViewKind
pytestmark = [pytest.mark.engine, pytest.mark.snowflake]
@pytest.fixture
def snowflake_mocked_engine_adapter(
make_mocked_engine_adapter: t.Callable,
) -> SnowflakeEngineAdapter:
return make_mocked_engine_adapter(SnowflakeEngineAdapter)
def test_get_temp_table(mocker: MockerFixture, make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
mocker.patch("sqlmesh.core.engine_adapter.base.random_id", return_value="abcdefgh")
value = adapter._get_temp_table(
normalize_model_name("catalog.db.test_table", default_catalog=None, dialect=adapter.dialect)
)
assert value.sql(dialect=adapter.dialect) == '"CATALOG"."DB"."__temp_TEST_TABLE_abcdefgh"'
@pytest.mark.parametrize(
"current_warehouse, current_warehouse_exp, configured_warehouse, configured_warehouse_exp, should_change",
[
(
"test_warehouse",
'"test_warehouse"',
exp.to_identifier("test_warehouse", quoted=True),
'"test_warehouse"',
False,
),
("test_warehouse", '"test_warehouse"', "test_warehouse", '"TEST_WAREHOUSE"', True),
("TEST_WAREHOUSE", '"TEST_WAREHOUSE"', "test_warehouse", '"TEST_WAREHOUSE"', False),
("test warehouse", '"test warehouse"', "test warehouse", '"test warehouse"', False),
("test warehouse", '"test warehouse"', "another warehouse", '"another warehouse"', True),
(
"test warehouse",
'"test warehouse"',
exp.column("another warehouse"),
'"another warehouse"',
True,
),
("test warehouse", '"test warehouse"', "another_warehouse", '"ANOTHER_WAREHOUSE"', True),
("TEST_WAREHOUSE", '"TEST_WAREHOUSE"', "another_warehouse", '"ANOTHER_WAREHOUSE"', True),
("test_warehouse", '"test_warehouse"', "another_warehouse", '"ANOTHER_WAREHOUSE"', True),
(
"test_warehouse",
'"test_warehouse"',
exp.column("another_warehouse"),
'"ANOTHER_WAREHOUSE"',
True,
),
(
"test_warehouse",
'"test_warehouse"',
exp.to_identifier("another_warehouse"),
'"ANOTHER_WAREHOUSE"',
True,
),
(
"test_warehouse",
'"test_warehouse"',
exp.to_identifier("another_warehouse", quoted=True),
'"another_warehouse"',
True,
),
],
)
def test_session(
mocker: MockerFixture,
make_mocked_engine_adapter: t.Callable,
current_warehouse: t.Union[str, exp.Expression],
current_warehouse_exp: str,
configured_warehouse: t.Optional[str],
configured_warehouse_exp: t.Optional[str],
should_change: bool,
):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.cursor.fetchone.return_value = (current_warehouse,)
# Test normal execution
with adapter.session({"warehouse": configured_warehouse}):
pass
expected_calls = []
if configured_warehouse:
expected_calls.append("SELECT CURRENT_WAREHOUSE()")
if should_change:
expected_calls.extend(
[
f"USE WAREHOUSE {configured_warehouse_exp}",
f"USE WAREHOUSE {current_warehouse_exp}",
]
)
assert to_sql_calls(adapter) == expected_calls
# Test exception handling - warehouse should still be reset
if should_change:
adapter.cursor.execute.reset_mock()
adapter.cursor.fetchone.return_value = (current_warehouse,)
try:
with adapter.session({"warehouse": configured_warehouse}):
adapter.execute("SELECT 1")
raise RuntimeError("Test exception")
except RuntimeError:
pass
expected_exception_calls = [
"SELECT CURRENT_WAREHOUSE()",
f"USE WAREHOUSE {configured_warehouse_exp}",
"SELECT 1",
f"USE WAREHOUSE {current_warehouse_exp}",
]
assert to_sql_calls(adapter) == expected_exception_calls
def test_comments(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_table(
"test_table",
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
table_description="table description",
column_descriptions={"a": "a column description"},
)
adapter.ctas(
"test_table",
parse_one("SELECT a, b FROM source_table"),
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
table_description="table description",
column_descriptions={"a": "a column description"},
)
adapter.create_view(
"test_view",
parse_one("SELECT a, b FROM source_table"),
table_description="table description",
column_descriptions={"a": "a column description"},
)
adapter._create_table_comment(
"test_table",
"table description",
)
adapter._create_column_comments(
"test_table",
{"a": "a column description"},
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
"""CREATE TABLE IF NOT EXISTS "test_table" ("a" INT COMMENT 'a column description', "b" INT) COMMENT='table description'""",
"""CREATE TABLE IF NOT EXISTS "test_table" ("a" INT COMMENT 'a column description', "b" INT) COMMENT='table description' AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
"""CREATE OR REPLACE VIEW "test_view" COPY GRANTS COMMENT='table description' AS SELECT "a", "b" FROM "source_table\"""",
"""ALTER VIEW "test_view" ALTER COLUMN "a" COMMENT 'a column description'""",
"""COMMENT ON TABLE "test_table" IS 'table description'""",
"""ALTER TABLE "test_table" ALTER COLUMN "a" COMMENT 'a column description'""",
]
def test_multiple_column_comments(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_table(
"test_table",
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
column_descriptions={"a": "a column description", "b": "b column description"},
)
adapter.create_view(
"test_view",
parse_one("SELECT a, b FROM test_table"),
column_descriptions={"a": "a column description", "b": "b column description"},
)
adapter._create_column_comments(
"test_table",
{"a": "a column description changed", "b": "b column description changed"},
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
"""CREATE TABLE IF NOT EXISTS "test_table" ("a" INT COMMENT 'a column description', "b" INT COMMENT 'b column description')""",
"""CREATE OR REPLACE VIEW "test_view" COPY GRANTS AS SELECT "a", "b" FROM "test_table\"""",
"""ALTER VIEW "test_view" ALTER COLUMN "a" COMMENT 'a column description', COLUMN "b" COMMENT 'b column description'""",
"""ALTER TABLE "test_table" ALTER COLUMN "a" COMMENT 'a column description changed', COLUMN "b" COMMENT 'b column description changed'""",
]
def test_df_to_source_queries_use_schema(
make_mocked_engine_adapter: t.Callable, mocker: MockerFixture
):
mocker.patch(
"sqlmesh.core.engine_adapter.snowflake.SnowflakeEngineAdapter.table_exists",
return_value=False,
)
mocker.patch("snowflake.connector.pandas_tools.write_pandas", return_value=None)
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.DEFAULT_BATCH_SIZE = 1
df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})
adapter.replace_query(
"other_db.test_table", df, {"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}
)
assert 'USE SCHEMA "other_db"' in to_sql_calls(adapter)
adapter.replace_query(
"other_catalog.other_db.test_table",
df,
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
)
assert 'USE SCHEMA "other_catalog"."other_db"' in to_sql_calls(adapter)
def test_create_managed_table(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
mocker.patch(
"sqlmesh.core.engine_adapter.snowflake.SnowflakeEngineAdapter._current_warehouse",
return_value=exp.to_identifier("default_warehouse"),
new_callable=mocker.PropertyMock,
)
query = parse_one("SELECT a, b FROM source_table")
columns_to_types = {"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}
# no properties, should raise about TARGET_LAG
with pytest.raises(SQLMeshError, match=r".*`target_lag` must be specified.*"):
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
)
# warehouse not specified, should default to current_warehouse()
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
table_properties={"target_lag": exp.Literal.string("20 minutes")},
)
# warehouse specified, should use it
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
table_properties={
"target_lag": exp.Literal.string("20 minutes"),
"warehouse": exp.to_identifier("foo"),
},
)
# clustered by, partitioned by (partitioned by should get ignored)
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
table_properties={
"target_lag": exp.Literal.string("20 minutes"),
},
clustered_by=[exp.column("a")],
partitioned_by=["b"],
)
# other properties
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
table_properties={
"target_lag": exp.Literal.string("20 minutes"),
"refresh_mode": exp.Literal.string("auto"),
"initialize": exp.Literal.string("on_create"),
},
)
# table_format=iceberg
adapter.create_managed_table(
table_name="test_table",
query=query,
target_columns_to_types=columns_to_types,
table_properties={
"target_lag": exp.Literal.string("20 minutes"),
"catalog": exp.Literal.string("snowflake"),
"external_volume": exp.Literal.string("test"),
},
table_format="iceberg",
)
assert to_sql_calls(adapter) == [
"""CREATE OR REPLACE DYNAMIC TABLE "test_table" TARGET_LAG='20 minutes' WAREHOUSE="default_warehouse" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
"""CREATE OR REPLACE DYNAMIC TABLE "test_table" TARGET_LAG='20 minutes' WAREHOUSE="foo" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
"""CREATE OR REPLACE DYNAMIC TABLE "test_table" CLUSTER BY ("a") TARGET_LAG='20 minutes' WAREHOUSE="default_warehouse" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
"""CREATE OR REPLACE DYNAMIC TABLE "test_table" TARGET_LAG='20 minutes' REFRESH_MODE='auto' INITIALIZE='on_create' WAREHOUSE="default_warehouse" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
"""CREATE OR REPLACE DYNAMIC ICEBERG TABLE "test_table" TARGET_LAG='20 minutes' CATALOG='snowflake' EXTERNAL_VOLUME='test' WAREHOUSE="default_warehouse" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery\"""",
]
def test_drop_managed_table(make_mocked_engine_adapter: t.Callable, mocker: MockerFixture):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.drop_managed_table(table_name=exp.parse_identifier("foo"), exists=False)
adapter.drop_managed_table(table_name=exp.parse_identifier("foo"), exists=True)
assert to_sql_calls(adapter) == [
'DROP DYNAMIC TABLE "foo"',
'DROP DYNAMIC TABLE IF EXISTS "foo"',
]
def test_ctas_skips_dynamic_table_properties(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
query = parse_one("SELECT a, b FROM source_table")
columns_to_types = {"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")}
adapter.ctas(
table_name="test_table",
query_or_df=query,
target_columns_to_types=columns_to_types,
table_properties={
"warehouse": exp.to_identifier("foo"),
"target_lag": exp.Literal.string("20 minutes"),
"refresh_mode": exp.Literal.string("auto"),
"initialize": exp.Literal.string("on_create"),
},
)
assert to_sql_calls(adapter) == [
'CREATE TABLE IF NOT EXISTS "test_table" AS SELECT CAST("a" AS INT) AS "a", CAST("b" AS INT) AS "b" FROM (SELECT "a", "b" FROM "source_table") AS "_subquery"'
]
def test_set_current_catalog(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter._default_catalog = "foo"
adapter.set_current_catalog("foo")
adapter.set_current_catalog("FOO")
adapter.set_current_catalog("fOo")
adapter.set_current_catalog("bar")
adapter.set_current_catalog("BAR")
model_a: SqlModel = t.cast(
SqlModel,
load_sql_based_model(
d.parse(
"""
MODEL (
name external.test.table,
kind full,
dialect bigquery
);
SELECT 1;
"""
)
),
)
model_b: SqlModel = t.cast(
SqlModel,
load_sql_based_model(
d.parse(
"""
MODEL (
name "exTERnal".test.table,
kind full,
dialect bigquery
);
SELECT 1;
"""
)
),
)
assert model_a.catalog == "external"
assert model_b.catalog == "exTERnal"
adapter.set_current_catalog(model_a.catalog)
adapter.set_current_catalog(model_b.catalog)
assert to_sql_calls(adapter) == [
'USE "FOO"',
'USE "FOO"',
'USE "FOO"',
'USE "bar"',
'USE "BAR"',
'USE "external"',
'USE "exTERnal"',
]
def test_set_current_schema(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter._default_catalog = "foo"
adapter.set_current_schema('"foo"')
adapter.set_current_schema('foo."foo"')
# in this example, the catalog of '"foo"' is normalized in duckdb.
# even though it's quoted, it should get replaced with "FOO"
# because it matches the default catalog
adapter.set_current_schema('"foo"."fOo"')
assert to_sql_calls(adapter) == [
'USE SCHEMA "foo"',
'USE SCHEMA "FOO"."foo"',
'USE SCHEMA "FOO"."fOo"',
]
def test_replace_query_snowpark_dataframe(
mocker: MockerFixture, make_mocked_engine_adapter: t.Callable
):
if not optional_import("snowflake.snowpark"):
pytest.skip("Snowpark not available in this environment")
from snowflake.snowpark.session import Session
from snowflake.snowpark.dataframe import DataFrame as SnowparkDataFrame
session = Session.builder.config("local_testing", True).create()
# df.createOrReplaceTempView() throws "[Local Testing] Mocking SnowflakePlan Rename is not supported" when used against the Snowflake local_testing session
# since we cant trace any queries from the Snowpark library anyway, we just suppress this and verify the cleanup queries issued by our EngineAdapter
session._conn._suppress_not_implemented_error = True
df: SnowparkDataFrame = session.create_dataframe([(1, "name")], schema=["ID", "NAME"])
assert isinstance(df, SnowparkDataFrame)
mocker.patch("sqlmesh.core.engine_adapter.base.random_id", return_value="e6wjkjj6")
spy = mocker.spy(df, "createOrReplaceTempView")
adapter: SnowflakeEngineAdapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter._default_catalog = "foo"
adapter.replace_query(
table_name="foo",
query_or_df=df,
target_columns_to_types={
"ID": exp.DataType.build("INT"),
"NAME": exp.DataType.build("VARCHAR"),
},
)
# verify that DROP VIEW is called instead of DROP TABLE
assert to_sql_calls(adapter) == [
'CREATE OR REPLACE TABLE "foo" AS SELECT CAST("ID" AS INT) AS "ID", CAST("NAME" AS VARCHAR) AS "NAME" FROM (SELECT CAST("ID" AS INT) AS "ID", CAST("NAME" AS VARCHAR) AS "NAME" FROM "__temp_foo_e6wjkjj6") AS "_subquery"',
'DROP VIEW IF EXISTS "__temp_foo_e6wjkjj6"',
]
def test_creatable_type_materialized_view_properties(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_view(
"test_table",
parse_one("SELECT 1"),
materialized=True,
materialized_properties={
# Partitioned by is not supported so we are confirming it is ignored
"partitioned_by": [exp.column("ds")],
"clustered_by": [exp.column("a")],
"partition_interval_unit": IntervalUnit.DAY,
},
)
sql_calls = to_sql_calls(adapter)
# https://docs.snowflake.com/en/sql-reference/sql/create-materialized-view#syntax
assert sql_calls == [
'CREATE OR REPLACE MATERIALIZED VIEW "test_table" COPY GRANTS CLUSTER BY ("a") AS SELECT 1',
]
def test_creatable_type_secure_view(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_view(
"test_table",
parse_one("SELECT 1"),
view_properties={
"creatable_type": exp.Column(this=exp.Identifier(this="secure")),
},
)
sql_calls = to_sql_calls(adapter)
# https://docs.snowflake.com/en/sql-reference/sql/create-view.html
assert sql_calls == [
'CREATE OR REPLACE SECURE VIEW "test_table" COPY GRANTS AS SELECT 1',
]
def test_creatable_type_secure_materialized_view(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_view(
"test_table",
parse_one("SELECT 1"),
materialized=True,
view_properties={
"creatable_type": exp.Column(this=exp.Identifier(this="secure")),
},
)
sql_calls = to_sql_calls(adapter)
# https://docs.snowflake.com/en/sql-reference/sql/create-view.html
assert sql_calls == [
'CREATE OR REPLACE SECURE MATERIALIZED VIEW "test_table" COPY GRANTS AS SELECT 1',
]
def test_creatable_type_temporary_view(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_view(
"test_table",
parse_one("SELECT 1"),
view_properties={
"creatable_type": exp.column("temporary"),
},
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE OR REPLACE TEMPORARY VIEW "test_table" COPY GRANTS AS SELECT 1',
]
def test_creatable_type_temporary_table(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_table(
"test_table",
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
table_properties={
"creatable_type": exp.column("temporary"),
},
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE TEMPORARY TABLE IF NOT EXISTS "test_table" ("a" INT, "b" INT)',
]
def test_creatable_type_transient_table(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_table(
"test_table",
{"a": exp.DataType.build("INT"), "b": exp.DataType.build("INT")},
table_properties={
"creatable_type": exp.column("transient"),
},
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE TRANSIENT TABLE IF NOT EXISTS "test_table" ("a" INT, "b" INT)',
]
def test_creatable_type_materialize_creatable_type_raise_error(
make_mocked_engine_adapter: t.Callable,
):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
with pytest.raises(SQLMeshError):
adapter.create_view(
"test_view",
parse_one("SELECT 1"),
view_properties={
"creatable_type": exp.column("materialized"),
},
)
def test_creatable_type_transient_type_from_model_definition(
make_mocked_engine_adapter: t.Callable,
):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
model: SqlModel = t.cast(
SqlModel,
load_sql_based_model(
d.parse(
"""
MODEL (
name external.test.table,
kind full,
physical_properties (
creatable_type = transient
)
);
SELECT a::INT;
"""
)
),
)
adapter.create_table(
model.name,
target_columns_to_types=model.columns_to_types_or_raise,
table_properties=model.physical_properties,
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE TRANSIENT TABLE IF NOT EXISTS "external"."test"."table" ("a" INT)',
]
def test_creatable_type_transient_type_from_model_definition_with_other_property(
make_mocked_engine_adapter: t.Callable,
):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
model: SqlModel = t.cast(
SqlModel,
load_sql_based_model(
d.parse(
"""
MODEL (
name external.test.table,
kind full,
physical_properties (
creatable_type = transient,
require_partition_filter = true
)
);
SELECT a::INT;
"""
)
),
)
adapter.create_table(
model.name,
target_columns_to_types=model.columns_to_types_or_raise,
table_properties=model.physical_properties,
)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE TRANSIENT TABLE IF NOT EXISTS "external"."test"."table" ("a" INT) REQUIRE_PARTITION_FILTER=TRUE'
]
def test_create_view(make_mocked_engine_adapter: t.Callable):
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter)
adapter.create_view("test_view", parse_one("SELECT 1"))
adapter.create_view("test_view", parse_one("SELECT 1"), replace=False)
sql_calls = to_sql_calls(adapter)
assert sql_calls == [
'CREATE OR REPLACE VIEW "test_view" COPY GRANTS AS SELECT 1',
'CREATE VIEW "test_view" AS SELECT 1',
]
def test_clone_table(mocker: MockerFixture, make_mocked_engine_adapter: t.Callable):
mocker.patch("sqlmesh.core.engine_adapter.snowflake.SnowflakeEngineAdapter.set_current_catalog")
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter, default_catalog="test_catalog")
adapter.clone_table("target_table", "source_table")
adapter.cursor.execute.assert_called_once_with(
'CREATE TABLE IF NOT EXISTS "target_table" CLONE "source_table"'
)
# Validate with transient type we create the clone table accordingly
rendered_physical_properties = {
"creatable_type": exp.column("transient"),
}
adapter = make_mocked_engine_adapter(SnowflakeEngineAdapter, default_catalog="test_catalog")
adapter.clone_table(
"target_table", "source_table", rendered_physical_properties=rendered_physical_properties
)
adapter.cursor.execute.assert_called_once_with(
'CREATE TRANSIENT TABLE IF NOT EXISTS "target_table" CLONE "source_table"'
)
# Validate other engine adapters would work as usual even when we pass the properties
adapter = make_mocked_engine_adapter(EngineAdapter, default_catalog="test_catalog")
adapter.SUPPORTS_CLONING = True
adapter.clone_table(
"target_table", "source_table", rendered_physical_properties=rendered_physical_properties
)
adapter.cursor.execute.assert_called_once_with(
'CREATE TABLE IF NOT EXISTS "target_table" CLONE "source_table"'
)
def test_table_format_iceberg(snowflake_mocked_engine_adapter: SnowflakeEngineAdapter) -> None:
adapter = snowflake_mocked_engine_adapter
model = load_sql_based_model(
expressions=d.parse("""
MODEL (
name test.table,
kind full,
table_format iceberg,
physical_properties (
catalog = 'snowflake',
external_volume = 'test'
)
);
SELECT a::INT;
""")
)
assert isinstance(model, SqlModel)
assert model.table_format == "iceberg"
adapter.create_table(
table_name=model.name,
target_columns_to_types=model.columns_to_types_or_raise,
table_format=model.table_format,
table_properties=model.physical_properties,
)
adapter.ctas(
table_name=model.name,
query_or_df=model.render_query_or_raise(),
target_columns_to_types=model.columns_to_types_or_raise,
table_format=model.table_format,
table_properties=model.physical_properties,
)
assert to_sql_calls(adapter) == [
'CREATE ICEBERG TABLE IF NOT EXISTS "test"."table" ("a" INT) CATALOG=\'snowflake\' EXTERNAL_VOLUME=\'test\'',
'CREATE ICEBERG TABLE IF NOT EXISTS "test"."table" CATALOG=\'snowflake\' EXTERNAL_VOLUME=\'test\' AS SELECT CAST("a" AS INT) AS "a" FROM (SELECT CAST("a" AS INT) AS "a") AS "_subquery"',
]
def test_create_view_with_schema_and_grants(
snowflake_mocked_engine_adapter: SnowflakeEngineAdapter,
):
adapter = snowflake_mocked_engine_adapter
model_v = load_sql_based_model(
d.parse(f"""
MODEL (
name test.v,
kind VIEW,
description 'normal **view** from integration test',
dialect 'snowflake'
);
select 1 as "ID", 'foo' as "NAME";
""")
)
model_mv = load_sql_based_model(
d.parse(f"""
MODEL (
name test.mv,
kind VIEW (
materialized true
),
description 'materialized **view** from integration test',
dialect 'snowflake'
);
select 1 as "ID", 'foo' as "NAME";
""")
)
assert isinstance(model_v.kind, ViewKind)
assert isinstance(model_mv.kind, ViewKind)
adapter.create_view(
"target_view",
model_v.render_query_or_raise(),
model_v.columns_to_types,
materialized=model_v.kind.materialized,
view_properties=model_v.render_physical_properties(),
table_description=model_v.description,
column_descriptions=model_v.column_descriptions,
)
adapter.create_view(
"target_materialized_view",
model_mv.render_query_or_raise(),
model_mv.columns_to_types,
materialized=model_mv.kind.materialized,
view_properties=model_mv.render_physical_properties(),
table_description=model_mv.description,
column_descriptions=model_mv.column_descriptions,
)
assert to_sql_calls(adapter) == [
# normal view - COPY GRANTS goes after the column list
"""CREATE OR REPLACE VIEW "target_view" ("ID", "NAME") COPY GRANTS COMMENT='normal **view** from integration test' AS SELECT 1 AS "ID", 'foo' AS "NAME\"""",
# materialized view - COPY GRANTS goes before the column list
"""CREATE OR REPLACE MATERIALIZED VIEW "target_materialized_view" COPY GRANTS ("ID", "NAME") COMMENT='materialized **view** from integration test' AS SELECT 1 AS "ID", 'foo' AS "NAME\"""",
]
def test_create_catalog(snowflake_mocked_engine_adapter: SnowflakeEngineAdapter) -> None:
adapter = snowflake_mocked_engine_adapter
adapter.create_catalog(exp.to_identifier("foo"))
assert to_sql_calls(adapter) == [
"CREATE DATABASE IF NOT EXISTS \"foo\" COMMENT='sqlmesh_managed'"
]
def test_drop_catalog(snowflake_mocked_engine_adapter: SnowflakeEngineAdapter) -> None:
adapter = snowflake_mocked_engine_adapter
adapter.drop_catalog(exp.to_identifier("foo"))
assert to_sql_calls(adapter) == [
"""SELECT 1 FROM "INFORMATION_SCHEMA"."DATABASES" WHERE "DATABASE_NAME" = 'foo' AND "COMMENT" = 'sqlmesh_managed'""",
'DROP DATABASE IF EXISTS "foo"',
]