Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

.add_foreign_key() corrupts database if column contains a space #238

Closed
simonw opened this issue Feb 25, 2021 · 1 comment
Closed

.add_foreign_key() corrupts database if column contains a space #238

simonw opened this issue Feb 25, 2021 · 1 comment
Labels
bug Something isn't working

Comments

@simonw
Copy link
Owner

simonw commented Feb 25, 2021

I ran this:

db["Reports"].add_foreign_key("Reported by ID", "Reporters", "id")

And got this:

~/jupyter-venv/lib/python3.9/site-packages/sqlite_utils/db.py in add_foreign_keys(self, foreign_keys)
    616         # Have to VACUUM outside the transaction to ensure .foreign_keys property
    617         # can see the newly created foreign key.
--> 618         self.vacuum()
    619 
    620     def index_foreign_keys(self):

~/jupyter-venv/lib/python3.9/site-packages/sqlite_utils/db.py in vacuum(self)
    629 
    630     def vacuum(self):
--> 631         self.execute("VACUUM;")
    632 
    633 

~/jupyter-venv/lib/python3.9/site-packages/sqlite_utils/db.py in execute(self, sql, parameters)
    234             return self.conn.execute(sql, parameters)
    235         else:
--> 236             return self.conn.execute(sql)
    237 
    238     def executescript(self, sql):

DatabaseError: database disk image is malformed
@simonw simonw added the bug Something isn't working label Feb 25, 2021
@simonw
Copy link
Owner Author

simonw commented Feb 25, 2021

I bet the bug is in here:

table_sql = {}
for table, column, other_table, other_column in foreign_keys_to_create:
old_sql = table_sql.get(table, self[table].schema)
extra_sql = ",\n FOREIGN KEY({column}) REFERENCES {other_table}({other_column})\n".format(
column=column, other_table=other_table, other_column=other_column
)
# Stick that bit in at the very end just before the closing ')'
last_paren = old_sql.rindex(")")
new_sql = old_sql[:last_paren].strip() + extra_sql + old_sql[last_paren:]
table_sql[table] = new_sql

@simonw simonw closed this as completed in a76e3b3 Feb 25, 2021
simonw added a commit that referenced this issue May 29, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant