migrations and get_from_db

This commit is contained in:
Cayo Puigdefabregas 2022-12-13 14:02:38 +01:00
parent fac6380bcf
commit 756925d657
2 changed files with 74 additions and 18 deletions

View File

@ -0,0 +1,67 @@
"""add hash hid to device
Revision ID: 93daff872771
Revises: 564952310b17
Create Date: 2022-12-13 10:14:45.500087
"""
from alembic import context, op
import sqlalchemy as sa
import citext
import hashlib
# revision identifiers, used by Alembic.
revision = '93daff872771'
down_revision = '564952310b17'
branch_labels = None
depends_on = None
def get_inv():
INV = context.get_x_argument(as_dictionary=True).get('inventory')
if not INV:
raise ValueError("Inventory value is not specified")
return INV
def upgrade_data():
con = op.get_bind()
sql = f"update {get_inv()}.computer set user_trusts='t';"
con.execute(sql)
dev_sql = f"select id, hid from {get_inv()}.device;"
for d in con.execute(dev_sql):
if not d.hid:
continue
dev_id = d.id
chid = hashlib.sha3_256(d.hid.encode('utf-8')).hexdigest()
sql = f"update {get_inv()}.device set chid={chid} where id={dev_id};"
def upgrade():
op.add_column(
'computer',
sa.Column('user_trusts', sa.Boolean(), default=True, nullable=True),
schema=f'{get_inv()}',
)
op.add_column(
'device',
sa.Column('chid', citext.CIText(), nullable=True),
schema=f'{get_inv()}',
)
upgrade_data()
op.alter_column(
'computer',
'user_trusts',
nullable=False,
schema=f'{get_inv()}'
)
def downgrade():
op.drop_column('computer', 'user_trusts', schema=f'{get_inv()}')
op.drop_column('device', 'chid', schema=f'{get_inv()}')

View File

@ -1,6 +1,5 @@
import copy
import difflib
from contextlib import suppress
from itertools import groupby
from typing import Iterable, Set
@ -16,13 +15,18 @@ from ereuse_devicehub.db import db
from ereuse_devicehub.resources.action.models import Remove
from ereuse_devicehub.resources.device.models import (
Component,
Computer,
DataStorage,
Device,
Placeholder,
)
from ereuse_devicehub.resources.tag.model import Tag
try:
from modules.device.models import Computer
except:
from ereuse_devicehub.resources.device.models import Computer
DEVICES_ALLOW_DUPLICITY = [
'RamModule',
'Display',
@ -200,22 +204,7 @@ class Sync:
assert all(
inspect(tag).transient for tag in device.tags
), 'Tags cannot be synced from DB'
db_device = None
if isinstance(device, Computer):
# first search by uuid
if device.system_uuid:
with suppress(ResourceNotFound):
db_device = Computer.query.filter_by(
system_uuid=device.system_uuid,
owner_id=g.user.id,
active=True,
placeholder=None,
).one()
# if no there are any Computer by uuid search by hid
if not db_device:
db_device = device.get_from_db()
elif device.hid:
db_device = device.get_from_db()
db_device = device.get_from_db()
if db_device and db_device.allocated:
raise ResourceNotFound('device is actually allocated {}'.format(device))