Skip to content

Commit cf0b4a3

Browse files
fangchenlifeefladder
authored andcommitted
TST: refactor iris table creation in SQL test (pandas-dev#42988)
1 parent 06c4873 commit cf0b4a3

File tree

1 file changed

+77
-61
lines changed

1 file changed

+77
-61
lines changed

pandas/tests/io/test_sql.py

+77-61
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
time,
2525
)
2626
from io import StringIO
27+
from pathlib import Path
2728
import sqlite3
2829
import warnings
2930

@@ -72,34 +73,6 @@
7273
SQLALCHEMY_INSTALLED = False
7374

7475
SQL_STRINGS = {
75-
"create_iris": {
76-
"sqlite": """CREATE TABLE iris (
77-
"SepalLength" REAL,
78-
"SepalWidth" REAL,
79-
"PetalLength" REAL,
80-
"PetalWidth" REAL,
81-
"Name" TEXT
82-
)""",
83-
"mysql": """CREATE TABLE iris (
84-
`SepalLength` DOUBLE,
85-
`SepalWidth` DOUBLE,
86-
`PetalLength` DOUBLE,
87-
`PetalWidth` DOUBLE,
88-
`Name` VARCHAR(200)
89-
)""",
90-
"postgresql": """CREATE TABLE iris (
91-
"SepalLength" DOUBLE PRECISION,
92-
"SepalWidth" DOUBLE PRECISION,
93-
"PetalLength" DOUBLE PRECISION,
94-
"PetalWidth" DOUBLE PRECISION,
95-
"Name" VARCHAR(200)
96-
)""",
97-
},
98-
"insert_iris": {
99-
"sqlite": """INSERT INTO iris VALUES(?, ?, ?, ?, ?)""",
100-
"mysql": """INSERT INTO iris VALUES(%s, %s, %s, %s, "%s");""",
101-
"postgresql": """INSERT INTO iris VALUES(%s, %s, %s, %s, %s);""",
102-
},
10376
"create_test_types": {
10477
"sqlite": """CREATE TABLE types_test_data (
10578
"TextCol" TEXT,
@@ -192,7 +165,7 @@
192165
},
193166
"read_parameters": {
194167
"sqlite": "SELECT * FROM iris WHERE Name=? AND SepalLength=?",
195-
"mysql": 'SELECT * FROM iris WHERE `Name`="%s" AND `SepalLength`=%s',
168+
"mysql": "SELECT * FROM iris WHERE `Name`=%s AND `SepalLength`=%s",
196169
"postgresql": 'SELECT * FROM iris WHERE "Name"=%s AND "SepalLength"=%s',
197170
},
198171
"read_named_parameters": {
@@ -201,7 +174,7 @@
201174
""",
202175
"mysql": """
203176
SELECT * FROM iris WHERE
204-
`Name`="%(name)s" AND `SepalLength`=%(length)s
177+
`Name`=%(name)s AND `SepalLength`=%(length)s
205178
""",
206179
"postgresql": """
207180
SELECT * FROM iris WHERE
@@ -222,6 +195,73 @@
222195
}
223196

224197

198+
def iris_table_metadata(dialect: str):
199+
from sqlalchemy import (
200+
REAL,
201+
Column,
202+
Float,
203+
MetaData,
204+
String,
205+
Table,
206+
)
207+
208+
dtype = Float if dialect == "postgresql" else REAL
209+
metadata = MetaData()
210+
iris = Table(
211+
"iris",
212+
metadata,
213+
Column("SepalLength", dtype),
214+
Column("SepalWidth", dtype),
215+
Column("PetalLength", dtype),
216+
Column("PetalWidth", dtype),
217+
Column("Name", String(200)),
218+
)
219+
return iris
220+
221+
222+
def create_and_load_iris_sqlite3(conn: sqlite3.Connection, iris_file: Path):
223+
cur = conn.cursor()
224+
stmt = """CREATE TABLE iris (
225+
"SepalLength" REAL,
226+
"SepalWidth" REAL,
227+
"PetalLength" REAL,
228+
"PetalWidth" REAL,
229+
"Name" TEXT
230+
)"""
231+
cur.execute(stmt)
232+
with iris_file.open(newline=None) as csvfile:
233+
reader = csv.reader(csvfile)
234+
next(reader)
235+
stmt = "INSERT INTO iris VALUES(?, ?, ?, ?, ?)"
236+
cur.executemany(stmt, reader)
237+
238+
239+
def create_and_load_iris(conn, iris_file: Path, dialect: str):
240+
from sqlalchemy import insert
241+
from sqlalchemy.engine import Engine
242+
243+
iris = iris_table_metadata(dialect)
244+
iris.drop(conn, checkfirst=True)
245+
iris.create(bind=conn)
246+
247+
with iris_file.open(newline=None) as csvfile:
248+
reader = csv.reader(csvfile)
249+
header = next(reader)
250+
params = [{key: value for key, value in zip(header, row)} for row in reader]
251+
stmt = insert(iris).values(params)
252+
if isinstance(conn, Engine):
253+
with conn.connect() as conn:
254+
conn.execute(stmt)
255+
else:
256+
conn.execute(stmt)
257+
258+
259+
@pytest.fixture
260+
def iris_path(datapath):
261+
iris_path = datapath("io", "data", "csv", "iris.csv")
262+
return Path(iris_path)
263+
264+
225265
@pytest.fixture
226266
def test_frame1():
227267
columns = ["index", "A", "B", "C", "D"]
@@ -341,24 +381,15 @@ def _get_exec(self):
341381
else:
342382
return self.conn.cursor()
343383

344-
@pytest.fixture(params=[("io", "data", "csv", "iris.csv")])
345-
def load_iris_data(self, datapath, request):
346-
347-
iris_csv_file = datapath(*request.param)
348-
384+
@pytest.fixture
385+
def load_iris_data(self, iris_path):
349386
if not hasattr(self, "conn"):
350387
self.setup_connect()
351-
352388
self.drop_table("iris")
353-
self._get_exec().execute(SQL_STRINGS["create_iris"][self.flavor])
354-
355-
with open(iris_csv_file, newline=None) as iris_csv:
356-
r = csv.reader(iris_csv)
357-
next(r) # skip header row
358-
ins = SQL_STRINGS["insert_iris"][self.flavor]
359-
360-
for row in r:
361-
self._get_exec().execute(ins, row)
389+
if isinstance(self.conn, sqlite3.Connection):
390+
create_and_load_iris_sqlite3(self.conn, iris_path)
391+
else:
392+
create_and_load_iris(self.conn, iris_path, self.flavor)
362393

363394
def _load_iris_view(self):
364395
self.drop_table("iris_view")
@@ -1248,21 +1279,6 @@ def test_database_uri_string(self, test_frame1):
12481279
with pytest.raises(ImportError, match="pg8000"):
12491280
sql.read_sql("select * from table", db_uri)
12501281

1251-
def _make_iris_table_metadata(self):
1252-
sa = sqlalchemy
1253-
metadata = sa.MetaData()
1254-
iris = sa.Table(
1255-
"iris",
1256-
metadata,
1257-
sa.Column("SepalLength", sa.REAL),
1258-
sa.Column("SepalWidth", sa.REAL),
1259-
sa.Column("PetalLength", sa.REAL),
1260-
sa.Column("PetalWidth", sa.REAL),
1261-
sa.Column("Name", sa.TEXT),
1262-
)
1263-
1264-
return iris
1265-
12661282
def test_query_by_text_obj(self):
12671283
# WIP : GH10846
12681284
name_text = sqlalchemy.text("select * from iris where name=:name")
@@ -1272,7 +1288,7 @@ def test_query_by_text_obj(self):
12721288

12731289
def test_query_by_select_obj(self):
12741290
# WIP : GH10846
1275-
iris = self._make_iris_table_metadata()
1291+
iris = iris_table_metadata(self.flavor)
12761292

12771293
name_select = sqlalchemy.select([iris]).where(
12781294
iris.c.Name == sqlalchemy.bindparam("name")

0 commit comments

Comments
 (0)