77 lines
2.5 KiB
C#
77 lines
2.5 KiB
C#
using MycroForge.Core.CodeGen;
|
|
|
|
namespace MycroForge.CLI.CodeGen;
|
|
|
|
public class DbEnvInitializer
|
|
{
|
|
private readonly Source _source;
|
|
private SourceMatch? _alembicImport;
|
|
private SourceMatch? _targetMetaDataAssignment;
|
|
private SourceMatch? _urlAssignmentContext;
|
|
private SourceMatch? _connectableAssignmentContext;
|
|
|
|
public DbEnvInitializer(string source)
|
|
{
|
|
_source = new Source(source);
|
|
}
|
|
|
|
public string Rewrite()
|
|
{
|
|
InsertDefaultDbImports();
|
|
|
|
InsertTargetMetadata();
|
|
|
|
InsertConnectionstringFromDbSettings();
|
|
|
|
InsertSqlAlchemyConfigUpdate();
|
|
|
|
return _source.Text;
|
|
}
|
|
|
|
private void InsertSqlAlchemyConfigUpdate()
|
|
{
|
|
_connectableAssignmentContext = _source.Find(@"connectable\s*=\s*.+\(\s*");
|
|
|
|
if (_connectableAssignmentContext is null)
|
|
throw new Exception("Could not find connectable insertion point.");
|
|
|
|
const string indent = " ";
|
|
_source.InsertMultiLine(_connectableAssignmentContext.StartIndex, [
|
|
$"url = DbSettings.get_connectionstring()",
|
|
$"{indent}context.config.set_main_option('sqlalchemy.url', url)\n{indent}",
|
|
]);
|
|
}
|
|
|
|
private void InsertConnectionstringFromDbSettings()
|
|
{
|
|
_urlAssignmentContext = _source.Find("""url\s*=\s*config\s*.+\s*get_main_option\(\s*"sqlalchemy.url"\s*\)""");
|
|
|
|
if (_urlAssignmentContext is null)
|
|
throw new Exception("Could not find url insertion point.");
|
|
|
|
_source.Replace(_urlAssignmentContext, "url = DbSettings.get_connectionstring()");
|
|
}
|
|
|
|
private void InsertTargetMetadata()
|
|
{
|
|
_targetMetaDataAssignment = _source.Find(@"target_metadata\s*=\s*None");
|
|
|
|
if (_targetMetaDataAssignment is null)
|
|
throw new Exception("Could not find metadata insertion point.");
|
|
|
|
_source.Replace(_targetMetaDataAssignment, "target_metadata = EntityBase.metadata");
|
|
}
|
|
|
|
private void InsertDefaultDbImports()
|
|
{
|
|
_alembicImport = _source.Find(@"from\s+alembic\s+import\s+context");
|
|
|
|
if (_alembicImport is null)
|
|
throw new Exception("Could not find import insertion point.");
|
|
|
|
_source.InsertMultiLine(_alembicImport.EndIndex, [
|
|
$"\nfrom {Features.Db.FeatureName}.settings import DbSettings",
|
|
$"from {Features.Db.FeatureName}.entities.entity_base import EntityBase\n"
|
|
]);
|
|
}
|
|
} |