first commit
This commit is contained in:
37
backend/migrations/alembic.ini
Normal file
37
backend/migrations/alembic.ini
Normal file
@@ -0,0 +1,37 @@
|
||||
[alembic]
|
||||
script_location = migrations
|
||||
prepend_sys_path = .
|
||||
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
64
backend/migrations/env.py
Normal file
64
backend/migrations/env.py
Normal file
@@ -0,0 +1,64 @@
|
||||
import logging
|
||||
from logging.config import fileConfig
|
||||
from flask import current_app
|
||||
from alembic import context
|
||||
|
||||
config = context.config
|
||||
fileConfig(config.config_file_name)
|
||||
logger = logging.getLogger('alembic.env')
|
||||
|
||||
|
||||
def get_engine():
|
||||
try:
|
||||
return current_app.extensions['migrate'].db.get_engine()
|
||||
except (TypeError, AttributeError):
|
||||
return current_app.extensions['migrate'].db.engine
|
||||
|
||||
|
||||
def get_engine_url():
|
||||
try:
|
||||
return get_engine().url.render_as_string(hide_password=False).replace('%', '%%')
|
||||
except AttributeError:
|
||||
return str(get_engine().url).replace('%', '%%')
|
||||
|
||||
|
||||
config.set_main_option('sqlalchemy.url', get_engine_url())
|
||||
target_db = current_app.extensions['migrate'].db
|
||||
|
||||
|
||||
def get_metadata():
|
||||
if hasattr(target_db, 'metadatas'):
|
||||
return target_db.metadatas[None]
|
||||
return target_db.metadata
|
||||
|
||||
|
||||
def run_migrations_offline():
|
||||
url = config.get_main_option("sqlalchemy.url")
|
||||
context.configure(url=url, target_metadata=get_metadata(), literal_binds=True)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
def run_migrations_online():
|
||||
def process_revision_directives(context, revision, directives):
|
||||
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||
script = directives[0]
|
||||
if script.upgrade_ops.is_empty():
|
||||
directives[:] = []
|
||||
logger.info('No changes in schema detected.')
|
||||
|
||||
conf_args = current_app.extensions['migrate'].configure_args
|
||||
if conf_args.get("process_revision_directives") is None:
|
||||
conf_args["process_revision_directives"] = process_revision_directives
|
||||
|
||||
connectable = get_engine()
|
||||
with connectable.connect() as connection:
|
||||
context.configure(connection=connection, target_metadata=get_metadata(), **conf_args)
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
||||
24
backend/migrations/script.py.mako
Normal file
24
backend/migrations/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
||||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision | comma,n}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
branch_labels = ${repr(branch_labels)}
|
||||
depends_on = ${repr(depends_on)}
|
||||
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
||||
122
backend/migrations/versions/0001_initial_schema.py
Normal file
122
backend/migrations/versions/0001_initial_schema.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Initial schema
|
||||
|
||||
Revision ID: 0001
|
||||
Revises:
|
||||
Create Date: 2025-01-01 00:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision = '0001'
|
||||
down_revision = None
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Alle tabellen aanmaken als ze nog niet bestaan
|
||||
# (idempotent via checkfirst=True)
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schools (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
slug VARCHAR(100) NOT NULL UNIQUE,
|
||||
email_domains TEXT[] NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS school_years (
|
||||
id SERIAL PRIMARY KEY,
|
||||
school_id INTEGER REFERENCES schools(id) ON DELETE CASCADE,
|
||||
label VARCHAR(20) NOT NULL UNIQUE,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id SERIAL PRIMARY KEY,
|
||||
email VARCHAR(255) NOT NULL UNIQUE,
|
||||
password_hash VARCHAR(255),
|
||||
first_name VARCHAR(100),
|
||||
last_name VARCHAR(100),
|
||||
role VARCHAR(20) NOT NULL DEFAULT 'teacher',
|
||||
school_id INTEGER REFERENCES schools(id) ON DELETE SET NULL,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
last_login TIMESTAMP,
|
||||
oauth_provider VARCHAR(20),
|
||||
oauth_id VARCHAR(255),
|
||||
entra_tenant_id VARCHAR(255)
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS classes (
|
||||
id SERIAL PRIMARY KEY,
|
||||
school_id INTEGER NOT NULL REFERENCES schools(id) ON DELETE CASCADE,
|
||||
name VARCHAR(50) NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
UNIQUE(school_id, name)
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS teacher_classes (
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
||||
class_id INTEGER REFERENCES classes(id) ON DELETE CASCADE,
|
||||
PRIMARY KEY (user_id, class_id)
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS assessments (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
school_id INTEGER NOT NULL REFERENCES schools(id) ON DELETE CASCADE,
|
||||
school_year_id INTEGER NOT NULL REFERENCES school_years(id) ON DELETE CASCADE,
|
||||
vak_id VARCHAR(50) NOT NULL,
|
||||
goal_id VARCHAR(50) NOT NULL,
|
||||
status VARCHAR(10) NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
UNIQUE(user_id, school_year_id, vak_id, goal_id)
|
||||
)
|
||||
""")
|
||||
op.execute("""
|
||||
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
timestamp TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
school_id INTEGER REFERENCES schools(id) ON DELETE SET NULL,
|
||||
action VARCHAR(50) NOT NULL,
|
||||
category VARCHAR(20) NOT NULL,
|
||||
target_type VARCHAR(50),
|
||||
target_id VARCHAR(100),
|
||||
detail TEXT,
|
||||
ip_address VARCHAR(45)
|
||||
)
|
||||
""")
|
||||
op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_timestamp ON audit_logs(timestamp)")
|
||||
op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_action ON audit_logs(action)")
|
||||
op.execute("CREATE INDEX IF NOT EXISTS ix_audit_logs_category ON audit_logs(category)")
|
||||
|
||||
# Verwijder school_year_id van classes als die nog bestaat (oude structuur)
|
||||
op.execute("""
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM information_schema.columns
|
||||
WHERE table_name='classes' AND column_name='school_year_id'
|
||||
) THEN
|
||||
ALTER TABLE classes DROP COLUMN school_year_id;
|
||||
END IF;
|
||||
END $$
|
||||
""")
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.execute("DROP TABLE IF EXISTS audit_logs CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS assessments CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS teacher_classes CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS classes CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS users CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS school_years CASCADE")
|
||||
op.execute("DROP TABLE IF EXISTS schools CASCADE")
|
||||
Reference in New Issue
Block a user