Skip to content

Commit cafebdd

Browse files
committed
⚡ use f-strings where appropriate
1 parent 2375400 commit cafebdd

File tree

10 files changed

+69
-127
lines changed

10 files changed

+69
-127
lines changed

sqlite3_to_mysql/cli.py

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -147,12 +147,7 @@ def cli(
147147
)
148148
if mysql_collation not in set(charset_collations):
149149
raise click.ClickException(
150-
"Error: Invalid value for '--collation' of charset '{charset}': '{collation}' is not one of "
151-
"{collations}.".format(
152-
collation=mysql_collation,
153-
charset=mysql_charset,
154-
collations="'" + "', '".join(charset_collations) + "'",
155-
)
150+
f"""Error: Invalid value for '--collation' of charset '{mysql_charset}': '{mysql_collation}' is not one of {"'" + "', '".join(charset_collations) + "'"}."""
156151
)
157152

158153
SQLite3toMySQL(

sqlite3_to_mysql/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

sqlite3_to_mysql/debug_info.py

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

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

5856

5957
def _mysql_version() -> str:
@@ -72,10 +70,7 @@ def _mysql_version() -> str:
7270
def info() -> t.List[t.List[str]]:
7371
"""Generate information for a bug report."""
7472
try:
75-
platform_info = "{system} {release}".format(
76-
system=platform.system(),
77-
release=platform.release(),
78-
)
73+
platform_info = f"{platform.system()} {platform.release()}"
7974
except IOError:
8075
platform_info = "Unknown"
8176

sqlite3_to_mysql/sqlite_utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def convert_date(value) -> date:
4343
try:
4444
return date.fromisoformat(value.decode())
4545
except ValueError as err:
46-
raise ValueError("DATE field contains {}".format(err)) # pylint: disable=W0707
46+
raise ValueError(f"DATE field contains {err}") # pylint: disable=W0707
4747

4848

4949
def check_sqlite_table_xinfo_support(version_string: str) -> bool:

sqlite3_to_mysql/transporter.py

Lines changed: 30 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ def _get_sqlite_version(self) -> str:
215215

216216
def _sqlite_table_has_rowid(self, table: str) -> bool:
217217
try:
218-
self._sqlite_cur.execute("""SELECT rowid FROM "{}" LIMIT 1""".format(table))
218+
self._sqlite_cur.execute(f'SELECT rowid FROM "{table}" LIMIT 1')
219219
self._sqlite_cur.fetchall()
220220
return True
221221
except sqlite3.OperationalError:
@@ -224,15 +224,11 @@ def _sqlite_table_has_rowid(self, table: str) -> bool:
224224
def _create_database(self) -> None:
225225
try:
226226
self._mysql_cur.execute(
227-
"""
228-
CREATE DATABASE IF NOT EXISTS `{database}`
229-
DEFAULT CHARACTER SET {charset}
230-
DEFAULT COLLATE {collation}
231-
""".format(
232-
database=self._mysql_database,
233-
charset=self._mysql_charset,
234-
collation=self._mysql_collation,
235-
)
227+
f"""
228+
CREATE DATABASE IF NOT EXISTS `{self._mysql_database}`
229+
DEFAULT CHARACTER SET {self._mysql_charset}
230+
DEFAULT COLLATE {self._mysql_collation}
231+
"""
236232
)
237233
self._mysql_cur.close()
238234
self._mysql.commit()
@@ -300,23 +296,21 @@ def _column_type_length(cls, column_type: str, default: t.Optional[t.Union[str,
300296
if suffix:
301297
return suffix.group(0)
302298
if default:
303-
return "({})".format(default)
299+
return f"({default})"
304300
return ""
305301

306302
def _create_table(self, table_name: str, transfer_rowid: bool = False) -> None:
307303
primary_keys: t.List[t.Dict[str, str]] = []
308304

309-
sql: str = "CREATE TABLE IF NOT EXISTS `{}` ( ".format(safe_identifier_length(table_name))
305+
sql: str = f"CREATE TABLE IF NOT EXISTS `{safe_identifier_length(table_name)}` ( "
310306

311307
if transfer_rowid:
312308
sql += " `rowid` BIGINT NOT NULL, "
313309

314-
self._sqlite_cur.execute(
315-
'PRAGMA {command}("{table_name}")'.format(
316-
command="table_xinfo" if self._sqlite_table_xinfo_support else "table_info",
317-
table_name=table_name,
318-
)
319-
)
310+
if self._sqlite_table_xinfo_support:
311+
self._sqlite_cur.execute(f'PRAGMA table_xinfo("{table_name}")')
312+
else:
313+
self._sqlite_cur.execute(f'PRAGMA table_info("{table_name}")')
320314

321315
rows: t.List[t.Any] = self._sqlite_cur.fetchall()
322316
compound_primary_key: bool = len(tuple(True for row in rows if dict(row)["pk"] > 0)) > 1
@@ -364,12 +358,9 @@ def _create_table(self, table_name: str, transfer_rowid: bool = False) -> None:
364358
)
365359

366360
if transfer_rowid:
367-
sql += ", CONSTRAINT `{}_rowid` UNIQUE (`rowid`)".format(safe_identifier_length(table_name))
361+
sql += f", CONSTRAINT `{safe_identifier_length(table_name)}_rowid` UNIQUE (`rowid`)"
368362

369-
sql += " ) ENGINE=InnoDB DEFAULT CHARSET={charset} COLLATE={collation}".format(
370-
charset=self._mysql_charset,
371-
collation=self._mysql_collation,
372-
)
363+
sql += f" ) ENGINE=InnoDB DEFAULT CHARSET={self._mysql_charset} COLLATE={self._mysql_collation}"
373364

374365
try:
375366
self._mysql_cur.execute(sql)
@@ -395,27 +386,23 @@ def _truncate_table(self, table_name: str) -> None:
395386
)
396387
if len(self._mysql_cur.fetchall()) > 0:
397388
self._logger.info("Truncating table %s", safe_identifier_length(table_name))
398-
self._mysql_cur.execute(
399-
"TRUNCATE TABLE `{}`".format(
400-
safe_identifier_length(table_name),
401-
),
402-
)
389+
self._mysql_cur.execute(f"TRUNCATE TABLE `{safe_identifier_length(table_name)}`")
403390

404391
def _add_indices(self, table_name: str) -> None:
405-
self._sqlite_cur.execute('PRAGMA table_info("{}")'.format(table_name))
392+
self._sqlite_cur.execute(f'PRAGMA table_info("{table_name}")')
406393
table_columns: t.Dict[str, str] = {}
407394
for row in self._sqlite_cur.fetchall():
408395
column: t.Dict[str, t.Any] = dict(row)
409396
table_columns[column["name"]] = column["type"]
410397

411-
self._sqlite_cur.execute('PRAGMA index_list("{}")'.format(table_name))
398+
self._sqlite_cur.execute(f'PRAGMA index_list("{table_name}")')
412399
indices: t.Tuple[t.Dict[str, t.Any], ...] = tuple(dict(row) for row in self._sqlite_cur.fetchall())
413400

414401
for index in indices:
415402
if index["origin"] == "pk":
416403
continue
417404

418-
self._sqlite_cur.execute('PRAGMA index_info("{}")'.format(index["name"]))
405+
self._sqlite_cur.execute(f'PRAGMA index_info("{index["name"]}")')
419406
index_infos: t.Tuple[t.Dict[str, t.Any], ...] = tuple(dict(row) for row in self._sqlite_cur.fetchall())
420407

421408
index_type: str = "UNIQUE" if int(index["unique"]) == 1 else "INDEX"
@@ -428,14 +415,14 @@ def _add_indices(self, table_name: str) -> None:
428415
# Use fulltext if requested and available
429416
index_type = "FULLTEXT"
430417
index_columns: str = ",".join(
431-
"`{}`".format(safe_identifier_length(index_info["name"])) for index_info in index_infos
418+
f'`{safe_identifier_length(index_info["name"])}`' for index_info in index_infos
432419
)
433420
else:
434421
# Limit the max TEXT field index length to 255
435422
index_columns = ", ".join(
436423
"`{column}`{length}".format(
437424
column=safe_identifier_length(index_info["name"]),
438-
length="({})".format(255)
425+
length="(255)"
439426
if table_columns[index_info["name"]].upper() in MYSQL_TEXT_COLUMN_TYPES_WITH_JSON
440427
else "",
441428
)
@@ -447,19 +434,14 @@ def _add_indices(self, table_name: str) -> None:
447434
index_length: str = ""
448435
# Limit the max BLOB field index length to 255
449436
if table_columns[index_info["name"]].upper() in MYSQL_BLOB_COLUMN_TYPES:
450-
index_length = "({})".format(255)
437+
index_length = "(255)"
451438
else:
452439
suffix: t.Optional[t.Match[str]] = self.COLUMN_LENGTH_PATTERN.search(
453440
table_columns[index_info["name"]]
454441
)
455442
if suffix:
456443
index_length = suffix.group(0)
457-
column_list.append(
458-
"`{column}`{length}".format(
459-
column=safe_identifier_length(index_info["name"]),
460-
length=index_length,
461-
)
462-
)
444+
column_list.append(f'`{safe_identifier_length(index_info["name"])}`{index_length}')
463445
index_columns = ", ".join(column_list)
464446

465447
try:
@@ -480,7 +462,7 @@ def _add_indices(self, table_name: str) -> None:
480462
index_columns=", ".join(
481463
"`{column}`{length}".format(
482464
column=safe_identifier_length(index_info["name"]),
483-
length="({})".format(255)
465+
length="(255)"
484466
if table_columns[index_info["name"]].upper() in MYSQL_TEXT_COLUMN_TYPES_WITH_JSON
485467
else "",
486468
)
@@ -508,10 +490,7 @@ def _add_index(
508490
index_type=index_type,
509491
name=safe_identifier_length(index["name"])
510492
if index_iteration == 0
511-
else "{name}_{index_iteration}".format(
512-
name=safe_identifier_length(index["name"], max_length=60),
513-
index_iteration=index_iteration,
514-
),
493+
else f'{safe_identifier_length(index["name"], max_length=60)}_{index_iteration}',
515494
columns=index_columns,
516495
)
517496

@@ -567,7 +546,7 @@ def _add_index(
567546
raise
568547

569548
def _add_foreign_keys(self, table_name: str) -> None:
570-
self._sqlite_cur.execute('PRAGMA foreign_key_list("{}")'.format(table_name))
549+
self._sqlite_cur.execute(f'PRAGMA foreign_key_list("{table_name}")')
571550

572551
for row in self._sqlite_cur.fetchall():
573552
foreign_key: t.Dict[str, t.Any] = dict(row)
@@ -640,14 +619,12 @@ def transfer(self) -> None:
640619
if len(self._sqlite_tables) > 0:
641620
# transfer only specific tables
642621
self._sqlite_cur.execute(
643-
"""
622+
f"""
644623
SELECT name FROM sqlite_master
645624
WHERE type='table'
646625
AND name NOT LIKE 'sqlite_%'
647-
AND name IN({placeholders})
648-
""".format(
649-
placeholders=("?, " * len(self._sqlite_tables)).rstrip(" ,")
650-
),
626+
AND name IN({("?, " * len(self._sqlite_tables)).rstrip(" ,")})
627+
""",
651628
self._sqlite_tables,
652629
)
653630
else:
@@ -676,17 +653,15 @@ def transfer(self) -> None:
676653
self._truncate_table(table["name"])
677654

678655
# get the size of the data
679-
self._sqlite_cur.execute('SELECT COUNT(*) AS total_records FROM "{}"'.format(table["name"]))
656+
self._sqlite_cur.execute(f'SELECT COUNT(*) AS total_records FROM "{table["name"]}"')
680657
total_records = int(dict(self._sqlite_cur.fetchone())["total_records"])
681658

682659
# only continue if there is anything to transfer
683660
if total_records > 0:
684661
# populate it
685662
self._logger.info("Transferring table %s", table["name"])
686663
self._sqlite_cur.execute(
687-
"""
688-
SELECT {rowid} * FROM "{table_name}"
689-
""".format(
664+
'''SELECT {rowid} * FROM "{table_name}"'''.format(
690665
rowid='rowid as "rowid",' if transfer_rowid else "",
691666
table_name=table["name"],
692667
)

tests/conftest.py

Lines changed: 7 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ def not_raises(exception: t.Type[Exception]) -> t.Generator:
124124
try:
125125
yield
126126
except exception:
127-
raise pytest.fail("DID RAISE {0}".format(exception))
127+
raise pytest.fail(f"DID RAISE {exception}")
128128

129129
@staticmethod
130130
@contextmanager
@@ -151,13 +151,13 @@ def sqlite_database(pytestconfig: Config, _session_faker: Faker, tmpdir_factory:
151151
db_file: LocalPath = pytestconfig.getoption("sqlite_file")
152152
if db_file:
153153
if not isfile(realpath(db_file)):
154-
pytest.fail("{} does not exist".format(db_file))
154+
pytest.fail(f"{db_file} does not exist")
155155
return str(realpath(db_file))
156156

157157
temp_data_dir: LocalPath = tmpdir_factory.mktemp("data")
158158
temp_image_dir: LocalPath = tmpdir_factory.mktemp("images")
159159
db_file = temp_data_dir.join(Path("db.sqlite3"))
160-
db: Database = Database("sqlite:///{}".format(str(db_file)))
160+
db: Database = Database(f"sqlite:///{db_file}")
161161

162162
with Helpers.session_scope(db) as session:
163163
for _ in range(_session_faker.pyint(min_value=12, max_value=24)):
@@ -220,9 +220,7 @@ def mysql_credentials(pytestconfig: Config) -> MySQLCredentials:
220220
if pytestconfig.getoption("use_docker"):
221221
while is_port_in_use(port, pytestconfig.getoption("mysql_host")):
222222
if port >= 2**16 - 1:
223-
pytest.fail(
224-
"No ports appear to be available on the host {}".format(pytestconfig.getoption("mysql_host"))
225-
)
223+
pytest.fail(f'No ports appear to be available on the host {pytestconfig.getoption("mysql_host")}')
226224
port += 1
227225

228226
return MySQLCredentials(
@@ -259,7 +257,7 @@ def mysql_instance(mysql_credentials: MySQLCredentials, pytestconfig: Config) ->
259257
docker_mysql_image = pytestconfig.getoption("docker_mysql_image") or "mysql:latest"
260258

261259
if not any(docker_mysql_image in image.tags for image in client.images.list()):
262-
print("Attempting to download Docker image {}'".format(docker_mysql_image))
260+
print(f"Attempting to download Docker image {docker_mysql_image}'")
263261
try:
264262
client.images.pull(docker_mysql_image)
265263
except (HTTPError, NotFound) as err:
@@ -271,7 +269,7 @@ def mysql_instance(mysql_credentials: MySQLCredentials, pytestconfig: Config) ->
271269
ports={
272270
"3306/tcp": (
273271
mysql_credentials.host,
274-
"{}/tcp".format(mysql_credentials.port),
272+
f"{mysql_credentials.port}/tcp",
275273
)
276274
},
277275
environment={
@@ -322,13 +320,7 @@ def mysql_database(mysql_instance: t.Generator, mysql_credentials: MySQLCredenti
322320
yield # type: ignore[misc]
323321

324322
engine: Engine = create_engine(
325-
"mysql+pymysql://{user}:{password}@{host}:{port}/{database}".format(
326-
user=mysql_credentials.user,
327-
password=mysql_credentials.password,
328-
host=mysql_credentials.host,
329-
port=mysql_credentials.port,
330-
database=mysql_credentials.database,
331-
)
323+
f"mysql+pymysql://{mysql_credentials.user}:{mysql_credentials.password}@{mysql_credentials.host}:{mysql_credentials.port}/{mysql_credentials.database}"
332324
)
333325

334326
if database_exists(engine.url):

0 commit comments

Comments
 (0)