netgescon-day0/update_schema.py

70 lines
3.1 KiB
Python

import os
import re
schema_path = 'database/schema/mysql-schema.sql'
# Discard manual changes first by git checkout
os.system(f'git checkout -- {schema_path}')
# Read clean schema
with open(schema_path, 'r') as f:
lines = f.readlines()
schema_content = ''.join(lines)
schema_tables = set(re.findall(r'CREATE TABLE `([^`]+)`', schema_content))
print("Tables in schema dump:", len(schema_tables))
# Filter out old migration inserts
new_lines = []
for line in lines:
if 'INSERT INTO `migrations` ' not in line:
new_lines.append(line)
# Scan migrations <= 2026_03_10
migrations_to_mark = []
for f in sorted(os.listdir('database/migrations')):
if f.endswith('.php'):
m = re.match(r'^(\d{4}_\d{2}_\d{2}_\d{6})_(.+)\.php$', f)
if m:
timestamp = m.group(1)
name = f[:-4]
if timestamp <= '2026_03_10_235959':
# Check if it creates or modifies any table
with open(os.path.join('database/migrations', f), 'r') as mf:
content = mf.read()
created_tables = re.findall(r"Schema::create\s*\(\s*['\"]([^'\"]+)['\"]", content)
modified_tables = re.findall(r"Schema::table\s*\(\s*['\"]([^'\"]+)['\"]", content)
all_tables = set(created_tables + modified_tables)
# Logic: If ALL tables referenced (created or modified) already exist in the schema dump,
# we can mark this migration as completed.
# If only SOME tables exist, we should NOT mark it as completed, but print a warning.
all_exist = True
any_exist = False
for t in all_tables:
if t in schema_tables:
any_exist = True
else:
all_exist = False
# Only mark as completed if it only creates tables and they all exist, or if it doesn't reference any tables.
# Do not mark as completed if it modifies tables (Schema::table), so that column updates are applied.
if (len(created_tables) > 0 and len(modified_tables) == 0 and all_exist) or len(all_tables) == 0:
migrations_to_mark.append(name)
elif any_exist:
print(f"Warning: Migration {name} has partial tables. Exist: {all_tables & schema_tables}, Missing: {all_tables - schema_tables}. Will execute.")
else:
print(f"Migration {name} references tables {all_tables} which are all missing from schema dump. Will execute.")
# Append migration inserts to mysql-schema.sql
new_lines.append('\n-- Marked migrations <= 2026-03-10 whose tables/logic exist in schema baseline\n')
for i, m in enumerate(migrations_to_mark, start=1):
new_lines.append(f"INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES ({i}, '{m}', 1);\n")
# Write back to mysql-schema.sql
with open(schema_path, 'w') as f:
f.writelines(new_lines)
print('Success! Updated schema dump with', len(migrations_to_mark), 'migrations.')