84 lines
5.0 KiB
Python
84 lines
5.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Plan/apply gold columns from the actual selected schemas; never truncate balances."""
|
|
import argparse
|
|
import hashlib
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import re
|
|
import subprocess
|
|
|
|
MAXIMUM=2000000000000000
|
|
|
|
|
|
def validate_column(kind):
|
|
if not re.fullmatch(r'(tinyint|smallint|mediumint|int|bigint)(\(\d+\))?( unsigned)?',kind.lower()):
|
|
raise ValueError('Unexpected money column definition: '+kind)
|
|
|
|
|
|
def fingerprint(value):
|
|
return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
|
|
|
|
|
def save(path,value):
|
|
temporary=path.with_name(path.name+'.new')
|
|
with temporary.open('x') as out:
|
|
os.chmod(temporary,0o600);json.dump(value,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno())
|
|
os.replace(temporary,path)
|
|
fd=os.open(path.parent,os.O_RDONLY)
|
|
try:os.fsync(fd)
|
|
finally:os.close(fd)
|
|
|
|
|
|
def main():
|
|
p=argparse.ArgumentParser(description=__doc__)
|
|
p.add_argument('--player',required=True);p.add_argument('--log',required=True)
|
|
p.add_argument('--plan',type=Path,required=True);p.add_argument('--apply',action='store_true')
|
|
p.add_argument('--offline',action='store_true');p.add_argument('--backup-id')
|
|
a=p.parse_args()
|
|
if not all(re.fullmatch(r'[A-Za-z0-9_]+',s) for s in (a.player,a.log)):p.error('Invalid schema name')
|
|
if a.apply and (not a.offline or not a.backup_id):p.error('Apply requires --offline --backup-id')
|
|
def sql(query):
|
|
r=subprocess.run(['mysql','-N','-B'],input=query,text=True,capture_output=True,check=True)
|
|
return [line.split('\t') for line in r.stdout.splitlines()]
|
|
identity=sql('SELECT @@hostname,@@port,@@server_id,@@version;')
|
|
if len(identity)!=1:raise RuntimeError('Unknown server identity')
|
|
required=[(a.player,t,'gold',True) for t in ('player','player_deleted','safebox','guild')]+[(a.log,'money_log','gold',False)]
|
|
optional=[(a.log,'log','what',False)]+[(a.player,t,c,False) for t,c in [('player','shop_money'),('offline_shop_item','price'),('offline_shop_log','price'),('offline_shop_log_important','price')]]
|
|
rows=[];ddl={}
|
|
for schema,table,column,unsigned in required+optional:
|
|
definition=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(schema,table,column))
|
|
if len(definition)!=1:
|
|
if (schema,table,column,unsigned) in optional:continue
|
|
raise RuntimeError('Missing required column: '+'.'.join((schema,table,column)))
|
|
validate_column(definition[0][0])
|
|
if definition[0][3]:raise RuntimeError('Generated/automatic money columns require explicit review')
|
|
target='bigint(20)'+(' unsigned' if unsigned else '')
|
|
upper=(2**63-1) if schema==a.log else MAXIMUM
|
|
lower=-(2**63) if schema==a.log else 0
|
|
invalid=sql('SELECT COUNT(*) FROM `%s`.`%s` WHERE `%s` IS NULL OR `%s`>%d OR `%s`<%d;'%(schema,table,column,column,upper,column,lower))
|
|
if invalid!=[['0']]:raise RuntimeError('Out of range/null money data: '+schema+'.'+table+'.'+column)
|
|
key=schema+'.'+table
|
|
if key not in ddl:ddl[key]=sql('SHOW CREATE TABLE `%s`.`%s`;'%(schema,table))
|
|
rows.append({'schema':schema,'table':table,'column':column,'before':definition[0],'target':target})
|
|
if a.plan.exists():
|
|
plan=json.loads(a.plan.read_text());checksum=plan.get('sha256');base={k:v for k,v in plan.items() if k!='sha256'}
|
|
if plan.get('version')!=1 or plan.get('identity')!=identity[0] or checksum!=fingerprint(base):raise RuntimeError('Foreign/stale/corrupt plan')
|
|
if [(r['schema'],r['table'],r['column']) for r in rows]!=[(r['schema'],r['table'],r['column']) for r in plan['columns']]:raise RuntimeError('Column inventory differs from plan')
|
|
for current,bound in zip(rows,plan['columns']):
|
|
if current['before']!=bound['before'] and current['before'][:2]!=[bound['target'],'NO']:raise RuntimeError('Column changed since planning')
|
|
else:
|
|
plan={'version':1,'identity':identity[0],'columns':rows,'show_create':ddl};plan['sha256']=fingerprint(plan)
|
|
a.plan.parent.mkdir(parents=True,exist_ok=True);save(a.plan,plan)
|
|
if not a.apply:
|
|
print('PLAN ONLY: review '+str(a.plan));return
|
|
for row in plan['columns']:
|
|
sql('ALTER TABLE `%s`.`%s` MODIFY COLUMN `%s` %s NOT NULL DEFAULT 0;'%(row['schema'],row['table'],row['column'],row['target']))
|
|
actual=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(row['schema'],row['table'],row['column']))
|
|
if actual!=[[row['target'],'NO','0']]:raise RuntimeError('Money column post-validation failed')
|
|
save(a.plan.with_name(a.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'backup_id':a.backup_id,'verified':True})
|
|
print('PASS: columns verified; balances preserved. Runtime release acceptance is separate.')
|
|
|
|
|
|
if __name__=='__main__':main()
|