Skip to content

Commit

Permalink
- 补充 IDbFirst GetTableByDatabase 返回 uk/fk/index 名称,以便迁移;
Browse files Browse the repository at this point in the history
  • Loading branch information
28810 authored and 28810 committed Apr 26, 2019
1 parent 24df5d6 commit 5bb90a9
Show file tree
Hide file tree
Showing 11 changed files with 145 additions and 110 deletions.
44 changes: 44 additions & 0 deletions FreeSql.Tests/UnitTest1.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using NpgsqlTypes;
using Npgsql.LegacyPostgis;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace FreeSql.Tests {
public class UnitTest1 {
Expand Down Expand Up @@ -51,8 +52,51 @@ class ServiceRequestNew {
public string srvReqstCntt { get; set; }
}

public class TestEntity : EntityBase<int> {
public int Test { get; set; }
public string Title { get; set; }
public override Task Persistent(IRepositoryUnitOfWork uof) {
uof.GetGuidRepository<TestEntity>().Insert(this);
return Task.CompletedTask;
}
public override Task Persistent() {
var res = FreeSqlDb.Insert(this);
res.ExecuteInserted();
return Task.CompletedTask;
}
}
public abstract class EntityBase<TKey> : DomainInfrastructure {
[Column(IsPrimary = true, IsIdentity = true)]
public TKey Id { get; set; }
public Guid CompanyId { get; set; }
[Column(IsVersion = true)]
public int Version { get; set; }
}

public abstract class DomainInfrastructure {
[Column(IsIgnore = true)]
public IFreeSql FreeSqlDb {
get {
return g.sqlite;
}
}


public abstract Task Persistent(IRepositoryUnitOfWork uof);
public abstract Task Persistent();
}

[Fact]
public void Test1() {

var testddd = new TestEntity {
Test = 22,
Title = "xxx"
};
//testddd.Persistent().Wait();
g.sqlite.GetRepository<TestEntity, int>().Insert(testddd);


var testpid1 = g.mysql.Insert<TestTypeInfo>().AppendData(new TestTypeInfo { Name = "Name" + DateTime.Now.ToString("yyyyMMddHHmmss") }).ExecuteIdentity();
g.mysql.Insert<TestInfo>().AppendData(new TestInfo { Title = "Title" + DateTime.Now.ToString("yyyyMMddHHmmss"), CreateTime = DateTime.Now, TypeGuid = (int)testpid1 }).ExecuteAffrows();

Expand Down
4 changes: 4 additions & 0 deletions FreeSql/DataAnnotations/ColumnAttribute.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,10 @@ public class ColumnAttribute : Attribute {
/// </summary>
public bool IsVersion { get => _IsVersion ?? false; set => _IsVersion = value; }

/// <summary>
/// 唯一键,多个属性指定相同的标识,代表联合键
/// </summary>
public string Unique { get; set; }
/// <summary>
/// 数据库默认值
/// </summary>
Expand Down
9 changes: 9 additions & 0 deletions FreeSql/DataAnnotations/ColumnFluent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,15 @@ public ColumnFluent IsVersion(bool value) {
return this;
}
/// <summary>
/// 唯一键,多个属性指定相同的标识,代表联合键
/// </summary>
/// <param name="value">标识</param>
/// <returns></returns>
public ColumnFluent Unique(string value) {
_column.Unique = value;
return this;
}
/// <summary>
/// 类型映射,比如:可将 enum 属性映射成 typeof(string)
/// </summary>
/// <param name="type"></param>
Expand Down
10 changes: 7 additions & 3 deletions FreeSql/DatabaseModel/DBTableInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,19 @@ public class DbTableInfo {
/// <summary>
/// 唯一键/组合
/// </summary>
public List<List<DbColumnInfo>> Uniques { get; internal set; } = new List<List<DbColumnInfo>>();
public Dictionary<string, List<DbColumnInfo>> UniquesDict { get; internal set; } = new Dictionary<string, List<DbColumnInfo>>();
/// <summary>
/// 索引/组合
/// </summary>
public List<List<DbColumnInfo>> Indexes { get; internal set; } = new List<List<DbColumnInfo>>();
public Dictionary<string, List<DbColumnInfo>> IndexesDict { get; internal set; } = new Dictionary<string, List<DbColumnInfo>>();
/// <summary>
/// 外键
/// </summary>
public List<DbForeignInfo> Foreigns { get; internal set; } = new List<DbForeignInfo>();
public Dictionary<string, DbForeignInfo> ForeignsDict { get; internal set; } = new Dictionary<string, DbForeignInfo>();

public IEnumerable<List<DbColumnInfo>> Uniques => UniquesDict.Values;
public IEnumerable<List<DbColumnInfo>> Indexes => IndexesDict.Values;
public IEnumerable<DbForeignInfo> Foreigns => ForeignsDict.Values;
}

public enum DbTableType {
Expand Down
3 changes: 2 additions & 1 deletion FreeSql/Extensions/EntityUtilExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -264,14 +264,15 @@ public static void MapEntityValue(this IFreeSql orm, Type entityType, object ent
Expression.Assign(var2Parm, Expression.TypeAs(parm2, t))
});
foreach (var prop in _table.Properties.Values) {
if (_table.ColumnsByCsIgnore.ContainsKey(prop.Name)) continue;
if (_table.ColumnsByCs.ContainsKey(prop.Name)) {
exps.Add(
Expression.Assign(
Expression.MakeMemberAccess(var2Parm, prop),
Expression.MakeMemberAccess(var1Parm, prop)
)
);
} else {
} else if (prop.GetSetMethod() != null) {
exps.Add(
Expression.Assign(
Expression.MakeMemberAccess(var2Parm, prop),
Expand Down
1 change: 1 addition & 0 deletions FreeSql/Internal/Model/TableInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ public class TableInfo {
public Dictionary<string, ColumnInfo> ColumnsByCs { get; set; } = new Dictionary<string, ColumnInfo>(StringComparer.CurrentCultureIgnoreCase);
public Dictionary<string, ColumnInfo> ColumnsByCsIgnore { get; set; } = new Dictionary<string, ColumnInfo>(StringComparer.CurrentCultureIgnoreCase);
public ColumnInfo[] Primarys { get; set; }
public Dictionary<string, List<ColumnInfo>> Uniques { get; set; }
public string CsName { get; set; }
public string DbName { get; set; }
public string DbOldName { get; set; }
Expand Down
12 changes: 11 additions & 1 deletion FreeSql/Internal/UtilsExpressionTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) {
IsIgnore = false,
MapType = p.PropertyType
};
if (colattr._IsNullable == null) colattr._IsNullable = tp.Value.isnullable;
if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable;
if (string.IsNullOrEmpty(colattr.DbType)) colattr.DbType = tp?.dbtypeFull ?? "varchar(255)";
colattr.DbType = colattr.DbType.ToUpper();

Expand Down Expand Up @@ -164,11 +164,21 @@ internal static TableInfo GetTableByEntity(Type entity, CommonUtils common) {
trycol.Attribute.IsPrimary = true;
}
}
foreach(var dbuk in dbtb.UniquesDict) {
foreach (var dbcol in dbuk.Value) {
if (trytb.Columns.TryGetValue(dbcol.Name, out var trycol) && trycol.Attribute.MapType == dbcol.CsType ||
trytb.ColumnsByCs.TryGetValue(dbcol.Name, out trycol) && trycol.Attribute.MapType == dbcol.CsType) {
trycol.Attribute.Unique = dbuk.Key;
}
}
}
}
}
} catch { }
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
}
trytb.Uniques = trytb.Columns.Values.Where(a => !string.IsNullOrEmpty(a.Attribute.Unique))
.ToDictionary(a => a.Attribute.Unique, a => trytb.Columns.Values.Where(b => b.Attribute.Unique == a.Attribute.Unique).ToList());
tbc.AddOrUpdate(entity, trytb, (oldkey, oldval) => trytb);

#region 查找导航属性的关系、virtual 属性延时加载,动态产生新的重写类
Expand Down
38 changes: 14 additions & 24 deletions FreeSql/MySql/MySqlDbFirst.cs
Original file line number Diff line number Diff line change
Expand Up @@ -239,9 +239,9 @@ where a.table_schema in ({1}) and a.table_name in ({0})
select
concat(a.constraint_schema, '.', a.table_name) 'table_id',
a.column_name,
concat(a.constraint_schema, '/', a.table_name, '/', a.constraint_name) 'index_id',
a.constraint_name 'index_id',
1 'IsUnique',
case when constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
case when a.constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
0 'IsClustered',
0 'IsDesc'
from information_schema.key_column_usage a
Expand Down Expand Up @@ -283,21 +283,21 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position
}
}
foreach (string table_id in indexColumns.Keys) {
foreach (var columns in indexColumns[table_id].Values)
loc2[table_id].Indexes.Add(columns);
foreach (var column in indexColumns[table_id])
loc2[table_id].IndexesDict.Add(column.Key, column.Value);
}
foreach (string table_id in uniqueColumns.Keys) {
foreach (var columns in uniqueColumns[table_id].Values) {
columns.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
loc2[table_id].Uniques.Add(columns);
foreach (var column in uniqueColumns[table_id]) {
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
}
}

sql = string.Format(@"
select
concat(a.constraint_schema, '.', a.table_name) 'table_id',
a.column_name,
concat(a.constraint_schema, '/', a.constraint_name) 'FKId',
a.constraint_name 'FKId',
concat(a.referenced_table_schema, '.', a.referenced_table_name) 'ref_table_id',
1 'IsForeignKey',
a.referenced_column_name 'ref_column'
Expand Down Expand Up @@ -335,8 +335,8 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
loc13.ReferencedColumns.Add(loc11);
}
foreach (var table_id in fkColumns.Keys)
foreach (var fk in fkColumns[table_id].Values)
loc2[table_id].Foreigns.Add(fk);
foreach (var fk in fkColumns[table_id])
loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value);

foreach (var table_id in loc3.Keys) {
foreach (var loc5 in loc3[table_id].Values) {
Expand All @@ -346,8 +346,8 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
}
}
foreach (var loc4 in loc2.Values) {
if (loc4.Primarys.Count == 0 && loc4.Uniques.Count > 0) {
foreach (var loc5 in loc4.Uniques[0]) {
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) {
foreach (var loc5 in loc4.UniquesDict.First().Value) {
loc5.IsPrimary = true;
loc4.Primarys.Add(loc5);
}
Expand All @@ -356,8 +356,8 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
loc4.Columns.Sort((c1, c2) => {
int compare = c2.IsPrimary.CompareTo(c1.IsPrimary);
if (compare == 0) {
bool b1 = loc4.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c1.Name) != null) != null;
bool b2 = loc4.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c2.Name) != null) != null;
bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any();
bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any();
compare = b2.CompareTo(b1);
}
if (compare == 0) compare = c1.Name.CompareTo(c2.Name);
Expand All @@ -370,16 +370,6 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and not isnull(posi
if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
return ret;
});
foreach(var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach(var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}

loc2.Clear();
loc3.Clear();
Expand Down
36 changes: 13 additions & 23 deletions FreeSql/Oracle/OracleDbFirst.cs
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ where a.owner in ({1}) and a.table_name in ({0})
select
a.owner || '.' || a.table_name,
c.column_name,
a.owner || '/' || a.table_name || '/' || c.constraint_name,
c.constraint_name,
case when a.constraint_type = 'U' then 1 else 0 end,
case when a.constraint_type = 'P' then 1 else 0 end,
0,
Expand Down Expand Up @@ -302,21 +302,21 @@ and a.owner in ({1}) and a.table_name in ({0})
}
}
foreach (string table_id in indexColumns.Keys) {
foreach (var columns in indexColumns[table_id].Values)
loc2[table_id].Indexes.Add(columns);
foreach (var column in indexColumns[table_id])
loc2[table_id].IndexesDict.Add(column.Key, column.Value);
}
foreach (string table_id in uniqueColumns.Keys) {
foreach (var columns in uniqueColumns[table_id].Values) {
columns.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
loc2[table_id].Uniques.Add(columns);
foreach (var column in uniqueColumns[table_id]) {
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
}
}

sql = string.Format(@"
select
a.owner || '.' || a.table_name,
c.column_name,
a.owner || '/' || a.table_name || '/' || c.constraint_name,
c.constraint_name,
b.owner || '.' || b.table_name,
1,
d.column_name
Expand Down Expand Up @@ -379,8 +379,8 @@ and a.owner in ({1}) and a.table_name in ({0})
loc13.ReferencedColumns.Add(loc11);
}
foreach (var table_id in fkColumns.Keys)
foreach (var fk in fkColumns[table_id].Values)
loc2[table_id].Foreigns.Add(fk);
foreach (var fk in fkColumns[table_id])
loc2[table_id].ForeignsDict.Add(fk.Key, fk.Value);

foreach (var table_id in loc3.Keys) {
foreach (var loc5 in loc3[table_id].Values) {
Expand All @@ -390,8 +390,8 @@ and a.owner in ({1}) and a.table_name in ({0})
}
}
foreach (var loc4 in loc2.Values) {
if (loc4.Primarys.Count == 0 && loc4.Uniques.Count > 0) {
foreach (var loc5 in loc4.Uniques[0]) {
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) {
foreach (var loc5 in loc4.UniquesDict.First().Value) {
loc5.IsPrimary = true;
loc4.Primarys.Add(loc5);
}
Expand All @@ -400,8 +400,8 @@ and a.owner in ({1}) and a.table_name in ({0})
loc4.Columns.Sort((c1, c2) => {
int compare = c2.IsPrimary.CompareTo(c1.IsPrimary);
if (compare == 0) {
bool b1 = loc4.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c1.Name) != null) != null;
bool b2 = loc4.Foreigns.Find(fk => fk.Columns.Find(c3 => c3.Name == c2.Name) != null) != null;
bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any();
bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any();
compare = b2.CompareTo(b1);
}
if (compare == 0) compare = c1.Name.CompareTo(c2.Name);
Expand All @@ -414,16 +414,6 @@ and a.owner in ({1}) and a.table_name in ({0})
if (ret == 0) ret = t1.Name.CompareTo(t2.Name);
return ret;
});
foreach (var loc4 in loc1) {
var dicUniques = new Dictionary<string, List<DbColumnInfo>>();
if (loc4.Primarys.Count > 0) dicUniques.Add(string.Join(",", loc4.Primarys.Select(a => a.Name)), loc4.Primarys);
foreach (var loc5 in loc4.Uniques) {
var dickey = string.Join(",", loc5.Select(a => a.Name));
if (dicUniques.ContainsKey(dickey)) continue;
dicUniques.Add(dickey, loc5);
}
loc4.Uniques = dicUniques.Values.ToList();
}

loc2.Clear();
loc3.Clear();
Expand Down
Loading

0 comments on commit 5bb90a9

Please sign in to comment.