переработал бд
This commit is contained in:
1 parent
6720970fa0
commit
ac228ae0c3
31 files changed
+1686
-288
No files matched your search
@@ -0,0 +1,390 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Собирает единую полную схему из DDL; база данных не используется."""
|
||||
|
||||
from pathlib import Path
|
||||
from html import escape as esc
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
SOURCE = ROOT / 'backend/src/main/resources/db/migration/V1__init.sql'
|
||||
OUTPUT = Path(__file__).with_name('database-schema.html')
|
||||
RAW = SOURCE.read_text()
|
||||
|
||||
|
||||
def clean_sql(text):
|
||||
# Строки сохраняются; комментарии и тела процедур не участвуют в разборе DDL.
|
||||
pattern = r"('(?:''|[^'])*')|\$\$.*?\$\$|--[^\n]*|/\*.*?\*/"
|
||||
return re.sub(pattern, lambda m: m[1] or ' ', text, flags=re.S)
|
||||
|
||||
|
||||
def split_top(text, separator=','):
|
||||
parts, start, depth, quoted, i = [], 0, 0, False, 0
|
||||
while i < len(text):
|
||||
char = text[i]
|
||||
if char == "'":
|
||||
if quoted and i + 1 < len(text) and text[i + 1] == "'":
|
||||
i += 2
|
||||
continue
|
||||
quoted = not quoted
|
||||
if not quoted:
|
||||
depth += (char == '(') - (char == ')')
|
||||
if char == separator and depth == 0:
|
||||
parts.append(text[start:i].strip())
|
||||
start = i + 1
|
||||
i += 1
|
||||
parts.append(text[start:].strip())
|
||||
return parts
|
||||
|
||||
|
||||
TABLES, FKS = {}, []
|
||||
|
||||
|
||||
def add_fk(table, columns, target, keys, action=None):
|
||||
columns = [c.strip() for c in columns.split(',')]
|
||||
keys = [k.strip() for k in keys.split(',')]
|
||||
assert len(columns) == len(keys)
|
||||
FKS.append(dict(source=table, columns=columns, column=columns[0], target=target,
|
||||
keys=keys, key=keys[0], action=action or 'NO ACTION'))
|
||||
|
||||
|
||||
def constraint_fk(table, entry):
|
||||
ref = re.search(r'FOREIGN KEY\s*\(([^)]+)\)\s+REFERENCES\s+(\w+)\s*\(([^)]+)\)(?:\s+ON DELETE\s+(CASCADE|SET NULL|RESTRICT|NO ACTION))?', entry)
|
||||
if ref:
|
||||
columns, target, keys, action = ref.groups()
|
||||
add_fk(table, columns, target, keys, action)
|
||||
|
||||
|
||||
def add_column(table, definition):
|
||||
match = re.match(r'(\w+)\s+((?:BIGSERIAL|BIGINT|SMALLINT|INTEGER|INT|BOOLEAN|DATE|TIME\b|TIMESTAMPTZ|TEXT|VARCHAR)(?:\s*\(\d+\))?)', definition, re.I)
|
||||
if not match:
|
||||
raise ValueError(f'Не удалось разобрать столбец {table}: {definition}')
|
||||
name, sql_type = match.groups()
|
||||
pk = 'PRIMARY KEY' in definition
|
||||
TABLES[table]['columns'][name] = dict(name=name, type=sql_type.upper(), pk=pk,
|
||||
nn=pk or 'NOT NULL' in definition, uq=bool(re.search(r'\bUNIQUE\b', definition)), ddl=definition)
|
||||
ref = re.search(r'REFERENCES\s+(\w+)\s*\((\w+)\)(?:\s+ON DELETE\s+(CASCADE|SET NULL|RESTRICT|NO ACTION))?', definition, re.I)
|
||||
if ref:
|
||||
target, key, action = ref.groups()
|
||||
add_fk(table, name, target, key, action)
|
||||
|
||||
|
||||
for statement in split_top(clean_sql(RAW), ';'):
|
||||
statement = ' '.join(statement.split())
|
||||
create = re.match(r'CREATE TABLE (?:IF NOT EXISTS )?(\w+)\s*\((.*)\)$', statement, re.S)
|
||||
if create:
|
||||
table, body = create.groups()
|
||||
TABLES[table] = dict(columns={}, constraints=[], indexes=[])
|
||||
for entry in split_top(body):
|
||||
if re.match(r'(CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN|EXCLUDE)\b', entry):
|
||||
TABLES[table]['constraints'].append(entry)
|
||||
constraint_fk(table, entry)
|
||||
key = re.search(r'PRIMARY KEY\s*\(([^)]+)\)', entry)
|
||||
if key:
|
||||
for name in key[1].split(','):
|
||||
TABLES[table]['columns'][name.strip()].update(pk=True, nn=True)
|
||||
else:
|
||||
add_column(table, entry)
|
||||
continue
|
||||
alter = re.match(r'ALTER TABLE (\w+) (.*)', statement, re.S)
|
||||
if alter:
|
||||
table, body = alter.groups()
|
||||
for entry in split_top(body):
|
||||
if entry.startswith('ADD COLUMN '):
|
||||
add_column(table, entry[len('ADD COLUMN '):])
|
||||
elif entry.startswith('ALTER COLUMN ') and entry.endswith(' SET NOT NULL'):
|
||||
TABLES[table]['columns'][entry.split()[2]]['nn'] = True
|
||||
elif entry.startswith('DROP CONSTRAINT '):
|
||||
# Единственное удаление в baseline — старый UNIQUE(group_id, name).
|
||||
if table == 'subgroups':
|
||||
TABLES[table]['constraints'] = [x for x in TABLES[table]['constraints'] if x != 'UNIQUE(group_id, name)']
|
||||
elif entry.startswith('ADD CONSTRAINT '):
|
||||
TABLES[table]['constraints'].append(entry[4:])
|
||||
constraint_fk(table, entry)
|
||||
elif entry.startswith('VALIDATE CONSTRAINT '):
|
||||
constraint_name = entry.split()[2]
|
||||
TABLES[table]['constraints'] = [
|
||||
re.sub(r' NOT VALID$', '', c) if c.startswith('CONSTRAINT ' + constraint_name + ' ') else c
|
||||
for c in TABLES[table]['constraints']
|
||||
]
|
||||
continue
|
||||
index = re.match(r'CREATE (?:UNIQUE )?INDEX (?:IF NOT EXISTS )?(\w+) ON (\w+)\b', statement)
|
||||
if index:
|
||||
TABLES[index[2]]['indexes'].append(statement)
|
||||
|
||||
ROUTES = []
|
||||
for number, fk in enumerate(FKS, 1):
|
||||
fk['number'] = number
|
||||
for part, (column, key) in enumerate(zip(fk['columns'], fk['keys'])):
|
||||
assert column in TABLES[fk['source']]['columns'], fk
|
||||
assert key in TABLES[fk['target']]['columns'], fk
|
||||
TABLES[fk['source']]['columns'][column].setdefault('fks', []).append(fk)
|
||||
ROUTES.append(dict(fk, column=column, key=key, part=part))
|
||||
|
||||
LABELS = {
|
||||
'schedule_rule_loads':'Нагрузка правила по видам занятий',
|
||||
'departments':'Кафедры', 'specialties':'Направления подготовки', 'specialty_profiles':'Профили подготовки',
|
||||
'users':'Пользователи', 'auth_refresh_tokens':'Refresh-токены', 'auth_login_rate_limits':'Ограничение попыток входа', 'auth_login_attempt_audit':'Аудит неудачных входов',
|
||||
'teacher_department_assignments':'История принадлежности к кафедрам', 'teacher_creation_requests':'Заявки на создание преподавателя',
|
||||
'education_forms':'Формы обучения', 'student_groups':'Студенческие группы', 'subgroups':'Подгруппы',
|
||||
'subjects':'Дисциплины', 'subject_comments':'Комментарии к дисциплинам', 'lesson_types':'Виды занятий',
|
||||
'equipments':'Оборудование', 'classrooms':'Аудитории', 'classroom_equipments':'Оснащение аудиторий', 'teacher_subjects':'Закрепление дисциплин за преподавателями',
|
||||
'time_slot_scopes':'Наборы звонков', 'time_slots':'Временные слоты', 'time_slot_date_assignments':'Наборы звонков по датам',
|
||||
'academic_years':'Учебные годы', 'semesters':'Семестры', 'academic_calendar_activity_types':'Виды учебной активности',
|
||||
'academic_calendars':'Учебные календари', 'academic_calendar_periods':'Календарные периоды', 'academic_calendar_subjects':'Дисциплины календаря',
|
||||
'student_group_calendar_assignments':'Назначения календарей группам', 'schedule_rules':'Правила расписания',
|
||||
'schedule_rule_groups':'Группы правила', 'schedule_rule_slots':'Повторяющиеся занятия', 'schedule_rule_slot_subgroups':'Подгруппы занятия',
|
||||
'schedule_overrides':'Точечные изменения занятий', 'teacher_absences':'Отсутствия преподавателей', 'teacher_absence_decisions':'Решения мастера замены',
|
||||
'teacher_preferences':'Пожелания преподавателей', 'teacher_change_requests':'Заявки на изменение занятия', 'teacher_change_request_history':'История согласования заявки',
|
||||
'schedule_versions':'Версии расписания', 'schedule_version_history':'История версий расписания',
|
||||
'study_plans':'Учебные планы', 'study_plan_subjects':'Дисциплины учебного плана', 'study_plan_loads':'Нагрузка учебного плана', 'student_group_plan_assignments':'Назначения планов группам',
|
||||
}
|
||||
|
||||
# Все таблицы располагаются на одном полотне. Колонки задают только компоновку:
|
||||
# между ними сохраняются все связи, включая служебные и самоссылки.
|
||||
COLUMNS = [
|
||||
('ГРУППЫ И НАПРАВЛЕНИЯ', ['specialties', 'specialty_profiles', 'education_forms', 'student_groups', 'subgroups']),
|
||||
('УЧЕБНЫЙ КАЛЕНДАРЬ', ['academic_years', 'semesters', 'academic_calendars', 'academic_calendar_activity_types', 'academic_calendar_periods', 'academic_calendar_subjects', 'student_group_calendar_assignments']),
|
||||
('ПЛАНЫ И ВРЕМЯ', ['study_plans', 'study_plan_subjects', 'study_plan_loads', 'student_group_plan_assignments', 'time_slot_scopes', 'time_slots', 'time_slot_date_assignments']),
|
||||
('ПОЛЬЗОВАТЕЛИ И КАФЕДРЫ', ['auth_login_rate_limits', 'auth_login_attempt_audit', 'departments', 'users', 'auth_refresh_tokens', 'teacher_department_assignments', 'teacher_creation_requests']),
|
||||
('РАСПИСАНИЕ', ['schedule_versions', 'schedule_version_history', 'schedule_rules', 'schedule_rule_loads', 'schedule_rule_groups', 'schedule_rule_slots', 'schedule_rule_slot_subgroups']),
|
||||
('ДИСЦИПЛИНЫ И РЕСУРСЫ', ['subjects', 'lesson_types', 'teacher_subjects', 'subject_comments', 'classrooms', 'equipments', 'classroom_equipments']),
|
||||
('ИЗМЕНЕНИЯ И ЗАЯВКИ', ['teacher_preferences', 'teacher_change_requests', 'teacher_change_request_history', 'schedule_overrides', 'teacher_absences', 'teacher_absence_decisions']),
|
||||
]
|
||||
assert set(TABLES) == set(LABELS) == {t for _, tables in COLUMNS for t in tables}
|
||||
assert sum(len(tables) for _, tables in COLUMNS) == len(TABLES)
|
||||
|
||||
WIDTH, TABLE_WIDTH, HEADER, ROW = 4864, 512, 64, 28
|
||||
PAPER, INK, MUTED, ACCENT = '#f8fafc', '#0f172a', '#475569', '#4f46e5'
|
||||
|
||||
|
||||
def svg_text(x, y, value, size=12, fill=INK, weight=400, anchor='start', mono=False):
|
||||
return f'<text x="{x}" y="{y}" font-size="{size}" fill="{fill}" font-weight="{weight}" text-anchor="{anchor}" class="{"mono" if mono else "sans"}">{esc(str(value))}</text>'
|
||||
|
||||
|
||||
def layout():
|
||||
from collections import defaultdict
|
||||
colmap = {name: i for i, (_, names) in enumerate(COLUMNS) for name in names}
|
||||
ports = defaultdict(list)
|
||||
for e in ROUTES:
|
||||
e['source_side'] = 'right' if colmap[e['target']] >= colmap[e['source']] else 'left'
|
||||
e['target_side'] = 'left' if colmap[e['source']] < colmap[e['target']] else 'right'
|
||||
ports[e['source'], e['column'], e['source_side']].append((e, 'start'))
|
||||
ports[e['target'], e['key'], e['target_side']].append((e, 'end'))
|
||||
positions = {}
|
||||
for ci, (_, names) in enumerate(COLUMNS):
|
||||
y = 152
|
||||
for name in names:
|
||||
rows, offset = {}, HEADER
|
||||
for column, c in TABLES[name]['columns'].items():
|
||||
n = max(len(ports[name, column, side]) for side in ['left', 'right'])
|
||||
height = max(ROW, (n + 1) * 12)
|
||||
rows[column] = dict(top=y+offset, height=height, center=y+offset+height/2)
|
||||
offset += height
|
||||
positions[name] = dict(x=64+ci*704, y=y, width=TABLE_WIDTH, height=offset, rows=rows, column=ci)
|
||||
y += offset + 112
|
||||
for e in ROUTES:
|
||||
src, dst = positions[e['source']], positions[e['target']]
|
||||
for kind, node, field, side in [('start', src, e['column'], e['source_side']),
|
||||
('end', dst, e['key'], e['target_side'])]:
|
||||
row = node['rows'][field]
|
||||
attachments = ports[e['source'] if kind == 'start' else e['target'], field, side]
|
||||
index = next(i for i, (route, endpoint) in enumerate(attachments) if route is e and endpoint == kind)
|
||||
port = row['top'] + row['height'] * (index+1)/(len(attachments)+1)
|
||||
e[kind] = (node['x'] + (TABLE_WIDTH if side == 'right' else 0), port)
|
||||
e['start_stub'] = (e['start'][0] + (24 if e['source_side'] == 'right' else -24), e['start'][1])
|
||||
e['end_stub'] = (e['end'][0] + (24 if e['target_side'] == 'right' else -24), e['end'][1])
|
||||
height = int(max(p['y']+p['height'] for p in positions.values())+152)
|
||||
return positions, height
|
||||
|
||||
|
||||
def route_all(positions, height):
|
||||
"""Ортогональные пути по свободным коридорам с учётом занятых трасс."""
|
||||
import heapq
|
||||
xs = {16, 28, 40, WIDTH-40, WIDTH-28, WIDTH-16}
|
||||
for ci in range(len(COLUMNS)-1):
|
||||
xs.update(64+ci*704+TABLE_WIDTH+24+j*12 for j in range(13))
|
||||
ys = {28, 40, 52, 64, 88, 100, height-100, height-88, height-76}
|
||||
for p in positions.values():
|
||||
for j in range(1, 8):
|
||||
ys.add(p['y']-j*12)
|
||||
ys.add(p['y']+p['height']+j*12)
|
||||
for e in ROUTES:
|
||||
for key in ['start_stub', 'end_stub']:
|
||||
xs.add(e[key][0])
|
||||
ys.add(e[key][1])
|
||||
xs, ys = sorted(xs), sorted(ys)
|
||||
nx, ny = len(xs), len(ys)
|
||||
xmap, ymap = {x:i for i,x in enumerate(xs)}, {y:i for i,y in enumerate(ys)}
|
||||
barriers = []
|
||||
for a,b in zip(xs,xs[1:]):
|
||||
barriers.append(next((ci for ci in range(len(COLUMNS)) if a < 64+ci*704 < b), -1))
|
||||
occupied = []
|
||||
for ci in range(len(COLUMNS)):
|
||||
boxes = [p for p in positions.values() if p['column'] == ci]
|
||||
occupied.append([any(p['y']-12 <= y <= p['y']+p['height']+12 for p in boxes) for y in ys])
|
||||
used = {}
|
||||
|
||||
def route(e):
|
||||
start = (xmap[e['start_stub'][0]],ymap[e['start_stub'][1]])
|
||||
goal = (xmap[e['end_stub'][0]],ymap[e['end_stub'][1]])
|
||||
sx,sy = start
|
||||
gx,gy = goal
|
||||
initial = (sy*nx+sx)*2
|
||||
queue = [(0, 0, initial)]
|
||||
best, previous = {initial:0}, {}
|
||||
final = None
|
||||
while queue:
|
||||
_, cost, state = heapq.heappop(queue)
|
||||
if cost != best.get(state):
|
||||
continue
|
||||
axis, node = state%2, state//2
|
||||
yi,xi = divmod(node,nx)
|
||||
if (xi,yi) == goal:
|
||||
final = state
|
||||
break
|
||||
options = []
|
||||
if xi > 0 and (barriers[xi-1] < 0 or not occupied[barriers[xi-1]][yi]):
|
||||
options.append((xi-1,yi,0,xs[xi]-xs[xi-1]))
|
||||
if xi+1 < nx and (barriers[xi] < 0 or not occupied[barriers[xi]][yi]):
|
||||
options.append((xi+1,yi,0,xs[xi+1]-xs[xi]))
|
||||
if yi > 0:
|
||||
options.append((xi,yi-1,1,ys[yi]-ys[yi-1]))
|
||||
if yi+1 < ny:
|
||||
options.append((xi,yi+1,1,ys[yi+1]-ys[yi]))
|
||||
for xx,yy,aa,length in options:
|
||||
neighbor = yy*nx+xx
|
||||
key = (min(node,neighbor), max(node,neighbor))
|
||||
nxt = neighbor*2+aa
|
||||
new_cost = cost + length*(1+used.get(key,0)*1.4) + (20 if aa != axis else 0)
|
||||
if new_cost < best.get(nxt,float('inf')):
|
||||
best[nxt], previous[nxt] = new_cost, state
|
||||
heuristic = abs(xs[xx]-xs[gx])+abs(ys[yy]-ys[gy])
|
||||
heapq.heappush(queue,(new_cost+heuristic,new_cost,nxt))
|
||||
if final is None:
|
||||
raise ValueError(f'Не удалось провести FK {e["source"]}.{e["column"]}')
|
||||
path = []
|
||||
while True:
|
||||
yi,xi = divmod(final//2,nx)
|
||||
path.append((xs[xi],ys[yi]))
|
||||
if final == initial:
|
||||
break
|
||||
before = previous[final]
|
||||
a,b = final//2,before//2
|
||||
key = (min(a,b),max(a,b))
|
||||
used[key] = used.get(key,0)+1
|
||||
final = before
|
||||
path.reverse()
|
||||
points = [e['start']] + path + [e['end']]
|
||||
simplified = []
|
||||
for p in points:
|
||||
if simplified and p == simplified[-1]:
|
||||
continue
|
||||
if len(simplified)>1 and ((simplified[-2][0] == simplified[-1][0] == p[0]) or (simplified[-2][1] == simplified[-1][1] == p[1])):
|
||||
simplified[-1] = p
|
||||
else:
|
||||
simplified.append(p)
|
||||
e['points'] = simplified
|
||||
|
||||
# Короткие связи получают ближайшие коридоры, длинные обходят их.
|
||||
for e in sorted(ROUTES,key=lambda e: sum(abs(a-b) for a,b in zip(e['start'],e['end']))):
|
||||
route(e)
|
||||
|
||||
|
||||
def rounded_path(points):
|
||||
import math
|
||||
result = f'M {points[0][0]:g} {points[0][1]:g}'
|
||||
for a,b,c in zip(points,points[1:],points[2:]):
|
||||
ab,bc = math.dist(a,b),math.dist(b,c)
|
||||
radius = min(8,ab/2,bc/2)
|
||||
before = tuple(b[i]+(a[i]-b[i])*radius/ab for i in range(2))
|
||||
after = tuple(b[i]+(c[i]-b[i])*radius/bc for i in range(2))
|
||||
result += f' L {before[0]:g} {before[1]:g} Q {b[0]:g} {b[1]:g} {after[0]:g} {after[1]:g}'
|
||||
return result+f' L {points[-1][0]:g} {points[-1][1]:g}'
|
||||
|
||||
|
||||
def build_svg(positions, height):
|
||||
parts = [f'<svg id="schema" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {WIDTH} {height}" width="{WIDTH}" height="{height}" role="img" aria-labelledby="database-schema-title database-schema-desc">',
|
||||
'<title id="database-schema-title">Полная схема базы данных «Магистр»</title>',
|
||||
f'<desc id="database-schema-desc">Все {len(TABLES)} таблиц, {sum(len(t["columns"]) for t in TABLES.values())} столбцов и {len(FKS)} внешних ключей одной tenant-БД на едином полотне.</desc>',
|
||||
'<defs><marker id="fk-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M 1 1 L 7 4 L 1 7" fill="none" stroke="context-stroke" stroke-width="1.4"/></marker></defs>',
|
||||
f'<rect width="{WIDTH}" height="{height}" fill="{PAPER}"/>',
|
||||
svg_text(64,44,'МАГИСТР / ПОЛНАЯ ФИЗИЧЕСКАЯ СХЕМА',20,INK,600),
|
||||
svg_text(64,72,f'{len(TABLES)} таблиц · {sum(len(t["columns"]) for t in TABLES.values())} столбцов · {len(FKS)} FK · одна tenant-БД · источник: V1__init.sql',12,MUTED)]
|
||||
for ci,(title,_) in enumerate(COLUMNS):
|
||||
parts.append(svg_text(64+ci*704,124,title,14,MUTED,600))
|
||||
parts.append('<g id="relations">')
|
||||
for e in ROUTES:
|
||||
label = f'FK{e["number"]:02}: {e["source"]}.({", ".join(e["columns"])}) → {e["target"]}.({", ".join(e["keys"])}) · ON DELETE {e["action"]}'
|
||||
path = rounded_path(e['points'])
|
||||
parts.append(f'<g id="fk-{e["number"]}-{e["part"]}" class="relation" data-source="{e["source"]}" data-target="{e["target"]}" data-number="{e["number"]}"><title>{esc(label)}</title><path class="wire-under" d="{path}"/><path class="wire" d="{path}" marker-end="url(#fk-arrow)"/><path class="wire-hit" d="{path}"/></g>')
|
||||
parts.append('</g><g id="tables">')
|
||||
for name,table in TABLES.items():
|
||||
p = positions[name]
|
||||
x,y,w,h = p['x'],p['y'],p['width'],p['height']
|
||||
outgoing = [e for e in FKS if e['source'] == name]
|
||||
incoming = [e for e in FKS if e['target'] == name]
|
||||
parts.append(f'<g class="entity" id="table-{name}" data-table="{name}" tabindex="0" role="button" aria-label="{name}: {LABELS[name]}">')
|
||||
parts.append(f'<title>{esc(name+": "+LABELS[name])}\n{len(table["columns"])} столбцов · {len(outgoing)} исходящих и {len(incoming)} входящих FK</title>')
|
||||
parts.append(f'<rect class="table-box" x="{x}" y="{y}" width="{w}" height="{h}" rx="6"/>')
|
||||
parts.append(f'<path d="M {x+6} {y} H {x+w-6} Q {x+w} {y} {x+w} {y+6} V {y+HEADER} H {x} V {y+6} Q {x} {y} {x+6} {y} Z" fill="{"#eeedff" if name in ["users","schedule_rules"] else "#e8edf3"}"/>')
|
||||
parts += [svg_text(x+16,y+26,name,16,INK,600),svg_text(x+16,y+48,LABELS[name],12,MUTED)]
|
||||
for i,(column,c) in enumerate(table['columns'].items()):
|
||||
row = p['rows'][column]
|
||||
top,cy,rh = row['top'],row['center'],row['height']
|
||||
parts.append(f'<g data-column="{column}" data-row-top="{top}" data-row-height="{rh}">')
|
||||
parts.append(f'<title>{esc(c["ddl"])}</title>')
|
||||
parts.append(f'<rect x="{x+1}" y="{top}" width="{w-2}" height="{rh}" fill="{"#eef2f7" if i%2==0 else PAPER}"/>')
|
||||
flags = []
|
||||
if c['pk']:
|
||||
flags.append('PK')
|
||||
for fk in c.get('fks', []):
|
||||
flags.append(f'FK{fk["number"]:02}')
|
||||
if c['uq']:
|
||||
flags.append('UQ')
|
||||
if flags:
|
||||
parts.append(svg_text(x+12,cy+4,'·'.join(flags),9,ACCENT if c['pk'] else MUTED,mono=True))
|
||||
parts += [svg_text(x+82,cy+4,column,13),svg_text(x+w-44,cy+4,c['type'].lower(),11,MUTED,anchor='end',mono=True),
|
||||
svg_text(x+w-18,cy+4,'●' if c['nn'] else '○',10,MUTED,anchor='middle')]
|
||||
parts.append('</g>')
|
||||
parts.append('</g>')
|
||||
parts.append('</g>')
|
||||
parts += [svg_text(64,height-92,f'PK — первичный ключ FK01…FK{len(FKS):02} — внешние ключи UQ — одиночный UNIQUE ● NOT NULL ○ NULL',13,MUTED),
|
||||
svg_text(64,height-64,'Каждая стрелка: столбец FK → столбец PK. Имя связи и ON DELETE доступны при наведении на линию или выборе таблицы.',13,MUTED),
|
||||
svg_text(64,height-36,'Составные FK показаны отдельными линиями столбцов с одним номером. version_group_id и semester_number не являются REFERENCES.',12,MUTED),'</svg>']
|
||||
return ''.join(parts)
|
||||
|
||||
|
||||
def verify_geometry(positions):
|
||||
# Трассы не должны проходить через таблицы; пересечения связей допустимы.
|
||||
for e in ROUTES:
|
||||
assert e['start'] == e['points'][0] and e['end'] == e['points'][-1]
|
||||
for a,b in zip(e['points'],e['points'][1:]):
|
||||
assert a[0] == b[0] or a[1] == b[1], e
|
||||
for name,p in positions.items():
|
||||
left,right,top,bottom = p['x'],p['x']+p['width'],p['y'],p['y']+p['height']
|
||||
if a[1] == b[1]:
|
||||
through = top+.1 < a[1] < bottom-.1 and max(min(a[0],b[0]),left+.1) < min(max(a[0],b[0]),right-.1)
|
||||
else:
|
||||
through = left+.1 < a[0] < right-.1 and max(min(a[1],b[1]),top+.1) < min(max(a[1],b[1]),bottom-.1)
|
||||
assert not through, (e['source'],e['column'],name,a,b)
|
||||
|
||||
|
||||
def generate():
|
||||
import json
|
||||
positions,height = layout()
|
||||
route_all(positions,height)
|
||||
verify_geometry(positions)
|
||||
svg = build_svg(positions,height)
|
||||
metadata = dict(width=WIDTH,height=height,source='V1__init.sql',sha256=hashlib.sha256(RAW.encode()).hexdigest(),
|
||||
tables={name:dict(label=LABELS[name],columns=table['columns'],constraints=table['constraints'],indexes=table['indexes'],**positions[name]) for name,table in TABLES.items()},
|
||||
edges=[{k:v for k,v in e.items() if k not in ['points','start_stub','end_stub']} for e in FKS])
|
||||
template = Path(__file__).with_name('database-schema.template.html').read_text()
|
||||
html = template.replace('@@SCHEMA@@',svg).replace('@@DATA@@',json.dumps(metadata,ensure_ascii=False).replace('<','\\u003c'))
|
||||
html = html.replace('@@SHA@@',metadata['sha256'][:12]).replace('@@TABLE_COUNT@@',str(len(TABLES))).replace('@@COLUMN_COUNT@@',str(sum(len(t['columns']) for t in TABLES.values()))).replace('@@FK_COUNT@@',str(len(FKS)))
|
||||
OUTPUT.write_text(html)
|
||||
print(f'Создана единая схема: {OUTPUT}\nТаблиц: {len(TABLES)}; столбцов: {sum(len(t["columns"]) for t in TABLES.values())}; связей: {len(FKS)}; полотно: {WIDTH} × {height}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
generate()
|
||||
Reference in new issue
Block a user