am-freescan/scripts/apply_scan_only.py

125 lines
6.1 KiB
Python
Raw Normal View History

2026-10-22 16:18:37 +08:00
"""Add scan-only structures and reorganize menus in owned am-freescan only.
Default is an offline dry run. Run bootstrap_db.py and bootstrap_cmvr.py first,
then pass --apply explicitly. No business rows or historical executions are
removed. Existing columns/indexes are skipped rather than modified.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
import re
import sys
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / '.tools/python'))
from bootstrap_db import DATABASE, HOST, META, OWNER, finalize_permissions, split_sql, validate_target
from bootstrap_cmvr import load_reference, references, verify_references
MIGRATION = ROOT / 'am-backend/sql/freescan/005_scan_only.sql'
IDENTIFIER = r'`?(lab_[a-z0-9_]+)`?'
def load_migration(path=MIGRATION):
"""Validate every statement before opening a connection or changing data."""
operations = []
for sql in split_sql(path.read_text(encoding='utf-8-sig')):
# The approved migration is simple DDL. Remove quoted strings before
# checking SQL keywords so comments/default text cannot spoof syntax.
syntax = re.sub(r"'(?:\\.|''|[^'])*'", "''", sql)
syntax = re.sub(r'\bON\s+UPDATE\s+CURRENT_TIMESTAMP(?:\(\d*\))?', '', syntax, flags=re.I)
if re.search(r'(?i)\b(?:DROP|TRUNCATE|DELETE|UPDATE|INSERT|SELECT|RENAME|MODIFY|CHANGE|REFERENCES)\b', syntax):
raise ValueError('Scan migration permits additive standalone lab DDL only')
if re.search(r'`?\w+`?\s*\.\s*`?\w+`?', syntax):
raise ValueError('Qualified database references are forbidden in scan migration')
table = re.match(r'CREATE\s+TABLE\s+IF\s+NOT\s+EXISTS\s+' + IDENTIFIER + r'\s*\(', sql, re.I)
if table:
operations.append(dict(kind='table', table=table[1], name=table[1], sql=sql))
continue
column = re.match(r'ALTER\s+TABLE\s+' + IDENTIFIER + r'\s+ADD\s+COLUMN\s+`?([a-z0-9_]+)`?\s+\S', sql, re.I)
index = re.match(r'ALTER\s+TABLE\s+' + IDENTIFIER + r'\s+ADD\s+(?:UNIQUE\s+)?(?:KEY|INDEX)\s+`?([a-z0-9_]+)`?\s*\(', sql, re.I)
match = column or index
if not match or re.search(r',\s*ADD\b', syntax, re.I):
raise ValueError('Each ALTER must add one named column or index to a lab table')
operations.append(dict(kind='column' if column else 'index', table=match[1], name=match[2], sql=sql))
if not operations:
raise ValueError('Scan migration is empty')
return operations
def apply_schema(cursor, operations):
changed = 0
for operation in operations:
kind, table, name = operation['kind'], operation['table'], operation['name']
if kind == 'table':
cursor.execute('SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s LIMIT 1',
(DATABASE, table))
elif kind == 'column':
cursor.execute('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s AND COLUMN_NAME=%s LIMIT 1',
(DATABASE, table, name))
else:
cursor.execute('SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA=%s AND TABLE_NAME=%s AND INDEX_NAME=%s LIMIT 1',
(DATABASE, table, name))
if cursor.fetchone():
continue
cursor.execute(operation['sql'])
changed += 1
return changed
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true', help='apply only to guarded owned target')
args = parser.parse_args(argv)
operations = load_migration()
reference = load_reference()
if not args.apply:
print(f'DRY RUN: {HOST}/{DATABASE}; {len(operations)} additive schema statements; unified intelligence/resource menus; no database connection')
return 0
runtime = json.loads((ROOT / '.local/runtime.json').read_text(encoding='utf-8-sig'))
mysql = runtime['mysql']
validate_target(mysql)
import pymysql
connection = pymysql.connect(host=HOST, port=int(mysql.get('port', 3306)), user=mysql['user'],
password=mysql['password'], database=DATABASE, charset='utf8mb4', autocommit=True,
connect_timeout=10, read_timeout=30, write_timeout=30)
locked = False
try:
with connection.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')
# Share the base bootstrap lock; DDL is auto-committing on MySQL.
# All operations are additive so interruption is safely rerunnable.
cursor.execute('SELECT GET_LOCK(%s,10)', (OWNER,))
locked = cursor.fetchone() == (1,)
if not locked:
raise RuntimeError('Another owned-database bootstrap is running')
schema_changes = apply_schema(cursor, operations)
menu_changes = references(cursor, reference)
verify_references(cursor, reference)
finalize_permissions(cursor)
checksum = hashlib.sha256(MIGRATION.read_bytes()).hexdigest()
cursor.execute(f'INSERT INTO `{META}` (name,value) VALUES (%s,%s) ON DUPLICATE KEY UPDATE value=VALUES(value)',
('005_scan_only.sql', checksum))
print(json.dumps(dict(target=DATABASE, schemaChanges=schema_changes, menus=menu_changes,
verified=True, historicalDataPreserved=True), ensure_ascii=False))
finally:
if locked:
with connection.cursor() as cursor:
cursor.execute('SELECT RELEASE_LOCK(%s)', (OWNER,))
connection.close()
return 0
if __name__ == '__main__':
try:
raise SystemExit(main())
except Exception as error:
# Driver exceptions can contain connection details or SQL row values.
detail = str(error) if isinstance(error, (ValueError, RuntimeError, FileNotFoundError)) else type(error).__name__
print('Scan migration stopped: ' + detail, file=sys.stderr)
raise SystemExit(1)