tomoya 2 years ago
parent
commit
384c61b73c

+ 9 - 1
backend/app/alembic/env.py

@@ -29,13 +29,21 @@ target_metadata = Base.metadata
 # my_important_option = config.get_main_option("my_important_option")
 # ... etc.
 
-
+'''
 def get_url():
     user = os.getenv("POSTGRES_USER", "postgres")
     password = os.getenv("POSTGRES_PASSWORD", "")
     server = os.getenv("POSTGRES_SERVER", "db")
     db = os.getenv("POSTGRES_DB", "app")
     return f"postgresql://{user}:{password}@{server}/{db}"
+'''
+
+def get_url():
+    user = "choozmo"
+    password = "pAssw0rd"
+    host = "db.ptt.cx:3306"
+    db_name = "video_maker"
+    return f'mysql://{user}:{password}@{host}/{db_name}'
 
 
 def run_migrations_offline():

+ 0 - 68
backend/app/alembic/versions/208dd144a013_add_membership_progress_and_modify_user_.py

@@ -1,68 +0,0 @@
-"""add membership, progress and modify user and add video
-
-Revision ID: 208dd144a013
-Revises: d4867f3a4c0a
-Create Date: 2023-02-19 17:25:35.565786
-
-"""
-from alembic import op
-import sqlalchemy as sa
-
-
-# revision identifiers, used by Alembic.
-revision = '208dd144a013'
-down_revision = 'd4867f3a4c0a'
-branch_labels = None
-depends_on = None
-
-
-def upgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.create_table('membership',
-    sa.Column('status', sa.String(length=20), nullable=False),
-    sa.PrimaryKeyConstraint('status')
-    )
-    op.create_table('progress',
-    sa.Column('state', sa.String(length=20), nullable=False),
-    sa.PrimaryKeyConstraint('state')
-    )
-    op.create_table('video',
-    sa.Column('id', sa.Integer(), nullable=False),
-    sa.Column('title', sa.String(), nullable=True),
-    sa.Column('progress_state', sa.String(length=20), nullable=True),
-    sa.Column('owner_id', sa.Integer(), nullable=True),
-    sa.ForeignKeyConstraint(['owner_id'], ['user.id'], ),
-    sa.ForeignKeyConstraint(['progress_state'], ['progress.state'], onupdate='CASCADE', ondelete='RESTRICT'),
-    sa.PrimaryKeyConstraint('id')
-    )
-    op.create_index(op.f('ix_video_id'), 'video', ['id'], unique=False)
-    op.create_index(op.f('ix_video_title'), 'video', ['title'], unique=False)
-    op.add_column('user', sa.Column('membership_status', sa.String(length=20), nullable=True))
-    op.add_column('user', sa.Column('available_time', sa.Integer(), nullable=True))
-    op.alter_column('user', 'email',
-               existing_type=sa.VARCHAR(),
-               nullable=False)
-    op.alter_column('user', 'hashed_password',
-               existing_type=sa.VARCHAR(),
-               nullable=False)
-    op.create_foreign_key(None, 'user', 'membership', ['membership_status'], ['status'], onupdate='CASCADE', ondelete='RESTRICT')
-    # ### end Alembic commands ###
-
-
-def downgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.drop_constraint(None, 'user', type_='foreignkey')
-    op.alter_column('user', 'hashed_password',
-               existing_type=sa.VARCHAR(),
-               nullable=True)
-    op.alter_column('user', 'email',
-               existing_type=sa.VARCHAR(),
-               nullable=True)
-    op.drop_column('user', 'available_time')
-    op.drop_column('user', 'membership_status')
-    op.drop_index(op.f('ix_video_title'), table_name='video')
-    op.drop_index(op.f('ix_video_id'), table_name='video')
-    op.drop_table('video')
-    op.drop_table('progress')
-    op.drop_table('membership')
-    # ### end Alembic commands ###

+ 0 - 52
backend/app/alembic/versions/ad8a076d04a6_add_membership_progress_and_modify_user_.py

@@ -1,52 +0,0 @@
-"""add membership, progress and modify user and add video
-
-Revision ID: ad8a076d04a6
-Revises: 208dd144a013
-Create Date: 2023-02-19 18:29:18.179836
-
-"""
-from alembic import op
-import sqlalchemy as sa
-
-
-# revision identifiers, used by Alembic.
-revision = 'ad8a076d04a6'
-down_revision = '208dd144a013'
-branch_labels = None
-depends_on = None
-
-
-def upgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.alter_column('user', 'membership_status',
-               existing_type=sa.VARCHAR(length=20),
-               type_=sa.String(length=10),
-               existing_nullable=True)
-    op.add_column('video', sa.Column('stored_file_name', sa.String(), nullable=False))
-    op.alter_column('video', 'title',
-               existing_type=sa.VARCHAR(),
-               nullable=False)
-    op.alter_column('video', 'progress_state',
-               existing_type=sa.VARCHAR(length=20),
-               type_=sa.String(length=10),
-               existing_nullable=True)
-    op.create_unique_constraint(None, 'video', ['stored_file_name'])
-    # ### end Alembic commands ###
-
-
-def downgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.drop_constraint(None, 'video', type_='unique')
-    op.alter_column('video', 'progress_state',
-               existing_type=sa.String(length=10),
-               type_=sa.VARCHAR(length=20),
-               existing_nullable=True)
-    op.alter_column('video', 'title',
-               existing_type=sa.VARCHAR(),
-               nullable=True)
-    op.drop_column('video', 'stored_file_name')
-    op.alter_column('user', 'membership_status',
-               existing_type=sa.String(length=10),
-               type_=sa.VARCHAR(length=20),
-               existing_nullable=True)
-    # ### end Alembic commands ###

+ 0 - 59
backend/app/alembic/versions/d4867f3a4c0a_first_revision.py

@@ -1,59 +0,0 @@
-"""First revision
-
-Revision ID: d4867f3a4c0a
-Revises:
-Create Date: 2019-04-17 13:53:32.978401
-
-"""
-from alembic import op
-import sqlalchemy as sa
-
-
-# revision identifiers, used by Alembic.
-revision = "d4867f3a4c0a"
-down_revision = None
-branch_labels = None
-depends_on = None
-
-
-def upgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.create_table(
-        "user",
-        sa.Column("id", sa.Integer(), nullable=False),
-        sa.Column("full_name", sa.String(), nullable=True),
-        sa.Column("email", sa.String(), nullable=True),
-        sa.Column("hashed_password", sa.String(), nullable=True),
-        sa.Column("is_active", sa.Boolean(), nullable=True),
-        sa.Column("is_superuser", sa.Boolean(), nullable=True),
-        sa.PrimaryKeyConstraint("id"),
-    )
-    op.create_index(op.f("ix_user_email"), "user", ["email"], unique=True)
-    op.create_index(op.f("ix_user_full_name"), "user", ["full_name"], unique=False)
-    op.create_index(op.f("ix_user_id"), "user", ["id"], unique=False)
-    op.create_table(
-        "item",
-        sa.Column("id", sa.Integer(), nullable=False),
-        sa.Column("title", sa.String(), nullable=True),
-        sa.Column("description", sa.String(), nullable=True),
-        sa.Column("owner_id", sa.Integer(), nullable=True),
-        sa.ForeignKeyConstraint(["owner_id"], ["user.id"],),
-        sa.PrimaryKeyConstraint("id"),
-    )
-    op.create_index(op.f("ix_item_description"), "item", ["description"], unique=False)
-    op.create_index(op.f("ix_item_id"), "item", ["id"], unique=False)
-    op.create_index(op.f("ix_item_title"), "item", ["title"], unique=False)
-    # ### end Alembic commands ###
-
-
-def downgrade():
-    # ### commands auto generated by Alembic - please adjust! ###
-    op.drop_index(op.f("ix_item_title"), table_name="item")
-    op.drop_index(op.f("ix_item_id"), table_name="item")
-    op.drop_index(op.f("ix_item_description"), table_name="item")
-    op.drop_table("item")
-    op.drop_index(op.f("ix_user_id"), table_name="user")
-    op.drop_index(op.f("ix_user_full_name"), table_name="user")
-    op.drop_index(op.f("ix_user_email"), table_name="user")
-    op.drop_table("user")
-    # ### end Alembic commands ###

+ 18 - 3
backend/app/app/core/config.py

@@ -14,8 +14,8 @@ class Settings(BaseSettings):
     # BACKEND_CORS_ORIGINS is a JSON-formatted list of origins
     # e.g: '["http://localhost", "http://localhost:4200", "http://localhost:3000", \
     # "http://localhost:8080", "http://local.dockertoolbox.tiangolo.com"]'
-    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
-
+    BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = ["*"]
+    '''
     @validator("BACKEND_CORS_ORIGINS", pre=True)
     def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
         if isinstance(v, str) and not v.startswith("["):
@@ -23,7 +23,7 @@ class Settings(BaseSettings):
         elif isinstance(v, (list, str)):
             return v
         raise ValueError(v)
-
+    '''
     PROJECT_NAME: str = "ai-anchor"
     SENTRY_DSN: Optional[HttpUrl] = None
 
@@ -39,6 +39,7 @@ class Settings(BaseSettings):
     POSTGRES_DB: str
     SQLALCHEMY_DATABASE_URI: Optional[PostgresDsn] = None
 
+    '''
     @validator("SQLALCHEMY_DATABASE_URI", pre=True)
     def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
         if isinstance(v, str):
@@ -50,6 +51,20 @@ class Settings(BaseSettings):
             host=values.get("POSTGRES_SERVER"),
             path=f"/{values.get('POSTGRES_DB') or ''}",
         )
+    '''
+    '''
+    @validator("SQLALCHEMY_DATABASE_URI", pre=True)
+    def assemble_db_connection(cls, v: Optional[str], values: Dict[str, Any]) -> Any:
+        if isinstance(v, str):
+            return v
+        return PostgresDsn.build(
+            scheme="mysql",
+            user="choozmo",
+            password="pAssw0rd",
+            host="db.ptt.cx:3306",
+            path=f"/ai-anchor",
+        )
+    '''
 
     SMTP_TLS: bool = True
     SMTP_PORT: Optional[int] = None

+ 24 - 1
backend/app/app/db/init_db.py

@@ -4,6 +4,8 @@ from app import crud, schemas
 from app.core.config import settings
 from app.db import base  # noqa: F401
 from app.models.enum import Membership, Progress
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy import create_engine
 # make sure all SQL Alchemy models are imported (app.db.base) before initializing DB
 # otherwise, SQL Alchemy might fail to initialize relationships properly
 # for more details: https://github.com/tiangolo/full-stack-fastapi-postgresql/issues/28
@@ -13,8 +15,29 @@ def init_db(db: Session) -> None:
     # Tables should be created with Alembic migrations
     # But if you don't want to use migrations, create
     # the tables un-commenting the next line
-    # Base.metadata.create_all(bind=engine)
+    '''
+    Base = declarative_base()
+    #Base.query  = db.query_property()
+    '''
+    user = "choozmo"
+    password = "pAssw0rd"
+    host = "db.ptt.cx:3306"
+    db_name = "video_maker"
+    engine = create_engine(f'mysql://{user}:{password}@{host}/{db_name}', pool_pre_ping=True)
+    base.Base.metadata.create_all(bind=engine)
 
+    if settings.MEMBERSHIP_TYPES:
+      for TYPE in settings.MEMBERSHIP_TYPES:
+          if not db.query(Membership).filter(Membership.status == TYPE).first():
+                db.add(Membership(status=TYPE))
+      db.commit()
+
+    if settings.PROGRESS_TYPES:
+        for TYPE in settings.PROGRESS_TYPES:
+            if not db.query(Progress).filter(Progress.state == TYPE).first():
+                db.add(Progress(state=TYPE))
+        db.commit()
+    
     user = crud.user.get_by_email(db, email=settings.FIRST_SUPERUSER)
     if not user:
         user_in = schemas.UserCreate(

+ 6 - 1
backend/app/app/db/session.py

@@ -3,5 +3,10 @@ from sqlalchemy.orm import sessionmaker
 
 from app.core.config import settings
 
-engine = create_engine(settings.SQLALCHEMY_DATABASE_URI, pool_pre_ping=True)
+
+user = "choozmo"
+password = "pAssw0rd"
+host = "db.ptt.cx:3306"
+db_name = "video_maker"
+engine = create_engine(f'mysql://{user}:{password}@{host}/{db_name}', pool_pre_ping=True)
 SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

+ 3 - 3
backend/app/app/models/item.py

@@ -1,6 +1,6 @@
 from typing import TYPE_CHECKING
 
-from sqlalchemy import Column, ForeignKey, Integer, String
+from sqlalchemy import Column, ForeignKey, Integer, String, Text
 from sqlalchemy.orm import relationship
 
 from app.db.base_class import Base
@@ -11,7 +11,7 @@ if TYPE_CHECKING:
 
 class Item(Base):
     id = Column(Integer, primary_key=True, index=True)
-    title = Column(String, index=True)
-    description = Column(String, index=True)
+    title = Column(String(30), index=True)
+    description = Column(Text)
     owner_id = Column(Integer, ForeignKey("user.id"))
     owner = relationship("User", back_populates="items")

+ 2 - 2
backend/app/app/models/style.py

@@ -1,11 +1,11 @@
 from typing import TYPE_CHECKING
 
-from sqlalchemy import Column, ForeignKey, Integer, String
+from sqlalchemy import Column, ForeignKey, Integer, String, Text
 from sqlalchemy.orm import relationship
 
 from app.db.base_class import Base
 
 class VideoStyle(Base):
   id = Column(Integer, primary_key=True, index=True)
-  
+  style = Column(Text)
 

+ 3 - 3
backend/app/app/models/user.py

@@ -11,9 +11,9 @@ if TYPE_CHECKING:
 
 class User(Base):
   id = Column(Integer, primary_key=True, index=True)
-  full_name = Column(String, index=True)
-  email = Column(String, unique=True, index=True, nullable=False)
-  hashed_password = Column(String, nullable=False)
+  full_name = Column(String(20), index=True)
+  email = Column(String(30), unique=True, index=True, nullable=False)
+  hashed_password = Column(String(100), nullable=False)
   membership_status = Column(String(10), 
                       ForeignKey("membership.status", onupdate="CASCADE", ondelete="RESTRICT"), 
                       default="normal")

+ 2 - 2
backend/app/app/models/video.py

@@ -12,8 +12,8 @@ if TYPE_CHECKING:
 
 class Video(Base):
   id = Column(Integer, primary_key=True, index=True)
-  title = Column(String, index=True, nullable=False)
-  stored_file_name = Column(String, unique=True, nullable=False)
+  title = Column(String(20), index=True, nullable=False)
+  stored_file_name = Column(String(30), unique=True, nullable=False)
   progress_state = Column(String(10), 
                     ForeignKey("progress.state", ondelete="RESTRICT", onupdate="CASCADE"),
                     default="waiting")

+ 1 - 1
backend/app/prestart.sh

@@ -4,7 +4,7 @@
 python /app/app/backend_pre_start.py
 
 # Run migrations
-alembic upgrade head
+# alembic upgrade head
 
 # Create initial data in DB
 python /app/app/initial_data.py

+ 2 - 0
backend/app/pyproject.toml

@@ -8,6 +8,8 @@ authors = ["tomoya <tomoya@choozmo.com>"]
 python = "^3.10.0"
 uvicorn = "^0.20.0"
 fastapi = "^0.89.0"
+mysql-connector-python = "^8.0.32"
+mysqlclient = "^2.1.1"
 python-multipart = "^0.0.5"
 email-validator = "^1.0.5"
 requests = "^2.23.0"