#!/usr/bin/env python3 """Inspect/expand item quantity columns; never narrows columns or rewrites item rows.""" import argparse import hashlib import json import re import subprocess def sql(query): result = subprocess.run(['mysql', '--batch', '--skip-column-names', '-e', query], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) return [line.split('\t') for line in result.stdout.splitlines()] def identifier(value): if not re.fullmatch(r'[A-Za-z0-9_]+', value): raise ValueError('invalid database identifier') return '`' + value + '`' def run(schema, apply=False): identifier(schema) rows = sql("SELECT TABLE_NAME,COLUMN_NAME,COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT " "FROM information_schema.COLUMNS WHERE TABLE_SCHEMA='%s' " "AND COLUMN_NAME IN ('count','item_count')" % schema) report = [] for table, column, kind, nullable, default in rows: if not (table in ('item','item_orphan_quarantine','shop_item','item_award') or 'item' in table or 'custody' in table): continue target = identifier(schema) + '.' + identifier(table) field = identifier(column) before = sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target)) def fingerprint(): # Data-only canonical dump includes item identities and every saved # field; column widening must preserve more than aggregate totals. data=subprocess.check_output(['mysqldump','--no-create-info','--skip-extended-insert', '--skip-comments','--compact','--order-by-primary','--hex-blob',schema,table],stderr=subprocess.PIPE) return hashlib.sha256(data).hexdigest() old_fingerprint=fingerprint() change = kind.lower().startswith(('tinyint','smallint','mediumint')) entry = dict(table=table,column=column,old_type=kind,needs_expansion=change,before=before,data_sha256=old_fingerprint) if change and apply: if default != 'NULL' and not re.fullmatch(r'\d+',default): raise RuntimeError('unexpected quantity default for '+table) declaration = 'INT UNSIGNED ' + ('NULL' if nullable=='YES' else 'NOT NULL') if default != 'NULL': declaration += ' DEFAULT ' + default sql('ALTER TABLE %s MODIFY COLUMN %s %s' % (target,field,declaration)) after=sql('SELECT COUNT(*),COALESCE(SUM(%s),0) FROM %s' % (field,target)) if before != after: raise RuntimeError('quantity totals changed: '+table) after_fingerprint=fingerprint() if after_fingerprint!=old_fingerprint:raise RuntimeError('item identities/data changed: '+table) entry.update(after=after,new_type='int unsigned',after_data_sha256=after_fingerprint) report.append(entry) if not any(row['table']=='item' for row in report): raise RuntimeError('item table was not found') return dict(schema=schema,applied=apply,columns=report) if __name__=='__main__': parser=argparse.ArgumentParser();parser.add_argument('--schema',required=True);parser.add_argument('--apply',action='store_true') args=parser.parse_args();print(json.dumps(run(args.schema,args.apply),indent=2))