Skip to content

Commit 91bd38f

Browse files
committed
🐛 ensure index names do not collide with table names
1 parent bcaa34b commit 91bd38f

File tree

2 files changed

+29
-9
lines changed

2 files changed

+29
-9
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
# 2.1.8
2+
3+
* [FIX] ensure index names do not collide with table names
4+
15
# 2.1.7
26

37
* [FIX] use more precise foreign key constraints

mysql_to_sqlite3/transporter.py

Lines changed: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -405,8 +405,29 @@ def _build_create_table_sql(self, table_name: str) -> str:
405405
""",
406406
(self._mysql_database, table_name),
407407
)
408-
for index in self._mysql_cur_dict.fetchall():
408+
mysql_indices: t.Sequence[t.Optional[t.Dict[str, ToPythonOutputTypes]]] = self._mysql_cur_dict.fetchall()
409+
for index in mysql_indices:
409410
if index is not None:
411+
index_name: str
412+
if isinstance(index["name"], bytes):
413+
index_name = index["name"].decode()
414+
elif isinstance(index["name"], str):
415+
index_name = index["name"]
416+
else:
417+
index_name = str(index["name"])
418+
419+
# check if the index name collides with any table name
420+
self._mysql_cur_dict.execute(
421+
"""
422+
SELECT COUNT(*)
423+
FROM information_schema.TABLES
424+
WHERE TABLE_SCHEMA = %s
425+
AND TABLE_NAME = %s
426+
""",
427+
(self._mysql_database, index_name),
428+
)
429+
index_name_collision: t.Optional[t.Dict[str, ToPythonOutputTypes]] = self._mysql_cur_dict.fetchone()
430+
410431
columns: str = ""
411432
if isinstance(index["columns"], bytes):
412433
columns = index["columns"].decode()
@@ -421,14 +442,9 @@ def _build_create_table_sql(self, table_name: str) -> str:
421442
else:
422443
indices += """CREATE {unique} INDEX IF NOT EXISTS "{name}" ON "{table}" ({columns});""".format(
423444
unique="UNIQUE" if index["unique"] in {1, "1"} else "",
424-
name="{table}_{name}".format(
425-
table=table_name,
426-
name=index["name"].decode() if isinstance(index["name"], bytes) else index["name"],
427-
)
428-
if self._prefix_indices
429-
else index["name"].decode()
430-
if isinstance(index["name"], bytes)
431-
else index["name"],
445+
name=f"{table_name}_{index_name}"
446+
if (index_name_collision is not None or self._prefix_indices)
447+
else index_name,
432448
table=table_name,
433449
columns=", ".join(f'"{column}"' for column in columns.split(",")),
434450
)

0 commit comments

Comments
 (0)