In solutions where I need something like this, I try to store the .sql file located in the same directory as my code containing the assembly instructions for the database, using constructs similar to the following:
# setup PRAGMA foreign_keys=ON; PRAGMA journal_mode=TRUNCATE; PRAGMA locking_mode=EXCLUSIVE; PRAGMA synchronous=NORMAL;
just taking care that all SQL statements end with a semicolon as the last character without a space, as I have code similar to the following method, which ensures the execution of the schema every time my application starts:
def db_schema(self): cur= self._db.cursor() with io.open(self.SQLPATH, "r") as fp: sql_statement= "" for line in fp: line= line.rstrip() if line.startswith('#'): continue sql_statement+= line if line.endswith(";"): try: cur.execute(sql_statement) except sql.OperationalError: print("Failed:\n%s" % sql_statement) sql_statement= ""
Note the use of CREATE TABLE IF NOT EXISTS and CREATE INDEX IF NOT EXISTS .
source share