add json filed example

This commit is contained in:
grillazz 2025-07-29 17:26:37 +02:00
parent 72bb711227
commit f14c586389
7 changed files with 69 additions and 6 deletions

View File

@ -21,7 +21,7 @@ docker-apply-db-migrations: ## apply alembic migrations to database/schema
docker compose run --rm app alembic upgrade head
.PHONY: docker-create-db-migration
docker-create-db-migration: ## Create new alembic database migration aka database revision.
docker-create-db-migration: ## Create new alembic database migration aka database revision. Example: make docker-create-db-migration msg="add users table"
docker compose up -d db | true
docker compose run --no-deps app alembic revision --autogenerate -m "$(msg)"

View File

@ -0,0 +1,37 @@
"""add json chaos
Revision ID: d021bd4763a5
Revises: 0c69050b5a3e
Create Date: 2025-07-29 15:21:19.415583
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = 'd021bd4763a5'
down_revision = '0c69050b5a3e'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('random_stuff',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('chaos', postgresql.JSON(astext_type=sa.Text()), nullable=False),
sa.PrimaryKeyConstraint('id'),
schema='happy_hog'
)
op.create_unique_constraint(None, 'nonsense', ['name'], schema='happy_hog')
op.create_unique_constraint(None, 'stuff', ['name'], schema='happy_hog')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_constraint(None, 'stuff', schema='happy_hog', type_='unique')
op.drop_constraint(None, 'nonsense', schema='happy_hog', type_='unique')
op.drop_table('random_stuff', schema='happy_hog')
# ### end Alembic commands ###

View File

@ -4,14 +4,23 @@ from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
from app.database import get_db
from app.models.stuff import Stuff
from app.schemas.stuff import StuffResponse, StuffSchema
from app.models.stuff import Stuff, RandomStuff
from app.schemas.stuff import StuffResponse, StuffSchema, RandomStuff as RandomStuffSchema
logger = AppStructLogger().get_logger()
router = APIRouter(prefix="/v1/stuff")
@router.post("/random", status_code=status.HTTP_201_CREATED)
async def create_random_stuff(
payload: RandomStuffSchema, db_session: AsyncSession = Depends(get_db)
) -> dict[str, str]:
random_stuff = RandomStuff(**payload.model_dump())
await random_stuff.save(db_session)
return {"id": str(random_stuff.id)}
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
async def create_multi_stuff(
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)

View File

@ -27,7 +27,8 @@ class Base(DeclarativeBase):
"""
try:
db_session.add(self)
return await db_session.commit()
await db_session.commit()
return await db_session.refresh(self)
except SQLAlchemyError as ex:
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
raise HTTPException(

View File

@ -9,6 +9,18 @@ from app.models.base import Base
from app.models.nonsense import Nonsense
from app.utils.decorators import compile_sql_or_scalar
from sqlalchemy.dialects.postgresql import JSON
class RandomStuff(Base):
__tablename__ = "random_stuff"
__table_args__ = ({"schema": "happy_hog"},)
id: Mapped[uuid.UUID] = mapped_column(
UUID(as_uuid=True), default=uuid.uuid4, primary_key=True
)
chaos: Mapped[dict] = mapped_column(JSON)
class Stuff(Base):
__tablename__ = "stuff"

View File

@ -1,10 +1,13 @@
from uuid import UUID
from pydantic import BaseModel, ConfigDict, Field
from pydantic import BaseModel, ConfigDict, Field, Json
from typing import Any
config = ConfigDict(from_attributes=True)
class RandomStuff(BaseModel):
chaos: dict[str, Any] = Field(..., description="JSON data for chaos field")
class StuffSchema(BaseModel):
name: str = Field(
title="",

View File

@ -18,6 +18,7 @@ services:
- ./app:/panettone/app
- ./tests:/panettone/tests
- ./templates:/panettone/templates
- ./alembic:/panettone/alembic
ports:
- "8080:8080"
depends_on: