Browse Source

Merge branch '1468-migracao-com-sqlite'

Fix #1468
pull/1477/head
Marcio Mazza 7 years ago
parent
commit
d37fa466a9
  1. 1
      .coveragerc
  2. 2
      sapl/legacy/management/commands/migracao_25_31.py
  3. 22
      sapl/legacy/migration.py
  4. 5
      sapl/legacy/scripts/migra_um_db.sh
  5. 10
      sapl/legacy_migration_settings.py
  6. 50
      sapl/rules/apps.py

1
.coveragerc

@ -1,4 +1,5 @@
[run] [run]
source = sapl
omit = omit =
sapl/wsgi.py sapl/wsgi.py
manage.py manage.py

2
sapl/legacy/management/commands/migracao_25_31.py

@ -1,3 +1,4 @@
from django.core import management
from django.core.management.base import BaseCommand from django.core.management.base import BaseCommand
from sapl.legacy import migration from sapl.legacy import migration
@ -17,4 +18,5 @@ class Command(BaseCommand):
) )
def handle(self, *args, **options): def handle(self, *args, **options):
management.call_command('migrate')
migration.migrate(interativo=not options['force']) migration.migrate(interativo=not options['force'])

22
sapl/legacy/migration.py

@ -165,20 +165,6 @@ def get_last_value(model):
return last_value['pk__max'] or 0 return last_value['pk__max'] or 0
def alter_sequence(model, id):
sequence_name = '%s_id_seq' % model._meta.db_table
exec_sql('ALTER SEQUENCE %s RESTART WITH %s MINVALUE -1;' % (
sequence_name, id))
def save_with_id(new, id):
last_value = get_last_value(type(new))
alter_sequence(type(new), id)
new.save()
alter_sequence(type(new), last_value + 1)
assert new.id == id, 'New id is different from provided!'
def save_relation(obj, nome_campo='', problema='', descricao='', def save_relation(obj, nome_campo='', problema='', descricao='',
eh_stub=False, critico=False): eh_stub=False, critico=False):
link = ProblemaMigracao( link = ProblemaMigracao(
@ -364,7 +350,9 @@ class DataMigrator:
else: else:
def save(new, old): def save(new, old):
with reversion.create_revision(): with reversion.create_revision():
save_with_id(new, getattr(old, legacy_pk_name)) # salva new com id de old
new.id = getattr(old, legacy_pk_name)
new.save()
reversion.set_comment('Objeto criado pela migração') reversion.set_comment('Objeto criado pela migração')
old_records = legacy_model.objects.all().order_by(legacy_pk_name) old_records = legacy_model.objects.all().order_by(legacy_pk_name)
@ -400,10 +388,6 @@ class DataMigrator:
reversion.set_comment( reversion.set_comment(
'Ajuste de data pela migração') 'Ajuste de data pela migração')
# necessário para ajustar sequence da tabela para o ultimo valor de id
ultimo_valor = get_last_value(model)
alter_sequence(model, ultimo_valor + 1)
def migrate(obj=appconfs, interativo=True): def migrate(obj=appconfs, interativo=True):
dm = DataMigrator() dm = DataMigrator()

5
sapl/legacy/scripts/migra_um_db.sh

@ -14,11 +14,6 @@ echo "########################################" | tee -a $LOG
echo >> $LOG echo >> $LOG
echo "--- DJANGO MIGRATE ---" | tee -a $LOG
echo >> $LOG
DATABASE_NAME=$1 ./manage.py migrate --settings sapl.legacy_migration_settings
echo >> $LOG
echo "--- MIGRACAO DE DADOS ---" | tee -a $LOG echo "--- MIGRACAO DE DADOS ---" | tee -a $LOG
echo >> $LOG echo >> $LOG
DATABASE_NAME=$1 ./manage.py migracao_25_31 -f --settings sapl.legacy_migration_settings |& tee -a $LOG DATABASE_NAME=$1 ./manage.py migracao_25_31 -f --settings sapl.legacy_migration_settings |& tee -a $LOG

10
sapl/legacy_migration_settings.py

@ -12,14 +12,18 @@ INSTALLED_APPS += (
'sapl.legacy', # legacy reversed model definitions 'sapl.legacy', # legacy reversed model definitions
) )
DATABASES['legacy'] = config('DATABASE_URL', cast=db_url,) DATABASES['legacy'] = config('DATABASE_URL_FONTE', cast=db_url,)
DATABASES['default'] = config('DATABASE_URL_DESTINO', cast=db_url,
default=DATABASES['default'])
# Sobrescreve o nome dos bancos caso a variável de ambiente seja definida # Sobrescreve o nome dos bancos caso a variável de ambiente seja definida
# Útil para migração em lote de vários bancos # Útil para migração em lote de vários bancos
DATABASE_NAME_OVERRIDE = os.environ.get('DATABASE_NAME') DATABASE_NAME_OVERRIDE = os.environ.get('DATABASE_NAME')
if DATABASE_NAME_OVERRIDE: if DATABASE_NAME_OVERRIDE:
for db in DATABASES.values(): DATABASES['legacy']['NAME'] = DATABASE_NAME_OVERRIDE
db['NAME'] = DATABASE_NAME_OVERRIDE # não altera o nome se o destino é um banco em memória
if not DATABASES['default']['NAME'] == ':memory:':
DATABASES['default']['NAME'] = DATABASE_NAME_OVERRIDE
DATABASE_ROUTERS = ['sapl.legacy.router.LegacyRouter', ] DATABASE_ROUTERS = ['sapl.legacy.router.LegacyRouter', ]

50
sapl/rules/apps.py

@ -3,7 +3,6 @@ from builtins import LookupError
import django import django
import reversion import reversion
from django.apps import apps from django.apps import apps
from django.conf import settings
from django.contrib.auth import get_user_model from django.contrib.auth import get_user_model
from django.contrib.auth.management import _get_all_permissions from django.contrib.auth.management import _get_all_permissions
from django.core import exceptions from django.core import exceptions
@ -116,7 +115,8 @@ def create_proxy_permissions(
def update_groups(app_config, verbosity=2, interactive=True, def update_groups(app_config, verbosity=2, interactive=True,
using=DEFAULT_DB_ALIAS, **kwargs): using=DEFAULT_DB_ALIAS, cria_usuarios_padrao=False,
**kwargs):
if app_config != AppConfig and not isinstance(app_config, AppConfig): if app_config != AppConfig and not isinstance(app_config, AppConfig):
return return
@ -149,41 +149,16 @@ def update_groups(app_config, verbosity=2, interactive=True,
if not group_name: if not group_name:
return return
g = Group.objects.get_or_create(name=group_name) group, created = Group.objects.get_or_create(name=group_name)
if not isinstance(g, Group): group.permissions.clear()
g = g[0]
g.permissions.clear()
try: try:
print(' ', group_name) print(' ', group_name)
for model, perms in rules_list: for model, perms in rules_list:
self.associar(g, model, perms) self.associar(group, model, perms)
except Exception as e: except Exception as e:
print(group_name, e) print(group_name, e)
if settings.DEBUG:
user = ''
if group_name == SAPL_GROUP_ADMINISTRATIVO:
user = 'operador_administrativo'
elif group_name == SAPL_GROUP_PROTOCOLO:
user = 'operador_protocoloadm'
elif group_name == SAPL_GROUP_COMISSOES:
user = 'operador_comissoes'
elif group_name == SAPL_GROUP_MATERIA:
user = 'operador_materia'
elif group_name == SAPL_GROUP_NORMA:
user = 'operador_norma'
elif group_name == SAPL_GROUP_SESSAO:
user = 'operador_sessao'
elif group_name == SAPL_GROUP_PAINEL:
user = 'operador_painel'
elif group_name == SAPL_GROUP_GERAL:
user = 'operador_geral'
if user:
self.cria_usuario(user, g)
def groups_add_user(self, user, groups_name): def groups_add_user(self, user, groups_name):
if not isinstance(groups_name, list): if not isinstance(groups_name, list):
groups_name = [groups_name, ] groups_name = [groups_name, ]
@ -213,6 +188,19 @@ def update_groups(app_config, verbosity=2, interactive=True,
usuario.save() usuario.save()
grupo.user_set.add(usuario) grupo.user_set.add(usuario)
def cria_usuarios_padrao(self):
for group, user in (
(SAPL_GROUP_ADMINISTRATIVO, 'operador_administrativo'),
(SAPL_GROUP_PROTOCOLO, 'operador_protocoloadm'),
(SAPL_GROUP_COMISSOES, 'operador_comissoes'),
(SAPL_GROUP_MATERIA, 'operador_materia'),
(SAPL_GROUP_NORMA, 'operador_norma'),
(SAPL_GROUP_SESSAO, 'operador_sessao'),
(SAPL_GROUP_PAINEL, 'operador_painel'),
(SAPL_GROUP_GERAL, 'operador_geral'),
):
self.cria_usuario(user, group)
def update_groups(self): def update_groups(self):
print('') print('')
print(string_concat('\033[93m\033[1m', print(string_concat('\033[93m\033[1m',
@ -225,6 +213,8 @@ def update_groups(app_config, verbosity=2, interactive=True,
rules = Rules(rules_patterns) rules = Rules(rules_patterns)
rules.update_groups() rules.update_groups()
if cria_usuarios_padrao:
rules.cria_usuarios_padrao()
def revision_pre_delete_signal(sender, **kwargs): def revision_pre_delete_signal(sender, **kwargs):

Loading…
Cancel
Save