Skip to content

Commit f14c586

Browse files
committed
add json filed example
1 parent 72bb711 commit f14c586

File tree

7 files changed

+69
-6
lines changed

7 files changed

+69
-6
lines changed

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ docker-apply-db-migrations: ## apply alembic migrations to database/schema
2121
docker compose run --rm app alembic upgrade head
2222

2323
.PHONY: docker-create-db-migration
24-
docker-create-db-migration: ## Create new alembic database migration aka database revision.
24+
docker-create-db-migration: ## Create new alembic database migration aka database revision. Example: make docker-create-db-migration msg="add users table"
2525
docker compose up -d db | true
2626
docker compose run --no-deps app alembic revision --autogenerate -m "$(msg)"
2727

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""add json chaos
2+
3+
Revision ID: d021bd4763a5
4+
Revises: 0c69050b5a3e
5+
Create Date: 2025-07-29 15:21:19.415583
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
from sqlalchemy.dialects import postgresql
11+
12+
# revision identifiers, used by Alembic.
13+
revision = 'd021bd4763a5'
14+
down_revision = '0c69050b5a3e'
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('random_stuff',
22+
sa.Column('id', sa.UUID(), nullable=False),
23+
sa.Column('chaos', postgresql.JSON(astext_type=sa.Text()), nullable=False),
24+
sa.PrimaryKeyConstraint('id'),
25+
schema='happy_hog'
26+
)
27+
op.create_unique_constraint(None, 'nonsense', ['name'], schema='happy_hog')
28+
op.create_unique_constraint(None, 'stuff', ['name'], schema='happy_hog')
29+
# ### end Alembic commands ###
30+
31+
32+
def downgrade():
33+
# ### commands auto generated by Alembic - please adjust! ###
34+
op.drop_constraint(None, 'stuff', schema='happy_hog', type_='unique')
35+
op.drop_constraint(None, 'nonsense', schema='happy_hog', type_='unique')
36+
op.drop_table('random_stuff', schema='happy_hog')
37+
# ### end Alembic commands ###

app/api/stuff.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,23 @@
44
from sqlalchemy.ext.asyncio import AsyncSession
55

66
from app.database import get_db
7-
from app.models.stuff import Stuff
8-
from app.schemas.stuff import StuffResponse, StuffSchema
7+
from app.models.stuff import Stuff, RandomStuff
8+
from app.schemas.stuff import StuffResponse, StuffSchema, RandomStuff as RandomStuffSchema
99

1010
logger = AppStructLogger().get_logger()
1111

1212
router = APIRouter(prefix="/v1/stuff")
1313

1414

15+
@router.post("/random", status_code=status.HTTP_201_CREATED)
16+
async def create_random_stuff(
17+
payload: RandomStuffSchema, db_session: AsyncSession = Depends(get_db)
18+
) -> dict[str, str]:
19+
random_stuff = RandomStuff(**payload.model_dump())
20+
await random_stuff.save(db_session)
21+
return {"id": str(random_stuff.id)}
22+
23+
1524
@router.post("/add_many", status_code=status.HTTP_201_CREATED)
1625
async def create_multi_stuff(
1726
payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)

app/models/base.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,8 @@ async def save(self, db_session: AsyncSession):
2727
"""
2828
try:
2929
db_session.add(self)
30-
return await db_session.commit()
30+
await db_session.commit()
31+
return await db_session.refresh(self)
3132
except SQLAlchemyError as ex:
3233
await logger.aerror(f"Error inserting instance of {self}: {repr(ex)}")
3334
raise HTTPException(

app/models/stuff.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,18 @@
99
from app.models.nonsense import Nonsense
1010
from app.utils.decorators import compile_sql_or_scalar
1111

12+
from sqlalchemy.dialects.postgresql import JSON
13+
14+
15+
class RandomStuff(Base):
16+
__tablename__ = "random_stuff"
17+
__table_args__ = ({"schema": "happy_hog"},)
18+
19+
id: Mapped[uuid.UUID] = mapped_column(
20+
UUID(as_uuid=True), default=uuid.uuid4, primary_key=True
21+
)
22+
chaos: Mapped[dict] = mapped_column(JSON)
23+
1224

1325
class Stuff(Base):
1426
__tablename__ = "stuff"

app/schemas/stuff.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
from uuid import UUID
22

3-
from pydantic import BaseModel, ConfigDict, Field
4-
3+
from pydantic import BaseModel, ConfigDict, Field, Json
4+
from typing import Any
55
config = ConfigDict(from_attributes=True)
66

77

8+
class RandomStuff(BaseModel):
9+
chaos: dict[str, Any] = Field(..., description="JSON data for chaos field")
10+
811
class StuffSchema(BaseModel):
912
name: str = Field(
1013
title="",

compose.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ services:
1818
- ./app:/panettone/app
1919
- ./tests:/panettone/tests
2020
- ./templates:/panettone/templates
21+
- ./alembic:/panettone/alembic
2122
ports:
2223
- "8080:8080"
2324
depends_on:

0 commit comments

Comments
 (0)