Search code examples
pythonflaskflask-sqlalchemyflask-migrate

migrations are getting created repeatedly


I have created some models and when I run python manage.py db migrate command it creates migrations file, so that is fine.
python manage.py db upgrade command also creates table in Database.
If I again run the python manage.py db migrate command then it is creating migrations file for those models that I have upgraded recently.
Can you please help me to resolve it.


Solution

  • I had same problem and i've resolved it.

    In my case, There is a problem on getting current table names. (when calling get_table_names function in _autogen_for_tables((alembic/autogenerate/compare.py))

    I am using sqlalchemy with the mysql-connector. mysql-connector return table information as bytearray. so i've changed temporally the following. (base.py(sqlalchemy/dialects/mysql))

    @reflection.cache
    def get_table_names(self, connection, schema=None, **kw):
        """Return a Unicode SHOW TABLES from a given schema."""
        if schema is not None:
            current_schema = schema
        else:
            current_schema = self.default_schema_name
    
        charset = self._connection_charset
        if self.server_version_info < (5, 0, 2):
            rp = connection.execute(
                "SHOW TABLES FROM %s"
                % self.identifier_preparer.quote_identifier(current_schema)
            )
            return [
                row[0] for row in self._compat_fetchall(rp, charset=charset)
            ]
        else:
            rp = connection.execute(
                "SHOW FULL TABLES FROM %s"
                % self.identifier_preparer.quote_identifier(current_schema)
            )
    
            return [
                row[0]
                for row in self._compat_fetchall(rp, charset=charset)
                if row[1]  == "BASE TABLE"
            ]
    

    to

    @reflection.cache
    def get_table_names(self, connection, schema=None, **kw):
        """Return a Unicode SHOW TABLES from a given schema."""
        if schema is not None:
            current_schema = schema
        else:
            current_schema = self.default_schema_name
    
        charset = self._connection_charset
        if self.server_version_info < (5, 0, 2):
            rp = connection.execute(
                "SHOW TABLES FROM %s"
                % self.identifier_preparer.quote_identifier(current_schema)
            )
            return [
                row[0] for row in self._compat_fetchall(rp, charset=charset)
            ]
        else:
            rp = connection.execute(
                "SHOW FULL TABLES FROM %s"
                % self.identifier_preparer.quote_identifier(current_schema)
            )
    
            return [
                row[0].decode("utf-8")
                for row in self._compat_fetchall(rp, charset=charset)
                if row[1].decode("utf-8")  == "BASE TABLE"
            ]