using MycroForge.CLI.CodeGen; namespace MycroForge.CLI.Features; public sealed class Db : IFeature { #region Defaults private static readonly string[] Settings = [ "class DbSettings:", "\tdef get_connectionstring() -> str:", "\t\t# Example", "\t\t# connectionstring = \"mysql+asyncmy://root:root@localhost:3306/your_database\"", "\t\t# return connectionstring", "\t\traise Exception(\"DbSettings.get_connectionstring was not implemented.\")", ]; private static readonly string[] AsyncSession = [ "from sqlalchemy.ext.asyncio import create_async_engine, AsyncEngine, AsyncSession", $"from {FeatureName}.settings import DbSettings", "", "async_engine: AsyncEngine = create_async_engine(DbSettings.get_connectionstring())", "", "def async_session() -> AsyncSession:", "\treturn AsyncSession(async_engine, expire_on_commit=False)" ]; private static readonly string[] EntityBase = [ "from sqlalchemy.orm import DeclarativeBase", "", "class EntityBase(DeclarativeBase):", "\tpass" ]; private static readonly string[] User = [ "from sqlalchemy import String", "from sqlalchemy.orm import Mapped, mapped_column", $"from {FeatureName}.entities.entity_base import EntityBase", "", "class User(EntityBase):", "\t__tablename__ = \"users\"", "\tid: Mapped[int] = mapped_column(primary_key=True)", "\tfirstname: Mapped[str] = mapped_column(String(255))", "\tlastname: Mapped[str] = mapped_column(String(255))", "", "\tdef __repr__(self) -> str:", "\t\treturn f\"User(id={self.id!r}, firstname={self.firstname!r}, lastname={self.lastname!r})\"" ]; #endregion public const string FeatureName = "db"; public string Name => FeatureName; public async Task ExecuteAsync(ProjectContext context) { var config = await context.LoadConfig(); await context.Bash( "source .venv/bin/activate", "python3 -m pip install asyncmy sqlalchemy alembic", "python3 -m pip freeze > requirements.txt", $"alembic init -t async {FeatureName}" ); var env = await context.ReadFile($"{FeatureName}/env.py"); env = new DbEnvInitializer(env).Rewrite(); // env = new DbEnvUpdater(env, "user", "User").Rewrite(); await context.WriteFile($"{FeatureName}/env.py", env); await context.CreateFile($"{FeatureName}/settings.py", Settings); await context.CreateFile($"{FeatureName}/engine/async_session.py", AsyncSession); await context.CreateFile($"{FeatureName}/entities/entity_base.py", EntityBase); // await context.CreateFile($"{FeatureName}/entities/user.py", User); await context.SaveConfig(config); } }