88 lines
5.0 KiB
Python
88 lines
5.0 KiB
Python
"""Development-only, data-only migration planning shared by the installed brokers."""
|
|
import copy
|
|
import re
|
|
from pathlib import Path
|
|
|
|
from release import canonical, conditions, file_digest, require
|
|
|
|
PLAN_FIELDS = ('starting_schema_sha256', 'resulting_schema_sha256', 'migrations',
|
|
'omitted_migrations', 'prerequisites', 'postconditions', 'qualification')
|
|
|
|
|
|
def plan_source(source, baseline, sql, historical_source=None):
|
|
"""Keep every recorded hash; append new numbered migrations in filename order."""
|
|
import shutil
|
|
sql = Path(sql)
|
|
sql.mkdir()
|
|
plan = {k: copy.deepcopy(baseline[k]) for k in PLAN_FIELDS}
|
|
plan['starting_schema_sha256'] = baseline['resulting_schema_sha256']
|
|
known = {m['file']: m for m in baseline['migrations']}
|
|
omitted = {m['id']: m for m in baseline['omitted_migrations']}
|
|
pending = []
|
|
for candidate in sorted((Path(source)/'PlotLine/Sql').glob('*.sql')):
|
|
require(not candidate.is_symlink(), 'SQL symlink refused')
|
|
name = candidate.name
|
|
if name in known:
|
|
require(file_digest(candidate) == known[name]['sha256'], 'Historical SQL changed: '+name)
|
|
elif candidate.stem in omitted or name in omitted:
|
|
item = omitted.get(candidate.stem, omitted.get(name))
|
|
require(file_digest(candidate) == item['sha256'], 'Omitted historical SQL changed: '+name)
|
|
elif historical_source and historical_source.get(name) == file_digest(candidate):
|
|
# Some legacy SQL was never part of the ledger (for example a
|
|
# superseded runtime-permissions script). Preserve its exclusion only
|
|
# when the actual successful source tree has the exact same bytes.
|
|
continue
|
|
elif re.fullmatch(r'[0-9]{3,}_[A-Za-z0-9_.-]+\.sql', name):
|
|
pending.append(candidate)
|
|
previous = plan['migrations'][-1]['id']
|
|
highest = max(int(m['file'].split('_')[0]) for m in baseline['migrations']
|
|
if re.match(r'^\d+_', m['file']))
|
|
numbers = set()
|
|
for candidate in pending:
|
|
number = int(candidate.name.split('_')[0])
|
|
require(number > highest and number not in numbers,
|
|
'New migration number collides with recorded history: '+candidate.name)
|
|
numbers.add(number)
|
|
# These checks are structural smoke checks; the complete resulting schema
|
|
# is measured on a disposable database and verified again at activation.
|
|
text = candidate.read_text(encoding='utf-8-sig')
|
|
objects = re.findall(r'\bCREATE\s+(?:OR\s+ALTER\s+)?(TABLE|PROCEDURE|PROC|FUNCTION|VIEW)\s+\[?dbo\]?\.\[?([A-Za-z_][A-Za-z0-9_]*)\]?', text, re.I)
|
|
types = {'TABLE':'U', 'PROCEDURE':'P', 'PROC':'P', 'VIEW':'V'}
|
|
checks = [{'kind':'object','name':'dbo.'+name,'type':types[kind.upper()]}
|
|
for kind, name in objects if kind.upper() in types]
|
|
checks = list({canonical(c): c for c in checks}.values())
|
|
if not checks:
|
|
checks = [{'kind':'object','name':'dbo.DatabaseMigrationHistory','type':'U'}]
|
|
step = dict(id=candidate.stem, file=candidate.name, sha256=file_digest(candidate),
|
|
requires=[previous], mode='execute', prerequisites=[], postconditions=checks)
|
|
plan['migrations'].append(step)
|
|
previous = step['id']
|
|
shutil.copyfile(candidate, sql/candidate.name)
|
|
return plan, pending
|
|
|
|
|
|
def validate_extension(plan, baseline):
|
|
require(set(plan) == set(PLAN_FIELDS), 'Unexpected migration plan fields')
|
|
old = baseline['migrations']
|
|
require(plan['migrations'][:len(old)] == old, 'Historical migration plan changed')
|
|
require(plan['omitted_migrations'] == baseline['omitted_migrations'], 'Historical omissions changed')
|
|
require(plan['starting_schema_sha256'] == baseline['resulting_schema_sha256'], 'Stale Development baseline')
|
|
require(plan['prerequisites'] == baseline['prerequisites'] and
|
|
plan['postconditions'] == baseline['postconditions'], 'Baseline conditions changed')
|
|
seen = {m['id'] for m in old}
|
|
numbers = [int(m['file'].split('_')[0]) for m in old if re.match(r'^\d+_', m['file'])]
|
|
highest = max(numbers)
|
|
previous = old[-1]['id']
|
|
for step in plan['migrations'][len(old):]:
|
|
require(set(step) == {'id','file','sha256','requires','mode','prerequisites','postconditions'}, 'Invalid new migration')
|
|
require(re.fullmatch(r'[0-9]{3,}_[A-Za-z0-9_.-]+\.sql', step['file']), 'Invalid SQL filename')
|
|
number = int(step['file'].split('_')[0])
|
|
require(number > highest, 'Migration order collision')
|
|
highest = number
|
|
require(step['id'] == Path(step['file']).stem and step['id'] not in seen and
|
|
step['requires'] == [previous] and step['mode'] == 'execute', 'Invalid migration ordering')
|
|
require(re.fullmatch(r'[a-f0-9]{64}', step['sha256']), 'Invalid SQL checksum')
|
|
conditions(step['prerequisites']); conditions(step['postconditions'])
|
|
require(bool(step['postconditions']), 'Migration health check required')
|
|
previous = step['id']; seen.add(previous)
|