Changeset - 6849b3fad164
[Not reviewed]
default
0 1 0
domruf - 9 years ago 2017-03-21 22:44:21
dominikruf@gmail.com
db: drop and re-create old schemas instead of Base.metadata.drop_all()

Sadly, Base.metadata.drop_all() sometimes doesn't work because of foreign key
constraints. We only know this is the case on PostgreSQL and MySQL - use
workarounds for these.
1 file changed with 24 insertions and 1 deletions:
0 comments (0 inline, 0 general)
kallithea/lib/db_manage.py
Show inline comments
 
@@ -28,12 +28,13 @@ Original author and date, and relevant c
 

	
 
import os
 
import sys
 
import time
 
import uuid
 
import logging
 
import sqlalchemy
 
from os.path import dirname
 

	
 
import alembic.config
 
import alembic.command
 

	
 
from kallithea.model.user import UserModel
 
@@ -100,13 +101,35 @@ class DbManage(object):
 
        else:
 
            destroy = self._ask_ok('Are you sure to destroy old database ? [y/n]')
 
        if not destroy:
 
            print 'Nothing done.'
 
            sys.exit(0)
 
        if destroy:
 
            Base.metadata.drop_all()
 
            # drop and re-create old schemas
 

	
 
            url = sqlalchemy.engine.url.make_url(self.dburi)
 
            database = url.database
 

	
 
            # Some databases enforce foreign key constraints and Base.metadata.drop_all() doesn't work
 
            if url.drivername == 'mysql':
 
                url.database = None  # don't connect to the database (it might not exist)
 
                engine = sqlalchemy.create_engine(url)
 
                with engine.connect() as conn:
 
                    conn.execute('DROP DATABASE IF EXISTS ' + database)
 
                    conn.execute('CREATE DATABASE ' + database)
 
            elif url.drivername == 'postgresql':
 
                from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
 
                url.database = 'postgres'  # connect to the system database (as the real one might not exist)
 
                engine = sqlalchemy.create_engine(url)
 
                with engine.connect() as conn:
 
                    conn.connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
 
                    conn.execute('DROP DATABASE IF EXISTS ' + database)
 
                    conn.execute('CREATE DATABASE ' + database)
 
            else:
 
                # known to work on SQLite - possibly not on other databases with strong referential integrity
 
                Base.metadata.drop_all()
 

	
 
        checkfirst = not override
 
        Base.metadata.create_all(checkfirst=checkfirst)
 

	
 
        # Create an Alembic configuration and generate the version table,
 
        # "stamping" it with the most recent Alembic migration revision, to
0 comments (0 inline, 0 general)