This commit is contained in:
2026-04-21 19:00:53 +05:45
commit ebb12e6ab7
20 changed files with 1391 additions and 0 deletions
+1
View File
@@ -0,0 +1 @@
Generic single-database configuration.
+91
View File
@@ -0,0 +1,91 @@
from dotenv import load_dotenv
import os
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
from sqlalchemy_declarative_extensions import register_alembic_events
register_alembic_events(schemas = True, roles = True, grants = True, rows = True)
import os
load_dotenv()
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
DATABASE_URL = os.getenv('DATABASE_URL', '')
# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)
config.set_main_option('sqlalchemy.url', DATABASE_URL)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from app.models import Base
target_metadata = Base.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section, {}),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+28
View File
@@ -0,0 +1,28 @@
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, Sequence[str], None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
def upgrade() -> None:
"""Upgrade schema."""
${upgrades if upgrades else "pass"}
def downgrade() -> None:
"""Downgrade schema."""
${downgrades if downgrades else "pass"}
+106
View File
@@ -0,0 +1,106 @@
"""Init
Revision ID: 34ec41e7908b
Revises:
Create Date: 2026-04-21 18:48:24.829721
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision: str = '34ec41e7908b'
down_revision: Union[str, Sequence[str], None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None
def upgrade() -> None:
"""Upgrade schema."""
op.create_table('users',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('username', sa.String(), nullable=False),
sa.Column('full_name', sa.String(), nullable=False),
sa.Column('email', sa.String(), nullable=False),
sa.Column('type', sa.String(), nullable=False),
sa.Column('is_archived', sa.Boolean(), nullable=False),
sa.Column('hashed_password', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_users'))
)
# ### commands auto generated by Alembic - please adjust! ###
op.execute("""CREATE FUNCTION "public_users_audit_insert"() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO "users_audit" ("audit_operation", "audit_timestamp", "audit_current_user", "id", "username", "full_name", "email", "type", "is_archived", "hashed_password")
SELECT 'I', now(), current_user, NEW."id", NEW."username", NEW."full_name", NEW."email", NEW."type", NEW."is_archived", NEW."hashed_password";
RETURN NULL;
END
$$;""")
op.execute("""CREATE FUNCTION "public_users_audit_update"() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO "users_audit" ("audit_operation", "audit_timestamp", "audit_current_user", "id", "username", "full_name", "email", "type", "is_archived", "hashed_password")
SELECT 'U', now(), current_user, NEW."id", NEW."username", NEW."full_name", NEW."email", NEW."type", NEW."is_archived", NEW."hashed_password";
RETURN NULL;
END
$$;""")
op.execute("""CREATE FUNCTION "public_users_audit_delete"() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO "users_audit" ("audit_operation", "audit_timestamp", "audit_current_user", "id", "username", "full_name", "email", "type", "is_archived", "hashed_password")
SELECT 'D', now(), current_user, OLD."id", OLD."username", OLD."full_name", OLD."email", OLD."type", OLD."is_archived", OLD."hashed_password";
RETURN NULL;
END
$$;""")
op.execute("""CREATE TRIGGER "public_users_audit_insert" AFTER INSERT ON "users" FOR EACH ROW EXECUTE PROCEDURE "public_users_audit_insert"();""")
op.execute("""CREATE TRIGGER "public_users_audit_update" AFTER UPDATE ON "users" FOR EACH ROW EXECUTE PROCEDURE "public_users_audit_update"();""")
op.execute("""CREATE TRIGGER "public_users_audit_delete" AFTER DELETE ON "users" FOR EACH ROW EXECUTE PROCEDURE "public_users_audit_delete"();""")
op.create_table('api_log',
sa.Column('id', sa.Uuid(), nullable=False),
sa.Column('api_key', sa.Uuid(), nullable=True),
sa.Column('ip_address', postgresql.INET(), nullable=False),
sa.Column('path', sa.String(), nullable=False),
sa.Column('method', sa.String(), nullable=False),
sa.Column('status_code', sa.Integer(), nullable=False),
sa.Column('request_body', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('response_body', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('query_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('path_params', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
sa.Column('process_time', sa.Float(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id', name=op.f('pk_api_log'))
)
op.create_index('ix_unique_active_email', 'users', ['email'], unique=True, postgresql_where='is_archived = false')
op.create_index('ix_unique_active_username', 'users', ['username'], unique=True, postgresql_where='is_archived = false')
op.create_table('users_audit',
sa.Column('audit_pk', sa.Integer(), nullable=False),
sa.Column('audit_operation', sa.Unicode(length=1), nullable=False),
sa.Column('audit_timestamp', sa.DateTime(timezone=True), nullable=False),
sa.Column('audit_current_user', sa.Unicode(length=64), nullable=False),
sa.Column('id', sa.Uuid(), nullable=True),
sa.Column('username', sa.String(), nullable=True),
sa.Column('full_name', sa.String(), nullable=True),
sa.Column('email', sa.String(), nullable=True),
sa.Column('type', sa.String(), nullable=True),
sa.Column('is_archived', sa.Boolean(), nullable=True),
sa.Column('hashed_password', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('audit_pk', name=op.f('pk_users_audit'))
)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users_audit')
op.drop_index('ix_unique_active_username', table_name='users', postgresql_where='is_archived = false')
op.drop_index('ix_unique_active_email', table_name='users', postgresql_where='is_archived = false')
op.drop_table('users')
op.drop_table('api_log')
op.execute("""DROP TRIGGER "public_users_audit_delete" ON "users";""")
op.execute("""DROP TRIGGER "public_users_audit_update" ON "users";""")
op.execute("""DROP TRIGGER "public_users_audit_insert" ON "users";""")
op.execute("""DROP FUNCTION public_users_audit_delete();""")
op.execute("""DROP FUNCTION public_users_audit_update();""")
op.execute("""DROP FUNCTION public_users_audit_insert();""")
# ### end Alembic commands ###