Browse Source

Arruma problema do objeto inexistente

Signed-off-by: Luciano Almeida <mdiebr@gmail.com>
pull/883/head
Luciano Almeida 8 years ago
parent
commit
bc0afcbd96
  1. 27
      sapl/legacy/migration.py
  2. 3
      sapl/legacy/scripts/fix_tables.sql
  3. 2
      sapl/legacy_migration_settings.py
  4. 2
      sapl/norma/forms.py

27
sapl/legacy/migration.py

@ -6,7 +6,7 @@ from django.apps import apps
from django.apps.config import AppConfig from django.apps.config import AppConfig
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from django.db import connections, models from django.db import connections, models, OperationalError, ProgrammingError
from django.db.models import CharField, TextField, ProtectedError from django.db.models import CharField, TextField, ProtectedError
from django.db.models.base import ModelBase from django.db.models.base import ModelBase
from model_mommy import mommy from model_mommy import mommy
@ -115,8 +115,13 @@ def get_fk_related(field, value, label=None):
if value == 0: if value == 0:
if not field.null: if not field.null:
fields_dict = get_fields_dict(field.related_model) fields_dict = get_fields_dict(field.related_model)
value = mommy.make(field.related_model, # Cria stub ao final da tabela para evitar erros
**fields_dict) pk = 1
if hasattr(field.related_model.objects.last(), 'pk'):
pk = field.related_model.objects.last().pk
value = mommy.make(
field.related_model, **fields_dict,
pk=(pk + 1 or 1))
descricao = 'stub criado para campos não nuláveis!' descricao = 'stub criado para campos não nuláveis!'
save_relation(value, [field.name], msg, descricao, save_relation(value, [field.name], msg, descricao,
eh_stub=True) eh_stub=True)
@ -141,6 +146,15 @@ def get_field(model, fieldname):
return model._meta.get_field(fieldname) return model._meta.get_field(fieldname)
def exec_sql_file(path, db='default'):
cursor = connections[db].cursor()
for line in open(path):
try:
cursor.execute(line)
except (OperationalError, ProgrammingError) as e:
print("Args: '%s'" % (str(e.args)))
def exec_sql(sql, db='default'): def exec_sql(sql, db='default'):
cursor = connections[db].cursor() cursor = connections[db].cursor()
cursor.execute(sql) cursor.execute(sql)
@ -221,11 +235,13 @@ def save_with_id(new, id):
sequence_name = '%s_id_seq' % type(new)._meta.db_table sequence_name = '%s_id_seq' % type(new)._meta.db_table
cursor = exec_sql('SELECT last_value from %s;' % sequence_name) cursor = exec_sql('SELECT last_value from %s;' % sequence_name)
(last_value,) = cursor.fetchone() (last_value,) = cursor.fetchone()
if last_value == 1 or id != last_value + 1: if last_value == 1 or id != last_value + 1:
# we explicitly set the next id if last_value == 1 # we explicitly set the next id if last_value == 1
# because last_value == 1 for a table containing either 0 or 1 records # because last_value == 1 for a table containing either 0 or 1 records
# (we would have trouble for id == 2 and a missing id == 1) # (we would have trouble for id == 2 and a missing id == 1)
exec_sql('ALTER SEQUENCE %s RESTART WITH %s;' % (sequence_name, id)) cursor = exec_sql(
'ALTER SEQUENCE %s RESTART WITH %s;' % (sequence_name, id))
new.save() new.save()
assert new.id == id, 'New id is different from provided!' assert new.id == id, 'New id is different from provided!'
@ -241,7 +257,7 @@ def save_relation(obj, nome_campo='', problema='', descricao='',
def make_stub(model, id): def make_stub(model, id):
fields_dict = get_fields_dict(model) fields_dict = get_fields_dict(model)
new = mommy.prepare(model, **fields_dict) new = mommy.prepare(model, **fields_dict, pk=id)
save_with_id(new, id) save_with_id(new, id)
return new return new
@ -332,6 +348,7 @@ class DataMigrator:
# warning: model/app migration order is of utmost importance # warning: model/app migration order is of utmost importance
self.to_delete = [] self.to_delete = []
ProblemaMigracao.objects.all().delete() ProblemaMigracao.objects.all().delete()
exec_sql_file('sapl/legacy/scripts/fix_tables.sql', 'legacy')
get_user_model().objects.exclude(is_superuser=True).delete() get_user_model().objects.exclude(is_superuser=True).delete()
info('Começando migração: %s...' % obj) info('Começando migração: %s...' % obj)

3
sapl/legacy/scripts/fix_tables.sql

@ -0,0 +1,3 @@
DROP PROCEDURE IF EXISTS verifica_campos;
CREATE PROCEDURE verifica_campos() BEGIN IF NOT EXISTS (SELECT * FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='proposicao' AND column_name='num_proposicao') THEN ALTER TABLE proposicao add column num_proposicao int(11) NULL after txt_justif_devolucao; END IF; END;
CALL verifica_campos;

2
sapl/legacy_migration_settings.py

@ -28,6 +28,8 @@ DATABASES['legacy'] = config('DATABASE_URL', cast=db_url,)
DATABASE_ROUTERS = ['sapl.legacy.router.LegacyRouter', ] DATABASE_ROUTERS = ['sapl.legacy.router.LegacyRouter', ]
DEBUG = False
MOMMY_CUSTOM_FIELDS_GEN = { MOMMY_CUSTOM_FIELDS_GEN = {
'django.db.models.ForeignKey': 'sapl.legacy.migration.make_with_log' 'django.db.models.ForeignKey': 'sapl.legacy.migration.make_with_log'
} }

2
sapl/norma/forms.py

@ -35,8 +35,6 @@ ORDENACAO_CHOICES = [('', '---------'),
class NormaFilterSet(django_filters.FilterSet): class NormaFilterSet(django_filters.FilterSet):
RANGE_ANOS.insert(0, ('', 'Selecione'))
filter_overrides = {models.DateField: { filter_overrides = {models.DateField: {
'filter_class': django_filters.DateFromToRangeFilter, 'filter_class': django_filters.DateFromToRangeFilter,
'extra': lambda f: { 'extra': lambda f: {

Loading…
Cancel
Save