Skip to content

Commit 216a365

Browse files
committed
⚡ use f-strings where appropriate
1 parent 641d81e commit 216a365

File tree

9 files changed

+68
-131
lines changed

9 files changed

+68
-131
lines changed

mysql_to_sqlite3/click_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ def __init__(self, *args, **kwargs):
1313
self.save_other_options = kwargs.pop("save_other_options", True)
1414
nargs = kwargs.pop("nargs", -1)
1515
if nargs != -1:
16-
raise ValueError("nargs, if set, must be -1 not {}".format(nargs))
16+
raise ValueError(f"nargs, if set, must be -1 not {nargs}")
1717
super(OptionEatAll, self).__init__(*args, **kwargs)
1818
self._previous_parser_process = None
1919
self._eat_all_parser = None

mysql_to_sqlite3/debug_info.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,7 @@ def _implementation() -> str:
5252
else:
5353
implementation_version = "Unknown"
5454

55-
return "{implementation} {implementation_version}".format(
56-
implementation=implementation, implementation_version=implementation_version
57-
)
55+
return f"{implementation} {implementation_version}"
5856

5957

6058
def _mysql_version() -> str:
@@ -73,10 +71,7 @@ def _mysql_version() -> str:
7371
def info() -> t.List[t.List[str]]:
7472
"""Generate information for a bug report."""
7573
try:
76-
platform_info: str = "{system} {release}".format(
77-
system=platform.system(),
78-
release=platform.release(),
79-
)
74+
platform_info: str = f"{platform.system()} {platform.release()}"
8075
except IOError:
8176
platform_info = "Unknown"
8277

mysql_to_sqlite3/sqlite_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,4 +51,4 @@ def convert_date(value: t.Any) -> date:
5151
try:
5252
return date.fromisoformat(value.decode())
5353
except ValueError as err:
54-
raise ValueError("DATE field contains {}".format(err)) # pylint: disable=W0707
54+
raise ValueError(f"DATE field contains {err}") # pylint: disable=W0707

mysql_to_sqlite3/transporter.py

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ def _translate_default_from_mysql_to_sqlite(
261261
"TINYBLOB",
262262
"VARBINARY",
263263
}:
264-
return "DEFAULT x'{}'".format(column_default.hex())
264+
return f"DEFAULT x'{column_default.hex()}'"
265265
try:
266266
column_default = column_default.decode()
267267
except (UnicodeDecodeError, AttributeError):
@@ -273,15 +273,15 @@ def _translate_default_from_mysql_to_sqlite(
273273
if column_default:
274274
return "DEFAULT(TRUE)"
275275
return "DEFAULT(FALSE)"
276-
return "DEFAULT '{}'".format(int(column_default))
276+
return f"DEFAULT '{int(column_default)}'"
277277
if isinstance(column_default, str):
278278
if column_default.upper() in {
279279
"CURRENT_TIME",
280280
"CURRENT_DATE",
281281
"CURRENT_TIMESTAMP",
282282
}:
283-
return "DEFAULT {}".format(column_default.upper())
284-
return "DEFAULT '{}'".format(str(column_default))
283+
return f"DEFAULT {column_default.upper()}"
284+
return f"DEFAULT '{str(column_default)}'"
285285

286286
@classmethod
287287
def _data_type_collation_sequence(
@@ -297,7 +297,7 @@ def _data_type_collation_sequence(
297297
"VARCHAR",
298298
)
299299
):
300-
return "COLLATE {collation}".format(collation=collation)
300+
return f"COLLATE {collation}"
301301
return ""
302302

303303
def _check_sqlite_json1_extension_enabled(self) -> bool:
@@ -308,11 +308,11 @@ def _check_sqlite_json1_extension_enabled(self) -> bool:
308308
return False
309309

310310
def _build_create_table_sql(self, table_name: str) -> str:
311-
sql: str = 'CREATE TABLE IF NOT EXISTS "{}" ('.format(table_name)
311+
sql: str = f'CREATE TABLE IF NOT EXISTS "{table_name}" ('
312312
primary: str = ""
313313
indices: str = ""
314314

315-
self._mysql_cur_dict.execute("SHOW COLUMNS FROM `{}`".format(table_name))
315+
self._mysql_cur_dict.execute(f"SHOW COLUMNS FROM `{table_name}`")
316316

317317
for row in self._mysql_cur_dict.fetchall():
318318
if row is not None:
@@ -351,8 +351,8 @@ def _build_create_table_sql(self, table_name: str) -> str:
351351

352352
if len(columns) > 0:
353353
if index["primary"] in {1, "1"}:
354-
primary += "\n\tPRIMARY KEY ({columns})".format(
355-
columns=", ".join('"{}"'.format(column) for column in columns.split(","))
354+
primary += "\n\tPRIMARY KEY ({})".format(
355+
", ".join(f'"{column}"' for column in columns.split(","))
356356
)
357357
else:
358358
indices += """CREATE {unique} INDEX IF NOT EXISTS "{name}" ON "{table}" ({columns});""".format(
@@ -366,7 +366,7 @@ def _build_create_table_sql(self, table_name: str) -> str:
366366
if isinstance(index["name"], bytes)
367367
else index["name"],
368368
table=table_name,
369-
columns=", ".join('"{}"'.format(column) for column in columns.split(",")),
369+
columns=", ".join(f'"{column}"' for column in columns.split(",")),
370370
)
371371

372372
sql += primary
@@ -554,18 +554,12 @@ def transfer(self) -> None:
554554
if self._limit_rows > 0:
555555
# limit to the requested number of rows
556556
self._mysql_cur_dict.execute(
557-
"""
558-
SELECT COUNT(*) AS `total_records`
559-
FROM (SELECT * FROM `{table_name}` LIMIT {limit}) AS `table`
560-
""".format(
561-
table_name=table_name, limit=self._limit_rows
562-
)
557+
"SELECT COUNT(*) AS `total_records` "
558+
f"FROM (SELECT * FROM `{table_name}` LIMIT {self._limit_rows}) AS `table`"
563559
)
564560
else:
565561
# get all rows
566-
self._mysql_cur_dict.execute(
567-
"SELECT COUNT(*) AS `total_records` FROM `{table_name}`".format(table_name=table_name)
568-
)
562+
self._mysql_cur_dict.execute(f"SELECT COUNT(*) AS `total_records` FROM `{table_name}`")
569563

570564
total_records: t.Optional[t.Dict[str, ToPythonOutputTypes]] = self._mysql_cur_dict.fetchone()
571565
if total_records is not None:
@@ -579,7 +573,7 @@ def transfer(self) -> None:
579573
self._mysql_cur.execute(
580574
"SELECT * FROM `{table_name}` {limit}".format(
581575
table_name=table_name,
582-
limit="LIMIT {}".format(self._limit_rows) if self._limit_rows > 0 else "",
576+
limit=f"LIMIT {self._limit_rows}" if self._limit_rows > 0 else "",
583577
)
584578
)
585579
columns: t.Tuple[str, ...] = tuple(column[0] for column in self._mysql_cur.description) # type: ignore[union-attr]

tests/conftest.py

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def not_raises(exception: t.Type[Exception]) -> t.Generator:
117117
try:
118118
yield
119119
except exception:
120-
raise pytest.fail("DID RAISE {0}".format(exception))
120+
raise pytest.fail(f"DID RAISE {exception}")
121121

122122
@staticmethod
123123
@contextmanager
@@ -142,7 +142,7 @@ def helpers() -> t.Type[Helpers]:
142142
@pytest.fixture()
143143
def sqlite_database(tmpdir: LocalPath) -> t.Union[str, Path, "os.PathLike[t.Any]"]:
144144
db_name: str = "".join(choice(ascii_uppercase + ascii_lowercase + digits) for _ in range(32))
145-
return Path(tmpdir.join(Path("{}.sqlite3".format(db_name))))
145+
return Path(tmpdir.join(Path(f"{db_name}.sqlite3")))
146146

147147

148148
def is_port_in_use(port: int, host: str = "0.0.0.0") -> bool:
@@ -178,9 +178,7 @@ def mysql_credentials(pytestconfig: Config) -> MySQLCredentials:
178178
if pytestconfig.getoption("use_docker"):
179179
while is_port_in_use(port, pytestconfig.getoption("mysql_host")):
180180
if port >= 2**16 - 1:
181-
pytest.fail(
182-
"No ports appear to be available on the host {}".format(pytestconfig.getoption("mysql_host"))
183-
)
181+
pytest.fail(f"No ports appear to be available on the host {pytestconfig.getoption('mysql_host')}")
184182
port += 1
185183

186184
return MySQLCredentials(
@@ -217,7 +215,7 @@ def mysql_instance(mysql_credentials: MySQLCredentials, pytestconfig: Config) ->
217215
docker_mysql_image = pytestconfig.getoption("docker_mysql_image") or "mysql:latest"
218216

219217
if not any(docker_mysql_image in image.tags for image in client.images.list()):
220-
print("Attempting to download Docker image {}'".format(docker_mysql_image))
218+
print(f"Attempting to download Docker image {docker_mysql_image}'")
221219
try:
222220
client.images.pull(docker_mysql_image)
223221
except (HTTPError, NotFound) as err:
@@ -226,12 +224,7 @@ def mysql_instance(mysql_credentials: MySQLCredentials, pytestconfig: Config) ->
226224
container = client.containers.run(
227225
image=docker_mysql_image,
228226
name="pytest_mysql_to_sqlite3",
229-
ports={
230-
"3306/tcp": (
231-
mysql_credentials.host,
232-
"{}/tcp".format(mysql_credentials.port),
233-
)
234-
},
227+
ports={"3306/tcp": (mysql_credentials.host, f"{mysql_credentials.port}/tcp")},
235228
environment={
236229
"MYSQL_RANDOM_ROOT_PASSWORD": "yes",
237230
"MYSQL_USER": mysql_credentials.user,
@@ -285,13 +278,7 @@ def mysql_database(
285278
temp_image_dir: LocalPath = tmpdir_factory.mktemp("images")
286279

287280
db: database.Database = database.Database(
288-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
289-
user=mysql_credentials.user,
290-
password=mysql_credentials.password,
291-
host=mysql_credentials.host,
292-
port=mysql_credentials.port,
293-
database=mysql_credentials.database,
294-
)
281+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
295282
)
296283

297284
with Helpers.session_scope(db) as session:

tests/func/mysql_to_sqlite3_test.py

Lines changed: 12 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -417,7 +417,7 @@ def test_transfer_transfers_all_tables_from_mysql_to_sqlite(
417417
assert not any(record.levelname == "ERROR" for record in caplog.records)
418418

419419
sqlite_engine: Engine = create_engine(
420-
"sqlite:///{database}".format(database=sqlite_database),
420+
f"sqlite:///{sqlite_database}",
421421
json_serializer=json.dumps,
422422
json_deserializer=json.loads,
423423
)
@@ -426,13 +426,7 @@ def test_transfer_transfers_all_tables_from_mysql_to_sqlite(
426426
sqlite_inspect: Inspector = inspect(sqlite_engine)
427427
sqlite_tables: t.List[str] = sqlite_inspect.get_table_names()
428428
mysql_engine: Engine = create_engine(
429-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
430-
user=mysql_credentials.user,
431-
password=mysql_credentials.password,
432-
host=mysql_credentials.host,
433-
port=mysql_credentials.port,
434-
database=mysql_credentials.database,
435-
)
429+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
436430
)
437431
mysql_cnx: Connection = mysql_engine.connect()
438432
mysql_inspect: Inspector = inspect(mysql_engine)
@@ -466,10 +460,7 @@ def test_transfer_transfers_all_tables_from_mysql_to_sqlite(
466460
mysql_index: t.Dict[str, t.Any] = {}
467461
for key in index_keys:
468462
if key == "name" and prefix_indices:
469-
mysql_index[key] = "{table}_{name}".format(
470-
table=table_name,
471-
name=index[key], # type: ignore[literal-required]
472-
)
463+
mysql_index[key] = f"{table_name}_{index[key]}" # type: ignore[literal-required]
473464
else:
474465
mysql_index[key] = index[key] # type: ignore[literal-required]
475466
mysql_indices.append(t.cast(ReflectedIndex, mysql_index))
@@ -510,7 +501,7 @@ def test_transfer_transfers_all_tables_from_mysql_to_sqlite(
510501
mysql_fk_result: CursorResult = mysql_cnx.execute(mysql_fk_stmt)
511502
mysql_foreign_keys: t.List[t.Dict[str, t.Any]] = [dict(row) for row in mysql_fk_result.mappings()]
512503

513-
sqlite_fk_stmt: TextClause = text('PRAGMA foreign_key_list("{table}")'.format(table=table_name))
504+
sqlite_fk_stmt: TextClause = text(f'PRAGMA foreign_key_list("{table_name}")')
514505
sqlite_fk_result: CursorResult = sqlite_cnx.execute(sqlite_fk_stmt)
515506
if sqlite_fk_result.returns_rows:
516507
for row in sqlite_fk_result.mappings():
@@ -884,13 +875,7 @@ def test_transfer_specific_tables_transfers_only_specified_tables_from_mysql_to_
884875
exclude_tables: bool,
885876
) -> None:
886877
mysql_engine: Engine = create_engine(
887-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
888-
user=mysql_credentials.user,
889-
password=mysql_credentials.password,
890-
host=mysql_credentials.host,
891-
port=mysql_credentials.port,
892-
database=mysql_credentials.database,
893-
)
878+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
894879
)
895880
mysql_cnx: Connection = mysql_engine.connect()
896881
mysql_inspect: Inspector = inspect(mysql_engine)
@@ -921,7 +906,7 @@ def test_transfer_specific_tables_transfers_only_specified_tables_from_mysql_to_
921906
message in [record.message for record in caplog.records]
922907
for message in set(
923908
[
924-
"Transferring table {}".format(table)
909+
f"Transferring table {table}"
925910
for table in (remaining_tables if exclude_tables else random_mysql_tables)
926911
]
927912
+ ["Done!"]
@@ -931,7 +916,7 @@ def test_transfer_specific_tables_transfers_only_specified_tables_from_mysql_to_
931916
assert not any(record.levelname == "ERROR" for record in caplog.records)
932917

933918
sqlite_engine: Engine = create_engine(
934-
"sqlite:///{database}".format(database=sqlite_database),
919+
f"sqlite:///{sqlite_database}",
935920
json_serializer=json.dumps,
936921
json_deserializer=json.loads,
937922
)
@@ -960,10 +945,7 @@ def test_transfer_specific_tables_transfers_only_specified_tables_from_mysql_to_
960945
mysql_index: t.Dict[str, t.Any] = {}
961946
for key in index_keys:
962947
if key == "name" and prefix_indices:
963-
mysql_index[key] = "{table}_{name}".format(
964-
table=table_name,
965-
name=index[key], # type: ignore[literal-required]
966-
)
948+
mysql_index[key] = f"{table_name}_{index[key]}" # type: ignore[literal-required]
967949
else:
968950
mysql_index[key] = index[key] # type: ignore[literal-required]
969951
mysql_indices.append(t.cast(ReflectedIndex, mysql_index))
@@ -1185,7 +1167,7 @@ def test_transfer_limited_rows_from_mysql_to_sqlite(
11851167
assert not any(record.levelname == "ERROR" for record in caplog.records)
11861168

11871169
sqlite_engine: Engine = create_engine(
1188-
"sqlite:///{database}".format(database=sqlite_database),
1170+
f"sqlite:///{sqlite_database}",
11891171
json_serializer=json.dumps,
11901172
json_deserializer=json.loads,
11911173
)
@@ -1194,13 +1176,7 @@ def test_transfer_limited_rows_from_mysql_to_sqlite(
11941176
sqlite_inspect: Inspector = inspect(sqlite_engine)
11951177
sqlite_tables: t.List[str] = sqlite_inspect.get_table_names()
11961178
mysql_engine: Engine = create_engine(
1197-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
1198-
user=mysql_credentials.user,
1199-
password=mysql_credentials.password,
1200-
host=mysql_credentials.host,
1201-
port=mysql_credentials.port,
1202-
database=mysql_credentials.database,
1203-
)
1179+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
12041180
)
12051181
mysql_cnx: Connection = mysql_engine.connect()
12061182
mysql_inspect: Inspector = inspect(mysql_engine)
@@ -1234,10 +1210,7 @@ def test_transfer_limited_rows_from_mysql_to_sqlite(
12341210
mysql_index: t.Dict[str, t.Any] = {}
12351211
for key in index_keys:
12361212
if key == "name" and prefix_indices:
1237-
mysql_index[key] = "{table}_{name}".format(
1238-
table=table_name,
1239-
name=index[key], # type: ignore[literal-required]
1240-
)
1213+
mysql_index[key] = f"{table_name}_{index[key]}" # type: ignore[literal-required]
12411214
else:
12421215
mysql_index[key] = index[key] # type: ignore[literal-required]
12431216
mysql_indices.append(t.cast(ReflectedIndex, mysql_index))
@@ -1278,7 +1251,7 @@ def test_transfer_limited_rows_from_mysql_to_sqlite(
12781251
mysql_fk_result: CursorResult = mysql_cnx.execute(mysql_fk_stmt)
12791252
mysql_foreign_keys: t.List[t.Dict[str, t.Any]] = [dict(row) for row in mysql_fk_result.mappings()]
12801253

1281-
sqlite_fk_stmt: TextClause = text('PRAGMA foreign_key_list("{table}")'.format(table=table_name))
1254+
sqlite_fk_stmt: TextClause = text(f'PRAGMA foreign_key_list("{table_name}")')
12821255
sqlite_fk_result: CursorResult = sqlite_cnx.execute(sqlite_fk_stmt)
12831256
if sqlite_fk_result.returns_rows:
12841257
for row in sqlite_fk_result.mappings():

tests/func/test_cli.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -374,13 +374,7 @@ def test_specific_tables_include_and_exclude_are_mutually_exclusive_options(
374374
mysql_database: Database,
375375
) -> None:
376376
mysql_engine: Engine = create_engine(
377-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
378-
user=mysql_credentials.user,
379-
password=mysql_credentials.password,
380-
host=mysql_credentials.host,
381-
port=mysql_credentials.port,
382-
database=mysql_credentials.database,
383-
)
377+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
384378
)
385379
mysql_cnx: Connection = mysql_engine.connect()
386380
mysql_inspect: Inspector = inspect(mysql_engine)
@@ -428,13 +422,7 @@ def test_transfer_specific_tables_only(
428422
mysql_database: Database,
429423
) -> None:
430424
mysql_engine: Engine = create_engine(
431-
"mysql+mysqldb://{user}:{password}@{host}:{port}/{database}".format(
432-
user=mysql_credentials.user,
433-
password=mysql_credentials.password,
434-
host=mysql_credentials.host,
435-
port=mysql_credentials.port,
436-
database=mysql_credentials.database,
437-
)
425+
f"mysql+mysqldb://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
438426
)
439427
mysql_inspect: Inspector = inspect(mysql_engine)
440428
mysql_tables: t.List[str] = mysql_inspect.get_table_names()

0 commit comments

Comments
 (0)