Skip to content

Commit

Permalink
(backend): Added psycopg2-binary package and fixed non async support
Browse files Browse the repository at this point in the history
  • Loading branch information
Imanuel Febie committed Nov 14, 2024
1 parent 398423a commit c6aea5b
Show file tree
Hide file tree
Showing 6 changed files with 209 additions and 18 deletions.
1 change: 1 addition & 0 deletions langkah-api/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ asyncpg = "*"
fastapi-users = {extras = ["redis", "oauth", "sqlalchemy"], version = "*"}
supabase = "*"
python-decouple = "*"
psycopg2-binary = "*"

[dev-packages]

Expand Down
76 changes: 75 additions & 1 deletion langkah-api/Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 16 additions & 9 deletions langkah-api/langkah/lib/dependencies/db.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from collections.abc import AsyncGenerator

from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

from langkah.lib.config.settings import (
supabase_db_host,
Expand All @@ -10,12 +9,20 @@
supabase_db_user,
)

DB_URL = f"postgresql://{supabase_db_user}:{supabase_db_password}@{supabase_db_host}:{supabase_db_port}/{supabase_db_name}"
# Construct the database URL
DB_URL = f"postgresql+psycopg2://{supabase_db_user}:{supabase_db_password}@{supabase_db_host}:{supabase_db_port}/{supabase_db_name}"

# Create a synchronous SQLAlchemy engine
engine = create_engine(DB_URL)

engine = create_async_engine(DB_URL)
session_maker = async_sessionmaker(engine, expire_on_commit=False)
# Create a sessionmaker for creating new sessions
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
async with session_maker() as session:
yield session
# Dependency to provide a new database session for each request
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
7 changes: 6 additions & 1 deletion langkah-api/langkah/types/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,16 @@
"meal_food_product",
Base.metadata,
Column("meal_id", ForeignKey("meals.id"), primary_key=True),
Column("food_product_id", ForeignKey("food_products.id", primary_key=True)),
Column("food_product_id", ForeignKey("food_products.id"), primary_key=True),
)


class User(Base):
__tablename__ = "users"

id: Mapped[UUID] = mapped_column(
UUID(as_uuid=True), primary_key=True, unique=True, default=uuid.uuid4
)
name: Mapped[str] = mapped_column(String, nullable=False)
avatar: Mapped[str] = mapped_column(String, nullable=True)
height: Mapped[float] = mapped_column(Float, nullable=False)
Expand Down
14 changes: 7 additions & 7 deletions langkah-api/migrations/env.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context
from sqlalchemy import engine_from_config, pool

from langkah.lib.dependencies.db import DB_URL
from langkah.types import models

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", DB_URL)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
Expand All @@ -18,7 +20,7 @@
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None
target_metadata = models.Base.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
Expand Down Expand Up @@ -64,9 +66,7 @@ def run_migrations_online() -> None:
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()
Expand Down
104 changes: 104 additions & 0 deletions langkah-api/migrations/versions/ca1296c1d73a_first_migration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
"""first migration
Revision ID: ca1296c1d73a
Revises:
Create Date: 2024-11-14 12:42:02.877254
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'ca1296c1d73a'
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('food_products',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('code', sa.String(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('brand', sa.String(), nullable=True),
sa.Column('energy_kcal', sa.Integer(), nullable=False),
sa.Column('fat', sa.Float(), nullable=False),
sa.Column('saturated_fat', sa.Float(), nullable=False),
sa.Column('trans_fat', sa.Float(), nullable=False),
sa.Column('carbohydrates', sa.Float(), nullable=False),
sa.Column('sugars', sa.Float(), nullable=False),
sa.Column('fiber', sa.Float(), nullable=True),
sa.Column('proteins', sa.Float(), nullable=False),
sa.Column('salt', sa.Float(), nullable=True),
sa.Column('sodium', sa.Float(), nullable=True),
sa.Column('calcium', sa.Float(), nullable=True),
sa.Column('iron', sa.Float(), nullable=True),
sa.Column('vitamin_a', sa.Float(), nullable=True),
sa.Column('vitamin_c', sa.Float(), nullable=True),
sa.Column('completeness', sa.Float(), nullable=True),
sa.Column('nutriscore_grade', sa.String(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
sa.UniqueConstraint('id')
)
op.create_table('users',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('name', sa.String(), nullable=False),
sa.Column('avatar', sa.String(), nullable=True),
sa.Column('height', sa.Float(), nullable=False),
sa.Column('sex', sa.Enum('MALE', 'FEMALE', name='sex'), nullable=False),
sa.Column('activity_level', sa.Enum('SEDENTARY', 'LIGHTLY_ACTIVE', 'MODERATELY_ACTIVE', 'VERY_ACTIVE', name='activitylevel'), nullable=False),
sa.Column('goal', sa.Enum('WEIGHT_LOSS', 'MUSCLE_GAIN', 'MAINTAIN', 'BODY_RECOMPOSITION', name='goal'), nullable=False),
sa.Column('daily_caloric_needs', sa.Float(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
op.create_table('body_metrics',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('timestamp', sa.Date(), nullable=False),
sa.Column('weight', sa.Float(), nullable=False),
sa.Column('body_fat_percentage', sa.Float(), nullable=True),
sa.Column('muscle_mass', sa.Float(), nullable=True),
sa.Column('waist', sa.Float(), nullable=True),
sa.Column('left_arm', sa.Float(), nullable=True),
sa.Column('right_arm', sa.Float(), nullable=True),
sa.Column('left_leg', sa.Float(), nullable=True),
sa.Column('right_leg', sa.Float(), nullable=True),
sa.Column('chest', sa.Float(), nullable=True),
sa.Column('hips', sa.Float(), nullable=True),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
op.create_table('meals',
sa.Column('id', sa.UUID(), nullable=False),
sa.Column('name', sa.String(length=222), nullable=False),
sa.Column('timestamp', sa.Date(), nullable=False),
sa.Column('user_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('id')
)
op.create_table('meal_food_product',
sa.Column('meal_id', sa.UUID(), nullable=False),
sa.Column('food_product_id', sa.UUID(), nullable=False),
sa.ForeignKeyConstraint(['food_product_id'], ['food_products.id'], ),
sa.ForeignKeyConstraint(['meal_id'], ['meals.id'], ),
sa.PrimaryKeyConstraint('meal_id', 'food_product_id')
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('meal_food_product')
op.drop_table('meals')
op.drop_table('body_metrics')
op.drop_table('users')
op.drop_table('food_products')
# ### end Alembic commands ###

0 comments on commit c6aea5b

Please sign in to comment.