165 lines
7.4 KiB
Python
165 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
"""LOCAL spawn baselines and reviewable SQL diffs. Never applies exported SQL."""
|
|
import argparse
|
|
import datetime
|
|
import decimal
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
TABLES = ('creature', 'gameobject')
|
|
NUMERIC = {'tinyint', 'smallint', 'mediumint', 'int', 'bigint', 'float', 'double', 'decimal'}
|
|
IDENT = re.compile(r'^[a-z][a-z0-9_]*$')
|
|
NUMBER = re.compile(r'^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$')
|
|
|
|
|
|
def query(sql):
|
|
result = subprocess.run([sys.executable, str(ROOT / 'ops/claude_itemsparse_773/tw_world_query.py'), sql],
|
|
capture_output=True, text=True, check=True)
|
|
if result.stderr.strip():
|
|
raise RuntimeError('LOCAL database query failed; no export produced')
|
|
return result.stdout
|
|
|
|
|
|
def snapshot(reader=query):
|
|
schema = reader("SELECT TABLE_NAME,COLUMN_NAME,DATA_TYPE,COLUMN_KEY FROM information_schema.COLUMNS "
|
|
"WHERE TABLE_SCHEMA='tw_world' AND TABLE_NAME IN ('creature','gameobject') "
|
|
"ORDER BY TABLE_NAME,ORDINAL_POSITION;")
|
|
tables = {name: {'columns': [], 'rows': {}} for name in TABLES}
|
|
primary = {name: [] for name in TABLES}
|
|
for line in schema.splitlines():
|
|
table, column, kind, key = line.split('\t')
|
|
if table not in tables or not IDENT.fullmatch(column) or kind not in NUMERIC:
|
|
raise ValueError('Unexpected spawn table schema')
|
|
tables[table]['columns'].append(column)
|
|
if key == 'PRI':
|
|
primary[table].append(column)
|
|
if any(primary[t] != ['guid'] or not tables[t]['columns'] for t in TABLES):
|
|
raise ValueError('Expected complete numeric spawn tables with GUID primary keys')
|
|
statements = ['LOCK TABLES `creature` READ, `gameobject` READ']
|
|
for name in TABLES:
|
|
statements.append("SELECT '__EDITOR_TABLE__%s'" % name)
|
|
# HEX preserves the DB's own numeric text, including exponent/precision,
|
|
# without tab, encoding, or NULL sentinel ambiguity.
|
|
fields = ["IF(`%s` IS NULL,'NULL',HEX(CAST(`%s` AS CHAR)))" % (c, c) for c in tables[name]['columns']]
|
|
statements.append('SELECT ' + ','.join(fields) + ' FROM `' + name + '` ORDER BY `guid`')
|
|
statements += ["SELECT '__EDITOR_END__'", 'UNLOCK TABLES']
|
|
output = reader(';'.join(statements) + ';')
|
|
current = None
|
|
seen, ended = set(), False
|
|
for line in output.splitlines():
|
|
if line == '__EDITOR_END__':
|
|
ended = True
|
|
continue
|
|
if line.startswith('__EDITOR_TABLE__'):
|
|
current = line[len('__EDITOR_TABLE__'):]
|
|
if current not in TABLES or current in seen:
|
|
raise ValueError('Invalid table boundary')
|
|
seen.add(current)
|
|
continue
|
|
if current is None or ended:
|
|
raise ValueError('Invalid snapshot boundary')
|
|
values = [None if v == 'NULL' else bytes.fromhex(v).decode('ascii') for v in line.split('\t')]
|
|
columns = tables[current]['columns']
|
|
if len(values) != len(columns):
|
|
raise ValueError('Truncated snapshot row')
|
|
for value in values:
|
|
literal(value)
|
|
guid = values[columns.index('guid')]
|
|
if guid is None or not guid.isdigit() or guid in tables[current]['rows']:
|
|
raise ValueError('Invalid or duplicate GUID')
|
|
tables[current]['rows'][guid] = values
|
|
if seen != set(TABLES) or not ended:
|
|
raise ValueError('Incomplete snapshot; refusing an apparent mass deletion')
|
|
result = {'format': 1, 'database': 'tw_world', 'captured_utc': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'tables': tables}
|
|
validate(result)
|
|
return result
|
|
|
|
|
|
def literal(value):
|
|
if value is None:
|
|
return 'NULL'
|
|
if not isinstance(value, str) or not NUMBER.fullmatch(value) or not decimal.Decimal(value).is_finite():
|
|
raise ValueError('Non-numeric spawn value')
|
|
return value
|
|
|
|
|
|
def validate(data):
|
|
if data.get('format') != 1 or data.get('database') != 'tw_world' or set(data.get('tables', {})) != set(TABLES):
|
|
raise ValueError('Unsupported or incomplete baseline')
|
|
for name in TABLES:
|
|
table = data['tables'][name]
|
|
cols = table['columns']
|
|
if not cols or len(set(cols)) != len(cols) or 'guid' not in cols or any(not IDENT.fullmatch(c) for c in cols):
|
|
raise ValueError('Invalid baseline columns')
|
|
for guid, row in table['rows'].items():
|
|
if not isinstance(guid, str) or not guid.isdigit() or len(row) != len(cols) or row[cols.index('guid')] != guid:
|
|
raise ValueError('Invalid baseline row')
|
|
for value in row:
|
|
literal(value)
|
|
|
|
|
|
def diff(before, after):
|
|
validate(before)
|
|
validate(after)
|
|
lines = ['-- LOCAL editor spawn diff; review before applying to a matching baseline.',
|
|
'-- No SQL was applied by the exporter. Numeric values retain database precision.',
|
|
'-- UPDATE/DELETE include old-value guards; verify affected rows when applying.',
|
|
'-- No transaction/rollback guarantee is made for MyISAM spawn tables.']
|
|
counts = {'insert': 0, 'update': 0, 'delete': 0}
|
|
for name in TABLES:
|
|
old, new = before['tables'][name], after['tables'][name]
|
|
columns = old['columns']
|
|
if columns != new['columns']:
|
|
raise ValueError('Schema changed during editing; rebuild baseline explicitly')
|
|
def guards(row):
|
|
return ' AND '.join('`%s` <=> %s' % (c, literal(v)) for c, v in zip(columns, row))
|
|
for guid in sorted(set(old['rows']) | set(new['rows']), key=int):
|
|
a, b = old['rows'].get(guid), new['rows'].get(guid)
|
|
if a == b:
|
|
continue
|
|
if b is None:
|
|
lines.append('DELETE FROM `%s` WHERE %s;' % (name, guards(a)))
|
|
counts['delete'] += 1
|
|
elif a is None:
|
|
lines.append('INSERT INTO `%s` (%s) VALUES (%s);' % (name, ','.join('`%s`' % c for c in columns), ','.join(map(literal, b))))
|
|
counts['insert'] += 1
|
|
else:
|
|
changed = ['`%s`=%s' % (c, literal(y)) for c, x, y in zip(columns, a, b) if x != y]
|
|
lines.append('UPDATE `%s` SET %s WHERE %s;' % (name, ','.join(changed), guards(a)))
|
|
counts['update'] += 1
|
|
lines.append('-- Counts: ' + ', '.join('%s=%d' % item for item in counts.items()))
|
|
return '\n'.join(lines) + '\n', counts
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
sub = parser.add_subparsers(dest='command', required=True)
|
|
take = sub.add_parser('snapshot')
|
|
take.add_argument('output', type=Path)
|
|
export = sub.add_parser('diff')
|
|
export.add_argument('baseline', type=Path)
|
|
export.add_argument('output', type=Path)
|
|
export.add_argument('--current', type=Path, help='Offline current snapshot; otherwise read LOCAL')
|
|
args = parser.parse_args()
|
|
if args.command == 'snapshot':
|
|
result = snapshot()
|
|
with args.output.open('x') as f:
|
|
json.dump(result, f, separators=(',', ':'))
|
|
f.write('\n')
|
|
print('Baseline saved:', args.output)
|
|
else:
|
|
old = json.loads(args.baseline.read_text())
|
|
new = json.loads(args.current.read_text()) if args.current else snapshot()
|
|
text, counts = diff(old, new)
|
|
with args.output.open('x') as f:
|
|
f.write(text)
|
|
print('SQL exported:', args.output, counts)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|