-
Notifications
You must be signed in to change notification settings - Fork 541
/
test_client.py
1428 lines (1222 loc) · 43.1 KB
/
test_client.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
import builtins
import contextlib
import importlib
import inspect
import os
import platform
import re
import string
import subprocess
import sys
from operator import itemgetter
from typing import TYPE_CHECKING
import numpy as np
import pandas as pd
import pandas.testing as tm
import pyarrow as pa
import pytest
import rich.console
import sqlalchemy as sa
from packaging.version import parse as vparse
from pytest import mark, param
import ibis
import ibis.common.exceptions as com
import ibis.expr.datatypes as dt
import ibis.expr.operations as ops
from ibis.backends.conftest import ALL_BACKENDS
from ibis.util import gen_name, guid
if TYPE_CHECKING:
from ibis.backends.base import BaseBackend
try:
from py4j.protocol import Py4JJavaError
except ImportError:
Py4JJavaError = None
@pytest.fixture
def new_schema():
return ibis.schema([("a", "string"), ("b", "bool"), ("c", "int32")])
def _create_temp_table_with_schema(con, temp_table_name, schema, data=None):
temporary = con.create_table(temp_table_name, schema=schema)
assert temporary.to_pandas().empty
if data is not None and isinstance(data, pd.DataFrame):
assert not data.empty
tmp = con.create_table(temp_table_name, data, overwrite=True)
result = tmp.to_pandas()
assert len(result) == len(data.index)
tm.assert_frame_equal(
result.sort_values(result.columns[0]).reset_index(drop=True),
data.sort_values(result.columns[0]).reset_index(drop=True),
)
return tmp
return temporary
@pytest.mark.parametrize(
"lamduh",
[
(lambda df: df),
param(
lambda df: pa.Table.from_pandas(df), marks=pytest.mark.notimpl(["impala"])
),
],
ids=["dataframe", "pyarrow table"],
)
@pytest.mark.parametrize(
"sch",
[
param(
None,
id="no schema",
),
param(
ibis.schema(
[
("first_name", "string"),
("last_name", "string"),
("department_name", "string"),
("salary", "float64"),
]
),
id="schema",
),
],
)
@pytest.mark.notimpl(["dask", "datafusion", "druid"])
def test_create_table(backend, con, temp_table, lamduh, sch):
df = pd.DataFrame(
{
"first_name": ["A", "B", "C"],
"last_name": ["D", "E", "F"],
"department_name": ["AA", "BB", "CC"],
"salary": [100.0, 200.0, 300.0],
}
)
obj = lamduh(df)
con.create_table(
temp_table,
obj,
schema=sch,
**{"tbl_properties": {"connector": None}} if backend.name() == "flink" else {},
)
result = (
con.table(temp_table).execute().sort_values("first_name").reset_index(drop=True)
)
backend.assert_frame_equal(df, result)
@pytest.mark.parametrize(
"lamduh",
[(lambda df: df), (lambda df: pa.Table.from_pandas(df))],
ids=["dataframe", "pyarrow table"],
)
def test_load_data_sqlalchemy(alchemy_backend, alchemy_con, alchemy_temp_table, lamduh):
sch = ibis.schema(
[
("first_name", "string"),
("last_name", "string"),
("department_name", "string"),
("salary", "float64"),
]
)
df = pd.DataFrame(
{
"first_name": ["A", "B", "C"],
"last_name": ["D", "E", "F"],
"department_name": ["AA", "BB", "CC"],
"salary": [100.0, 200.0, 300.0],
}
)
obj = lamduh(df)
alchemy_con.create_table(alchemy_temp_table, obj, schema=sch, overwrite=True)
result = (
alchemy_con.table(alchemy_temp_table)
.execute()
.sort_values("first_name")
.reset_index(drop=True)
)
alchemy_backend.assert_frame_equal(df, result)
@mark.parametrize(
("expr_fn", "expected"),
[
param(lambda t: t.string_col, [("string_col", dt.String)], id="column"),
param(
lambda t: t[t.string_col, t.bigint_col],
[("string_col", dt.String), ("bigint_col", dt.Int64)],
id="table",
),
],
)
@pytest.mark.broken(
["flink"],
raises=Py4JJavaError,
reason=(
"org.apache.flink.table.api.ValidationException: "
"Table `default_catalog`.`default_database`.`functional_alltypes` was not found."
),
)
def test_query_schema(ddl_backend, expr_fn, expected):
expr = expr_fn(ddl_backend.functional_alltypes)
# we might need a public API for it
schema = expr.as_table().schema()
# clickhouse columns has been defined as non-nullable
# whereas other backends don't support non-nullable columns yet
expected = ibis.schema(
[(name, dtype(nullable=schema[name].nullable)) for name, dtype in expected]
)
assert schema.equals(expected)
_LIMIT = {
"oracle": "FETCH FIRST 10 ROWS ONLY",
}
@pytest.mark.notimpl(["datafusion", "polars", "mssql"])
@pytest.mark.never(["dask", "pandas"], reason="dask and pandas do not support SQL")
@pytest.mark.notimpl(
["flink"], raises=AttributeError, reason="'Backend' object has no attribute 'sql'"
)
def test_sql(backend, con):
# execute the expression using SQL query
table = backend.format_table("functional_alltypes")
limit = _LIMIT.get(backend.name(), "LIMIT 10")
expr = con.sql(f"SELECT * FROM {table} {limit}")
result = expr.execute()
assert len(result) == 10
backend_type_mapping = {
# backends only implement int64
"bigquery": {
dt.int32: dt.int64,
},
"snowflake": {
dt.int32: dt.int64,
},
}
@mark.notimpl(["datafusion", "druid", "flink"])
def test_create_table_from_schema(con, new_schema, temp_table):
new_table = con.create_table(temp_table, schema=new_schema)
backend_mapping = backend_type_mapping.get(con.name, {})
result = ibis.schema(
{
column_name: backend_mapping.get(
new_schema[column_name], new_schema[column_name]
)
for column_name in new_table.schema().keys()
}
)
assert result == new_table.schema()
@pytest.fixture(scope="session")
def tmpcon(alchemy_con):
"""A fixture to scope the connection for temp table testing.
This prevents resetting the connection for subsequent tests that may depend
on connection state persisting across tests.
"""
return alchemy_con._from_url(alchemy_con.con.url)
@mark.broken(
["oracle"],
reason="oracle temp tables aren't cleaned up on reconnect -- they need to "
"be switched from using atexit to weakref.finalize",
)
@mark.notimpl(["trino", "druid"], reason="doesn't implement temporary tables")
@mark.never(
["mssql"],
reason="mssql supports support temporary tables through naming conventions",
)
def test_create_temporary_table_from_schema(tmpcon, new_schema):
temp_table = f"_{guid()}"
table = tmpcon.create_table(temp_table, schema=new_schema, temp=True)
# verify table exist in the current session
backend_mapping = backend_type_mapping.get(tmpcon.name, dict())
for column_name, column_type in table.schema().items():
assert (
backend_mapping.get(new_schema[column_name], new_schema[column_name])
== column_type
)
tmpcon.reconnect()
# verify table no longer exist after reconnect
assert temp_table not in tmpcon.tables.keys()
@mark.notimpl(
[
"bigquery",
"clickhouse",
"dask",
"datafusion",
"druid",
"duckdb",
"flink",
"mssql",
"mysql",
"oracle",
"pandas",
"polars",
"postgres",
"snowflake",
"sqlite",
"trino",
]
)
def test_rename_table(con, temp_table, temp_table_orig):
schema = ibis.schema({"a": "string", "b": "bool", "c": "int32"})
con.create_table(temp_table_orig, schema=schema)
con.rename_table(temp_table_orig, temp_table)
new = con.table(temp_table)
assert new.schema().equals(schema)
assert temp_table_orig not in con.list_tables()
@mark.notimpl(["datafusion", "polars", "druid"])
@mark.never(["impala", "pyspark"], reason="No non-nullable datatypes")
@mark.notyet(
["trino"], reason="trino doesn't support NOT NULL in its in-memory catalog"
)
@mark.broken(["snowflake", "flink"], reason="shows not nullable column as nullable")
def test_nullable_input_output(con, temp_table):
sch = ibis.schema(
[("foo", "int64"), ("bar", dt.int64(nullable=False)), ("baz", "boolean")]
)
t = con.create_table(
temp_table,
schema=sch,
**{"tbl_properties": {"connector": None}} if con.name == "flink" else {},
)
assert t.schema().types[0].nullable
assert not t.schema().types[1].nullable
assert t.schema().types[2].nullable
@mark.notimpl(["datafusion", "druid", "flink", "polars"])
def test_create_drop_view(ddl_con, temp_view):
# setup
table_name = "functional_alltypes"
tables = ddl_con.list_tables()
if table_name in tables or (table_name := table_name.upper()) in tables:
expr = ddl_con.table(table_name)
else:
raise ValueError(f"table `{table_name}` does not exist")
expr = expr.limit(1)
# create a new view
ddl_con.create_view(temp_view, expr)
# check if the view was created
assert temp_view in ddl_con.list_tables()
t_expr = ddl_con.table(table_name)
v_expr = ddl_con.table(temp_view)
# check if the view and the table has the same fields
assert set(t_expr.schema().names) == set(v_expr.schema().names)
@mark.notimpl(["postgres", "polars"])
@mark.notimpl(
["datafusion"],
raises=NotImplementedError,
reason="doesn't seem to have a stateful notion of 'current database'",
)
def test_separate_database(ddl_con, alternate_current_database):
current_data_db = ddl_con.current_database
# using alternate_current_database switches "con" current
# database to a temporary one until a test is over
tmp_db = ddl_con.database(alternate_current_database)
# verifying we can open another db which isn't equal to current
db = ddl_con.database(current_data_db)
assert db.name == current_data_db
assert tmp_db.name == alternate_current_database
@pytest.fixture
def employee_empty_temp_table(alchemy_con, test_employee_schema):
temp_table_name = f"temp_employee_empty_table_{guid()[:6]}"
_create_temp_table_with_schema(
alchemy_con,
temp_table_name,
test_employee_schema,
)
yield temp_table_name
alchemy_con.drop_table(temp_table_name, force=True)
@pytest.fixture
def employee_data_1_temp_table(
alchemy_con,
test_employee_schema,
test_employee_data_1,
):
temp_table_name = f"temp_employee_data_1_{guid()[:6]}"
_create_temp_table_with_schema(
alchemy_con,
temp_table_name,
test_employee_schema,
data=test_employee_data_1,
)
assert temp_table_name in alchemy_con.list_tables()
yield temp_table_name
alchemy_con.drop_table(temp_table_name, force=True)
@pytest.fixture
def employee_data_2_temp_table(
alchemy_con,
test_employee_schema,
test_employee_data_2,
):
temp_table_name = f"temp_employee_data_2_{guid()[:6]}"
_create_temp_table_with_schema(
alchemy_con,
temp_table_name,
test_employee_schema,
data=test_employee_data_2,
)
yield temp_table_name
alchemy_con.drop_table(temp_table_name, force=True)
def test_insert_no_overwrite_from_dataframe(
alchemy_con,
test_employee_data_2,
employee_empty_temp_table,
):
temporary = alchemy_con.table(employee_empty_temp_table)
alchemy_con.insert(
employee_empty_temp_table,
obj=test_employee_data_2,
overwrite=False,
)
result = temporary.execute()
assert len(result) == 3
tm.assert_frame_equal(
result.sort_values("first_name").reset_index(drop=True),
test_employee_data_2.sort_values("first_name").reset_index(drop=True),
)
@pytest.mark.notyet(
["trino"],
reason="Connector doesn't support deletion (required for overwrite=True)",
raises=sa.exc.ProgrammingError,
)
def test_insert_overwrite_from_dataframe(
alchemy_con,
employee_data_1_temp_table,
test_employee_data_2,
):
temporary = alchemy_con.table(employee_data_1_temp_table)
alchemy_con.insert(
employee_data_1_temp_table,
obj=test_employee_data_2,
overwrite=True,
)
result = temporary.execute()
assert len(result) == 3
tm.assert_frame_equal(
result.sort_values("first_name").reset_index(drop=True),
test_employee_data_2.sort_values("first_name").reset_index(drop=True),
)
def test_insert_no_overwrite_from_expr(
alchemy_con,
employee_empty_temp_table,
employee_data_2_temp_table,
):
temporary = alchemy_con.table(employee_empty_temp_table)
from_table = alchemy_con.table(employee_data_2_temp_table)
alchemy_con.insert(
employee_empty_temp_table,
obj=from_table,
overwrite=False,
)
result = temporary.execute()
assert len(result) == 3
tm.assert_frame_equal(
result.sort_values("first_name").reset_index(drop=True),
from_table.execute().sort_values("first_name").reset_index(drop=True),
)
def test_insert_overwrite_from_expr(
alchemy_con,
employee_data_1_temp_table,
employee_data_2_temp_table,
):
temporary = alchemy_con.table(employee_data_1_temp_table)
from_table = alchemy_con.table(employee_data_2_temp_table)
alchemy_con.insert(
employee_data_1_temp_table,
obj=from_table,
overwrite=True,
)
result = temporary.execute()
assert len(result) == 3
tm.assert_frame_equal(
result.sort_values("first_name").reset_index(drop=True),
from_table.execute().sort_values("first_name").reset_index(drop=True),
)
@pytest.mark.notyet(
["trino"], reason="memory connector doesn't allow writing to tables"
)
@pytest.mark.notyet(
"oracle",
reason="No support for in-place multirow inserts",
raises=sa.exc.CompileError,
)
def test_insert_overwrite_from_list(
alchemy_con,
employee_data_1_temp_table,
):
def _emp(a, b, c, d):
return dict(first_name=a, last_name=b, department_name=c, salary=d)
alchemy_con.insert(
employee_data_1_temp_table,
[
_emp("Adam", "Smith", "Accounting", 50000.0),
_emp("Mohammed", "Ali", "Boxing", 150000),
_emp("María", "Gonzalez", "Engineering", 100000.0),
],
overwrite=True,
)
assert len(alchemy_con.table(employee_data_1_temp_table).execute()) == 3
def test_insert_from_memtable(alchemy_con, alchemy_temp_table):
df = pd.DataFrame({"x": range(3)})
table_name = alchemy_temp_table
mt = ibis.memtable(df)
alchemy_con.create_table(table_name, schema=mt.schema())
alchemy_con.insert(table_name, mt)
alchemy_con.insert(table_name, mt)
table = alchemy_con.tables[table_name]
assert len(table.execute()) == 6
assert alchemy_con.tables[table_name].schema() == ibis.schema({"x": "int64"})
@pytest.mark.notyet(
["oracle"],
raises=AttributeError,
reason="oracle doesn't support the common notion of a database",
)
def test_list_databases(alchemy_con):
# Every backend has its own databases
test_databases = {
"sqlite": {"main"},
"postgres": {"postgres", "ibis_testing"},
"mssql": {"ibis_testing"},
"mysql": {"ibis_testing", "information_schema"},
"duckdb": {"memory"},
"snowflake": {"IBIS_TESTING"},
"trino": {"memory"},
"oracle": set(),
}
assert test_databases[alchemy_con.name] <= set(alchemy_con.list_databases())
@pytest.mark.never(
["bigquery", "postgres", "mssql", "mysql", "snowflake", "oracle"],
reason="backend does not support client-side in-memory tables",
raises=(sa.exc.OperationalError, TypeError),
)
@pytest.mark.notyet(
["trino"], reason="memory connector doesn't allow writing to tables"
)
def test_in_memory(alchemy_backend, alchemy_temp_table):
con = getattr(ibis, alchemy_backend.name()).connect(":memory:")
with con.begin() as c:
c.exec_driver_sql(f"CREATE TABLE {alchemy_temp_table} (x int)")
assert alchemy_temp_table in con.list_tables()
@pytest.mark.notyet(
["mssql", "mysql", "postgres", "snowflake", "sqlite", "trino"],
raises=TypeError,
reason="backend does not support unsigned integer types",
)
def test_unsigned_integer_type(alchemy_con, alchemy_temp_table):
alchemy_con.create_table(
alchemy_temp_table,
schema=ibis.schema(dict(a="uint8", b="uint16", c="uint32", d="uint64")),
overwrite=True,
)
assert alchemy_temp_table in alchemy_con.list_tables()
@pytest.mark.backend
@pytest.mark.parametrize(
"url",
[
param(
"clickhouse://default@localhost:8123/default",
marks=mark.clickhouse,
id="clickhouse",
),
param(
"dask://",
marks=[mark.dask, mark.xfail(raises=NotImplementedError)],
id="dask",
),
param(
"datafusion://",
marks=[mark.datafusion, mark.xfail(raises=NotImplementedError)],
id="datafusion",
),
param(
"impala://localhost:21050/default",
marks=mark.impala,
id="impala",
),
param(
"mysql://ibis:ibis@localhost:3306",
marks=mark.mysql,
id="mysql",
),
param(
"pandas://",
marks=[mark.pandas, mark.xfail(raises=NotImplementedError)],
id="pandas",
),
param(
"postgres://postgres:postgres@localhost:5432",
marks=mark.postgres,
id="postgres",
),
param(
"postgresql://postgres:postgres@localhost:5432/postgres",
marks=mark.postgres,
id="postgresql",
),
param(
"pyspark://?spark.app.name=test-pyspark",
marks=[
mark.pyspark,
pytest.mark.skipif(
sys.version_info >= (3, 11)
or vparse(pd.__version__) >= vparse("2")
or vparse(np.__version__) >= vparse("1.24"),
reason="passes on 3.11, but no other pyspark tests do",
),
],
id="pyspark",
),
param(
"pyspark://my-warehouse-dir?spark.app.name=test-pyspark",
marks=[
mark.pyspark,
pytest.mark.skipif(
sys.version_info >= (3, 11)
or vparse(pd.__version__) >= vparse("2")
or vparse(np.__version__) >= vparse("1.24"),
reason="passes on 3.11, but no other pyspark tests do",
),
],
id="pyspark_with_warehouse",
),
param(
"pyspark://my-warehouse-dir",
marks=[
mark.pyspark,
pytest.mark.skipif(
sys.version_info >= (3, 11)
or vparse(pd.__version__) >= vparse("2")
or vparse(np.__version__) >= vparse("1.24"),
reason="passes on 3.11, but no other pyspark tests do",
),
],
id="pyspark_with_warehouse_no_params",
),
],
)
def test_connect_url(url):
con = ibis.connect(url)
one = ibis.literal(1)
assert con.execute(one) == 1
not_windows = pytest.mark.skipif(
condition=platform.system() == "Windows",
reason=(
"windows prevents two connections to the same duckdb file even in "
"the same process"
),
)
@pytest.fixture(params=["duckdb", "sqlite"])
def tmp_db(request, tmp_path):
api = request.param
mod = pytest.importorskip(api)
db = tmp_path / "test.db"
mod.connect(str(db)).execute("CREATE TABLE tmp_t AS SELECT 1 AS a").fetchall()
return db
@pytest.mark.duckdb
@pytest.mark.parametrize(
"url",
[
param(lambda p: p, id="no-scheme-duckdb-ext"),
param(lambda p: f"duckdb://{p}", id="absolute-path"),
param(
lambda p: f"duckdb://{os.path.relpath(p)}",
marks=[
not_windows
], # hard to test in CI since tmpdir & cwd are on different drives
id="relative-path",
),
param(lambda p: "duckdb://", id="in-memory-empty"),
param(lambda p: "duckdb://:memory:", id="in-memory-explicit"),
param(
lambda p: f"duckdb://{p}?read_only=1",
id="duckdb_read_write_int",
),
param(
lambda p: f"duckdb://{p}?read_only=False",
id="duckdb_read_write_upper",
),
param(
lambda p: f"duckdb://{p}?read_only=false",
id="duckdb_read_write_lower",
),
],
)
def test_connect_duckdb(url, tmp_path):
duckdb = pytest.importorskip("duckdb")
path = os.path.abspath(tmp_path / "test.duckdb")
with duckdb.connect(path):
pass
con = ibis.connect(url(path))
one = ibis.literal(1)
assert con.execute(one) == 1
@pytest.mark.sqlite
@pytest.mark.parametrize(
"url, ext",
[
param(lambda p: p, "sqlite", id="no-scheme-sqlite-ext"),
param(lambda p: p, "db", id="no-scheme-db-ext"),
param(lambda p: f"sqlite://{p}", "db", id="absolute-path"),
param(
lambda p: f"sqlite://{os.path.relpath(p)}",
"db",
marks=[
not_windows
], # hard to test in CI since tmpdir & cwd are on different drives
id="relative-path",
),
param(lambda p: "sqlite://", "db", id="in-memory-empty"),
param(lambda p: "sqlite://:memory:", "db", id="in-memory-explicit"),
],
)
def test_connect_sqlite(url, ext, tmp_path):
import sqlite3
path = os.path.abspath(tmp_path / f"test.{ext}")
with sqlite3.connect(path):
pass
con = ibis.connect(url(path))
one = ibis.literal(1)
assert con.execute(one) == 1
@pytest.mark.duckdb
@pytest.mark.parametrize(
"out_method, extension",
[
("to_csv", "csv"),
("to_parquet", "parquet"),
],
)
def test_connect_local_file(out_method, extension, test_employee_data_1, tmp_path):
getattr(test_employee_data_1, out_method)(tmp_path / f"out.{extension}")
con = ibis.connect(tmp_path / f"out.{extension}")
t = next(iter(con.tables.values()))
assert not t.head().execute().empty
@not_windows
def test_invalid_connect(tmp_path):
pytest.importorskip("duckdb")
url = f"duckdb://{tmp_path}?read_only=invalid_value"
with pytest.raises(ValueError):
ibis.connect(url)
@pytest.mark.parametrize(
("expr", "expected"),
[
param(
ibis.memtable([(1, 2.0, "3")], columns=list("abc")),
pd.DataFrame([(1, 2.0, "3")], columns=list("abc")),
id="simple",
),
param(
ibis.memtable([(1, 2.0, "3")]),
pd.DataFrame([(1, 2.0, "3")], columns=["col0", "col1", "col2"]),
id="simple_auto_named",
),
param(
ibis.memtable(
[(1, 2.0, "3")],
schema=ibis.schema(dict(a="int8", b="float32", c="string")),
),
pd.DataFrame([(1, 2.0, "3")], columns=list("abc")).astype(
{"a": "int8", "b": "float32"}
),
id="simple_schema",
),
param(
ibis.memtable(
pd.DataFrame({"a": [1], "b": [2.0], "c": ["3"]}).astype(
{"a": "int8", "b": "float32"}
)
),
pd.DataFrame([(1, 2.0, "3")], columns=list("abc")).astype(
{"a": "int8", "b": "float32"}
),
id="dataframe",
),
param(
ibis.memtable([dict(a=1), dict(a=2)]),
pd.DataFrame({"a": [1, 2]}),
id="list_of_dicts",
),
],
)
def test_in_memory_table(backend, con, expr, expected):
result = con.execute(expr)
backend.assert_frame_equal(result, expected)
def test_filter_memory_table(backend, con):
t = ibis.memtable([(1, 2), (3, 4), (5, 6)], columns=["x", "y"])
expr = t.filter(t.x > 1)
expected = pd.DataFrame({"x": [3, 5], "y": [4, 6]})
result = con.execute(expr)
backend.assert_frame_equal(result, expected)
def test_agg_memory_table(con):
t = ibis.memtable([(1, 2), (3, 4), (5, 6)], columns=["x", "y"])
expr = t.x.count()
result = con.execute(expr)
assert result == 3
@pytest.mark.broken(
["polars"], reason="join column renaming is currently incorrect on polars"
)
def test_self_join_memory_table(backend, con):
t = ibis.memtable({"x": [1, 2], "y": [2, 1], "z": ["a", "b"]})
t_view = t.view()
expr = t.join(t_view, t.x == t_view.y).select("x", "y", "z", "z_right")
result = con.execute(expr).sort_values("x").reset_index(drop=True)
expected = pd.DataFrame(
{"x": [1, 2], "y": [2, 1], "z": ["a", "b"], "z_right": ["b", "a"]}
)
backend.assert_frame_equal(result, expected)
@pytest.mark.parametrize(
"t",
[
param(
ibis.memtable([("a", 1.0)], columns=["a", "b"]),
id="python",
marks=pytest.mark.notimpl(["flink"], raises=NotImplementedError),
),
param(
ibis.memtable(pd.DataFrame([("a", 1.0)], columns=["a", "b"])),
id="pandas-memtable",
marks=pytest.mark.notimpl(["flink"], raises=NotImplementedError),
),
param(pd.DataFrame([("a", 1.0)], columns=["a", "b"]), id="pandas"),
],
)
@pytest.mark.notimpl(["dask", "datafusion", "druid"])
def test_create_from_in_memory_table(backend, con, t, temp_table):
con.create_table(temp_table, t)
assert temp_table in con.list_tables()
@pytest.mark.usefixtures("backend")
def test_default_backend_option(monkeypatch):
monkeypatch.setattr(ibis.options, "default_backend", ibis.pandas)
backend = ibis.config._default_backend()
assert backend.name == "pandas"
# backend is used to ensure that this test runs in CI in the setting
# where only the dependencies for a given backend are installed
@pytest.mark.usefixtures("backend")
def test_default_backend_no_duckdb():
script = """\
import sys
sys.modules["duckdb"] = None
import ibis
t = ibis.memtable([{'a': 1}, {'a': 2}, {'a': 3}])
t.execute()"""
args = [sys.executable, "-c", script]
with pytest.raises(subprocess.CalledProcessError) as e:
subprocess.check_output(args, stderr=subprocess.STDOUT, universal_newlines=True)
assert (
re.search(
"You have used a function that relies on the default backend",
e.value.output,
)
is not None
)
@pytest.mark.usefixtures("backend")
def test_default_backend_no_duckdb_read_parquet():
script = """\
import sys
sys.modules["duckdb"] = None
import ibis
ibis.read_parquet("foo.parquet")"""
args = [sys.executable, "-c", script]
with pytest.raises(subprocess.CalledProcessError) as e:
subprocess.check_output(args, stderr=subprocess.STDOUT, universal_newlines=True)
assert (
re.search(
"You have used a function that relies on the default backend",
e.value.output,
)
is not None
)
@pytest.mark.duckdb
def test_default_backend():
pytest.importorskip("duckdb")
df = pd.DataFrame({"a": [1, 2, 3]})
t = ibis.memtable(df)
expr = t.a.sum()
# run this twice to ensure that we hit the optimizations in
# `_default_backend`
for _ in range(2):
assert expr.execute() == df.a.sum()
sql = str(ibis.to_sql(expr))
rx = """\
SELECT
SUM\\((\\w+)\\.a\\) AS ".+"
FROM \\w+ AS \\1"""
assert re.match(rx, sql) is not None
@pytest.mark.parametrize("dtype", [None, "f8"])
def test_dunder_array_table(alltypes, dtype):
expr = alltypes.group_by("string_col").int_col.sum().order_by("string_col")
result = np.asarray(expr, dtype=dtype)
expected = np.asarray(expr.execute(), dtype=dtype)
np.testing.assert_array_equal(result, expected)
@pytest.mark.parametrize("dtype", [None, "f8"])
def test_dunder_array_column(alltypes, dtype):
from ibis import _
expr = alltypes.group_by("string_col").agg(int_col=_.int_col.sum()).int_col
result = np.sort(np.asarray(expr, dtype=dtype))
expected = np.sort(np.asarray(expr.execute(), dtype=dtype))
np.testing.assert_array_equal(result, expected)
@pytest.mark.parametrize(
"interactive",
[
param(
True,
marks=pytest.mark.notimpl(["flink"], raises=NotImplementedError),
),
False,
],
)
def test_repr(alltypes, interactive, monkeypatch):
monkeypatch.setattr(ibis.options, "interactive", interactive)
expr = alltypes.select("date_string_col")
s = repr(expr)
# no control characters
assert all(c.isprintable() or c in "\n\r\t" for c in s)
if interactive:
assert "/" in s
else:
assert "/" not in s
@pytest.mark.parametrize("show_types", [True, False])
@pytest.mark.notimpl(["flink"], raises=NotImplementedError)