am-freescan/scripts/apply_scanner_integration.py

39 lines
2.2 KiB
Python
Raw Normal View History

"""Apply additive scanner integration schema only to the owned am-freescan database."""
import argparse
import hashlib
import json
from pathlib import Path
from apply_scan_only import load_migration, apply_schema
from bootstrap_db import HOST, DATABASE, META, OWNER, validate_target
ROOT=Path(__file__).resolve().parents[1]
MIGRATIONS=[ROOT/'am-backend/sql/freescan'/name for name in ('007_scanner_integration.sql','008_scanner_execution_view.sql','009_rotary_base_integration.sql','010_scanner_framework_reference.sql','011_fixture_framework.sql','012_robot_service_endpoint.sql')]
def main():
args=argparse.ArgumentParser(description=__doc__)
args.add_argument('--apply',action='store_true');options=args.parse_args()
operations=[operation for migration in MIGRATIONS for operation in load_migration(migration)]
if not options.apply:
print(f'DRY RUN: {HOST}/{DATABASE}; {len(operations)} additive scanner integration DDL statements')
return
import pymysql
config=json.loads((ROOT/'.local/runtime.json').read_text(encoding='utf-8-sig'))['mysql'];validate_target(config)
db=pymysql.connect(host=HOST,port=int(config.get('port',3306)),user=config['user'],password=config['password'],database=DATABASE,charset='utf8mb4',autocommit=True)
locked=False
try:
with db.cursor() as cursor:
cursor.execute(f'SELECT value FROM `{META}` WHERE name=%s',('owner',))
if cursor.fetchone()!=(OWNER,): raise RuntimeError('Independent database ownership verification failed')
cursor.execute('SELECT GET_LOCK(%s,10)',(OWNER,));locked=cursor.fetchone()==(1,)
if not locked: raise RuntimeError('Another owned-database bootstrap is running')
changed=apply_schema(cursor,operations)
for migration in MIGRATIONS:
cursor.execute(f'INSERT INTO `{META}` (name,value) VALUES (%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',(migration.name,hashlib.sha256(migration.read_bytes()).hexdigest()))
print(json.dumps(dict(target=DATABASE,schemaChanges=changed,historicalDataPreserved=True)))
finally:
if locked:
with db.cursor() as cursor: cursor.execute('SELECT RELEASE_LOCK(%s)',(OWNER,))
db.close()
if __name__=='__main__': main()