-
Notifications
You must be signed in to change notification settings - Fork 10
/
test_fakes.py
1536 lines (1244 loc) · 62.8 KB
/
test_fakes.py
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
from __future__ import annotations
# ruff: noqa: E501
# pyright: reportOptionalMemberAccess=false
import datetime
import json
import re
import tempfile
from decimal import Decimal
from typing import cast
import pandas as pd
import pytest
import pytz
import snowflake.connector
import snowflake.connector.cursor
import snowflake.connector.pandas_tools
from pandas.testing import assert_frame_equal
from snowflake.connector.cursor import ResultMetadata
from snowflake.connector.errors import ProgrammingError
import fakesnow
from tests.utils import dindent, indent
def test_alias_on_join(conn: snowflake.connector.SnowflakeConnection):
*_, cur = conn.execute_string(
"""
CREATE OR REPLACE TEMPORARY TABLE TEST (COL VARCHAR);
INSERT INTO TEST (COL) VALUES ('VARCHAR1'), ('VARCHAR2');
CREATE OR REPLACE TEMPORARY TABLE JOINED (COL VARCHAR, ANOTHER VARCHAR);
INSERT INTO JOINED (COL, ANOTHER) VALUES ('CHAR1', 'JOIN');
SELECT
T.COL
, SUBSTR(T.COL, 4) AS ALIAS
, J.ANOTHER
FROM TEST AS T
LEFT JOIN JOINED AS J
ON ALIAS = J.COL;
"""
)
assert cur.fetchall() == [("VARCHAR1", "CHAR1", "JOIN"), ("VARCHAR2", "CHAR2", None)]
def test_alter_table(dcur: snowflake.connector.cursor.SnowflakeCursor):
dcur.execute("create table table1 (id int)")
dcur.execute("alter table table1 add column name varchar(20)")
dcur.execute("select name from table1")
assert dcur.execute("alter table table1 cluster by (name)").fetchall() == [
{"status": "Statement executed successfully."}
]
def test_array_size(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("""select array_size(parse_json('["a","b"]'))""")
assert cur.fetchall() == [(2,)]
# when json is not an array
cur.execute("""select array_size(parse_json('{"a":"b"}'))""")
assert cur.fetchall() == [(None,)]
def test_array_agg(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create table table1 (id number, name varchar)")
values = [(1, "foo"), (2, "bar"), (1, "baz"), (2, "qux")]
dcur.executemany("insert into table1 values (%s, %s)", values)
dcur.execute("select array_agg(name) as names from table1")
assert dindent(dcur.fetchall()) == [{"NAMES": '[\n "foo",\n "bar",\n "baz",\n "qux"\n]'}]
# using over
dcur.execute(
"""
SELECT DISTINCT
ID
, ANOTHER
, ARRAY_AGG(DISTINCT COL) OVER(PARTITION BY ID) AS COLS
FROM (select column1 as ID, column2 as COL, column3 as ANOTHER from
(VALUES (1, 's1', 'c1'),(1, 's2', 'c1'),(1, 's3', 'c1'),(2, 's1', 'c2'), (2,'s2','c2')))
ORDER BY ID
"""
)
assert dindent(dcur.fetchall()) == [
{"ID": 1, "ANOTHER": "c1", "COLS": '[\n "s1",\n "s2",\n "s3"\n]'},
{"ID": 2, "ANOTHER": "c2", "COLS": '[\n "s1",\n "s2"\n]'},
]
def test_array_agg_within_group(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("CREATE TABLE table1 (ID INT, amount INT)")
# two unique ids, for id 1 there are 3 amounts, for id 2 there are 2 amounts
values = [
(2, 40),
(1, 10),
(1, 30),
(2, 50),
(1, 20),
]
dcur.executemany("INSERT INTO TABLE1 VALUES (%s, %s)", values)
dcur.execute("SELECT id, ARRAY_AGG(amount) WITHIN GROUP (ORDER BY amount DESC) amounts FROM table1 GROUP BY id")
rows = dcur.fetchall()
assert dindent(rows) == [
{"ID": 1, "AMOUNTS": "[\n 30,\n 20,\n 10\n]"},
{"ID": 2, "AMOUNTS": "[\n 50,\n 40\n]"},
]
dcur.execute("SELECT id, ARRAY_AGG(amount) WITHIN GROUP (ORDER BY amount ASC) amounts FROM table1 GROUP BY id")
rows = dcur.fetchall()
assert dindent(rows) == [
{"ID": 1, "AMOUNTS": "[\n 10,\n 20,\n 30\n]"},
{"ID": 2, "AMOUNTS": "[\n 40,\n 50\n]"},
]
def test_binding_default_paramstyle(conn: snowflake.connector.SnowflakeConnection):
assert snowflake.connector.paramstyle == "pyformat"
with conn.cursor() as cur:
cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)")
cur.execute("insert into customers values (%s, %s, %s)", (1, "Jenny", True))
cur.execute("select * from customers")
assert cur.fetchall() == [(1, "Jenny", True)]
def test_binding_default_paramstyle_dict(conn: snowflake.connector.SnowflakeConnection):
assert snowflake.connector.paramstyle == "pyformat"
with conn.cursor() as cur:
cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)")
cur.execute(
"insert into customers values (%(id)s, %(name)s, %(active)s)", {"id": 1, "name": "Jenny", "active": True}
)
cur.execute("select * from customers")
assert cur.fetchall() == [(1, "Jenny", True)]
def test_binding_qmark(_fakesnow: None):
snowflake.connector.paramstyle = "qmark"
with snowflake.connector.connect(database="db1", schema="schema1") as conn, conn.cursor() as cur:
cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)")
cur.execute("insert into customers values (?, ?, ?)", (1, "Jenny", True))
cur.execute("select * from customers")
assert cur.fetchall() == [(1, "Jenny", True)]
# this has no effect after connection created, so qmark style still works
snowflake.connector.paramstyle = "pyformat"
cur.execute("select * from customers where id = ?", (1,))
def test_clone(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create table customers (ID int, FIRST_NAME varchar, ACTIVE boolean)")
cur.execute("insert into customers values (1, 'Jenny', True)")
cur.execute("create table customers2 clone db1.schema1.customers")
cur.execute("select * from customers2")
# TODO check tags are copied too
assert cur.fetchall() == [(1, "Jenny", True)]
def test_close_conn(conn: snowflake.connector.SnowflakeConnection, cur: snowflake.connector.cursor.SnowflakeCursor):
assert not conn.is_closed()
conn.close()
with pytest.raises(snowflake.connector.errors.DatabaseError) as excinfo:
conn.execute_string("select 1")
# actual snowflake error message is:
# 250002 (08003): Connection is closed
assert "250002 (08003)" in str(excinfo.value)
assert conn.is_closed()
def test_close_cur(conn: snowflake.connector.SnowflakeConnection, cur: snowflake.connector.cursor.SnowflakeCursor):
assert cur.close() is True
def test_create_database_respects_if_not_exists() -> None:
with tempfile.TemporaryDirectory(prefix="fakesnow-test") as db_path, fakesnow.patch(db_path=db_path):
cursor = snowflake.connector.connect().cursor()
cursor.execute("CREATE DATABASE db2")
with pytest.raises(ProgrammingError, match='Database "DB2" is already attached with path'):
cursor.execute("CREATE DATABASE db2") # Fails as db already exists.
cursor.execute("CREATE DATABASE IF NOT EXISTS db2")
def test_dateadd_date_cast(dcur: snowflake.connector.DictCursor):
q = """
SELECT
dateadd(hour, 1, '2023-04-02'::date) as d_noop,
dateadd(day, 1, '2023-04-02'::date) as d_day,
dateadd(week, 1, '2023-04-02'::date) as d_week,
dateadd(month, 1, '2023-04-02'::date) as d_month,
dateadd(year, 1, '2023-04-02'::date) as d_year
"""
dcur.execute(q)
assert dcur.fetchall() == [
{
"D_NOOP": datetime.datetime(2023, 4, 2, 1, 0),
"D_DAY": datetime.date(2023, 4, 3),
"D_WEEK": datetime.date(2023, 4, 9),
"D_MONTH": datetime.date(2023, 5, 2),
"D_YEAR": datetime.date(2024, 4, 2),
}
]
def test_dateadd_string_literal_timestamp_cast(dcur: snowflake.connector.cursor.DictCursor):
q = """
SELECT
DATEADD('MINUTE', 3, '2023-04-02') AS D_MINUTE,
DATEADD('HOUR', 3, '2023-04-02') AS D_HOUR,
DATEADD('DAY', 3, '2023-04-02') AS D_DAY,
DATEADD('WEEK', 3, '2023-04-02') AS D_WEEK,
DATEADD('MONTH', 3, '2023-04-02') AS D_MONTH,
DATEADD('YEAR', 3, '2023-04-02') AS D_YEAR
;
"""
dcur.execute(q)
assert dcur.fetchall() == [
{
"D_MINUTE": datetime.datetime(2023, 4, 2, 0, 3),
"D_HOUR": datetime.datetime(2023, 4, 2, 3, 0),
"D_DAY": datetime.datetime(2023, 4, 5, 0, 0),
"D_WEEK": datetime.datetime(2023, 4, 23, 0, 0),
"D_MONTH": datetime.datetime(2023, 7, 2, 0, 0),
"D_YEAR": datetime.datetime(2026, 4, 2, 0, 0),
}
]
q = """
SELECT
DATEADD('MINUTE', 3, '2023-04-02 01:15:00') AS DT_MINUTE,
DATEADD('HOUR', 3, '2023-04-02 01:15:00') AS DT_HOUR,
DATEADD('DAY', 3, '2023-04-02 01:15:00') AS DT_DAY,
DATEADD('WEEK', 3, '2023-04-02 01:15:00') AS DT_WEEK,
DATEADD('MONTH', 3, '2023-04-02 01:15:00') AS DT_MONTH,
DATEADD('YEAR', 3, '2023-04-02 01:15:00') AS DT_YEAR
;
"""
dcur.execute(q)
assert dcur.fetchall() == [
{
"DT_MINUTE": datetime.datetime(2023, 4, 2, 1, 18),
"DT_HOUR": datetime.datetime(2023, 4, 2, 4, 15),
"DT_DAY": datetime.datetime(2023, 4, 5, 1, 15),
"DT_WEEK": datetime.datetime(2023, 4, 23, 1, 15),
"DT_MONTH": datetime.datetime(2023, 7, 2, 1, 15),
"DT_YEAR": datetime.datetime(2026, 4, 2, 1, 15),
}
]
def test_datediff_string_literal_timestamp_cast(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("SELECT DATEDIFF(DAY, '2023-04-02', '2023-03-02') AS D")
assert cur.fetchall() == [(-31,)]
cur.execute("SELECT DATEDIFF(HOUR, '2023-04-02', '2023-03-02') AS D")
assert cur.fetchall() == [(-744,)]
cur.execute("SELECT DATEDIFF(week, '2023-04-02', '2023-03-02') AS D")
assert cur.fetchall() == [(-4,)]
# noop
cur.execute("select '2023-04-02'::timestamp as c1, '2023-03-02'::timestamp as c2, DATEDIFF(minute, c1, c2) AS D")
assert cur.fetchall() == [(datetime.datetime(2023, 4, 2, 0, 0), datetime.datetime(2023, 3, 2, 0, 0), -44640)]
def test_current_database_schema(conn: snowflake.connector.SnowflakeConnection):
with conn.cursor(snowflake.connector.cursor.DictCursor) as cur:
cur.execute("select current_database(), current_schema()")
assert cur.fetchall() == [
{"current_database()": "DB1", "current_schema()": "SCHEMA1"},
]
def test_describe(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute(
"""
create or replace table example (
XBOOLEAN BOOLEAN, XDOUBLE DOUBLE, XFLOAT FLOAT,
XNUMBER82 NUMBER(8,2), XNUMBER NUMBER, XDECIMAL DECIMAL, XNUMERIC NUMERIC,
XINT INT, XINTEGER INTEGER, XBIGINT BIGINT, XSMALLINT SMALLINT, XTINYINT TINYINT, XBYTEINT BYTEINT,
XVARCHAR20 VARCHAR(20), XVARCHAR VARCHAR, XTEXT TEXT,
XTIMESTAMP TIMESTAMP, XTIMESTAMP_NTZ TIMESTAMP_NTZ, XTIMESTAMP_NTZ9 TIMESTAMP_NTZ(9), XTIMESTAMP_TZ TIMESTAMP_TZ, XDATE DATE, XTIME TIME,
XBINARY BINARY, /* XARRAY ARRAY, XOBJECT OBJECT */ XVARIANT VARIANT
)
"""
)
# fmt: off
expected_metadata = [
ResultMetadata(name='XBOOLEAN', type_code=13, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
# TODO: is_nullable should be False for non-boolean columns
ResultMetadata(name='XDOUBLE', type_code=1, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XFLOAT', type_code=1, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XNUMBER82', type_code=0, display_size=None, internal_size=None, precision=8, scale=2, is_nullable=True),
ResultMetadata(name='XNUMBER', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XDECIMAL', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XNUMERIC', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XINT', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XINTEGER', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XBIGINT', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XSMALLINT', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XTINYINT', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='XBYTEINT', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
# TODO: store actual size, ie: internal_size=20
ResultMetadata(name='XVARCHAR20', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XVARCHAR', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XTEXT', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XTIMESTAMP', type_code=8, display_size=None, internal_size=None, precision=0, scale=9, is_nullable=True),
ResultMetadata(name='XTIMESTAMP_NTZ', type_code=8, display_size=None, internal_size=None, precision=0, scale=9, is_nullable=True),
ResultMetadata(name='XTIMESTAMP_NTZ9', type_code=8, display_size=None, internal_size=None, precision=0, scale=9, is_nullable=True),
ResultMetadata(name='XTIMESTAMP_TZ', type_code=7, display_size=None, internal_size=None, precision=0, scale=9, is_nullable=True),
ResultMetadata(name='XDATE', type_code=3, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XTIME', type_code=12, display_size=None, internal_size=None, precision=0, scale=9, is_nullable=True),
ResultMetadata(name='XBINARY', type_code=11, display_size=None, internal_size=8388608, precision=None, scale=None, is_nullable=True),
# TODO: handle ARRAY and OBJECT see https://github.com/tekumara/fakesnow/issues/26
# ResultMetadata(name='XARRAY', type_code=10, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True),
# ResultMetadata(name='XOBJECT', type_code=9, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name='XVARIANT', type_code=5, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
]
# fmt: on
assert cur.describe("select * from example") == expected_metadata
cur.execute("select * from example")
assert cur.description == expected_metadata
# test with params
assert cur.describe("select * from example where XNUMBER = %s", (1,)) == expected_metadata
cur.execute("select * from example where XNUMBER = %s", (1,))
assert cur.description == expected_metadata
# test semi-structured ops return variant ie: type_code=5
# fmt: off
assert (
cur.describe("SELECT ['A', 'B'][0] as array_index, OBJECT_CONSTRUCT('k','v1')['k'] as object_key, ARRAY_CONSTRUCT('foo')::VARIANT[0] as variant_key")
== [
# NB: snowflake returns internal_size = 16777216 for all columns
ResultMetadata(name="ARRAY_INDEX", type_code=5, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name="OBJECT_KEY", type_code=5, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True),
ResultMetadata(name="VARIANT_KEY", type_code=5, display_size=None, internal_size=None, precision=None, scale=None, is_nullable=True)
]
)
# fmt: on
def test_describe_table(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute(
"""
create or replace table example (
XBOOLEAN BOOLEAN, XDOUBLE DOUBLE, XFLOAT FLOAT,
XNUMBER82 NUMBER(8,2), XNUMBER NUMBER, XDECIMAL DECIMAL, XNUMERIC NUMERIC,
XINT INT, XINTEGER INTEGER, XBIGINT BIGINT, XSMALLINT SMALLINT, XTINYINT TINYINT, XBYTEINT BYTEINT,
XVARCHAR20 VARCHAR(20), XVARCHAR VARCHAR, XTEXT TEXT,
XTIMESTAMP TIMESTAMP, XTIMESTAMP_NTZ TIMESTAMP_NTZ, XTIMESTAMP_NTZ9 TIMESTAMP_NTZ(9), XTIMESTAMP_TZ TIMESTAMP_TZ, XDATE DATE, XTIME TIME,
XBINARY BINARY, /* XARRAY ARRAY, XOBJECT OBJECT */ XVARIANT VARIANT
)
"""
)
# this table's columns shouldn't appear when describing the example table
dcur.execute("create table derived as select XVARCHAR20 from example")
common = {
"kind": "COLUMN",
"null?": "Y",
"default": None,
"primary key": "N",
"unique key": "N",
"check": None,
"expression": None,
"comment": None,
"policy name": None,
"privacy domain": None,
}
expected = [
{"name": "XBOOLEAN", "type": "BOOLEAN", **common},
{"name": "XDOUBLE", "type": "FLOAT", **common},
{"name": "XFLOAT", "type": "FLOAT", **common},
{"name": "XNUMBER82", "type": "NUMBER(8,2)", **common},
{"name": "XNUMBER", "type": "NUMBER(38,0)", **common},
{"name": "XDECIMAL", "type": "NUMBER(38,0)", **common},
{"name": "XNUMERIC", "type": "NUMBER(38,0)", **common},
{"name": "XINT", "type": "NUMBER(38,0)", **common},
{"name": "XINTEGER", "type": "NUMBER(38,0)", **common},
{"name": "XBIGINT", "type": "NUMBER(38,0)", **common},
{"name": "XSMALLINT", "type": "NUMBER(38,0)", **common},
{"name": "XTINYINT", "type": "NUMBER(38,0)", **common},
{"name": "XBYTEINT", "type": "NUMBER(38,0)", **common},
{"name": "XVARCHAR20", "type": "VARCHAR(20)", **common},
{"name": "XVARCHAR", "type": "VARCHAR(16777216)", **common},
{"name": "XTEXT", "type": "VARCHAR(16777216)", **common},
{"name": "XTIMESTAMP", "type": "TIMESTAMP_NTZ(9)", **common},
{"name": "XTIMESTAMP_NTZ", "type": "TIMESTAMP_NTZ(9)", **common},
{"name": "XTIMESTAMP_NTZ9", "type": "TIMESTAMP_NTZ(9)", **common},
{"name": "XTIMESTAMP_TZ", "type": "TIMESTAMP_TZ(9)", **common},
{"name": "XDATE", "type": "DATE", **common},
{"name": "XTIME", "type": "TIME(9)", **common},
{"name": "XBINARY", "type": "BINARY(8388608)", **common},
{"name": "XVARIANT", "type": "VARIANT", **common},
]
assert dcur.execute("describe table example").fetchall() == expected
assert dcur.execute("describe table schema1.example").fetchall() == expected
assert dcur.execute("describe table db1.schema1.example").fetchall() == expected
assert [r.name for r in dcur.description] == [
"name",
"type",
"kind",
"null?",
"default",
"primary key",
"unique key",
"check",
"expression",
"comment",
"policy name",
"privacy domain",
]
assert dcur.execute("describe table db1.schema1.derived").fetchall() == [
# TODO: preserve varchar size when derived - this should be VARCHAR(20)
{"name": "XVARCHAR20", "type": "VARCHAR(16777216)", **common},
]
with pytest.raises(snowflake.connector.errors.ProgrammingError) as excinfo:
dcur.execute("describe table this_does_not_exist")
# TODO: actual snowflake error is:
# 002003 (42S02): SQL compilation error:
# Table 'THIS_DOES_NOT_EXIST' does not exist or not authorized.
assert "002003 (42S02): Catalog Error: Table with name THIS_DOES_NOT_EXIST does not exist!" in str(excinfo.value)
def test_describe_view(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute(
"""
create or replace table example (
XVARCHAR VARCHAR
-- ,XVARCHAR20 VARCHAR(20) -- TODO: preserve varchar size
)
"""
)
common = {
"kind": "COLUMN",
"null?": "Y",
"default": None,
"primary key": "N",
"unique key": "N",
"check": None,
"expression": None,
"comment": None,
"policy name": None,
"privacy domain": None,
}
expected = [
{"name": "XVARCHAR", "type": "VARCHAR(16777216)", **common},
# TODO: preserve varchar size
# {"name": "XVARCHAR20", "type": "VARCHAR(20)", **common},
]
dcur.execute("create view v1 as select * from example")
assert dcur.execute("describe view v1").fetchall() == expected
assert [r.name for r in dcur.description] == [
"name",
"type",
"kind",
"null?",
"default",
"primary key",
"unique key",
"check",
"expression",
"comment",
"policy name",
"privacy domain",
]
## descriptions are needed for ipython-sql/jupysql which describes every statement
def test_description_create_drop_database(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create database example")
assert dcur.fetchall() == [{"status": "Database EXAMPLE successfully created."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
# TODO: support drop database
# dcur.execute("drop database example")
# assert dcur.fetchall() == [{"status": "EXAMPLE successfully dropped."}]
# assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
def test_description_create_drop_schema(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create schema example")
assert dcur.fetchall() == [{"status": "Schema EXAMPLE successfully created."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
# drop current schema
dcur.execute("drop schema schema1")
assert dcur.fetchall() == [{"status": "SCHEMA1 successfully dropped."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
def test_description_create_alter_drop_table(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create table example (x int)")
assert dcur.fetchall() == [{"status": "Table EXAMPLE successfully created."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
dcur.execute("alter table example add column name varchar(20)")
assert dcur.fetchall() == [{"status": "Statement executed successfully."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
dcur.execute("drop table example")
assert dcur.fetchall() == [{"status": "EXAMPLE successfully dropped."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
def test_description_create_drop_view(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create view example(id) as select 1")
assert dcur.fetchall() == [{"status": "View EXAMPLE successfully created."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
dcur.execute("drop view example")
assert dcur.fetchall() == [{"status": "EXAMPLE successfully dropped."}]
assert dcur.description == [ResultMetadata(name='status', type_code=2, display_size=None, internal_size=16777216, precision=None, scale=None, is_nullable=True)] # fmt: skip
def test_description_insert(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create table example (x int)")
dcur.execute("insert into example values (1), (2)")
assert dcur.fetchall() == [{"number of rows inserted": 2}]
# TODO: Snowflake is actually precision=19, is_nullable=False
assert dcur.description == [ResultMetadata(name='number of rows inserted', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True)] # fmt: skip
def test_description_update(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create table example (x int)")
dcur.execute("insert into example values (1), (2), (3)")
dcur.execute("update example set x=420 where x > 1")
assert dcur.fetchall() == [{"number of rows updated": 2, "number of multi-joined rows updated": 0}]
# TODO: Snowflake is actually precision=19, is_nullable=False
# fmt: off
assert dcur.description == [
ResultMetadata(name='number of rows updated', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
ResultMetadata(name='number of multi-joined rows updated', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True)
]
# fmt: on
def test_description_delete(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("create table example (x int)")
dcur.execute("insert into example values (1), (2), (3)")
dcur.execute("delete from example where x>1")
assert dcur.fetchall() == [{"number of rows deleted": 2}]
# TODO: Snowflake is actually precision=19, is_nullable=False
# fmt: off
assert dcur.description == [
ResultMetadata(name='number of rows deleted', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
]
# fmt: on
def test_description_select(dcur: snowflake.connector.cursor.DictCursor):
dcur.execute("SELECT DATEDIFF( DAY, '2023-04-02'::DATE, '2023-04-05'::DATE) as days")
assert dcur.fetchall() == [{"DAYS": 3}]
# TODO: Snowflake is actually precision=9, is_nullable=False
# fmt: off
assert dcur.description == [
ResultMetadata(name='DAYS', type_code=0, display_size=None, internal_size=None, precision=38, scale=0, is_nullable=True),
]
# fmt: on
def test_equal_null(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("select equal_null(NULL, NULL), equal_null(1, 1), equal_null(1, 2), equal_null(1, NULL)")
assert cur.fetchall() == [(True, True, False, False)]
def test_executemany(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
customers = [(1, "Jenny", "P"), (2, "Jasper", "M")]
cur.executemany("insert into customers (id, first_name, last_name) values (%s,%s,%s)", customers)
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchall() == customers
def test_execute_string(conn: snowflake.connector.SnowflakeConnection):
*_, cur = conn.execute_string(
"""
create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar);
-- test comments are ignored
select count(*) customers
"""
)
assert cur.fetchall() == [(1,)]
def test_fetchall(conn: snowflake.connector.SnowflakeConnection):
with conn.cursor() as cur:
# no result set
with pytest.raises(TypeError) as _:
cur.fetchall()
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
cur.execute("insert into customers values (2, 'Jasper', 'M')")
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchall() == [(1, "Jenny", "P"), (2, "Jasper", "M")]
assert cur.fetchall() == []
with conn.cursor(snowflake.connector.cursor.DictCursor) as cur:
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchall() == [
{"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"},
{"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"},
]
assert cur.fetchall() == []
def test_fetchone(conn: snowflake.connector.SnowflakeConnection):
with conn.cursor() as cur:
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
cur.execute("insert into customers values (2, 'Jasper', 'M')")
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchone() == (1, "Jenny", "P")
assert cur.fetchone() == (2, "Jasper", "M")
assert cur.fetchone() is None
with conn.cursor(snowflake.connector.cursor.DictCursor) as cur:
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchone() == {"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"}
assert cur.fetchone() == {"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"}
assert cur.fetchone() is None
def test_fetchmany(conn: snowflake.connector.SnowflakeConnection):
with conn.cursor() as cur:
# no result set
with pytest.raises(TypeError) as _:
cur.fetchmany()
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
cur.execute("insert into customers values (2, 'Jasper', 'M')")
cur.execute("insert into customers values (3, 'Jeremy', 'K')")
cur.execute("select id, first_name, last_name from customers")
# mimic jupysql fetchmany behaviour
assert cur.fetchmany(2) == [(1, "Jenny", "P"), (2, "Jasper", "M")]
assert cur.fetchmany(5) == [(3, "Jeremy", "K")]
assert cur.fetchmany(5) == []
with conn.cursor(snowflake.connector.cursor.DictCursor) as cur:
cur.execute("select id, first_name, last_name from customers")
assert cur.fetchmany(2) == [
{"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"},
{"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"},
]
assert cur.fetchmany(5) == [
{"ID": 3, "FIRST_NAME": "Jeremy", "LAST_NAME": "K"},
]
assert cur.fetchmany(5) == []
def test_fetch_pandas_all(cur: snowflake.connector.cursor.SnowflakeCursor):
# no result set
with pytest.raises(snowflake.connector.NotSupportedError) as _:
cur.fetch_pandas_all()
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
cur.execute("insert into customers values (2, 'Jasper', 'M')")
cur.execute("select id, first_name, last_name from customers")
expected_df = pd.DataFrame.from_records(
[
{"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"},
{"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"},
]
)
# integers have dtype int64
assert_frame_equal(cur.fetch_pandas_all(), expected_df)
# can refetch
assert_frame_equal(cur.fetch_pandas_all(), expected_df)
def test_flatten(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute(
"""
select t.id, flat.value:fruit from
(
select 1, parse_json('[{"fruit":"banana"}]')
union
select 2, parse_json('[{"fruit":"coconut"}, {"fruit":"durian"}]')
) as t(id, fruits), lateral flatten(input => t.fruits) AS flat
order by id
"""
# duckdb lateral join order is non-deterministic so order by id
# within an id the order of fruits should match the json array
)
assert cur.fetchall() == [(1, '"banana"'), (2, '"coconut"'), (2, '"durian"')]
def test_flatten_index(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute(
"""
select id, f.value::varchar as v, f.index as i
from (select column1 as id, column2 as col from (values (1, 's1,s3,s2'), (2, 's2,s1'))) as t
, lateral flatten(input => split(t.col, ',')) as f order by id;
"""
)
assert cur.fetchall() == [(1, "s1", 0), (1, "s3", 1), (1, "s2", 2), (2, "s2", 0), (2, "s1", 1)]
def test_flatten_value_cast_as_varchar(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute(
"""
select id, f.value::varchar as v
from (select column1 as id, column2 as col from (values (1, 's1,s2,s3'), (2, 's1,s2'))) as t
, lateral flatten(input => split(t.col, ',')) as f order by id
"""
)
# should be raw string not json string with double quotes
assert cur.fetchall() == [(1, "s1"), (1, "s2"), (1, "s3"), (2, "s1"), (2, "s2")]
def test_floats_are_64bit(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create or replace table example (f float, f4 float4, f8 float8, d double, r real)")
cur.execute("insert into example values (1.23, 1.23, 1.23, 1.23, 1.23)")
cur.execute("select * from example")
# 32 bit floats will return 1.2300000190734863 rather than 1.23
assert cur.fetchall() == [(1.23, 1.23, 1.23, 1.23, 1.23)]
def test_get_path_as_varchar(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("""select parse_json('{"fruit":"banana"}'):fruit""")
assert cur.fetchall() == [('"banana"',)]
# converting json to varchar returns unquoted string
cur.execute("""select parse_json('{"fruit":"banana"}'):fruit::varchar""")
assert cur.fetchall() == [("banana",)]
# nested json
cur.execute("""select get_path(parse_json('{"food":{"fruit":"banana"}}'), 'food.fruit')::varchar""")
assert cur.fetchall() == [("banana",)]
cur.execute("""select parse_json('{"food":{"fruit":"banana"}}'):food.fruit::varchar""")
assert cur.fetchall() == [("banana",)]
cur.execute("""select parse_json('{"food":{"fruit":"banana"}}'):food:fruit::varchar""")
assert cur.fetchall() == [("banana",)]
# json number is varchar
cur.execute("""select parse_json('{"count":42}'):count""")
assert cur.fetchall() == [("42",)]
# lower/upper converts to varchar (ie: no quotes) ¯\_(ツ)_/¯
cur.execute("""select upper(parse_json('{"fruit":"banana"}'):fruit)""")
assert cur.fetchall() == [("BANANA",)]
cur.execute("""select lower(parse_json('{"fruit":"banana"}'):fruit)""")
assert cur.fetchall() == [("banana",)]
# lower/upper converts json number to varchar too
cur.execute("""select upper(parse_json('{"count":"42"}'):count)""")
assert cur.fetchall() == [("42",)]
def test_get_path_precedence(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("select {'K1': {'K2': 1}} as col where col:K1:K2 > 0")
assert indent(cur.fetchall()) == [('{\n "K1": {\n "K2": 1\n }\n}',)]
cur.execute(
"""select parse_json('{"K1": "a", "K2": "b"}') as col, case when col:K1::VARCHAR = 'a' and col:K2::VARCHAR = 'b' then 'yes' end"""
)
assert indent(cur.fetchall()) == [('{\n "K1": "a",\n "K2": "b"\n}', "yes")]
def test_get_result_batches(cur: snowflake.connector.cursor.SnowflakeCursor):
# no result set
assert cur.get_result_batches() is None
cur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
cur.execute("insert into customers values (2, 'Jasper', 'M')")
cur.execute("select id, first_name, last_name from customers")
batches = cur.get_result_batches()
assert batches
rows = [row for batch in batches for row in batch]
assert rows == [(1, "Jenny", "P"), (2, "Jasper", "M")]
assert sum(batch.rowcount for batch in batches) == 2
def test_get_result_batches_dict(dcur: snowflake.connector.cursor.DictCursor):
# no result set
assert dcur.get_result_batches() is None
dcur.execute("create table customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
dcur.execute("insert into customers values (1, 'Jenny', 'P')")
dcur.execute("insert into customers values (2, 'Jasper', 'M')")
dcur.execute("select id, first_name, last_name from customers")
batches = dcur.get_result_batches()
assert batches
rows = [row for batch in batches for row in batch]
assert rows == [
{"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"},
{"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"},
]
assert sum(batch.rowcount for batch in batches) == 2
assert_frame_equal(
batches[0].to_pandas(),
pd.DataFrame.from_records(
[
{"ID": 1, "FIRST_NAME": "Jenny", "LAST_NAME": "P"},
{"ID": 2, "FIRST_NAME": "Jasper", "LAST_NAME": "M"},
]
),
)
def test_identifier(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create or replace table example (x int)")
cur.execute("insert into example values(1)")
cur.execute("select * from identifier('example')")
assert cur.fetchall() == [(1,)]
def test_nop_regexes():
with fakesnow.patch(nop_regexes=["^CALL.*"]), snowflake.connector.connect() as conn, conn.cursor() as cur:
cur.execute("call this_procedure_does_not_exist('foo', 'bar);")
assert cur.fetchall() == [("Statement executed successfully.",)]
def test_non_existent_table_throws_snowflake_exception(cur: snowflake.connector.cursor.SnowflakeCursor):
with pytest.raises(snowflake.connector.errors.ProgrammingError) as _:
cur.execute("select * from this_table_does_not_exist")
def test_object_construct(conn: snowflake.connector.SnowflakeConnection):
with conn.cursor() as cur:
cur.execute("SELECT OBJECT_CONSTRUCT('a',1,'b','BBBB', 'c',null)")
# TODO: strip null within duckdb via python UDF
def strip_none_values(d: dict) -> dict:
return {k: v for k, v in d.items() if v}
result = cur.fetchone()
assert isinstance(result, tuple)
assert strip_none_values(json.loads(result[0])) == json.loads('{\n "a": 1,\n "b": "BBBB"\n}')
with conn.cursor() as cur:
cur.execute("SELECT OBJECT_CONSTRUCT('a', 1, null, 'nulkeyed') as col")
result = cur.fetchone()
assert isinstance(result, tuple)
assert strip_none_values(json.loads(result[0])) == json.loads('{\n "a": 1\n}')
with conn.cursor() as cur:
cur.execute(
"SELECT NULL as col, OBJECT_CONSTRUCT( 'k1', 'v1', 'k2', CASE WHEN ZEROIFNULL(col) + 1 >= 2 THEN 'v2' ELSE NULL END, 'k3', 'v3')"
)
result = cur.fetchone()
assert isinstance(result, tuple)
assert strip_none_values(json.loads(result[1])) == json.loads('{\n "k1": "v1",\n "k3": "v3"\n}')
with conn.cursor() as cur:
cur.execute(
"SELECT 1 as col, OBJECT_CONSTRUCT( 'k1', 'v1', 'k2', CASE WHEN ZEROIFNULL(col) + 1 >= 2 THEN 'v2' ELSE NULL END, 'k3', 'v3')"
)
result = cur.fetchone()
assert isinstance(result, tuple)
assert strip_none_values(json.loads(result[1])) == json.loads(
'{\n "k1": "v1",\n "k2": "v2",\n "k3": "v3"\n}'
)
def test_percentile_cont(conn: snowflake.connector.SnowflakeConnection):
*_, cur = conn.execute_string(
"""
create or replace table aggr(k int, v decimal(10,2));
insert into aggr (k, v) values
(0, 0),
(0, 10),
(0, 20),
(0, 30),
(0, 40),
(1, 10),
(1, 20),
(2, 10),
(2, 20),
(2, 25),
(2, 30),
(3, 60),
(4, NULL);
select k, percentile_cont(0.25) within group (order by v)
from aggr
group by k
order by k;
"""
)
assert cur.fetchall() == [
(0, Decimal("10.00000")),
(1, Decimal("12.50000")),
(2, Decimal("17.50000")),
(3, Decimal("60.00000")),
(4, None),
]
def test_regex(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("select regexp_replace('abc123', '\\\\D', '')")
assert cur.fetchone() == ("123",)
def test_regex_substr(cur: snowflake.connector.cursor.SnowflakeCursor):
# see https://docs.snowflake.com/en/sql-reference/functions/regexp_substr
string1 = "It was the best of times, it was the worst of times."
cur.execute(f"select regexp_substr('{string1}', 'the\\\\W+\\\\w+')")
assert cur.fetchone() == ("the best",)
cur.execute(f"select regexp_substr('{string1}', 'the\\\\W+\\\\w+', 1, 2)")
assert cur.fetchone() == ("the worst",)
cur.execute(f"select regexp_substr('{string1}', 'the\\\\W+(\\\\w+)', 1, 2, 'e', 1)")
assert cur.fetchone() == ("worst",)
def test_random(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("select random(420)")
assert cur.fetchall() == [(-2595895151578578944,)]
cur.execute("select random(420)")
assert cur.fetchall() == [(-2595895151578578944,)]
cur.execute("select random(419)")
assert cur.fetchall() == [(4590143504000221184,)]
assert cur.execute("select random()").fetchall() != cur.execute("select random()").fetchall()
def test_rowcount(cur: snowflake.connector.cursor.SnowflakeCursor):
assert cur.rowcount is None
cur.execute("create or replace table example(id int)")
cur.execute("insert into example select * from (VALUES (1), (2), (3), (4));")
assert cur.rowcount == 4
cur.execute("select * from example where id > 1")
assert cur.rowcount == 3
cur.execute("update example set id = 22 where id > 2")
assert cur.rowcount == 2
def test_sample(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create table example(id int)")
cur.execute("insert into example select * from (VALUES (1), (2), (3), (4));")
cur.execute("select * from example SAMPLE (50) SEED (420)")
# sampling small sizes isn't exact
assert cur.fetchall() == [(1,), (2,), (3,)]
def test_schema_create_and_use(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create schema jaffles")
cur.execute("create table jaffles.customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
cur.execute("use schema jaffles")
# fully qualified works too
cur.execute("use schema db1.jaffles")
cur.execute("insert into customers values (1, 'Jenny', 'P')")
def test_schema_drop(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create schema jaffles")
cur.execute("create table jaffles.customers (ID int, FIRST_NAME varchar, LAST_NAME varchar)")
# dropping schema drops its contents
cur.execute("drop schema jaffles")
def test_semi_structured_types(cur: snowflake.connector.cursor.SnowflakeCursor):
cur.execute("create or replace table semis (emails array, names object, notes variant)")
cur.execute(
"""insert into semis(emails, names, notes) SELECT ['A', 'B'], OBJECT_CONSTRUCT('k','v1'), ARRAY_CONSTRUCT('foo')::VARIANT"""
)
cur.execute(
"""insert into semis(emails, names, notes) SELECT ['C','D'], parse_json('{"k": "v2"}'), parse_json('{"b": "ar"}')"""
)