forked from pandas-dev/pandas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_sql.py
2944 lines (2407 loc) · 99.9 KB
/
test_sql.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
"""SQL io tests
The SQL tests are broken down in different classes:
- `PandasSQLTest`: base class with common methods for all test classes
- Tests for the public API (only tests with sqlite3)
- `_TestSQLApi` base class
- `TestSQLApi`: test the public API with sqlalchemy engine
- `TestSQLiteFallbackApi`: test the public API with a sqlite DBAPI
connection
- Tests for the different SQL flavors (flavor specific type conversions)
- Tests for the sqlalchemy mode: `_TestSQLAlchemy` is the base class with
common methods. The different tested flavors (sqlite3, MySQL,
PostgreSQL) derive from the base class
- Tests for the fallback mode (`TestSQLiteFallback`)
"""
from __future__ import annotations
import contextlib
from contextlib import closing
import csv
from datetime import (
date,
datetime,
time,
)
from io import StringIO
from pathlib import Path
import sqlite3
import numpy as np
import pytest
import pandas.util._test_decorators as td
from pandas.core.dtypes.common import (
is_datetime64_dtype,
is_datetime64tz_dtype,
)
import pandas as pd
from pandas import (
DataFrame,
Index,
MultiIndex,
Series,
Timestamp,
concat,
date_range,
isna,
to_datetime,
to_timedelta,
)
import pandas._testing as tm
from pandas.io import sql
from pandas.io.sql import (
SQLAlchemyEngine,
SQLDatabase,
SQLiteDatabase,
get_engine,
pandasSQL_builder,
read_sql_query,
read_sql_table,
)
try:
import sqlalchemy
SQLALCHEMY_INSTALLED = True
except ImportError:
SQLALCHEMY_INSTALLED = False
SQL_STRINGS = {
"read_parameters": {
"sqlite": "SELECT * FROM iris WHERE Name=? AND SepalLength=?",
"mysql": "SELECT * FROM iris WHERE `Name`=%s AND `SepalLength`=%s",
"postgresql": 'SELECT * FROM iris WHERE "Name"=%s AND "SepalLength"=%s',
},
"read_named_parameters": {
"sqlite": """
SELECT * FROM iris WHERE Name=:name AND SepalLength=:length
""",
"mysql": """
SELECT * FROM iris WHERE
`Name`=%(name)s AND `SepalLength`=%(length)s
""",
"postgresql": """
SELECT * FROM iris WHERE
"Name"=%(name)s AND "SepalLength"=%(length)s
""",
},
"read_no_parameters_with_percent": {
"sqlite": "SELECT * FROM iris WHERE Name LIKE '%'",
"mysql": "SELECT * FROM iris WHERE `Name` LIKE '%'",
"postgresql": "SELECT * FROM iris WHERE \"Name\" LIKE '%'",
},
}
def iris_table_metadata(dialect: str):
from sqlalchemy import (
REAL,
Column,
Float,
MetaData,
String,
Table,
)
dtype = Float if dialect == "postgresql" else REAL
metadata = MetaData()
iris = Table(
"iris",
metadata,
Column("SepalLength", dtype),
Column("SepalWidth", dtype),
Column("PetalLength", dtype),
Column("PetalWidth", dtype),
Column("Name", String(200)),
)
return iris
def create_and_load_iris_sqlite3(conn: sqlite3.Connection, iris_file: Path):
cur = conn.cursor()
stmt = """CREATE TABLE iris (
"SepalLength" REAL,
"SepalWidth" REAL,
"PetalLength" REAL,
"PetalWidth" REAL,
"Name" TEXT
)"""
cur.execute(stmt)
with iris_file.open(newline=None) as csvfile:
reader = csv.reader(csvfile)
next(reader)
stmt = "INSERT INTO iris VALUES(?, ?, ?, ?, ?)"
cur.executemany(stmt, reader)
def create_and_load_iris(conn, iris_file: Path, dialect: str):
from sqlalchemy import insert
from sqlalchemy.engine import Engine
iris = iris_table_metadata(dialect)
iris.drop(conn, checkfirst=True)
iris.create(bind=conn)
with iris_file.open(newline=None) as csvfile:
reader = csv.reader(csvfile)
header = next(reader)
params = [dict(zip(header, row)) for row in reader]
stmt = insert(iris).values(params)
if isinstance(conn, Engine):
with conn.connect() as conn:
with conn.begin():
conn.execute(stmt)
else:
conn.execute(stmt)
def create_and_load_iris_view(conn):
stmt = "CREATE VIEW iris_view AS SELECT * FROM iris"
if isinstance(conn, sqlite3.Connection):
cur = conn.cursor()
cur.execute(stmt)
else:
from sqlalchemy import text
from sqlalchemy.engine import Engine
stmt = text(stmt)
if isinstance(conn, Engine):
with conn.connect() as conn:
with conn.begin():
conn.execute(stmt)
else:
conn.execute(stmt)
def types_table_metadata(dialect: str):
from sqlalchemy import (
TEXT,
Boolean,
Column,
DateTime,
Float,
Integer,
MetaData,
Table,
)
date_type = TEXT if dialect == "sqlite" else DateTime
bool_type = Integer if dialect == "sqlite" else Boolean
metadata = MetaData()
types = Table(
"types",
metadata,
Column("TextCol", TEXT),
Column("DateCol", date_type),
Column("IntDateCol", Integer),
Column("IntDateOnlyCol", Integer),
Column("FloatCol", Float),
Column("IntCol", Integer),
Column("BoolCol", bool_type),
Column("IntColWithNull", Integer),
Column("BoolColWithNull", bool_type),
)
if dialect == "postgresql":
types.append_column(Column("DateColWithTz", DateTime(timezone=True)))
return types
def create_and_load_types_sqlite3(conn: sqlite3.Connection, types_data: list[dict]):
cur = conn.cursor()
stmt = """CREATE TABLE types (
"TextCol" TEXT,
"DateCol" TEXT,
"IntDateCol" INTEGER,
"IntDateOnlyCol" INTEGER,
"FloatCol" REAL,
"IntCol" INTEGER,
"BoolCol" INTEGER,
"IntColWithNull" INTEGER,
"BoolColWithNull" INTEGER
)"""
cur.execute(stmt)
stmt = """
INSERT INTO types
VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)
"""
cur.executemany(stmt, types_data)
def create_and_load_types(conn, types_data: list[dict], dialect: str):
from sqlalchemy import insert
from sqlalchemy.engine import Engine
types = types_table_metadata(dialect)
types.drop(conn, checkfirst=True)
types.create(bind=conn)
stmt = insert(types).values(types_data)
if isinstance(conn, Engine):
with conn.connect() as conn:
with conn.begin():
conn.execute(stmt)
else:
conn.execute(stmt)
def check_iris_frame(frame: DataFrame):
pytype = frame.dtypes[0].type
row = frame.iloc[0]
assert issubclass(pytype, np.floating)
tm.equalContents(row.values, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
def count_rows(conn, table_name: str):
stmt = f"SELECT count(*) AS count_1 FROM {table_name}"
if isinstance(conn, sqlite3.Connection):
cur = conn.cursor()
result = cur.execute(stmt)
else:
from sqlalchemy import text
from sqlalchemy.engine import Engine
stmt = text(stmt)
if isinstance(conn, Engine):
with conn.connect() as conn:
result = conn.execute(stmt)
else:
result = conn.execute(stmt)
return result.fetchone()[0]
@pytest.fixture
def iris_path(datapath):
iris_path = datapath("io", "data", "csv", "iris.csv")
return Path(iris_path)
@pytest.fixture
def types_data():
return [
{
"TextCol": "first",
"DateCol": "2000-01-03 00:00:00",
"IntDateCol": 535852800,
"IntDateOnlyCol": 20101010,
"FloatCol": 10.10,
"IntCol": 1,
"BoolCol": False,
"IntColWithNull": 1,
"BoolColWithNull": False,
"DateColWithTz": "2000-01-01 00:00:00-08:00",
},
{
"TextCol": "first",
"DateCol": "2000-01-04 00:00:00",
"IntDateCol": 1356998400,
"IntDateOnlyCol": 20101212,
"FloatCol": 10.10,
"IntCol": 1,
"BoolCol": False,
"IntColWithNull": None,
"BoolColWithNull": None,
"DateColWithTz": "2000-06-01 00:00:00-07:00",
},
]
@pytest.fixture
def types_data_frame(types_data):
dtypes = {
"TextCol": "str",
"DateCol": "str",
"IntDateCol": "int64",
"IntDateOnlyCol": "int64",
"FloatCol": "float",
"IntCol": "int64",
"BoolCol": "int64",
"IntColWithNull": "float",
"BoolColWithNull": "float",
}
df = DataFrame(types_data)
return df[dtypes.keys()].astype(dtypes)
@pytest.fixture
def test_frame1():
columns = ["index", "A", "B", "C", "D"]
data = [
(
"2000-01-03 00:00:00",
0.980268513777,
3.68573087906,
-0.364216805298,
-1.15973806169,
),
(
"2000-01-04 00:00:00",
1.04791624281,
-0.0412318367011,
-0.16181208307,
0.212549316967,
),
(
"2000-01-05 00:00:00",
0.498580885705,
0.731167677815,
-0.537677223318,
1.34627041952,
),
(
"2000-01-06 00:00:00",
1.12020151869,
1.56762092543,
0.00364077397681,
0.67525259227,
),
]
return DataFrame(data, columns=columns)
@pytest.fixture
def test_frame3():
columns = ["index", "A", "B"]
data = [
("2000-01-03 00:00:00", 2**31 - 1, -1.987670),
("2000-01-04 00:00:00", -29, -0.0412318367011),
("2000-01-05 00:00:00", 20000, 0.731167677815),
("2000-01-06 00:00:00", -290867, 1.56762092543),
]
return DataFrame(data, columns=columns)
@pytest.fixture
def mysql_pymysql_engine(iris_path, types_data):
sqlalchemy = pytest.importorskip("sqlalchemy")
pymysql = pytest.importorskip("pymysql")
engine = sqlalchemy.create_engine(
"mysql+pymysql://root@localhost:3306/pandas",
connect_args={"client_flag": pymysql.constants.CLIENT.MULTI_STATEMENTS},
)
insp = sqlalchemy.inspect(engine)
if not insp.has_table("iris"):
create_and_load_iris(engine, iris_path, "mysql")
if not insp.has_table("types"):
for entry in types_data:
entry.pop("DateColWithTz")
create_and_load_types(engine, types_data, "mysql")
yield engine
with engine.connect() as conn:
with conn.begin():
stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;")
conn.execute(stmt)
engine.dispose()
@pytest.fixture
def mysql_pymysql_conn(mysql_pymysql_engine):
yield mysql_pymysql_engine.connect()
@pytest.fixture
def postgresql_psycopg2_engine(iris_path, types_data):
sqlalchemy = pytest.importorskip("sqlalchemy")
pytest.importorskip("psycopg2")
engine = sqlalchemy.create_engine(
"postgresql+psycopg2://postgres:postgres@localhost:5432/pandas"
)
insp = sqlalchemy.inspect(engine)
if not insp.has_table("iris"):
create_and_load_iris(engine, iris_path, "postgresql")
if not insp.has_table("types"):
create_and_load_types(engine, types_data, "postgresql")
yield engine
with engine.connect() as conn:
with conn.begin():
stmt = sqlalchemy.text("DROP TABLE IF EXISTS test_frame;")
conn.execute(stmt)
engine.dispose()
@pytest.fixture
def postgresql_psycopg2_conn(postgresql_psycopg2_engine):
yield postgresql_psycopg2_engine.connect()
@pytest.fixture
def sqlite_engine():
sqlalchemy = pytest.importorskip("sqlalchemy")
engine = sqlalchemy.create_engine("sqlite://")
yield engine
engine.dispose()
@pytest.fixture
def sqlite_conn(sqlite_engine):
yield sqlite_engine.connect()
@pytest.fixture
def sqlite_iris_engine(sqlite_engine, iris_path):
create_and_load_iris(sqlite_engine, iris_path, "sqlite")
return sqlite_engine
@pytest.fixture
def sqlite_iris_conn(sqlite_iris_engine):
yield sqlite_iris_engine.connect()
@pytest.fixture
def sqlite_buildin():
with contextlib.closing(sqlite3.connect(":memory:")) as closing_conn:
with closing_conn as conn:
yield conn
@pytest.fixture
def sqlite_buildin_iris(sqlite_buildin, iris_path):
create_and_load_iris_sqlite3(sqlite_buildin, iris_path)
return sqlite_buildin
mysql_connectable = [
"mysql_pymysql_engine",
"mysql_pymysql_conn",
]
postgresql_connectable = [
"postgresql_psycopg2_engine",
"postgresql_psycopg2_conn",
]
sqlite_connectable = [
"sqlite_engine",
"sqlite_conn",
]
sqlite_iris_connectable = [
"sqlite_iris_engine",
"sqlite_iris_conn",
]
sqlalchemy_connectable = mysql_connectable + postgresql_connectable + sqlite_connectable
sqlalchemy_connectable_iris = (
mysql_connectable + postgresql_connectable + sqlite_iris_connectable
)
all_connectable = sqlalchemy_connectable + ["sqlite_buildin"]
all_connectable_iris = sqlalchemy_connectable_iris + ["sqlite_buildin_iris"]
@pytest.mark.db
@pytest.mark.parametrize("conn", all_connectable)
@pytest.mark.parametrize("method", [None, "multi"])
def test_to_sql(conn, method, test_frame1, request):
conn = request.getfixturevalue(conn)
with pandasSQL_builder(conn) as pandasSQL:
pandasSQL.to_sql(test_frame1, "test_frame", method=method)
assert pandasSQL.has_table("test_frame")
assert count_rows(conn, "test_frame") == len(test_frame1)
@pytest.mark.db
@pytest.mark.parametrize("conn", all_connectable)
@pytest.mark.parametrize("mode, num_row_coef", [("replace", 1), ("append", 2)])
def test_to_sql_exist(conn, mode, num_row_coef, test_frame1, request):
conn = request.getfixturevalue(conn)
with pandasSQL_builder(conn) as pandasSQL:
pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
pandasSQL.to_sql(test_frame1, "test_frame", if_exists=mode)
assert pandasSQL.has_table("test_frame")
assert count_rows(conn, "test_frame") == num_row_coef * len(test_frame1)
@pytest.mark.db
@pytest.mark.parametrize("conn", all_connectable)
def test_to_sql_exist_fail(conn, test_frame1, request):
conn = request.getfixturevalue(conn)
with pandasSQL_builder(conn) as pandasSQL:
pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
assert pandasSQL.has_table("test_frame")
msg = "Table 'test_frame' already exists"
with pytest.raises(ValueError, match=msg):
pandasSQL.to_sql(test_frame1, "test_frame", if_exists="fail")
@pytest.mark.db
@pytest.mark.parametrize("conn", all_connectable_iris)
def test_read_iris(conn, request):
conn = request.getfixturevalue(conn)
with pandasSQL_builder(conn) as pandasSQL:
iris_frame = pandasSQL.read_query("SELECT * FROM iris")
check_iris_frame(iris_frame)
@pytest.mark.db
@pytest.mark.parametrize("conn", sqlalchemy_connectable)
def test_to_sql_callable(conn, test_frame1, request):
conn = request.getfixturevalue(conn)
check = [] # used to double check function below is really being used
def sample(pd_table, conn, keys, data_iter):
check.append(1)
data = [dict(zip(keys, row)) for row in data_iter]
conn.execute(pd_table.table.insert(), data)
with pandasSQL_builder(conn) as pandasSQL:
pandasSQL.to_sql(test_frame1, "test_frame", method=sample)
assert pandasSQL.has_table("test_frame")
assert check == [1]
assert count_rows(conn, "test_frame") == len(test_frame1)
@pytest.mark.db
@pytest.mark.parametrize("conn", mysql_connectable)
def test_default_type_conversion(conn, request):
conn = request.getfixturevalue(conn)
df = sql.read_sql_table("types", conn)
assert issubclass(df.FloatCol.dtype.type, np.floating)
assert issubclass(df.IntCol.dtype.type, np.integer)
# MySQL has no real BOOL type (it's an alias for TINYINT)
assert issubclass(df.BoolCol.dtype.type, np.integer)
# Int column with NA values stays as float
assert issubclass(df.IntColWithNull.dtype.type, np.floating)
# Bool column with NA = int column with NA values => becomes float
assert issubclass(df.BoolColWithNull.dtype.type, np.floating)
@pytest.mark.db
@pytest.mark.parametrize("conn", mysql_connectable)
def test_read_procedure(conn, request):
conn = request.getfixturevalue(conn)
# GH 7324
# Although it is more an api test, it is added to the
# mysql tests as sqlite does not have stored procedures
from sqlalchemy import text
from sqlalchemy.engine import Engine
df = DataFrame({"a": [1, 2, 3], "b": [0.1, 0.2, 0.3]})
df.to_sql("test_frame", conn, index=False)
proc = """DROP PROCEDURE IF EXISTS get_testdb;
CREATE PROCEDURE get_testdb ()
BEGIN
SELECT * FROM test_frame;
END"""
proc = text(proc)
if isinstance(conn, Engine):
with conn.connect() as engine_conn:
with engine_conn.begin():
engine_conn.execute(proc)
else:
conn.execute(proc)
res1 = sql.read_sql_query("CALL get_testdb();", conn)
tm.assert_frame_equal(df, res1)
# test delegation to read_sql_query
res2 = sql.read_sql("CALL get_testdb();", conn)
tm.assert_frame_equal(df, res2)
@pytest.mark.db
@pytest.mark.parametrize("conn", postgresql_connectable)
@pytest.mark.parametrize("expected_count", [2, "Success!"])
def test_copy_from_callable_insertion_method(conn, expected_count, request):
# GH 8953
# Example in io.rst found under _io.sql.method
# not available in sqlite, mysql
def psql_insert_copy(table, conn, keys, data_iter):
# gets a DBAPI connection that can provide a cursor
dbapi_conn = conn.connection
with dbapi_conn.cursor() as cur:
s_buf = StringIO()
writer = csv.writer(s_buf)
writer.writerows(data_iter)
s_buf.seek(0)
columns = ", ".join([f'"{k}"' for k in keys])
if table.schema:
table_name = f"{table.schema}.{table.name}"
else:
table_name = table.name
sql_query = f"COPY {table_name} ({columns}) FROM STDIN WITH CSV"
cur.copy_expert(sql=sql_query, file=s_buf)
return expected_count
conn = request.getfixturevalue(conn)
expected = DataFrame({"col1": [1, 2], "col2": [0.1, 0.2], "col3": ["a", "n"]})
result_count = expected.to_sql(
"test_frame", conn, index=False, method=psql_insert_copy
)
# GH 46891
if not isinstance(expected_count, int):
assert result_count is None
else:
assert result_count == expected_count
result = sql.read_sql_table("test_frame", conn)
tm.assert_frame_equal(result, expected)
class MixInBase:
def teardown_method(self):
# if setup fails, there may not be a connection to close.
if hasattr(self, "conn"):
self.conn.close()
# use a fresh connection to ensure we can drop all tables.
try:
conn = self.connect()
except (sqlalchemy.exc.OperationalError, sqlite3.OperationalError):
pass
else:
with conn:
for tbl in self._get_all_tables(conn):
self.drop_table(tbl, conn)
class SQLiteMixIn(MixInBase):
def connect(self):
return sqlite3.connect(":memory:")
def drop_table(self, table_name, conn):
conn.execute(f"DROP TABLE IF EXISTS {sql._get_valid_sqlite_name(table_name)}")
conn.commit()
def _get_all_tables(self, conn):
c = conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
return [table[0] for table in c.fetchall()]
class SQLAlchemyMixIn(MixInBase):
@classmethod
def teardown_class(cls):
cls.engine.dispose()
def connect(self):
return self.engine.connect()
def drop_table(self, table_name, conn):
with conn.begin():
sql.SQLDatabase(conn).drop_table(table_name)
def _get_all_tables(self, conn):
from sqlalchemy import inspect
return inspect(conn).get_table_names()
class PandasSQLTest:
"""
Base class with common private methods for SQLAlchemy and fallback cases.
"""
def load_iris_data(self, iris_path):
self.drop_table("iris", self.conn)
if isinstance(self.conn, sqlite3.Connection):
create_and_load_iris_sqlite3(self.conn, iris_path)
else:
create_and_load_iris(self.conn, iris_path, self.flavor)
def load_types_data(self, types_data):
if self.flavor != "postgresql":
for entry in types_data:
entry.pop("DateColWithTz")
if isinstance(self.conn, sqlite3.Connection):
types_data = [tuple(entry.values()) for entry in types_data]
create_and_load_types_sqlite3(self.conn, types_data)
else:
create_and_load_types(self.conn, types_data, self.flavor)
def _read_sql_iris_parameter(self):
query = SQL_STRINGS["read_parameters"][self.flavor]
params = ["Iris-setosa", 5.1]
iris_frame = self.pandasSQL.read_query(query, params=params)
check_iris_frame(iris_frame)
def _read_sql_iris_named_parameter(self):
query = SQL_STRINGS["read_named_parameters"][self.flavor]
params = {"name": "Iris-setosa", "length": 5.1}
iris_frame = self.pandasSQL.read_query(query, params=params)
check_iris_frame(iris_frame)
def _read_sql_iris_no_parameter_with_percent(self):
query = SQL_STRINGS["read_no_parameters_with_percent"][self.flavor]
iris_frame = self.pandasSQL.read_query(query, params=None)
check_iris_frame(iris_frame)
def _to_sql_empty(self, test_frame1):
self.drop_table("test_frame1", self.conn)
assert self.pandasSQL.to_sql(test_frame1.iloc[:0], "test_frame1") == 0
def _to_sql_with_sql_engine(self, test_frame1, engine="auto", **engine_kwargs):
"""`to_sql` with the `engine` param"""
# mostly copied from this class's `_to_sql()` method
self.drop_table("test_frame1", self.conn)
assert (
self.pandasSQL.to_sql(
test_frame1, "test_frame1", engine=engine, **engine_kwargs
)
== 4
)
assert self.pandasSQL.has_table("test_frame1")
num_entries = len(test_frame1)
num_rows = count_rows(self.conn, "test_frame1")
assert num_rows == num_entries
# Nuke table
self.drop_table("test_frame1", self.conn)
def _roundtrip(self, test_frame1):
self.drop_table("test_frame_roundtrip", self.conn)
assert self.pandasSQL.to_sql(test_frame1, "test_frame_roundtrip") == 4
result = self.pandasSQL.read_query("SELECT * FROM test_frame_roundtrip")
result.set_index("level_0", inplace=True)
# result.index.astype(int)
result.index.name = None
tm.assert_frame_equal(result, test_frame1)
def _execute_sql(self):
# drop_sql = "DROP TABLE IF EXISTS test" # should already be done
iris_results = self.pandasSQL.execute("SELECT * FROM iris")
row = iris_results.fetchone()
tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
def _to_sql_save_index(self):
df = DataFrame.from_records(
[(1, 2.1, "line1"), (2, 1.5, "line2")], columns=["A", "B", "C"], index=["A"]
)
assert self.pandasSQL.to_sql(df, "test_to_sql_saves_index") == 2
ix_cols = self._get_index_columns("test_to_sql_saves_index")
assert ix_cols == [["A"]]
def _transaction_test(self):
with self.pandasSQL.run_transaction() as trans:
stmt = "CREATE TABLE test_trans (A INT, B TEXT)"
if isinstance(self.pandasSQL, SQLiteDatabase):
trans.execute(stmt)
else:
from sqlalchemy import text
stmt = text(stmt)
trans.execute(stmt)
class DummyException(Exception):
pass
# Make sure when transaction is rolled back, no rows get inserted
ins_sql = "INSERT INTO test_trans (A,B) VALUES (1, 'blah')"
if isinstance(self.pandasSQL, SQLDatabase):
from sqlalchemy import text
ins_sql = text(ins_sql)
try:
with self.pandasSQL.run_transaction() as trans:
trans.execute(ins_sql)
raise DummyException("error")
except DummyException:
# ignore raised exception
pass
res = self.pandasSQL.read_query("SELECT * FROM test_trans")
assert len(res) == 0
# Make sure when transaction is committed, rows do get inserted
with self.pandasSQL.run_transaction() as trans:
trans.execute(ins_sql)
res2 = self.pandasSQL.read_query("SELECT * FROM test_trans")
assert len(res2) == 1
# -----------------------------------------------------------------------------
# -- Testing the public API
class _TestSQLApi(PandasSQLTest):
"""
Base class to test the public API.
From this two classes are derived to run these tests for both the
sqlalchemy mode (`TestSQLApi`) and the fallback mode
(`TestSQLiteFallbackApi`). These tests are run with sqlite3. Specific
tests for the different sql flavours are included in `_TestSQLAlchemy`.
Notes:
flavor can always be passed even in SQLAlchemy mode,
should be correctly ignored.
we don't use drop_table because that isn't part of the public api
"""
flavor = "sqlite"
mode: str
@pytest.fixture(autouse=True)
def setup_method(self, iris_path, types_data):
self.conn = self.connect()
if not isinstance(self.conn, sqlite3.Connection):
self.conn.begin()
self.load_iris_data(iris_path)
self.load_types_data(types_data)
self.load_test_data_and_sql()
def load_test_data_and_sql(self):
create_and_load_iris_view(self.conn)
def test_read_sql_view(self):
iris_frame = sql.read_sql_query("SELECT * FROM iris_view", self.conn)
check_iris_frame(iris_frame)
def test_read_sql_with_chunksize_no_result(self):
query = "SELECT * FROM iris_view WHERE SepalLength < 0.0"
with_batch = sql.read_sql_query(query, self.conn, chunksize=5)
without_batch = sql.read_sql_query(query, self.conn)
tm.assert_frame_equal(concat(with_batch), without_batch)
def test_to_sql(self, test_frame1):
sql.to_sql(test_frame1, "test_frame1", self.conn)
assert sql.has_table("test_frame1", self.conn)
def test_to_sql_fail(self, test_frame1):
sql.to_sql(test_frame1, "test_frame2", self.conn, if_exists="fail")
assert sql.has_table("test_frame2", self.conn)
msg = "Table 'test_frame2' already exists"
with pytest.raises(ValueError, match=msg):
sql.to_sql(test_frame1, "test_frame2", self.conn, if_exists="fail")
def test_to_sql_replace(self, test_frame1):
sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="fail")
# Add to table again
sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="replace")
assert sql.has_table("test_frame3", self.conn)
num_entries = len(test_frame1)
num_rows = count_rows(self.conn, "test_frame3")
assert num_rows == num_entries
def test_to_sql_truncate(self, test_frame1):
sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="fail")
# Add to table again
sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists="truncate")
assert sql.has_table("test_frame3", self.conn)
num_entries = len(test_frame1)
num_rows = count_rows(self.conn, "test_frame3")
assert num_rows == num_entries
def test_to_sql_truncate_no_table(self, test_frame1):
# creates new table if table doesn't exist
sql.to_sql(test_frame1, "test_frame_new", self.conn, if_exists="truncate")
assert sql.has_table("test_frame_new")
def test_to_sql_truncate_new_columns(self, test_frame1, test_frame3):
sql.to_sql(test_frame3, "test_frame3", self.conn, if_exists='fail')
# truncate and attempt to add more columns
msg = "table test_frame3 has no column named C"
with pytest.raises(Exception, match=msg):
sql.to_sql(test_frame1, "test_frame3", self.conn, if_exists='truncate')
def test_to_sql_append(self, test_frame1):
assert sql.to_sql(test_frame1, "test_frame4", self.conn, if_exists="fail") == 4
# Add to table again
assert (
sql.to_sql(test_frame1, "test_frame4", self.conn, if_exists="append") == 4
)
assert sql.has_table("test_frame4", self.conn)
num_entries = 2 * len(test_frame1)
num_rows = count_rows(self.conn, "test_frame4")
assert num_rows == num_entries
def test_to_sql_type_mapping(self, test_frame3):
sql.to_sql(test_frame3, "test_frame5", self.conn, index=False)
result = sql.read_sql("SELECT * FROM test_frame5", self.conn)
tm.assert_frame_equal(test_frame3, result)
def test_to_sql_series(self):
s = Series(np.arange(5, dtype="int64"), name="series")
sql.to_sql(s, "test_series", self.conn, index=False)
s2 = sql.read_sql_query("SELECT * FROM test_series", self.conn)
tm.assert_frame_equal(s.to_frame(), s2)
def test_roundtrip(self, test_frame1):
sql.to_sql(test_frame1, "test_frame_roundtrip", con=self.conn)
result = sql.read_sql_query("SELECT * FROM test_frame_roundtrip", con=self.conn)
# HACK!
result.index = test_frame1.index
result.set_index("level_0", inplace=True)
result.index.astype(int)
result.index.name = None
tm.assert_frame_equal(result, test_frame1)
def test_roundtrip_chunksize(self, test_frame1):
sql.to_sql(
test_frame1,
"test_frame_roundtrip",
con=self.conn,
index=False,
chunksize=2,
)
result = sql.read_sql_query("SELECT * FROM test_frame_roundtrip", con=self.conn)
tm.assert_frame_equal(result, test_frame1)
def test_execute_sql(self):
# drop_sql = "DROP TABLE IF EXISTS test" # should already be done
iris_results = sql.execute("SELECT * FROM iris", con=self.conn)
row = iris_results.fetchone()
tm.equalContents(row, [5.1, 3.5, 1.4, 0.2, "Iris-setosa"])
def test_date_parsing(self):
# Test date parsing in read_sql
# No Parsing
df = sql.read_sql_query("SELECT * FROM types", self.conn)
assert not issubclass(df.DateCol.dtype.type, np.datetime64)
df = sql.read_sql_query(
"SELECT * FROM types", self.conn, parse_dates=["DateCol"]
)
assert issubclass(df.DateCol.dtype.type, np.datetime64)
assert df.DateCol.tolist() == [
Timestamp(2000, 1, 3, 0, 0, 0),
Timestamp(2000, 1, 4, 0, 0, 0),
]
df = sql.read_sql_query(
"SELECT * FROM types",