18
18
"""
19
19
from __future__ import annotations
20
20
21
+ import contextlib
21
22
from contextlib import closing
22
23
import csv
23
24
from datetime import (
@@ -456,8 +457,9 @@ def sqlite_iris_conn(sqlite_iris_engine):
456
457
457
458
@pytest .fixture
458
459
def sqlite_buildin ():
459
- with sqlite3 .connect (":memory:" ) as conn :
460
- yield conn
460
+ with contextlib .closing (sqlite3 .connect (":memory:" )) as closing_conn :
461
+ with closing_conn as conn :
462
+ yield conn
461
463
462
464
463
465
@pytest .fixture
@@ -1561,9 +1563,12 @@ def __init__(self, *args, **kwargs) -> None:
1561
1563
def __getattr__ (self , name ):
1562
1564
return getattr (self .conn , name )
1563
1565
1564
- conn = MockSqliteConnection (":memory:" )
1565
- with tm .assert_produces_warning (UserWarning ):
1566
- sql .read_sql ("SELECT 1" , conn )
1566
+ def close (self ):
1567
+ self .conn .close ()
1568
+
1569
+ with contextlib .closing (MockSqliteConnection (":memory:" )) as conn :
1570
+ with tm .assert_produces_warning (UserWarning ):
1571
+ sql .read_sql ("SELECT 1" , conn )
1567
1572
1568
1573
def test_read_sql_delegate (self ):
1569
1574
iris_frame1 = sql .read_sql_query ("SELECT * FROM iris" , self .conn )
@@ -1945,7 +1950,7 @@ def test_datetime_date(self):
1945
1950
# comes back as datetime64
1946
1951
tm .assert_series_equal (result , expected )
1947
1952
1948
- def test_datetime_time (self ):
1953
+ def test_datetime_time (self , sqlite_buildin ):
1949
1954
# test support for datetime.time
1950
1955
df = DataFrame ([time (9 , 0 , 0 ), time (9 , 1 , 30 )], columns = ["a" ])
1951
1956
assert df .to_sql ("test_time" , self .conn , index = False ) == 2
@@ -1954,7 +1959,7 @@ def test_datetime_time(self):
1954
1959
1955
1960
# GH8341
1956
1961
# first, use the fallback to have the sqlite adapter put in place
1957
- sqlite_conn = TestSQLiteFallback . connect ()
1962
+ sqlite_conn = sqlite_buildin
1958
1963
assert sql .to_sql (df , "test_time2" , sqlite_conn , index = False ) == 2
1959
1964
res = sql .read_sql_query ("SELECT * FROM test_time2" , sqlite_conn )
1960
1965
ref = df .applymap (lambda _ : _ .strftime ("%H:%M:%S.%f" ))
@@ -2762,21 +2767,17 @@ def tquery(query, con=None):
2762
2767
2763
2768
2764
2769
class TestXSQLite :
2765
- def setup_method (self ):
2766
- self .conn = sqlite3 .connect (":memory:" )
2767
-
2768
- def teardown_method (self ):
2769
- self .conn .close ()
2770
-
2771
- def drop_table (self , table_name ):
2772
- cur = self .conn .cursor ()
2770
+ def drop_table (self , table_name , conn ):
2771
+ cur = conn .cursor ()
2773
2772
cur .execute (f"DROP TABLE IF EXISTS { sql ._get_valid_sqlite_name (table_name )} " )
2774
- self . conn .commit ()
2773
+ conn .commit ()
2775
2774
2776
- def test_basic (self ):
2775
+ def test_basic (self , sqlite_buildin ):
2777
2776
frame = tm .makeTimeDataFrame ()
2778
- assert sql .to_sql (frame , name = "test_table" , con = self .conn , index = False ) == 30
2779
- result = sql .read_sql ("select * from test_table" , self .conn )
2777
+ assert (
2778
+ sql .to_sql (frame , name = "test_table" , con = sqlite_buildin , index = False ) == 30
2779
+ )
2780
+ result = sql .read_sql ("select * from test_table" , sqlite_buildin )
2780
2781
2781
2782
# HACK! Change this once indexes are handled properly.
2782
2783
result .index = frame .index
@@ -2788,47 +2789,52 @@ def test_basic(self):
2788
2789
frame2 = frame .copy ()
2789
2790
new_idx = Index (np .arange (len (frame2 ))) + 10
2790
2791
frame2 ["Idx" ] = new_idx .copy ()
2791
- assert sql .to_sql (frame2 , name = "test_table2" , con = self .conn , index = False ) == 30
2792
- result = sql .read_sql ("select * from test_table2" , self .conn , index_col = "Idx" )
2792
+ assert (
2793
+ sql .to_sql (frame2 , name = "test_table2" , con = sqlite_buildin , index = False )
2794
+ == 30
2795
+ )
2796
+ result = sql .read_sql (
2797
+ "select * from test_table2" , sqlite_buildin , index_col = "Idx"
2798
+ )
2793
2799
expected = frame .copy ()
2794
2800
expected .index = new_idx
2795
2801
expected .index .name = "Idx"
2796
2802
tm .assert_frame_equal (expected , result )
2797
2803
2798
- def test_write_row_by_row (self ):
2804
+ def test_write_row_by_row (self , sqlite_buildin ):
2799
2805
frame = tm .makeTimeDataFrame ()
2800
2806
frame .iloc [0 , 0 ] = np .nan
2801
2807
create_sql = sql .get_schema (frame , "test" )
2802
- cur = self . conn .cursor ()
2808
+ cur = sqlite_buildin .cursor ()
2803
2809
cur .execute (create_sql )
2804
2810
2805
2811
ins = "INSERT INTO test VALUES (%s, %s, %s, %s)"
2806
2812
for _ , row in frame .iterrows ():
2807
2813
fmt_sql = format_query (ins , * row )
2808
- tquery (fmt_sql , con = self . conn )
2814
+ tquery (fmt_sql , con = sqlite_buildin )
2809
2815
2810
- self . conn .commit ()
2816
+ sqlite_buildin .commit ()
2811
2817
2812
- result = sql .read_sql ("select * from test" , con = self . conn )
2818
+ result = sql .read_sql ("select * from test" , con = sqlite_buildin )
2813
2819
result .index = frame .index
2814
2820
tm .assert_frame_equal (result , frame , rtol = 1e-3 )
2815
2821
2816
- def test_execute (self ):
2822
+ def test_execute (self , sqlite_buildin ):
2817
2823
frame = tm .makeTimeDataFrame ()
2818
2824
create_sql = sql .get_schema (frame , "test" )
2819
- cur = self . conn .cursor ()
2825
+ cur = sqlite_buildin .cursor ()
2820
2826
cur .execute (create_sql )
2821
2827
ins = "INSERT INTO test VALUES (?, ?, ?, ?)"
2822
2828
2823
2829
row = frame .iloc [0 ]
2824
- sql .execute (ins , self . conn , params = tuple (row ))
2825
- self . conn .commit ()
2830
+ sql .execute (ins , sqlite_buildin , params = tuple (row ))
2831
+ sqlite_buildin .commit ()
2826
2832
2827
- result = sql .read_sql ("select * from test" , self . conn )
2833
+ result = sql .read_sql ("select * from test" , sqlite_buildin )
2828
2834
result .index = frame .index [:1 ]
2829
2835
tm .assert_frame_equal (result , frame [:1 ])
2830
2836
2831
- def test_schema (self ):
2837
+ def test_schema (self , sqlite_buildin ):
2832
2838
frame = tm .makeTimeDataFrame ()
2833
2839
create_sql = sql .get_schema (frame , "test" )
2834
2840
lines = create_sql .splitlines ()
@@ -2840,10 +2846,10 @@ def test_schema(self):
2840
2846
create_sql = sql .get_schema (frame , "test" , keys = ["A" , "B" ])
2841
2847
lines = create_sql .splitlines ()
2842
2848
assert 'PRIMARY KEY ("A", "B")' in create_sql
2843
- cur = self . conn .cursor ()
2849
+ cur = sqlite_buildin .cursor ()
2844
2850
cur .execute (create_sql )
2845
2851
2846
- def test_execute_fail (self ):
2852
+ def test_execute_fail (self , sqlite_buildin ):
2847
2853
create_sql = """
2848
2854
CREATE TABLE test
2849
2855
(
@@ -2853,14 +2859,14 @@ def test_execute_fail(self):
2853
2859
PRIMARY KEY (a, b)
2854
2860
);
2855
2861
"""
2856
- cur = self . conn .cursor ()
2862
+ cur = sqlite_buildin .cursor ()
2857
2863
cur .execute (create_sql )
2858
2864
2859
- sql .execute ('INSERT INTO test VALUES("foo", "bar", 1.234)' , self . conn )
2860
- sql .execute ('INSERT INTO test VALUES("foo", "baz", 2.567)' , self . conn )
2865
+ sql .execute ('INSERT INTO test VALUES("foo", "bar", 1.234)' , sqlite_buildin )
2866
+ sql .execute ('INSERT INTO test VALUES("foo", "baz", 2.567)' , sqlite_buildin )
2861
2867
2862
2868
with pytest .raises (sql .DatabaseError , match = "Execution failed on sql" ):
2863
- sql .execute ('INSERT INTO test VALUES("foo", "bar", 7)' , self . conn )
2869
+ sql .execute ('INSERT INTO test VALUES("foo", "bar", 7)' , sqlite_buildin )
2864
2870
2865
2871
def test_execute_closed_connection (self ):
2866
2872
create_sql = """
@@ -2872,36 +2878,36 @@ def test_execute_closed_connection(self):
2872
2878
PRIMARY KEY (a, b)
2873
2879
);
2874
2880
"""
2875
- cur = self .conn .cursor ()
2876
- cur .execute (create_sql )
2881
+ with contextlib .closing (sqlite3 .connect (":memory:" )) as conn :
2882
+ cur = conn .cursor ()
2883
+ cur .execute (create_sql )
2877
2884
2878
- sql .execute ('INSERT INTO test VALUES("foo", "bar", 1.234)' , self .conn )
2879
- self .conn .close ()
2885
+ sql .execute ('INSERT INTO test VALUES("foo", "bar", 1.234)' , conn )
2880
2886
2881
2887
msg = "Cannot operate on a closed database."
2882
2888
with pytest .raises (sqlite3 .ProgrammingError , match = msg ):
2883
- tquery ("select * from test" , con = self . conn )
2889
+ tquery ("select * from test" , con = conn )
2884
2890
2885
- def test_keyword_as_column_names (self ):
2891
+ def test_keyword_as_column_names (self , sqlite_buildin ):
2886
2892
df = DataFrame ({"From" : np .ones (5 )})
2887
- assert sql .to_sql (df , con = self . conn , name = "testkeywords" , index = False ) == 5
2893
+ assert sql .to_sql (df , con = sqlite_buildin , name = "testkeywords" , index = False ) == 5
2888
2894
2889
- def test_onecolumn_of_integer (self ):
2895
+ def test_onecolumn_of_integer (self , sqlite_buildin ):
2890
2896
# GH 3628
2891
2897
# a column_of_integers dataframe should transfer well to sql
2892
2898
2893
2899
mono_df = DataFrame ([1 , 2 ], columns = ["c0" ])
2894
- assert sql .to_sql (mono_df , con = self . conn , name = "mono_df" , index = False ) == 2
2900
+ assert sql .to_sql (mono_df , con = sqlite_buildin , name = "mono_df" , index = False ) == 2
2895
2901
# computing the sum via sql
2896
- con_x = self . conn
2902
+ con_x = sqlite_buildin
2897
2903
the_sum = sum (my_c0 [0 ] for my_c0 in con_x .execute ("select * from mono_df" ))
2898
2904
# it should not fail, and gives 3 ( Issue #3628 )
2899
2905
assert the_sum == 3
2900
2906
2901
2907
result = sql .read_sql ("select * from mono_df" , con_x )
2902
2908
tm .assert_frame_equal (result , mono_df )
2903
2909
2904
- def test_if_exists (self ):
2910
+ def test_if_exists (self , sqlite_buildin ):
2905
2911
df_if_exists_1 = DataFrame ({"col1" : [1 , 2 ], "col2" : ["A" , "B" ]})
2906
2912
df_if_exists_2 = DataFrame ({"col1" : [3 , 4 , 5 ], "col2" : ["C" , "D" , "E" ]})
2907
2913
table_name = "table_if_exists"
@@ -2911,70 +2917,73 @@ def test_if_exists(self):
2911
2917
with pytest .raises (ValueError , match = msg ):
2912
2918
sql .to_sql (
2913
2919
frame = df_if_exists_1 ,
2914
- con = self . conn ,
2920
+ con = sqlite_buildin ,
2915
2921
name = table_name ,
2916
2922
if_exists = "notvalidvalue" ,
2917
2923
)
2918
- self .drop_table (table_name )
2924
+ self .drop_table (table_name , sqlite_buildin )
2919
2925
2920
2926
# test if_exists='fail'
2921
2927
sql .to_sql (
2922
- frame = df_if_exists_1 , con = self . conn , name = table_name , if_exists = "fail"
2928
+ frame = df_if_exists_1 , con = sqlite_buildin , name = table_name , if_exists = "fail"
2923
2929
)
2924
2930
msg = "Table 'table_if_exists' already exists"
2925
2931
with pytest .raises (ValueError , match = msg ):
2926
2932
sql .to_sql (
2927
- frame = df_if_exists_1 , con = self .conn , name = table_name , if_exists = "fail"
2933
+ frame = df_if_exists_1 ,
2934
+ con = sqlite_buildin ,
2935
+ name = table_name ,
2936
+ if_exists = "fail" ,
2928
2937
)
2929
2938
# test if_exists='replace'
2930
2939
sql .to_sql (
2931
2940
frame = df_if_exists_1 ,
2932
- con = self . conn ,
2941
+ con = sqlite_buildin ,
2933
2942
name = table_name ,
2934
2943
if_exists = "replace" ,
2935
2944
index = False ,
2936
2945
)
2937
- assert tquery (sql_select , con = self . conn ) == [(1 , "A" ), (2 , "B" )]
2946
+ assert tquery (sql_select , con = sqlite_buildin ) == [(1 , "A" ), (2 , "B" )]
2938
2947
assert (
2939
2948
sql .to_sql (
2940
2949
frame = df_if_exists_2 ,
2941
- con = self . conn ,
2950
+ con = sqlite_buildin ,
2942
2951
name = table_name ,
2943
2952
if_exists = "replace" ,
2944
2953
index = False ,
2945
2954
)
2946
2955
== 3
2947
2956
)
2948
- assert tquery (sql_select , con = self . conn ) == [(3 , "C" ), (4 , "D" ), (5 , "E" )]
2949
- self .drop_table (table_name )
2957
+ assert tquery (sql_select , con = sqlite_buildin ) == [(3 , "C" ), (4 , "D" ), (5 , "E" )]
2958
+ self .drop_table (table_name , sqlite_buildin )
2950
2959
2951
2960
# test if_exists='append'
2952
2961
assert (
2953
2962
sql .to_sql (
2954
2963
frame = df_if_exists_1 ,
2955
- con = self . conn ,
2964
+ con = sqlite_buildin ,
2956
2965
name = table_name ,
2957
2966
if_exists = "fail" ,
2958
2967
index = False ,
2959
2968
)
2960
2969
== 2
2961
2970
)
2962
- assert tquery (sql_select , con = self . conn ) == [(1 , "A" ), (2 , "B" )]
2971
+ assert tquery (sql_select , con = sqlite_buildin ) == [(1 , "A" ), (2 , "B" )]
2963
2972
assert (
2964
2973
sql .to_sql (
2965
2974
frame = df_if_exists_2 ,
2966
- con = self . conn ,
2975
+ con = sqlite_buildin ,
2967
2976
name = table_name ,
2968
2977
if_exists = "append" ,
2969
2978
index = False ,
2970
2979
)
2971
2980
== 3
2972
2981
)
2973
- assert tquery (sql_select , con = self . conn ) == [
2982
+ assert tquery (sql_select , con = sqlite_buildin ) == [
2974
2983
(1 , "A" ),
2975
2984
(2 , "B" ),
2976
2985
(3 , "C" ),
2977
2986
(4 , "D" ),
2978
2987
(5 , "E" ),
2979
2988
]
2980
- self .drop_table (table_name )
2989
+ self .drop_table (table_name , sqlite_buildin )
0 commit comments