power the optimization process where you provide a list of operations and you are returned a list of equal or shorter length operations are merged into one if possible for example a createmodel and an addfield can be optimized into a new createmodel and createmodel and deletemodel can be optimized into nothing main optimization entry point pass in a list of operation instances get out a new list of operation instances unfortunately due to the scope of the optimization two combinable operations might be separated by several hundred others this can t be done as a peephole optimization with checksoutput implemented on the operations themselves instead the optimizer looks at each individual operation and scans forwards in the list to see if there are any matches stopping at boundaries operations which can t be optimized over runsql operations on the same fieldmodel etc the inner loop is run until the starting list is the same as the result list and then the result is returned this means that operation optimization must be stable and always return an equal or shorter list internal tracking variable for test assertions about of loops inner optimization loop newoperations for i operation in enumerateoperations right true should we reduce on the right or on the left compare it to each operation after it for j other in enumerateoperationsi 1 result operation reduceother applabel if isinstanceresult list inbetween operationsi 1 i j 1 if right newoperations extendinbetween newoperations extendresult elif allop reduceother applabel is true for op in inbetween perform a left reduction if all of the inbetween operations can optimize through other newoperations extendresult newoperations extendinbetween else otherwise keep trying newoperations appendoperation break newoperations extendoperationsi j 2 return newoperations elif not result can t perform a right reduction right false else newoperations appendoperation return newoperations power the optimization process where you provide a list of operations and you are returned a list of equal or shorter length operations are merged into one if possible for example a createmodel and an addfield can be optimized into a new createmodel and createmodel and deletemodel can be optimized into nothing main optimization entry point pass in a list of operation instances get out a new list of operation instances unfortunately due to the scope of the optimization two combinable operations might be separated by several hundred others this can t be done as a peephole optimization with checks output implemented on the operations themselves instead the optimizer looks at each individual operation and scans forwards in the list to see if there are any matches stopping at boundaries operations which can t be optimized over runsql operations on the same field model etc the inner loop is run until the starting list is the same as the result list and then the result is returned this means that operation optimization must be stable and always return an equal or shorter list internal tracking variable for test assertions about of loops inner optimization loop should we reduce on the right or on the left compare it to each operation after it perform a left reduction if all of the in between operations can optimize through other otherwise keep trying can t perform a right reduction
class MigrationOptimizer:
    

    def optimize(self, operations, app_label):
        
        
        if app_label is None:
            raise TypeError("app_label must be a str.")
        self._iterations = 0
        while True:
            result = self.optimize_inner(operations, app_label)
            self._iterations += 1
            if result == operations:
                return result
            operations = result

    def optimize_inner(self, operations, app_label):
        
        new_operations = []
        for i, operation in enumerate(operations):
            right = True  
            
            for j, other in enumerate(operations[i + 1 :]):
                result = operation.reduce(other, app_label)
                if isinstance(result, list):
                    in_between = operations[i + 1 : i + j + 1]
                    if right:
                        new_operations.extend(in_between)
                        new_operations.extend(result)
                    elif all(op.reduce(other, app_label) is True for op in in_between):
                        
                        
                        new_operations.extend(result)
                        new_operations.extend(in_between)
                    else:
                        
                        new_operations.append(operation)
                        break
                    new_operations.extend(operations[i + j + 2 :])
                    return new_operations
                elif not result:
                    
                    right = False
            else:
                new_operations.append(operation)
        return new_operations