am-freescan/scripts/apply_dimension_comparison.py

42 lines
2.6 KiB
Python
Raw Normal View History

"""Add only the three comparison tables to the explicitly owned development database.
Default is offline. No menus, users, tasks, flows or historical results are changed.
"""
from pathlib import Path
import argparse,hashlib,json,sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
import bootstrap_db as base
from apply_scan_only import load_migration,apply_schema
SQL=base.SQL_ROOT/'017_dimension_comparison.sql'
TABLES={'lab_inspection_scan','lab_inspection_template','lab_dimension_comparison'}
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
operations=load_migration(SQL)
if {item['table'] for item in operations}!=TABLES or any(item['kind']!='table' for item in operations):raise ValueError('Unexpected schema operation')
if not args.apply:print(json.dumps(dict(offline=True,tables=sorted(TABLES),noDatabaseConnection=True)));return
import pymysql
config=json.loads((ROOT/'.local/runtime.json').read_text(encoding='utf-8-sig'))['mysql'];base.validate_target(config)
db=pymysql.connect(host=config['host'],port=int(config.get('port',3306)),user=config['user'],password=config['password'],database=config['database'],charset='utf8mb4',autocommit=True)
try:
with db.cursor() as cursor:
cursor.execute(f"SELECT value FROM `{base.META}` WHERE name='owner'")
if cursor.fetchone()!=(base.OWNER,):raise ValueError('Database ownership mismatch')
cursor.execute('SELECT GET_LOCK(%s,10)',(base.OWNER,))
if cursor.fetchone()!=(1,):raise ValueError('Another schema operation is running')
try:
before={}
for table in ['lab_test_task','lab_execution','lab_fixture','system_menu']:
cursor.execute(f'SELECT COUNT(*) FROM `{table}`');before[table]=cursor.fetchone()[0]
changes=apply_schema(cursor,operations)
for table,count in before.items():
cursor.execute(f'SELECT COUNT(*) FROM `{table}`')
if cursor.fetchone()[0]!=count:raise ValueError('Unexpected concurrent business change; review before continuing')
cursor.execute(f'INSERT INTO `{base.META}` (name,value) VALUES(%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',(SQL.name,hashlib.sha256(SQL.read_bytes()).hexdigest()))
print(json.dumps(dict(applied=True,additiveChanges=changes,existingRowsPreserved=True)))
finally:cursor.execute('SELECT RELEASE_LOCK(%s)',(base.OWNER,))
finally:db.close()
if __name__=='__main__':
try:main()
except Exception as error:
print('Comparison schema stopped: '+(str(error) if isinstance(error,ValueError) else type(error).__name__+'; inspect private configuration'),file=sys.stderr);raise SystemExit(1)