"""Add the task delivery tables, preserving all existing business rows and menus.""" from pathlib import Path import json,sys,hashlib,datetime,subprocess ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/'scripts')) from bootstrap_db import validate_target def apply(): import pymysql runtime=json.loads((ROOT/'.local/runtime.json').read_text(encoding='utf-8-sig'))['mysql'];validate_target(runtime) db=pymysql.connect(host=runtime['host'],port=int(runtime.get('port',3306)),user=runtime['user'],password=runtime['password'],database=runtime['database'],charset='utf8mb4',autocommit=True) sql=(ROOT/'am-backend/sql/freescan/014_dimension_delivery.sql').read_text(encoding='utf-8') # Only additive DDL from this exact reviewed migration is accepted. statements=['\n'.join(line for line in part.splitlines() if not line.lstrip().startswith('--')).strip() for part in sql.split(';')] if any(not s.upper().startswith('CREATE TABLE IF NOT EXISTS LAB_DIMENSION_') for s in statements if s):raise ValueError('Unexpected migration statement') with db.cursor() as c: c.execute('SELECT DATABASE()');assert c.fetchone()[0]=='am-freescan' counts={} for table in ['lab_test_task','lab_execution','lab_task_sample_unit','lab_artifact_file','lab_report','lab_device','iot_robot','iot_device']: c.execute('SELECT COUNT(*) FROM `'+table+'`');counts[table]=c.fetchone()[0] baseline=ROOT/'.local/dimension-baseline-20261103.json' if not baseline.exists():baseline.write_text(json.dumps({'at':datetime.datetime.now().isoformat(),'commit':subprocess.check_output(['git','rev-parse','HEAD'],cwd=ROOT,text=True).strip(),'counts':counts,'migrationSha256':hashlib.sha256(sql.encode()).hexdigest()},indent=2),encoding='utf-8') for statement in statements: if statement:c.execute(statement) for table,count in counts.items():c.execute('SELECT COUNT(*) FROM `'+table+'`');assert c.fetchone()[0]==count,table db.close();print('Delivery tables ready; existing data counts unchanged; private baseline saved locally.') if __name__=='__main__':apply()