Changed orm to db and added path resolution for entity generation

This commit is contained in:
2024-05-17 17:55:05 +02:00
parent 15bf94e195
commit d59dedc106
21 changed files with 232 additions and 155 deletions

View File

@@ -40,14 +40,14 @@ public partial class MycroForge
private async Task ExecuteAsync(string name)
{
_context.AssertDirectoryExists("api/routers");
_context.AssertDirectoryExists($"{Features.Api.FeatureName}/routers");
var moduleName = name.Underscore();
await _context.CreateFile($"api/routers/{moduleName}.py", Template);
await _context.CreateFile($"{Features.Api.FeatureName}/routers/{moduleName}.py", Template);
var main = await _context.ReadFile("main.py");
main += string.Join('\n',
$"\n\nfrom api.routers import {moduleName}",
$"\n\nfrom {Features.Api.FeatureName}.routers import {moduleName}",
$"app.include_router(prefix=\"/{name.Kebaberize()}\", router={moduleName}.router)"
);
await _context.WriteFile("main.py", main);

View File

@@ -0,0 +1,131 @@
using System.CommandLine;
using Humanizer;
using MycroForge.CLI.CodeGen;
using MycroForge.CLI.Commands.Interfaces;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Db
{
public partial class Generate
{
public class Entity : Command, ISubCommandOf<Generate>
{
private record ColumnDefinition(string Name, string NativeType, string OrmType);
private static readonly string[] Template =
[
"from sqlalchemy import %type_imports%",
"from sqlalchemy.orm import Mapped, mapped_column",
"from db.entities.entity_base import EntityBase",
"",
"class %class_name%(EntityBase):",
"\t__tablename__ = \"%table_name%\"",
"\tid: Mapped[int] = mapped_column(primary_key=True)",
"\t%column_definitions%",
"",
"\tdef __repr__(self) -> str:",
"\t\treturn f\"%class_name%(id={self.id!r})\""
];
private static readonly Argument<string> NameArgument =
new(name: "name", description: string.Join('\n', [
"The name of the database entity",
"",
"Supported formats:",
"\tEntity",
"\tpath/relative/to/entities:Entity",
]));
private static readonly Option<IEnumerable<string>> ColumnsOption =
new(aliases: ["--column", "-c"], description: string.Join('\n', [
"Specify the fields to add.",
"",
"Format:",
"\t<name>:<native_type>:<orm_type>",
"\t",
"\t<name> = Name of the column",
"\t<native_type> = The native Python type",
"\t<orm_type> = The SQLAlchemy type",
"",
"Example:",
"\tfirst_name:str:String(255)",
])) { AllowMultipleArgumentsPerToken = true };
private readonly ProjectContext _context;
public Entity(ProjectContext context) : base("entity", "Generate and database entity")
{
_context = context;
AddAlias("e");
AddArgument(NameArgument);
AddOption(ColumnsOption);
this.SetHandler(ExecuteAsync, NameArgument, ColumnsOption);
}
private async Task ExecuteAsync(string name, IEnumerable<string> columns)
{
_context.AssertDirectoryExists(Features.Db.FeatureName);
var path = string.Empty;
if (name.Split(':').Select(s => s.Trim()).ToArray() is { Length: 2 } fullName)
{
path = fullName[0];
name = fullName[1];
}
var _columns = GetColumnDefinitions(columns.ToArray());
var className = name.Underscore().Pascalize();
var typeImports = string.Join(", ", _columns.Select(c => c.OrmType.Split('(').First()).Distinct());
var columnDefinitions = string.Join("\n\t", _columns.Select(ColumnToString));
var code = string.Join('\n', Template);
code = code.Replace("%type_imports%", typeImports);
code = code.Replace("%class_name%", className);
code = code.Replace("%table_name%", name.Underscore().ToLower().Pluralize());
code = code.Replace("%column_definitions%", columnDefinitions);
var folderPath = Path.Join($"{Features.Db.FeatureName}/entities", path);
var fileName = $"{name.ToLower()}.py";
var filePath = Path.Join(folderPath, fileName);
await _context.CreateFile(filePath, code);
var importPathParts = new[] { path, fileName.Replace(".py", "") }
.Where(s => !string.IsNullOrEmpty(s));
var importPath = string.Join('.', importPathParts)
.Replace('/', '.')
.Replace('\\', '.')
.Underscore()
.ToLower();
var env = await _context.ReadFile($"{Features.Db.FeatureName}/env.py");
env = new DbEnvUpdater(env, importPath, className).Rewrite();
await _context.WriteFile($"{Features.Db.FeatureName}/env.py", env);
}
private List<ColumnDefinition> GetColumnDefinitions(string[] fields)
{
var definitions = new List<ColumnDefinition>();
foreach (var field in fields)
{
if (field.Split(':') is not { Length: 3 } definition)
throw new Exception($"Field definition {field} is invalid.");
definitions.Add(new ColumnDefinition(definition[0], definition[1], definition[2]));
}
return definitions;
}
private static string ColumnToString(ColumnDefinition definition)
{
return $"{definition.Name}: Mapped[{definition.NativeType}] = mapped_column({definition.OrmType})";
}
}
}
}
}

View File

@@ -5,7 +5,7 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public partial class Generate
{
@@ -26,7 +26,7 @@ public partial class MycroForge
private async Task ExecuteAsync(string name)
{
_context.AssertDirectoryExists("orm/versions");
_context.AssertDirectoryExists($"{Features.Db.FeatureName}/versions");
await _context.Bash(
"source .venv/bin/activate",

View File

@@ -5,12 +5,12 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public partial class Generate : Command, ISubCommandOf<Orm>
public partial class Generate : Command, ISubCommandOf<Db>
{
public Generate(IEnumerable<ISubCommandOf<Generate>> subCommands) :
base("generate", "Generate an ORM item")
base("generate", "Generate a database item")
{
AddAlias("g");
foreach (var subCommandOf in subCommands.Cast<Command>())

View File

@@ -6,7 +6,7 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public partial class Link
{
@@ -39,20 +39,20 @@ public partial class MycroForge
throw new Exception("Cannot set both --to-one and --to-many option.");
if (toOneOption is not null)
await ManyToOne(left, toOneOption);
await ToOne(left, toOneOption);
else if (toManyOption is not null)
await ManyToMany(left, toManyOption);
await ToMany(left, toManyOption);
else throw new Exception("Set --to-one or --to-many option.");
}
private async Task ManyToOne(string left, string toOneOption)
private async Task ToOne(string left, string toOneOption)
{
await new EntityLinker(_context, left, toOneOption).ManyToOne();
}
private async Task ManyToMany(string left, string toManyOption)
private async Task ToMany(string left, string toManyOption)
{
await new EntityLinker(_context, left, toManyOption).ManyToMany();
}

View File

@@ -6,7 +6,7 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public partial class Link
{
@@ -39,20 +39,20 @@ public partial class MycroForge
throw new Exception("Cannot set both --to-one and --to-many option.");
if (toOneOption is not null)
await OneToOne(left, toOneOption);
await ToOne(left, toOneOption);
else if (toManyOption is not null)
await OneToMany(left, toManyOption);
await ToMany(left, toManyOption);
else throw new Exception("Set --to-one or --to-many option.");
}
private async Task OneToOne(string left, string toOneOption)
private async Task ToOne(string left, string toOneOption)
{
await new EntityLinker(_context, left, toOneOption).OneToOne();
}
private async Task OneToMany(string left, string toManyOption)
private async Task ToMany(string left, string toManyOption)
{
await new EntityLinker(_context, left, toManyOption).OneToMany();
}

View File

@@ -5,9 +5,9 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public partial class Link : Command, ISubCommandOf<Orm>
public partial class Link : Command, ISubCommandOf<Db>
{
public Link(IEnumerable<ISubCommandOf<Link>> commands) :
base("link", "Define relationships between entities")

View File

@@ -5,9 +5,9 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public class Migrate : Command, ISubCommandOf<Orm>
public class Migrate : Command, ISubCommandOf<Db>
{
private readonly ProjectContext _context;

View File

@@ -5,9 +5,9 @@ namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
public partial class Db
{
public class Rollback : Command, ISubCommandOf<Orm>
public class Rollback : Command, ISubCommandOf<Db>
{
private readonly ProjectContext _context;

View File

@@ -0,0 +1,17 @@
using System.CommandLine;
using MycroForge.CLI.Commands.Interfaces;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Db : Command, ISubCommandOf<MycroForge>
{
public Db(IEnumerable<ISubCommandOf<Db>> commands)
: base("db", "Database related commands")
{
foreach (var command in commands.Cast<Command>())
AddCommand(command);
}
}
}

View File

@@ -30,9 +30,9 @@ public partial class MycroForge
private static readonly string[] WithSessionTemplate =
[
"from orm.engine.async_session import async_session",
"from db.engine.async_session import async_session",
"from sqlalchemy import select",
"# from orm.entities.some_entity import SomeEntity",
"# from db.entities.some_entity import SomeEntity",
"",
"class %class_name%Service:",
"",

View File

@@ -10,7 +10,7 @@ public partial class MycroForge
private readonly ProjectContext _context;
public Hydrate(ProjectContext context)
: base("hydrate", "Create a new venv and install dependencies listed in requirements.txt")
: base("hydrate", "Initialize venv and install dependencies from requirements.txt")
{
_context = context;
this.SetHandler(ExecuteAsync);

View File

@@ -59,7 +59,7 @@ public partial class MycroForge
[
Features.Git.FeatureName,
Features.Api.FeatureName,
Features.Orm.FeatureName
Features.Db.FeatureName
];
private static readonly Argument<string> NameArgument =
@@ -111,8 +111,17 @@ public partial class MycroForge
// Initialize default features
foreach (var feature in _features.Where(f => DefaultFeatures.Contains(f.Name)))
{
if (!withoutList.Contains(feature.Name))
{
Console.WriteLine($"Initializing feature {feature.Name}");
await feature.ExecuteAsync(_context);
}
else
{
Console.WriteLine($"Skipping feature {feature.Name}");
}
}
Console.WriteLine($"Directory {projectRoot} was successfully initialized");
}

View File

@@ -1,63 +0,0 @@
using System.CommandLine;
using Humanizer;
using MycroForge.CLI.CodeGen;
using MycroForge.CLI.Commands.Interfaces;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm
{
public partial class Generate
{
public class Entity : Command, ISubCommandOf<Generate>
{
private static readonly string[] Template =
[
"from sqlalchemy import String",
"from sqlalchemy.orm import Mapped, mapped_column",
"from orm.entities.entity_base import EntityBase",
"",
"class %class_name%(EntityBase):",
"\t__tablename__ = \"%table_name%\"",
"\tid: Mapped[int] = mapped_column(primary_key=True)",
"\tvalue: Mapped[str] = mapped_column(String(255))",
"",
"\tdef __repr__(self) -> str:",
"\t\treturn f\"%class_name%(id={self.id!r}, value={self.value!r})\""
];
private static readonly Argument<string> NameArgument =
new(name: "name", description: "The name of the orm entity");
private readonly ProjectContext _context;
public Entity(ProjectContext context) : base("entity", "Generate and orm entity")
{
_context = context;
AddAlias("e");
AddArgument(NameArgument);
this.SetHandler(ExecuteAsync, NameArgument);
}
private async Task ExecuteAsync(string name)
{
_context.AssertDirectoryExists("orm");
var className = name.Underscore().Pascalize();
var moduleName = name.Underscore();
var code = string.Join('\n', Template);
code = code.Replace("%class_name%", className);
code = code.Replace("%table_name%", name.Underscore().ToLower().Pluralize());
await _context.CreateFile($"orm/entities/{moduleName}.py", code);
var env = await _context.ReadFile("orm/env.py");
env = new OrmEnvUpdater(env, moduleName, className).Rewrite();
await _context.WriteFile("orm/env.py", env);
}
}
}
}
}

View File

@@ -1,17 +0,0 @@
using System.CommandLine;
using MycroForge.CLI.Commands.Interfaces;
namespace MycroForge.CLI.Commands;
public partial class MycroForge
{
public partial class Orm : Command, ISubCommandOf<MycroForge>
{
public Orm(IEnumerable<ISubCommandOf<Orm>> subCommands)
: base("orm", "ORM related commands")
{
foreach (var subCommandOf in subCommands.Cast<Command>())
AddCommand(subCommandOf);
}
}
}