How to use compile_sql method in dbt-osmosis

Best Python code snippet using dbt-osmosis_python

evolve.py

Source:evolve.py Github

copy

Full Screen

1from optparse import make_option2import sys3import copy4try:5 import cPickle as pickle6except ImportError:7 import pickle as pickle8from django.conf import settings9from django.core.exceptions import ImproperlyConfigured10from django.core.management.base import BaseCommand, CommandError11from django.db.models import get_apps, get_app, signals12from django.db import connection, transaction13from django_evolution import CannotSimulate, SimulationFailure, EvolutionException14from django_evolution.diff import Diff15from django_evolution.evolve import get_unapplied_evolutions, get_mutations16from django_evolution.models import Version, Evolution17from django_evolution.mutations import DeleteApplication18from django_evolution.signature import create_project_sig19from django_evolution.utils import write_sql, execute_sql20class Command(BaseCommand):21 option_list = BaseCommand.option_list + (22 make_option('--noinput', action='store_false', dest='interactive', default=True,23 help='Tells Django to NOT prompt the user for input of any kind.'),24 make_option('--hint', action='store_true', dest='hint', default=False,25 help='Generate an evolution script that would update the app.'),26 make_option('--purge', action='store_true', dest='purge', default=False,27 help='Generate evolutions to delete stale applications.'),28 make_option('--sql', action='store_true', dest='compile_sql', default=False,29 help='Compile a Django evolution script into SQL.'),30 make_option('-x','--execute', action='store_true', dest='execute', default=False,31 help='Apply the evolution to the database.'),32 )33 if '--verbosity' not in [opt.get_opt_string() for opt in BaseCommand.option_list]:34 option_list += make_option('-v','--verbosity', action='store', dest='verbosity', default='1',35 type='choice', choices=['0', '1', '2'],36 help='Verbosity level; 0=minimal output, 1=normal output, 2=all output'),37 help = 'Evolve the models in a Django project.'38 args = '<appname appname ...>'39 requires_model_validation = False40 def handle(self, *app_labels, **options):41 verbosity = int(options['verbosity'])42 interactive = options['interactive']43 execute = options['execute']44 compile_sql = options['compile_sql']45 hint = options['hint']46 purge = options['purge']47 # Use the list of all apps, unless app labels are specified.48 if app_labels:49 if execute:50 raise CommandError('Cannot specify an application name when executing evolutions.')51 try:52 app_list = [get_app(app_label) for app_label in app_labels]53 except (ImproperlyConfigured, ImportError), e:54 raise CommandError("%s. Are you sure your INSTALLED_APPS setting is correct?" % e)55 else:56 app_list = get_apps()57 # Iterate over all applications running the mutations58 evolution_required = False59 simulated = True60 sql = []61 new_evolutions = []62 current_proj_sig = create_project_sig()63 current_signature = pickle.dumps(current_proj_sig)64 try:65 latest_version = Version.objects.latest('when')66 database_sig = pickle.loads(str(latest_version.signature))67 diff = Diff(database_sig, current_proj_sig)68 except Evolution.DoesNotExist:69 print self.style.ERROR("Can't evolve yet. Need to set an evolution baseline.")70 sys.exit(1)71 try:72 for app in app_list:73 app_label = app.__name__.split('.')[-2]74 if hint:75 evolutions = []76 hinted_evolution = diff.evolution()77 mutations = hinted_evolution.get(app_label,[])78 else:79 evolutions = get_unapplied_evolutions(app)80 mutations = get_mutations(app, evolutions)81 if mutations:82 app_sql = ['-- Evolve application %s' % app_label]83 evolution_required = True84 for mutation in mutations:85 # Only compile SQL if we want to show it86 if compile_sql or execute:87 app_sql.extend(mutation.mutate(app_label, database_sig))88 # Now run the simulation, which will modify the signatures89 try:90 mutation.simulate(app_label, database_sig)91 except CannotSimulate:92 simulated = False93 new_evolutions.extend(Evolution(app_label=app_label, label=label)94 for label in evolutions)95 if not execute:96 if compile_sql:97 write_sql(app_sql)98 else:99 print '#----- Evolution for %s' % app_label100 print 'from django_evolution.mutations import *'101 print 'from django.db import models'102 print103 print 'MUTATIONS = ['104 print ' ',105 print ',\n '.join(unicode(m) for m in mutations)106 print ']'107 print '#----------------------'108 sql.extend(app_sql)109 else:110 if verbosity > 1:111 print 'Application %s is up to date' % app_label112 # Process the purged applications if requested to do so.113 if purge:114 if diff.deleted:115 evolution_required = True116 delete_app = DeleteApplication()117 purge_sql = []118 for app_label in diff.deleted:119 if compile_sql or execute:120 purge_sql.append('-- Purge application %s' % app_label)121 purge_sql.extend(delete_app.mutate(app_label, database_sig))122 delete_app.simulate(app_label, database_sig)123 if not execute:124 if compile_sql:125 write_sql(purge_sql)126 else:127 print 'The following application(s) can be purged:'128 for app_label in diff.deleted:129 print ' ', app_label130 print131 sql.extend(purge_sql)132 else:133 if verbosity > 1:134 print 'No applications need to be purged.'135 except EvolutionException, e:136 print self.style.ERROR(e)137 sys.exit(1)138 if simulated:139 diff = Diff(database_sig, current_proj_sig)140 if not diff.is_empty(not purge):141 if hint:142 print self.style.ERROR('Your models contain changes that Django Evolution cannot resolve automatically.')143 print 'This is probably due to a currently unimplemented mutation type.'144 print 'You will need to manually construct a mutation to resolve the remaining changes.'145 else:146 print self.style.ERROR('The stored evolutions do not completely resolve all model changes.')147 print 'Run `./manage.py evolve --hint` to see a suggestion for the changes required.'148 print149 print 'The following are the changes that could not be resolved:'150 print diff151 sys.exit(1)152 else:153 print self.style.NOTICE('Evolution could not be simulated, possibly due to raw SQL mutations')154 if evolution_required:155 if execute:156 # Now that we've worked out the mutations required,157 # and we know they simulate OK, run the evolutions158 if interactive:159 confirm = raw_input("""160You have requested a database evolution. This will alter tables161and data currently in the %r database, and may result in162IRREVERSABLE DATA LOSS. Evolutions should be *thoroughly* reviewed163prior to execution.164Are you sure you want to execute the evolutions?165Type 'yes' to continue, or 'no' to cancel: """ % settings.DATABASE_NAME)166 else:167 confirm = 'yes'168 if confirm.lower() == 'yes':169 # Begin Transaction170 transaction.enter_transaction_management()171 transaction.managed(True)172 cursor = connection.cursor()173 try:174 # Perform the SQL175 execute_sql(cursor, sql)176 # Now update the evolution table177 version = Version(signature=current_signature)178 version.save()179 for evolution in new_evolutions:180 evolution.version = version181 evolution.save()182 transaction.commit()183 except Exception, ex:184 transaction.rollback()185 print self.style.ERROR('Error applying evolution: %s' % str(ex))186 sys.exit(1)187 transaction.leave_transaction_management()188 if verbosity > 0:189 print 'Evolution successful.'190 else:191 print self.style.ERROR('Evolution cancelled.')192 elif not compile_sql:193 if verbosity > 0:194 if simulated:195 print "Trial evolution successful."196 print "Run './manage.py evolve %s--execute' to apply evolution." % (hint and '--hint ' or '')197 else:198 if verbosity > 0:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run dbt-osmosis automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful