/
Frexto
/
frexto-orm
Обзор
Документация
Войти
/
Frexto
/
frexto-orm
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
main
MigrationManager.cs
71 строка
2 KB
Maksim Fomin
orm
07 окт 2025, 10:58
07 окт 2025, 10:58
f4c0f72
Код
Авторство
О чём код?
using System.Reflection; using System.Text; namespace FrextoORM; public class MigrationManager { private static string GetDataType(PropertyInfo prop) { if (prop.Name == "Id") return "SERIAL"; var type = prop.PropertyType; if (type == typeof(int)) { if (prop.GetCustomAttribute<OneToOneAttribute>() != null) return "INT UNIQUE"; return "INT"; } if (type == typeof(string)) { var typeName = "VARCHAR"; var maxLength = prop.GetCustomAttribute<MaxLengthAttribute>()?.MaxLength; if (maxLength != null) typeName += $"({maxLength.ToString()})"; return typeName; } if (type == typeof(bool)) return "BIT"; throw new Exception("Unsupported migration type"); } public string GenerateCreateTableSql<T>() { var type = typeof(T); var tableName = type.Name.ToLower(); var properties = type.GetProperties(); var script = new StringBuilder(); script.AppendLine($"create table {tableName} ("); foreach (var prop in properties) { script.AppendLine($"{prop.Name.ToLower()} {GetDataType(prop)},"); var fk = prop.GetCustomAttribute<ForeignKeyAttribute>(); if (fk is OneToOneAttribute || fk is OneToManyAttribute) { script.AppendLine($"FOREIGN KEY ({prop.Name.ToLower()}) REFERENCES {fk.Name.ToLower()}(id),"); } } script.Append("PRIMARY KEY (id));"); return script.ToString(); } public string GetMigrationSql() { var ass = Assembly.GetExecutingAssembly(); var modelTypes = ass.GetTypes().Where(t => t.IsSubclassOf(typeof(FrextoModel))); var script = new StringBuilder(); foreach (var modelType in modelTypes) { var sql = typeof(MigrationManager) .GetMethod("GenerateCreateTableSql")! .MakeGenericMethod(modelType) .Invoke(this, null) as string; script.AppendLine(sql); } return script.ToString(); } }