127 lines
7.3 KiB
Python
127 lines
7.3 KiB
Python
"""Rehearse v4 DDL only on a fixed, disposable MySQL container.
|
|
|
|
The URL is read from a private environment file by the caller, never logged.
|
|
"""
|
|
import asyncio
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
|
|
from alembic import command
|
|
from alembic.config import Config
|
|
from sqlalchemy import inspect, text
|
|
from sqlalchemy.engine import make_url
|
|
from sqlalchemy.ext.asyncio import create_async_engine
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
URL = make_url(os.environ['CMVR_VERIFY_MYSQL_URL'])
|
|
if URL.host != 'cmvr-visual-v4-test-mysql':
|
|
raise SystemExit('Refusing a database outside the isolated v4 container')
|
|
|
|
CASES = [
|
|
(f'cmvr_visual_v4_{label}_{mode}', collation, mode == 'partial', None)
|
|
for label, collation in [
|
|
('unicode', 'utf8mb4_unicode_ci'),
|
|
('0900', 'utf8mb4_0900_ai_ci'),
|
|
('bin', 'utf8mb4_bin'),
|
|
]
|
|
for mode in ['full', 'partial']
|
|
] + [('cmvr_visual_v4_mixed', 'utf8mb4_0900_ai_ci', False, 'utf8mb4_bin')]
|
|
|
|
|
|
def config(database):
|
|
result = Config(str(ROOT / 'backend/alembic.ini'))
|
|
result.attributes['url'] = URL.set(database=database)
|
|
return result
|
|
|
|
|
|
async def reset(database, collation):
|
|
assert (database, collation) in {(case[0], case[1]) for case in CASES}
|
|
engine = create_async_engine(URL.set(database='mysql'))
|
|
async with engine.begin() as connection:
|
|
await connection.execute(text(f'DROP DATABASE IF EXISTS `{database}`'))
|
|
await connection.execute(text(f'CREATE DATABASE `{database}` CHARACTER SET utf8mb4 COLLATE {collation}'))
|
|
await engine.dispose()
|
|
|
|
|
|
async def column_shapes(connection):
|
|
rows = (await connection.execute(text(
|
|
'SELECT TABLE_NAME,COLUMN_NAME,COLUMN_TYPE,CHARACTER_SET_NAME,COLLATION_NAME,IS_NULLABLE '
|
|
"FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME LIKE 'visual\\_%'"
|
|
))).all()
|
|
return {(row[0], row[1]): tuple(row[2:]) for row in rows}
|
|
|
|
|
|
async def seed(database, partial, asset_collation=None):
|
|
engine = create_async_engine(URL.set(database=database))
|
|
async with engine.begin() as connection:
|
|
if asset_collation:
|
|
# A valid 003 schema can have differently collated user/asset IDs.
|
|
# Change both ends of the existing asset FK only in this fixture.
|
|
assert asset_collation == 'utf8mb4_bin'
|
|
def asset_fk(sync_connection):
|
|
matches = [fk for fk in inspect(sync_connection).get_foreign_keys('visual_job_assets')
|
|
if fk['referred_table'] == 'visual_assets']
|
|
assert len(matches) == 1
|
|
return sync_connection.dialect.identifier_preparer.quote(matches[0]['name'])
|
|
constraint = await connection.run_sync(asset_fk)
|
|
await connection.execute(text(f'ALTER TABLE visual_job_assets DROP FOREIGN KEY {constraint}'))
|
|
for table, column in [('visual_assets', 'id'), ('visual_job_assets', 'asset_id')]:
|
|
await connection.execute(text(f'ALTER TABLE {table} MODIFY {column} VARCHAR(32) CHARACTER SET utf8mb4 COLLATE {asset_collation} NOT NULL'))
|
|
await connection.execute(text(f'ALTER TABLE visual_job_assets ADD CONSTRAINT {constraint} FOREIGN KEY(asset_id) REFERENCES visual_assets(id)'))
|
|
await connection.execute(text("INSERT INTO visual_users(id,username,display_name,password_hash,role,disabled,must_change_password,created_at) VALUES('owner','owner','Owner','UNCHANGED','user',0,0,CURRENT_TIMESTAMP)"))
|
|
await connection.execute(text("INSERT INTO visual_assets(id,owner_id,name,storage_key,kind,mime_type,size_bytes,sha256,tags,favorite,origin,ready,created_at) VALUES('asset','owner','Original','owner/asset/source.png','image','image/png',123,:sha,'[]',0,'upload',1,CURRENT_TIMESTAMP)"), {'sha': '0' * 64})
|
|
if partial:
|
|
await connection.execute(text('ALTER TABLE visual_jobs ADD COLUMN deleted_at DATETIME NULL'))
|
|
await connection.execute(text("ALTER TABLE visual_assets ADD COLUMN library_scope VARCHAR(16) NOT NULL DEFAULT 'private'"))
|
|
before = await column_shapes(connection)
|
|
await engine.dispose()
|
|
return before
|
|
|
|
|
|
async def interrupt_after_table_create(database):
|
|
"""Model MySQL DDL committed before Alembic's version update/index finish."""
|
|
engine = create_async_engine(URL.set(database=database))
|
|
async with engine.begin() as connection:
|
|
await connection.execute(text('DROP INDEX ix_visual_shared_assets_created_at ON visual_shared_assets'))
|
|
await connection.execute(text("UPDATE alembic_version SET version_num='003'"))
|
|
await engine.dispose()
|
|
|
|
|
|
async def verify(database, before, user_collation, asset_collation):
|
|
engine = create_async_engine(URL.set(database=database))
|
|
async with engine.begin() as connection:
|
|
assert (await connection.execute(text('SELECT version_num FROM alembic_version'))).scalar_one() == '004'
|
|
assert tuple((await connection.execute(text("SELECT name,size_bytes,library_scope FROM visual_assets WHERE id='asset'"))).one()) == ('Original', 123, 'private')
|
|
assert (await connection.execute(text("SELECT password_hash FROM visual_users WHERE id='owner'"))).scalar_one() == 'UNCHANGED'
|
|
after = await column_shapes(connection)
|
|
assert all(after[key] == value for key, value in before.items()), 'Existing column definitions changed'
|
|
for column, collation in [('publisher_id', user_collation), ('asset_id', asset_collation), ('source_asset_id', asset_collation)]:
|
|
assert after[('visual_shared_assets', column)][:3] == ('varchar(32)', 'utf8mb4', collation)
|
|
await connection.execute(text("INSERT INTO visual_shared_assets(id,publisher_id,asset_id,source_asset_id,created_at) VALUES('publication','owner','asset','asset',CURRENT_TIMESTAMP)"))
|
|
|
|
def shape(sync_connection):
|
|
inspector = inspect(sync_connection)
|
|
assert 'visual_shared_assets' in inspector.get_table_names()
|
|
for table in ['visual_jobs', 'visual_drafts', 'visual_workflow_runs', 'visual_batches']:
|
|
assert next(c for c in inspector.get_columns(table) if c['name'] == 'deleted_at')['nullable']
|
|
assert len(inspector.get_foreign_keys('visual_shared_assets')) == 3
|
|
assert any(index['name'] == 'ix_visual_assets_library_scope' for index in inspector.get_indexes('visual_assets'))
|
|
assert any(index['name'] == 'ix_visual_shared_assets_created_at' for index in inspector.get_indexes('visual_shared_assets'))
|
|
await connection.run_sync(shape)
|
|
await engine.dispose()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
for database, collation, partial, asset_collation in CASES:
|
|
asyncio.run(reset(database, collation))
|
|
command.upgrade(config(database), '003')
|
|
before = asyncio.run(seed(database, partial, asset_collation))
|
|
command.upgrade(config(database), 'head')
|
|
if partial:
|
|
asyncio.run(interrupt_after_table_create(database))
|
|
command.upgrade(config(database), 'head')
|
|
command.upgrade(config(database), 'head')
|
|
asyncio.run(verify(database, before, collation, asset_collation or collation))
|
|
print(json.dumps({'mysql': '8.0.36', 'collation_cases': len(CASES), 'collations': ['utf8mb4_unicode_ci', 'utf8mb4_0900_ai_ci', 'utf8mb4_bin'], 'mixed_parent_collations': 'passed', 'upgrade_003_to_004': 'passed', 'partial_004_recovery': 'passed', 'repeat_upgrade': 'passed', 'existing_data_preserved': 'passed'}))
|