Compare commits

1 Commits
Author SHA1 Message Date
Shaun Kruger 9522762de5 Configure migrations as part of the package 2026-11-22 17:46:27 -07:00
10 changed files with 455 additions and 22 deletions
+149
View File
@@ -0,0 +1,149 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts.
# this is typically a path given in POSIX (e.g. forward slashes)
# format, relative to the token %(here)s which refers to the location of this
# ini file
script_location = %(here)s/privatestudio/migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# Or organize into date-based subdirectories (requires recursive_version_locations = true)
# file_template = %%(year)d/%%(month).2d/%%(day).2d_%%(hour).2d%%(minute).2d_%%(second).2d_%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory. for multiple paths, the path separator
# is defined by "path_separator" below.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the tzdata library which can be installed by adding
# `alembic[tz]` to the pip requirements.
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =
# max length of characters to apply to the "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version location specification; This defaults
# to <script_location>/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "path_separator"
# below.
# version_locations = %(here)s/bar:%(here)s/bat:%(here)s/alembic/versions
# path_separator; This indicates what character is used to split lists of file
# paths, including version_locations and prepend_sys_path within configparser
# files such as alembic.ini.
# The default rendered in new alembic.ini files is "os", which uses os.pathsep
# to provide os-dependent path splitting.
#
# Note that in order to support legacy alembic.ini files, this default does NOT
# take place if path_separator is not present in alembic.ini. If this
# option is omitted entirely, fallback logic is as follows:
#
# 1. Parsing of the version_locations option falls back to using the legacy
# "version_path_separator" key, which if absent then falls back to the legacy
# behavior of splitting on spaces and/or commas.
# 2. Parsing of the prepend_sys_path option falls back to the legacy
# behavior of splitting on spaces, commas, or colons.
#
# Valid values for path_separator are:
#
# path_separator = :
# path_separator = ;
# path_separator = space
# path_separator = newline
#
# Use os.pathsep. Default configuration used for new projects.
path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
# database URL. This is consumed by the user-maintained env.py script only.
# other means of configuring database URLs may be customized within the env.py
# file.
sqlalchemy.url = sqlite:///./transcoding.db
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the module runner, against the "ruff" module
# hooks = ruff
# ruff.type = module
# ruff.module = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Alternatively, use the exec runner to execute a binary found on your PATH
# hooks = ruff
# ruff.type = exec
# ruff.executable = ruff
# ruff.options = check --fix REVISION_SCRIPT_FILENAME
# Logging configuration. This is also consumed by the user-maintained
# env.py script only.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARNING
handlers = console
qualname =
[logger_sqlalchemy]
level = WARNING
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
+86
View File
@@ -0,0 +1,86 @@
from logging.config import fileConfig
import os
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# Import your models
from privatestudio.web.models import Base
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# 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)
# Use DATABASE_URL from environment or alembic.ini
target_metadata = Base.metadata
def get_sqlalchemy_url():
"""Get SQLAlchemy database URL from environment or config."""
url = os.environ.get("DATABASE_URL")
if url:
return url
return config.get_main_option("sqlalchemy.url")
# 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 = get_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:
def run(connection):
context.configure(connection=connection, target_metadata=target_metadata)
with context.begin_transaction():
context.run_migrations()
connection = config.attributes.get("connection")
if connection is not None:
run(connection)
return
configuration = config.get_section(config.config_ini_section, {})
configuration["sqlalchemy.url"] = get_sqlalchemy_url()
connectable = engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool
)
try:
with connectable.connect() as connection:
run(connection)
finally:
connectable.dispose()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
+29
View File
@@ -0,0 +1,29 @@
"""${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
import privatestudio.web.models
${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"}
@@ -0,0 +1,147 @@
"""Initial schema
Revision ID: 25cc5ed29873
Revises:
Create Date: 2026-11-22 16:57:27.821705
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
import privatestudio.web.models
# revision identifiers, used by Alembic.
revision: str = '25cc5ed29873'
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."""
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.Text(), nullable=False),
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('bucket_name', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_users_username'), 'users', ['username'], unique=True)
op.create_table('api_keys',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('key_hash', sa.Text(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('is_active', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_api_keys_key_hash'), 'api_keys', ['key_hash'], unique=True)
op.create_table('s3_credentials',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('access_key', sa.Text(), nullable=False),
sa.Column('secret_key', sa.Text(), nullable=False),
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('expires_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('authorized_key', sa.Text(), nullable=True),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_s3_credentials_access_key'), 's3_credentials', ['access_key'], unique=True)
op.create_index(op.f('ix_s3_credentials_user_id'), 's3_credentials', ['user_id'], unique=False)
op.create_table('transcode_profiles',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('name', sa.Text(), nullable=False),
sa.Column('profile_definition', sa.Text(), nullable=False),
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_transcode_profiles_user_id'), 'transcode_profiles', ['user_id'], unique=False)
op.create_table('uploaded_assets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('filename', sa.Text(), nullable=False),
sa.Column('size', sa.Integer(), nullable=False),
sa.Column('s3_path', sa.Text(), nullable=False),
sa.Column('upload_timestamp', privatestudio.web.models.TextDateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_uploaded_assets_user_id'), 'uploaded_assets', ['user_id'], unique=False)
op.create_table('transcode_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('asset_id', sa.Integer(), nullable=False),
sa.Column('profile_id', sa.Integer(), nullable=True),
sa.Column('status', sa.Text(), nullable=False),
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
sa.ForeignKeyConstraint(['asset_id'], ['uploaded_assets.id'], ),
sa.ForeignKeyConstraint(['profile_id'], ['transcode_profiles.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_transcode_jobs_user_id'), 'transcode_jobs', ['user_id'], unique=False)
op.create_table('packaging_jobs',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
sa.Column('status', sa.Text(), nullable=False),
sa.Column('requested_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.Column('completed_at', privatestudio.web.models.TextDateTime(), nullable=True),
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_packaging_jobs_user_id'), 'packaging_jobs', ['user_id'], unique=False)
op.create_table('transcoded_assets',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('transcode_job_id', sa.Integer(), nullable=False),
sa.Column('filename', sa.Text(), nullable=False),
sa.Column('s3_path', sa.Text(), nullable=False),
sa.Column('format', sa.Text(), nullable=False),
sa.Column('created_at', privatestudio.web.models.TextDateTime(), nullable=False),
sa.ForeignKeyConstraint(['transcode_job_id'], ['transcode_jobs.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sqlite_strict=True
)
op.create_index(op.f('ix_transcoded_assets_user_id'), 'transcoded_assets', ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade() -> None:
"""Downgrade schema."""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_transcoded_assets_user_id'), table_name='transcoded_assets')
op.drop_table('transcoded_assets')
op.drop_index(op.f('ix_packaging_jobs_user_id'), table_name='packaging_jobs')
op.drop_table('packaging_jobs')
op.drop_index(op.f('ix_transcode_jobs_user_id'), table_name='transcode_jobs')
op.drop_table('transcode_jobs')
op.drop_index(op.f('ix_uploaded_assets_user_id'), table_name='uploaded_assets')
op.drop_table('uploaded_assets')
op.drop_index(op.f('ix_transcode_profiles_user_id'), table_name='transcode_profiles')
op.drop_table('transcode_profiles')
op.drop_index(op.f('ix_s3_credentials_user_id'), table_name='s3_credentials')
op.drop_index(op.f('ix_s3_credentials_access_key'), table_name='s3_credentials')
op.drop_table('s3_credentials')
op.drop_index(op.f('ix_api_keys_key_hash'), table_name='api_keys')
op.drop_table('api_keys')
op.drop_index(op.f('ix_users_username'), table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
+9 -3
View File
@@ -1,10 +1,12 @@
"""FastAPI application setup and configuration."""
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from privatestudio.web.database import init_db
from privatestudio.web.database import upgrade_db
from privatestudio.web.routes import assets, transcode, profiles, keys, userinfo, s3_keys
@@ -23,14 +25,18 @@ class CacheBodyMiddleware(BaseHTTPMiddleware):
return response
# Initialize database
init_db()
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifespan context manager to initialize the database on startup."""
upgrade_db()
yield
# Create FastAPI app
app = FastAPI(
title="Private Studio",
description="Video transcoding web service with S3-compatible interface",
version="0.1.0",
lifespan=lifespan,
)
# Add middleware to cache request body (must be before CORS)
+7 -10
View File
@@ -3,15 +3,15 @@ import argparse
import os
import uvicorn
from privatestudio.web.database import init_db, get_db, SessionLocal
from privatestudio.web.database import upgrade_db, get_db, SessionLocal
from privatestudio.web.auth import create_user, create_api_key
from privatestudio.web.models import User
def init_command(args):
"""Initialize the database."""
init_db()
print("Database initialized")
def migrate_command(args):
"""Migrate the database."""
upgrade_db()
print("Database migrated")
def create_user_command(args):
@@ -52,9 +52,6 @@ def serve_command(args):
host = args.host or os.environ.get("SERVER_HOST", "0.0.0.0")
port = args.port or int(os.environ.get("SERVER_PORT", "8000"))
# Initialize database if needed
init_db()
print(f"Starting server at {host}:{port}")
uvicorn.run(
"privatestudio.web.app:app",
@@ -73,8 +70,8 @@ def main():
subparsers = parser.add_subparsers(dest="command", help="Command to run")
# Init command
init_parser = subparsers.add_parser("init", help="Initialize the database")
init_parser.set_defaults(func=init_command)
init_parser = subparsers.add_parser("migrate", help="Migrate the database")
init_parser.set_defaults(func=migrate_command)
# Create user command
user_parser = subparsers.add_parser("create-user", help="Create a new user")
+21 -6
View File
@@ -4,6 +4,10 @@ from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.pool import StaticPool
from alembic import command
from alembic.config import Config
from pathlib import Path
from privatestudio.web.models import Base
# Get database path from environment, default to ./transcoding.db
@@ -29,11 +33,22 @@ def get_db() -> Session:
db.close()
def init_db():
"""Initialize database tables."""
Base.metadata.create_all(bind=engine)
# def init_db():
# """Initialize database tables."""
# Base.metadata.create_all(bind=engine)
#
#
# def drop_db():
# """Drop all database tables (for testing)."""
# Base.metadata.drop_all(bind=engine)
def drop_db():
"""Drop all database tables (for testing)."""
Base.metadata.drop_all(bind=engine)
def upgrade_db():
config = Config()
config.set_main_option(
"script_location",
str(Path(__file__).resolve().parent.parent / "migrations"),
)
with engine.begin() as connection:
config.attributes["connection"] = connection
command.upgrade(config, "head")
+6 -2
View File
@@ -28,8 +28,12 @@ dev = [
ps-transcode = "privatestudio.transcode:main"
ps-serve = "privatestudio.web.cli:main"
[tool.setuptools]
packages = ["privatestudio"]
[tool.setuptools.packages.find]
include = ["privatestudio*"]
[tool.setuptools.package-data]
"privatestudio.migrations" = ["script.py.mako"]
[tool.setuptools_scm]
write_to = "privatestudio/_version.py"