sqliteexportsqlitestudio

How can I get SqlLiteStudio to export to SQL file with tables in the correct order?


I have a relational SQLite database with tables accessing each other via foreign keys. When I use SqlLiteStudio "Export" to output to a new SQL file, it writes out SQL "CREATE" and "INSERT INTO" statements based on alphabetical order of table names. When I then import the same SQL file into a new database (which requires use of the command "Execute SQL from File", because the import command seems to only import csv into a table), I get the "no such table" error, because the line to create the table being referenced is not yet read. So if I edit the SQL file to put the tables at the top, then I get the "FOREIGN KEY constraint failed" error. So then if I edit the SQL file to all the tables insert operations below the table creations, AND reorder the inserts by table so that no table precedes its table dependencies, only then I can successfully import the SQL file, reproducing the original SQLite database file. Seems like a bug in SqlLiteStudio. I suppose worse case I can write a post-processing script, but I'm hoping to find out if there's some better method people are using. I just prefer to save in text format for backup into an existing git repo, and also make it easier for db migration later. TIA.


Solution

  • You could turn Foreign Key Support Off before the import and then back On after the import using

    PRAGMA foreign_keys = off;
    ....
    PRAGMA foreign_keys = on;
    

    see https://sqlite.org/pragma.html#pragma_foreign_keys