mirror of
https://github.com/nsnail/FreeSql.git
synced 2025-04-22 10:42:52 +08:00
- 增加 IndexAttribute 特性,自动迁移索引,以及对应的 FluentApi 方法;
- 移除 ColumnAttribute.Unique 属性设置,改为 IndexAttribute 特性设置唯一键;
This commit is contained in:
parent
cb18b74830
commit
78fded3f8e
@ -46,17 +46,16 @@ namespace FreeSql.Tests.MySqlConnector
|
||||
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -46,17 +46,16 @@ namespace FreeSql.Tests.Odbc.MySql
|
||||
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -46,17 +46,16 @@ namespace FreeSql.Tests.Odbc.Oracle
|
||||
g.oracle.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
[Fact]
|
||||
|
@ -50,17 +50,16 @@ namespace FreeSql.Tests.Odbc.PostgreSQL
|
||||
g.pgsql.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -48,17 +48,16 @@ namespace FreeSql.Tests.Odbc.SqlServer
|
||||
g.sqlserver.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -163,6 +163,7 @@ namespace FreeSql.Tests.DataAnnotations
|
||||
Assert.NotEqual(item.testfield2, find.testfield2);
|
||||
Assert.Equal(1000, find.testfield1);
|
||||
}
|
||||
[Index("idx_xxx", "testfield1 ASC, testfield2 DESC")]
|
||||
class TestCanInsert
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
|
@ -46,17 +46,16 @@ namespace FreeSql.Tests.MySql
|
||||
g.mysql.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", false)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -46,17 +46,16 @@ namespace FreeSql.Tests.Oracle
|
||||
g.oracle.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22 desc", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
[Fact]
|
||||
|
@ -9,12 +9,13 @@ namespace Zeus
|
||||
/// 用户表
|
||||
/// </summary>
|
||||
[Table(Name = "system_user")]
|
||||
[Index("UK_DisplayName", "DisplayName", true)]
|
||||
public partial class SystemUser : EntityBase<long>
|
||||
{
|
||||
/// <summary>
|
||||
/// 显示名称
|
||||
/// </summary>
|
||||
[Column(DbType = "varchar(20)", IsNullable = false, Unique = "UK_DisplayName")]
|
||||
[Column(DbType = "varchar(20)", IsNullable = false)]
|
||||
public string DisplayName { get; set; }
|
||||
/// <summary>
|
||||
/// 真实名称
|
||||
|
@ -10,6 +10,7 @@ namespace Zeus
|
||||
/// 用户认证表
|
||||
/// </summary>
|
||||
[Table(Name = "system_user_authentication")]
|
||||
[Index("UK_Identifier", "Identifier", true)]
|
||||
public partial class SystemUserAuthentication : EntityBase<long>
|
||||
{
|
||||
/// <summary>
|
||||
@ -30,7 +31,7 @@ namespace Zeus
|
||||
/// <summary>
|
||||
/// 登录标识
|
||||
/// </summary>
|
||||
[Column(DbType = "varchar(50)", IsNullable = false, Unique = "UK_Identifier")]
|
||||
[Column(DbType = "varchar(50)", IsNullable = false)]
|
||||
public string Identifier { get; set; }
|
||||
/// <summary>
|
||||
/// 登录凭证
|
||||
|
@ -53,17 +53,16 @@ namespace FreeSql.Tests.PostgreSQL
|
||||
g.pgsql.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", false)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -57,17 +57,16 @@ namespace FreeSql.Tests.SqlServer
|
||||
_sqlserverFixture.SqlServer.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo", OldName = "AddUniquesInfo2")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group, index22", false)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -46,17 +46,16 @@ namespace FreeSql.Tests.Sqlite
|
||||
g.sqlite.CodeFirst.SyncStructure<AddUniquesInfo>();
|
||||
}
|
||||
[Table(Name = "AddUniquesInfo2", OldName = "AddUniquesInfo")]
|
||||
[Index("uk_phone", "phone", true)]
|
||||
[Index("uk_group_index", "group,index", true)]
|
||||
[Index("uk_group_index22", "group desc, index22", true)]
|
||||
class AddUniquesInfo
|
||||
{
|
||||
public Guid id { get; set; }
|
||||
[Column(Unique = "uk_phone")]
|
||||
public string phone { get; set; }
|
||||
|
||||
[Column(Unique = "uk_group_index, uk_group_index22")]
|
||||
public string group { get; set; }
|
||||
[Column(Unique = "uk_group_index")]
|
||||
public int index { get; set; }
|
||||
[Column(Unique = "uk_group_index22")]
|
||||
public string index22 { get; set; }
|
||||
}
|
||||
|
||||
|
@ -3,6 +3,7 @@ using System.Linq;
|
||||
|
||||
namespace FreeSql.DataAnnotations
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Property)]
|
||||
public class ColumnAttribute : Attribute
|
||||
{
|
||||
|
||||
@ -42,35 +43,6 @@ namespace FreeSql.DataAnnotations
|
||||
/// </summary>
|
||||
public bool IsVersion { get => _IsVersion ?? false; set => _IsVersion = value; }
|
||||
|
||||
internal string[] _Uniques;
|
||||
/// <summary>
|
||||
/// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。
|
||||
/// </summary>
|
||||
public string Unique
|
||||
{
|
||||
get => _Uniques == null ? null : string.Join(", ", _Uniques);
|
||||
set
|
||||
{
|
||||
if (string.IsNullOrEmpty(value))
|
||||
{
|
||||
_Uniques = null;
|
||||
return;
|
||||
}
|
||||
var val = value?.Trim(' ', '\t', ',');
|
||||
if (string.IsNullOrEmpty(val))
|
||||
{
|
||||
_Uniques = null;
|
||||
return;
|
||||
}
|
||||
var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray();
|
||||
if (arr.Any() == false)
|
||||
{
|
||||
_Uniques = null;
|
||||
return;
|
||||
}
|
||||
_Uniques = arr;
|
||||
}
|
||||
}
|
||||
/// <summary>
|
||||
/// 数据库默认值
|
||||
/// </summary>
|
||||
|
@ -77,16 +77,6 @@ namespace FreeSql.DataAnnotations
|
||||
return this;
|
||||
}
|
||||
/// <summary>
|
||||
/// 唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。
|
||||
/// </summary>
|
||||
/// <param name="value">标识</param>
|
||||
/// <returns></returns>
|
||||
public ColumnFluent Unique(string value)
|
||||
{
|
||||
_column.Unique = value;
|
||||
return this;
|
||||
}
|
||||
/// <summary>
|
||||
/// 类型映射,比如:可将 enum 属性映射成 typeof(string)
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
|
@ -1,8 +1,10 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql.DataAnnotations
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class)]
|
||||
public class TableAttribute : Attribute
|
||||
{
|
||||
|
||||
@ -27,5 +29,36 @@ namespace FreeSql.DataAnnotations
|
||||
|
||||
internal ConcurrentDictionary<string, ColumnAttribute> _columns { get; } = new ConcurrentDictionary<string, ColumnAttribute>(StringComparer.CurrentCultureIgnoreCase);
|
||||
internal ConcurrentDictionary<string, NavigateAttribute> _navigates { get; } = new ConcurrentDictionary<string, NavigateAttribute>(StringComparer.CurrentCultureIgnoreCase);
|
||||
internal ConcurrentDictionary<string, IndexAttribute> _indexs { get; } = new ConcurrentDictionary<string, IndexAttribute>(StringComparer.CurrentCultureIgnoreCase);
|
||||
}
|
||||
|
||||
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
|
||||
public class IndexAttribute : Attribute
|
||||
{
|
||||
public IndexAttribute(string name, string fields)
|
||||
{
|
||||
this.Name = name;
|
||||
this.Fields = fields;
|
||||
}
|
||||
public IndexAttribute(string name, string fields, bool isUnique)
|
||||
{
|
||||
this.Name = name;
|
||||
this.Fields = fields;
|
||||
this.IsUnique = isUnique;
|
||||
}
|
||||
/// <summary>
|
||||
/// 索引名
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
/// <summary>
|
||||
/// 索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC
|
||||
/// </summary>
|
||||
public string Fields { get; set; }
|
||||
|
||||
internal bool? _IsUnique;
|
||||
/// <summary>
|
||||
/// 是否唯一
|
||||
/// </summary>
|
||||
public bool IsUnique { get => _IsUnique ?? false; set => _IsUnique = value; }
|
||||
}
|
||||
}
|
||||
|
@ -59,6 +59,20 @@ namespace FreeSql.DataAnnotations
|
||||
var col = _table._columns.GetOrAdd(proto, name => new ColumnAttribute { Name = proto });
|
||||
return new ColumnFluent(col);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置实体的索引
|
||||
/// </summary>
|
||||
/// <param name="name">索引名</param>
|
||||
/// <param name="fields">索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC</param>
|
||||
/// <param name="isUnique">是否唯一</param>
|
||||
/// <returns></returns>
|
||||
public TableFluent Index(string name, string fields, bool isUnique = false)
|
||||
{
|
||||
var idx = new IndexAttribute(name, fields, isUnique);
|
||||
_table._indexs.AddOrUpdate(name, idx, (_, __) => idx);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
public class TableFluent<T>
|
||||
@ -128,5 +142,19 @@ namespace FreeSql.DataAnnotations
|
||||
_table._navigates.AddOrUpdate(member.Name, nav, (name, old) => nav);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置实体的索引
|
||||
/// </summary>
|
||||
/// <param name="name">索引名</param>
|
||||
/// <param name="fields">索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC</param>
|
||||
/// <param name="isUnique">是否唯一</param>
|
||||
/// <returns></returns>
|
||||
public TableFluent<T> Index(string name, string fields, bool isUnique = false)
|
||||
{
|
||||
var idx = new IndexAttribute(name, fields, isUnique);
|
||||
_table._indexs.AddOrUpdate(name, idx, (_, __) => idx);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -40,18 +40,18 @@ namespace FreeSql.DatabaseModel
|
||||
/// <summary>
|
||||
/// 唯一键/组合
|
||||
/// </summary>
|
||||
public Dictionary<string, List<DbColumnInfo>> UniquesDict { get; set; } = new Dictionary<string, List<DbColumnInfo>>();
|
||||
public Dictionary<string, DbIndexInfo> UniquesDict { get; set; } = new Dictionary<string, DbIndexInfo>();
|
||||
/// <summary>
|
||||
/// 索引/组合
|
||||
/// </summary>
|
||||
public Dictionary<string, List<DbColumnInfo>> IndexesDict { get; set; } = new Dictionary<string, List<DbColumnInfo>>();
|
||||
public Dictionary<string, DbIndexInfo> IndexesDict { get; set; } = new Dictionary<string, DbIndexInfo>();
|
||||
/// <summary>
|
||||
/// 外键
|
||||
/// </summary>
|
||||
public Dictionary<string, DbForeignInfo> ForeignsDict { get; set; } = new Dictionary<string, DbForeignInfo>();
|
||||
|
||||
public List<List<DbColumnInfo>> Uniques => UniquesDict.Values.ToList();
|
||||
public List<List<DbColumnInfo>> Indexes => IndexesDict.Values.ToList();
|
||||
public List<DbIndexInfo> Uniques => UniquesDict.Values.ToList();
|
||||
public List<DbIndexInfo> Indexes => IndexesDict.Values.ToList();
|
||||
public List<DbForeignInfo> Foreigns => ForeignsDict.Values.ToList();
|
||||
}
|
||||
|
||||
|
21
FreeSql/DatabaseModel/DbIndexInfo.cs
Normal file
21
FreeSql/DatabaseModel/DbIndexInfo.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql.DatabaseModel
|
||||
{
|
||||
public class DbIndexInfo
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public List<DbIndexColumnInfo> Columns { get; } = new List<DbIndexColumnInfo>();
|
||||
public bool IsUnique { get; set; }
|
||||
}
|
||||
|
||||
public class DbIndexColumnInfo
|
||||
{
|
||||
public DbColumnInfo Column { get; set; }
|
||||
public bool IsDesc { get; set; }
|
||||
}
|
||||
}
|
@ -45,11 +45,6 @@
|
||||
设置行锁(乐观锁)版本号,每次更新累加版本号,若更新整个实体时会附带当前的版本号判断(修改失败时抛出异常)
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.DataAnnotations.ColumnAttribute.Unique">
|
||||
<summary>
|
||||
唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.DataAnnotations.ColumnAttribute.DbDefautValue">
|
||||
<summary>
|
||||
数据库默认值
|
||||
@ -123,13 +118,6 @@
|
||||
乐观锁
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.ColumnFluent.Unique(System.String)">
|
||||
<summary>
|
||||
唯一键,在多个属性指定相同的标识,代表联合键;可使用逗号分割多个 UniqueKey 名。
|
||||
</summary>
|
||||
<param name="value">标识</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.ColumnFluent.MapType(System.Type)">
|
||||
<summary>
|
||||
类型映射,比如:可将 enum 属性映射成 typeof(string)
|
||||
@ -199,6 +187,21 @@
|
||||
禁用 CodeFirst 同步结构迁移
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.DataAnnotations.IndexAttribute.Name">
|
||||
<summary>
|
||||
索引名
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.DataAnnotations.IndexAttribute.Fields">
|
||||
<summary>
|
||||
索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.DataAnnotations.IndexAttribute.IsUnique">
|
||||
<summary>
|
||||
是否唯一
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent.Name(System.String)">
|
||||
<summary>
|
||||
数据库表名
|
||||
@ -219,6 +222,15 @@
|
||||
禁用 CodeFirst 同步结构迁移
|
||||
</summary>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent.Index(System.String,System.String,System.Boolean)">
|
||||
<summary>
|
||||
设置实体的索引
|
||||
</summary>
|
||||
<param name="name">索引名</param>
|
||||
<param name="fields">索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC</param>
|
||||
<param name="isUnique">是否唯一</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent`1.Name(System.String)">
|
||||
<summary>
|
||||
数据库表名
|
||||
@ -249,6 +261,15 @@
|
||||
<param name="manyToMany">多对多关系的中间实体类型</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="M:FreeSql.DataAnnotations.TableFluent`1.Index(System.String,System.String,System.Boolean)">
|
||||
<summary>
|
||||
设置实体的索引
|
||||
</summary>
|
||||
<param name="name">索引名</param>
|
||||
<param name="fields">索引字段,为属性名以逗号分隔,如:Create_time ASC, Title ASC</param>
|
||||
<param name="isUnique">是否唯一</param>
|
||||
<returns></returns>
|
||||
</member>
|
||||
<member name="P:FreeSql.DatabaseModel.DbColumnInfo.Table">
|
||||
<summary>
|
||||
所属表
|
||||
@ -551,7 +572,9 @@
|
||||
</member>
|
||||
<member name="M:FreeSql.FreeSqlBuilder.UseConfigEntityFromDbFirst(System.Boolean)">
|
||||
<summary>
|
||||
使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。
|
||||
将数据库的主键、自增、索引设置导入,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql/oracle。<para></para>
|
||||
本功能会影响 IFreeSql 首次访问的速度。<para></para>
|
||||
若使用 CodeFirst 创建索引后,又直接在数据库上建了索引,若无本功能下一次 CodeFirst 迁移时数据库上创建的索引将被删除
|
||||
</summary>
|
||||
<param name="value"></param>
|
||||
<returns></returns>
|
||||
@ -2288,7 +2311,9 @@
|
||||
</member>
|
||||
<member name="P:FreeSql.ICodeFirst.IsConfigEntityFromDbFirst">
|
||||
<summary>
|
||||
使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。
|
||||
将数据库的主键、自增、索引设置导入,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql/oracle。<para></para>
|
||||
本功能会影响 IFreeSql 首次访问的速度。<para></para>
|
||||
若使用 CodeFirst 创建索引后,又直接在数据库上建了索引,若无本功能下一次 CodeFirst 迁移时数据库上创建的索引将被删除
|
||||
</summary>
|
||||
</member>
|
||||
<member name="P:FreeSql.ICodeFirst.IsNoneCommandParameter">
|
||||
|
@ -78,7 +78,9 @@ namespace FreeSql
|
||||
return this;
|
||||
}
|
||||
/// <summary>
|
||||
/// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。
|
||||
/// 将数据库的主键、自增、索引设置导入,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql/oracle。<para></para>
|
||||
/// 本功能会影响 IFreeSql 首次访问的速度。<para></para>
|
||||
/// 若使用 CodeFirst 创建索引后,又直接在数据库上建了索引,若无本功能下一次 CodeFirst 迁移时数据库上创建的索引将被删除
|
||||
/// </summary>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
|
@ -21,7 +21,9 @@ namespace FreeSql
|
||||
/// </summary>
|
||||
bool IsSyncStructureToUpper { get; set; }
|
||||
/// <summary>
|
||||
/// 使用数据库的主键和自增,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql。
|
||||
/// 将数据库的主键、自增、索引设置导入,适用 DbFirst 模式,无须在实体类型上设置 [Column(IsPrimary)] 或者 ConfigEntity。此功能目前可用于 mysql/sqlserver/postgresql/oracle。<para></para>
|
||||
/// 本功能会影响 IFreeSql 首次访问的速度。<para></para>
|
||||
/// 若使用 CodeFirst 创建索引后,又直接在数据库上建了索引,若无本功能下一次 CodeFirst 迁移时数据库上创建的索引将被删除
|
||||
/// </summary>
|
||||
bool IsConfigEntityFromDbFirst { get; set; }
|
||||
/// <summary>
|
||||
|
@ -125,7 +125,6 @@ namespace FreeSql.Internal
|
||||
if (trycol._IsNullable != null) attr._IsNullable = trycol.IsNullable;
|
||||
if (trycol._IsIgnore != null) attr._IsIgnore = trycol.IsIgnore;
|
||||
if (trycol._IsVersion != null) attr._IsVersion = trycol.IsVersion;
|
||||
if (trycol._Uniques != null) attr._Uniques = trycol._Uniques;
|
||||
if (trycol.MapType != null) attr.MapType = trycol.MapType;
|
||||
if (trycol._Position != null) attr._Position = trycol.Position;
|
||||
if (trycol._CanInsert != null) attr._CanInsert = trycol.CanInsert;
|
||||
@ -145,7 +144,6 @@ namespace FreeSql.Internal
|
||||
if (tryattr._IsNullable != null) attr._IsNullable = tryattr.IsNullable;
|
||||
if (tryattr._IsIgnore != null) attr._IsIgnore = tryattr.IsIgnore;
|
||||
if (tryattr._IsVersion != null) attr._IsVersion = tryattr.IsVersion;
|
||||
if (tryattr._Uniques != null) attr._Uniques = tryattr._Uniques;
|
||||
if (tryattr.MapType != null) attr.MapType = tryattr.MapType;
|
||||
if (tryattr._Position != null) attr._Position = tryattr.Position;
|
||||
if (tryattr._CanInsert != null) attr._CanInsert = tryattr.CanInsert;
|
||||
@ -161,7 +159,6 @@ namespace FreeSql.Internal
|
||||
if (attr._IsNullable != null) ret = attr;
|
||||
if (attr._IsIgnore != null) ret = attr;
|
||||
if (attr._IsVersion != null) ret = attr;
|
||||
if (attr._Uniques != null) ret = attr;
|
||||
if (attr.MapType != null) ret = attr;
|
||||
if (attr._Position != null) ret = attr;
|
||||
if (attr._CanInsert != null) ret = attr;
|
||||
@ -191,6 +188,29 @@ namespace FreeSql.Internal
|
||||
if (attr.ManyToMany != null) ret = attr;
|
||||
return ret;
|
||||
}
|
||||
public IndexAttribute[] GetEntityIndexAttribute(Type type)
|
||||
{
|
||||
var ret = new Dictionary<string, IndexAttribute>(); ;
|
||||
if (dicConfigEntity.TryGetValue(type, out var trytb))
|
||||
{
|
||||
foreach (var idxattr in trytb._indexs.Values)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(idxattr.Name) && !string.IsNullOrEmpty(idxattr.Fields))
|
||||
ret.Add(idxattr.Name, new IndexAttribute(idxattr.Name, idxattr.Fields) { _IsUnique = idxattr._IsUnique });
|
||||
}
|
||||
}
|
||||
var attrs = type.GetCustomAttributes(typeof(IndexAttribute), true);
|
||||
foreach (var tryattrobj in attrs)
|
||||
{
|
||||
var idxattr = tryattrobj as IndexAttribute;
|
||||
if (idxattr == null) continue;
|
||||
if (string.IsNullOrEmpty(idxattr.Name)) continue;
|
||||
if (string.IsNullOrEmpty(idxattr.Fields)) continue;
|
||||
if (ret.ContainsKey(idxattr.Name)) ret.Remove(idxattr.Name);
|
||||
ret.Add(idxattr.Name, new IndexAttribute(idxattr.Name, idxattr.Fields) { _IsUnique = idxattr._IsUnique });
|
||||
}
|
||||
return ret.Values.ToArray();
|
||||
}
|
||||
|
||||
public string WhereObject(TableInfo table, string aliasAndDot, object dywhere)
|
||||
{
|
||||
|
21
FreeSql/Internal/Model/IndexInfo.cs
Normal file
21
FreeSql/Internal/Model/IndexInfo.cs
Normal file
@ -0,0 +1,21 @@
|
||||
using FreeSql.DataAnnotations;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq.Expressions;
|
||||
|
||||
namespace FreeSql.Internal.Model
|
||||
{
|
||||
public class IndexInfo
|
||||
{
|
||||
public string Name { get; set; }
|
||||
public IndexColumnInfo[] Columns { get; set; }
|
||||
public bool IsUnique { get; set; }
|
||||
}
|
||||
|
||||
public class IndexColumnInfo
|
||||
{
|
||||
public ColumnInfo Column { get; set; }
|
||||
public bool IsDesc { get; set; }
|
||||
}
|
||||
}
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using FreeSql.DataAnnotations;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
@ -16,7 +17,7 @@ namespace FreeSql.Internal.Model
|
||||
public Dictionary<string, ColumnInfo> ColumnsByCsIgnore { get; set; } = new Dictionary<string, ColumnInfo>(StringComparer.CurrentCultureIgnoreCase);
|
||||
public ColumnInfo[] ColumnsByPosition { get; set; }
|
||||
public ColumnInfo[] Primarys { get; set; }
|
||||
public Dictionary<string, List<ColumnInfo>> Uniques { get; set; }
|
||||
public IndexInfo[] Indexes { get; set; }
|
||||
public string CsName { get; set; }
|
||||
public string DbName { get; set; }
|
||||
public string DbOldName { get; set; }
|
||||
|
@ -103,7 +103,6 @@ namespace FreeSql.Internal
|
||||
IsNullable = tp.Value.isnullable ?? true,
|
||||
IsPrimary = false,
|
||||
IsIgnore = false,
|
||||
Unique = null,
|
||||
MapType = p.PropertyType
|
||||
};
|
||||
if (colattr._IsNullable == null) colattr._IsNullable = tp?.isnullable;
|
||||
@ -119,16 +118,8 @@ namespace FreeSql.Internal
|
||||
if (tp != null && tp.Value.isnullable == null) colattr.IsNullable = tp.Value.dbtypeFull.Contains("NOT NULL") == false;
|
||||
if (colattr.DbType?.Contains("NOT NULL") == true) colattr.IsNullable = false;
|
||||
if (string.IsNullOrEmpty(colattr.Name)) colattr.Name = p.Name;
|
||||
if (common.CodeFirst.IsSyncStructureToLower)
|
||||
{
|
||||
colattr.Name = colattr.Name.ToLower();
|
||||
colattr.Unique = colattr.Unique?.ToLower();
|
||||
}
|
||||
if (common.CodeFirst.IsSyncStructureToUpper)
|
||||
{
|
||||
colattr.Name = colattr.Name.ToUpper();
|
||||
colattr.Unique = colattr.Unique?.ToUpper();
|
||||
}
|
||||
if (common.CodeFirst.IsSyncStructureToLower) colattr.Name = colattr.Name.ToLower();
|
||||
if (common.CodeFirst.IsSyncStructureToUpper) colattr.Name = colattr.Name.ToUpper();
|
||||
|
||||
if ((colattr.IsNullable != true || colattr.IsIdentity == true || colattr.IsPrimary == true) && colattr.DbType.Contains("NOT NULL") == false)
|
||||
{
|
||||
@ -183,27 +174,9 @@ namespace FreeSql.Internal
|
||||
if (trytb.VersionColumn.Attribute.MapType.IsNullableType() || trytb.VersionColumn.Attribute.MapType.IsNumberType() == false)
|
||||
throw new Exception($"属性{trytb.VersionColumn.CsName} 被标注为行锁(乐观锁)(IsVersion),但其必须为数字类型,并且不可为 Nullable");
|
||||
}
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault();
|
||||
if (identcol != null) trytb.Primarys = new[] { identcol };
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, "id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
col.Attribute.IsPrimary = true;
|
||||
}
|
||||
//从数据库查找主键、自增
|
||||
|
||||
var indexesDict = new Dictionary<string, IndexInfo>(StringComparer.CurrentCultureIgnoreCase);
|
||||
//从数据库查找主键、自增、索引
|
||||
if (common.CodeFirst.IsConfigEntityFromDbFirst)
|
||||
{
|
||||
try
|
||||
@ -220,37 +193,99 @@ namespace FreeSql.Internal
|
||||
{
|
||||
foreach (var dbident in dbtb.Identitys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType == dbident.CsType ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType == dbident.CsType)
|
||||
if (trytb.Columns.TryGetValue(dbident.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbident.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbident.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsIdentity = true;
|
||||
}
|
||||
foreach (var dbpk in dbtb.Primarys)
|
||||
{
|
||||
if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType == dbpk.CsType ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType == dbpk.CsType)
|
||||
if (trytb.Columns.TryGetValue(dbpk.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbpk.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbpk.CsType.NullableTypeOrThis())
|
||||
trycol.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var dbuk in dbtb.UniquesDict)
|
||||
foreach (var dbidx in dbtb.IndexesDict)
|
||||
{
|
||||
foreach (var dbcol in dbuk.Value)
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var dbcol in dbidx.Value.Columns)
|
||||
{
|
||||
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)
|
||||
if (trycol.Attribute._Uniques?.Contains(dbuk.Key) != true)
|
||||
trycol.Attribute.Unique += $"," + dbuk.Key;
|
||||
if (trytb.Columns.TryGetValue(dbcol.Column.Name, out var trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis() ||
|
||||
trytb.ColumnsByCs.TryGetValue(dbcol.Column.Name, out trycol) && trycol.Attribute.MapType.NullableTypeOrThis() == dbcol.Column.CsType.NullableTypeOrThis())
|
||||
indexColumns.Add(new IndexColumnInfo
|
||||
{
|
||||
Column = trycol,
|
||||
IsDesc = dbcol.IsDesc
|
||||
});
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
if (indexesDict.ContainsKey(dbidx.Key)) indexesDict.Remove(dbidx.Key);
|
||||
indexesDict.Add(dbidx.Key, new IndexInfo
|
||||
{
|
||||
Name = dbidx.Key,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = dbidx.Value.IsUnique
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
|
||||
}
|
||||
var allunique = trytb.Columns.Values.Where(a => a.Attribute._Uniques != null).SelectMany(a => a.Attribute._Uniques).Distinct();
|
||||
trytb.Uniques = allunique.ToDictionary(a => a, a => trytb.Columns.Values.Where(b => b.Attribute._Uniques != null && b.Attribute._Uniques.Contains(a)).ToList());
|
||||
//索引和唯一键
|
||||
var indexes = common.GetEntityIndexAttribute(trytb.Type);
|
||||
foreach (var index in indexes)
|
||||
{
|
||||
var val = index.Fields?.Trim(' ', '\t', ',');
|
||||
if (string.IsNullOrEmpty(val)) continue;
|
||||
var arr = val.Split(',').Select(a => a.Trim(' ', '\t').Trim()).Where(a => !string.IsNullOrEmpty(a)).ToArray();
|
||||
if (arr.Any() == false) continue;
|
||||
var indexColumns = new List<IndexColumnInfo>();
|
||||
foreach (var field in arr)
|
||||
{
|
||||
var idxcol = new IndexColumnInfo();
|
||||
if (field.EndsWith(" DESC", StringComparison.CurrentCultureIgnoreCase)) idxcol.IsDesc = true;
|
||||
var colname = Regex.Replace(field, " (DESC|ASC)", "", RegexOptions.IgnoreCase);
|
||||
if (trytb.ColumnsByCs.TryGetValue(colname, out var trycol) || trytb.Columns.TryGetValue(colname, out trycol))
|
||||
{
|
||||
idxcol.Column = trycol;
|
||||
indexColumns.Add(idxcol);
|
||||
}
|
||||
}
|
||||
if (indexColumns.Any() == false) continue;
|
||||
var indexName = common.CodeFirst.IsSyncStructureToLower ? index.Name.ToLower() : (common.CodeFirst.IsSyncStructureToUpper ? index.Name.ToUpper() : index.Name);
|
||||
if (indexesDict.ContainsKey(indexName)) indexesDict.Remove(indexName);
|
||||
indexesDict.Add(indexName, new IndexInfo
|
||||
{
|
||||
Name = indexName,
|
||||
Columns = indexColumns.ToArray(),
|
||||
IsUnique = index.IsUnique
|
||||
});
|
||||
}
|
||||
trytb.Indexes = indexesDict.Values.ToArray();
|
||||
trytb.ColumnsByPosition = columnsList.Where(a => a.Attribute.Position > 0).OrderBy(a => a.Attribute.Position)
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position == 0))
|
||||
.Concat(columnsList.Where(a => a.Attribute.Position < 0).OrderBy(a => a.Attribute.Position)).ToArray();
|
||||
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => a.Attribute.IsPrimary == true).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, "id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
var identcol = trytb.Columns.Values.Where(a => a.Attribute.IsIdentity == true).FirstOrDefault();
|
||||
if (identcol != null) trytb.Primarys = new[] { identcol };
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}id", true) == 0).ToArray();
|
||||
if (trytb.Primarys.Any() == false)
|
||||
{
|
||||
trytb.Primarys = trytb.Columns.Values.Where(a => string.Compare(a.Attribute.Name, $"{trytb.DbName}_id", true) == 0).ToArray();
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach (var col in trytb.Primarys)
|
||||
col.Attribute.IsPrimary = true;
|
||||
}
|
||||
foreach (var col in trytb.Primarys) col.Attribute.IsNullable = false;
|
||||
tbc.AddOrUpdate(entity, trytb, (oldkey, oldval) => trytb);
|
||||
|
||||
#region 查找导航属性的关系、virtual 属性延时加载,动态产生新的重写类
|
||||
|
@ -131,7 +131,8 @@ namespace FreeSql.MySql
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ");
|
||||
@ -146,14 +147,22 @@ namespace FreeSql.MySql
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) Engine=InnoDB;\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
//如果新表,旧表在一个数据库下,直接修改表名
|
||||
@ -235,19 +244,28 @@ where a.table_schema in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
a.column_name,
|
||||
a.constraint_name 'index_id'
|
||||
from information_schema.key_column_usage a
|
||||
where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
a.index_name 'index_id',
|
||||
0 'IsDesc',
|
||||
case when a.non_unique = 0 then 1 else 0 end 'IsUnique'
|
||||
from information_schema.statistics a
|
||||
where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRIMARY'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (uk.Key == "PRIMARY" || string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
@ -277,12 +295,6 @@ where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbna
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) Engine=InnoDB;\r\n");
|
||||
sb.Append("INSERT INTO ").Append(tmptablename).Append(" (");
|
||||
@ -310,6 +322,20 @@ where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbna
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
}
|
||||
|
@ -252,21 +252,21 @@ where a.table_schema in ({1}) and a.table_name in ({0})
|
||||
|
||||
sql = string.Format(@"
|
||||
select
|
||||
concat(a.constraint_schema, '.', a.table_name) 'table_id',
|
||||
concat(a.table_schema, '.', a.table_name) 'table_id',
|
||||
a.column_name,
|
||||
a.constraint_name 'index_id',
|
||||
1 'IsUnique',
|
||||
case when a.constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
|
||||
a.index_name 'index_id',
|
||||
case when a.non_unique = 0 then 1 else 0 end 'IsUnique',
|
||||
case when a.index_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
|
||||
0 'IsClustered',
|
||||
0 'IsDesc'
|
||||
from information_schema.key_column_usage a
|
||||
where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position_in_unique_constraint)
|
||||
from information_schema.statistics a
|
||||
where a.table_schema in ({1}) and a.table_name in ({0}) and a.index_name <> 'PRIMARY'
|
||||
", loc8, databaseIn);
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (var row in ds)
|
||||
{
|
||||
string table_id = string.Concat(row[0]);
|
||||
@ -275,29 +275,27 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position
|
||||
bool is_unique = string.Concat(row[3]) == "1";
|
||||
bool is_primary_key = string.Concat(row[4]) == "1";
|
||||
bool is_clustered = string.Concat(row[5]) == "1";
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
if (database.Length == 1)
|
||||
{
|
||||
table_id = table_id.Substring(table_id.IndexOf('.') + 1);
|
||||
}
|
||||
if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue;
|
||||
var loc9 = loc3[table_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(table_id, out loc10))
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(table_id, out loc10))
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (string table_id in indexColumns.Keys)
|
||||
@ -309,7 +307,7 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position
|
||||
{
|
||||
foreach (var column in uniqueColumns[table_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -372,14 +370,14 @@ 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.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -119,7 +119,8 @@ namespace FreeSql.Odbc.MySql
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ");
|
||||
@ -134,14 +135,22 @@ namespace FreeSql.Odbc.MySql
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) Engine=InnoDB;\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
//如果新表,旧表在一个数据库下,直接修改表名
|
||||
@ -223,19 +232,28 @@ where a.table_schema in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
a.column_name,
|
||||
a.constraint_name 'index_id'
|
||||
from information_schema.key_column_usage a
|
||||
where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
a.index_name 'index_id',
|
||||
0 'IsDesc',
|
||||
case when a.non_unique = 0 then 1 else 0 end 'IsUnique'
|
||||
from information_schema.statistics a
|
||||
where a.table_schema IN ({0}) and a.table_name IN ({1}) and a.index_name <> 'PRIMARY'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (uk.Key == "PRIMARY" || string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
@ -265,12 +283,6 @@ where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbna
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n UNIQUE KEY ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) Engine=InnoDB;\r\n");
|
||||
sb.Append("INSERT INTO ").Append(tmptablename).Append(" (");
|
||||
@ -298,6 +310,20 @@ where a.constraint_schema IN ({0}) and a.table_name IN ({1})", tboldname ?? tbna
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(";\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
}
|
||||
|
@ -222,21 +222,21 @@ where a.table_schema in ({1}) and a.table_name in ({0})
|
||||
|
||||
sql = string.Format(@"
|
||||
select
|
||||
concat(a.constraint_schema, '.', a.table_name) 'table_id',
|
||||
concat(a.table_schema, '.', a.table_name) 'table_id',
|
||||
a.column_name,
|
||||
a.constraint_name 'index_id',
|
||||
1 'IsUnique',
|
||||
case when a.constraint_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
|
||||
a.index_name 'index_id',
|
||||
case when a.non_unique = 0 then 1 else 0 end 'IsUnique',
|
||||
case when a.index_name = 'PRIMARY' then 1 else 0 end 'IsPrimaryKey',
|
||||
0 'IsClustered',
|
||||
0 'IsDesc'
|
||||
from information_schema.key_column_usage a
|
||||
where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position_in_unique_constraint)
|
||||
from information_schema.statistics a
|
||||
where a.table_schema in ({1}) and a.table_name in ({0}) and a.index_name <> 'PRIMARY'
|
||||
", loc8, databaseIn);
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (var row in ds)
|
||||
{
|
||||
string table_id = string.Concat(row[0]);
|
||||
@ -245,29 +245,27 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position
|
||||
bool is_unique = string.Concat(row[3]) == "1";
|
||||
bool is_primary_key = string.Concat(row[4]) == "1";
|
||||
bool is_clustered = string.Concat(row[5]) == "1";
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
if (database.Length == 1)
|
||||
{
|
||||
table_id = table_id.Substring(table_id.IndexOf('.') + 1);
|
||||
}
|
||||
if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue;
|
||||
var loc9 = loc3[table_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(table_id, out loc10))
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(table_id, out loc10))
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (string table_id in indexColumns.Keys)
|
||||
@ -279,7 +277,7 @@ where a.constraint_schema in ({1}) and a.table_name in ({0}) and isnull(position
|
||||
{
|
||||
foreach (var column in uniqueColumns[table_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -342,14 +340,14 @@ 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.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -108,7 +108,8 @@ namespace FreeSql.Odbc.Oracle
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("execute immediate 'CREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("execute immediate 'CREATE TABLE ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(",");
|
||||
@ -121,14 +122,22 @@ namespace FreeSql.Odbc.Oracle
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE (");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) \r\nLOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -222,29 +231,39 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname);
|
||||
if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true));
|
||||
if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n");
|
||||
}
|
||||
|
||||
CreateOracleFunction(_orm);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
c.column_name,
|
||||
c.constraint_name
|
||||
from
|
||||
all_constraints a,
|
||||
all_cons_columns c
|
||||
where
|
||||
a.constraint_name = c.constraint_name
|
||||
and a.owner = c.owner
|
||||
nvl(freesql_long_2_varchar(a.index_name, c.table_name, c.column_position), c.column_name),
|
||||
a.index_name,
|
||||
case when c.descend = 'DESC' then 1 else 0 end,
|
||||
case when a.uniqueness = 'UNIQUE' then 1 else 0 end,
|
||||
c.column_position
|
||||
from all_indexes a,
|
||||
all_ind_columns c
|
||||
where a.index_name = c.index_name
|
||||
and a.table_owner = c.table_owner
|
||||
and a.table_name = c.table_name
|
||||
and a.constraint_type in ('U')
|
||||
and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
and a.owner in ({0}) and a.table_name in ({1})
|
||||
and not exists(select 1 from all_constraints where constraint_name = a.index_name and constraint_type = 'P')", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]).Trim('"'), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) }).ToArray();
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => uk.Columns.Where(b => (a[3] == "1") == uk.IsUnique && string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("';\r\n");
|
||||
sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("execute immediate 'DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append("';\r\n");
|
||||
sbalter.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
}
|
||||
@ -275,12 +294,6 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE (");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) LOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n");
|
||||
//备注
|
||||
@ -315,6 +328,20 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n");
|
||||
sb.Append("execute immediate 'DROP TABLE ").Append(tablename).Append("';\r\n");
|
||||
sb.Append("execute immediate 'ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
}
|
||||
Dictionary<string, bool> dicDeclare = new Dictionary<string, bool>();
|
||||
Action<string> dropSequence = seqname =>
|
||||
@ -407,5 +434,27 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
sqlType += $"({data_length})";
|
||||
return sqlType;
|
||||
}
|
||||
|
||||
internal static void CreateOracleFunction(IFreeSql fsql)
|
||||
{
|
||||
fsql.Ado.ExecuteNonQuery(CommandType.Text, @"
|
||||
CREATE OR REPLACE FUNCTION freesql_long_2_varchar (
|
||||
p_index_name IN user_ind_expressions.index_name%TYPE,
|
||||
p_table_name IN user_ind_expressions.table_name%TYPE,
|
||||
p_COLUMN_POSITION IN user_ind_expressions.table_name%TYPE)
|
||||
RETURN VARCHAR2
|
||||
AS
|
||||
l_COLUMN_EXPRESSION LONG;
|
||||
BEGIN
|
||||
SELECT COLUMN_EXPRESSION
|
||||
INTO l_COLUMN_EXPRESSION
|
||||
FROM user_ind_expressions
|
||||
WHERE index_name = p_index_name
|
||||
AND table_name = p_table_name
|
||||
AND COLUMN_POSITION = p_COLUMN_POSITION;
|
||||
|
||||
RETURN SUBSTR (l_COLUMN_EXPRESSION, 1, 4000);
|
||||
END;");
|
||||
}
|
||||
}
|
||||
}
|
@ -287,61 +287,59 @@ where a.owner in ({1}) and a.table_name in ({0})
|
||||
loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]);
|
||||
}
|
||||
|
||||
OdbcOracleCodeFirst.CreateOracleFunction(_orm);
|
||||
sql = string.Format(@"
|
||||
select
|
||||
a.owner || '.' || a.table_name,
|
||||
c.column_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,
|
||||
a.table_owner || '.' || a.table_name,
|
||||
nvl(freesql_long_2_varchar(a.index_name, c.table_name, c.column_position), c.column_name),
|
||||
c.index_name,
|
||||
case when a.uniqueness = 'UNIQUE' then 1 else 0 end,
|
||||
0,
|
||||
0
|
||||
from
|
||||
all_constraints a,
|
||||
all_cons_columns c
|
||||
where
|
||||
a.constraint_name = c.constraint_name
|
||||
and a.owner = c.owner
|
||||
0,
|
||||
case when c.descend = 'DESC' then 1 else 0 end,
|
||||
c.column_position
|
||||
from all_indexes a,
|
||||
all_ind_columns c
|
||||
where a.index_name = c.index_name
|
||||
and a.table_owner = c.table_owner
|
||||
and a.table_name = c.table_name
|
||||
and a.constraint_type in ('P', 'U')
|
||||
and a.owner in ({1}) and a.table_name in ({0})
|
||||
and a.table_owner in ({1}) and a.table_name in ({0})
|
||||
and not exists(select 1 from all_constraints where constraint_name = a.index_name and constraint_type = 'P')
|
||||
", loc8, databaseIn);
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (var row in ds)
|
||||
{
|
||||
string table_id = string.Concat(row[0]);
|
||||
string column = string.Concat(row[1]);
|
||||
string column = string.Concat(row[1]).Trim('"');
|
||||
string index_id = string.Concat(row[2]);
|
||||
bool is_unique = string.Concat(row[3]) == "1";
|
||||
bool is_primary_key = string.Concat(row[4]) == "1";
|
||||
bool is_clustered = string.Concat(row[5]) == "1";
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
if (database.Length == 1)
|
||||
{
|
||||
table_id = table_id.Substring(table_id.IndexOf('.') + 1);
|
||||
}
|
||||
if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue;
|
||||
var loc9 = loc3[table_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(table_id, out loc10))
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(table_id, out loc10))
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (string table_id in indexColumns.Keys)
|
||||
@ -353,7 +351,7 @@ and a.owner in ({1}) and a.table_name in ({0})
|
||||
{
|
||||
foreach (var column in uniqueColumns[table_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -441,14 +439,14 @@ and a.owner in ({1}) and a.table_name in ({0})
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -108,7 +108,8 @@ namespace FreeSql.Odbc.PostgreSQL
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(",");
|
||||
@ -120,14 +121,22 @@ namespace FreeSql.Odbc.PostgreSQL
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) WITH (OIDS=FALSE);\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -233,23 +242,32 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
c.attname,
|
||||
b.relname
|
||||
b.relname,
|
||||
case when pg_index_column_has_property(b.oid, c.attnum, 'desc') = 't' then 1 else 0 end IsDesc,
|
||||
case when indisunique = 't' then 1 else 0 end IsUnique
|
||||
from pg_index a
|
||||
inner join pg_class b on b.oid = a.indexrelid
|
||||
inner join pg_attribute c on c.attnum > 0 and c.attrelid = b.oid
|
||||
inner join pg_namespace ns on ns.oid = b.relnamespace
|
||||
inner join pg_class d on d.oid = a.indrelid
|
||||
where ns.nspname in ({0}) and d.relname in ({1}) and a.indisunique = 't'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
where ns.nspname in ({0}) and d.relname in ({1}) and a.indisprimary = 'f'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => uk.Columns.Where(b => (a[3] == "1") == uk.IsUnique && string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
@ -283,12 +301,6 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) WITH (OIDS=FALSE);\r\n");
|
||||
//备注
|
||||
@ -320,6 +332,20 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName(tbname[1])).Append(";\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
foreach (var seqcol in seqcols)
|
||||
{
|
||||
|
@ -251,7 +251,7 @@ b.relname as index_id,
|
||||
case when a.indisunique then 1 else 0 end IsUnique,
|
||||
case when a.indisprimary then 1 else 0 end IsPrimary,
|
||||
case when a.indisclustered then 0 else 1 end IsClustered,
|
||||
0 IsDesc,
|
||||
case when pg_index_column_has_property(b.oid, c.attnum, 'desc') = 't' then 1 else 0 end IsDesc,
|
||||
a.indkey::text,
|
||||
c.attnum
|
||||
from pg_index a
|
||||
@ -259,13 +259,13 @@ inner join pg_class b on b.oid = a.indexrelid
|
||||
inner join pg_attribute c on c.attnum > 0 and c.attrelid = b.oid
|
||||
inner join pg_namespace ns on ns.oid = b.relnamespace
|
||||
inner join pg_class d on d.oid = a.indrelid
|
||||
where ns.nspname || '.' || d.relname in ({loc8})
|
||||
where ns.nspname || '.' || d.relname in ({loc8}) and a.indisprimary = 'f'
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (object[] row in ds)
|
||||
{
|
||||
var object_id = string.Concat(row[0]);
|
||||
@ -274,7 +274,7 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
var is_unique = string.Concat(row[3]) == "1";
|
||||
var is_primary_key = string.Concat(row[4]) == "1";
|
||||
var is_clustered = string.Concat(row[5]) == "1";
|
||||
var is_desc = int.Parse(string.Concat(row[6]));
|
||||
var is_desc = string.Concat(row[6]) == "1";
|
||||
var inkey = string.Concat(row[7]).Split(' ');
|
||||
var attnum = int.Parse(string.Concat(row[8]));
|
||||
attnum = int.Parse(inkey[attnum - 1]);
|
||||
@ -290,20 +290,20 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
var loc9 = loc3[object_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(object_id, out loc10))
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(object_id, out loc10))
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (var object_id in indexColumns.Keys)
|
||||
@ -315,7 +315,7 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
{
|
||||
foreach (var column in uniqueColumns[object_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[object_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -382,14 +382,14 @@ where ns.nspname || '.' || b.relname in ({loc8})
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -156,8 +156,9 @@ ELSE
|
||||
}
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建新表
|
||||
sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(" ( ");
|
||||
//创建表
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}");
|
||||
sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(createTableName).Append(" ( ");
|
||||
var pkidx = 0;
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -177,13 +178,21 @@ ELSE
|
||||
}
|
||||
sb.Append(",");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -275,30 +284,39 @@ use " + database, tboldname ?? tbname);
|
||||
use [{0}];
|
||||
select
|
||||
c.name
|
||||
,d.name
|
||||
,b.name
|
||||
,case when a.is_descending_key = 1 then 1 else 0 end
|
||||
,case when b.is_unique = 1 then 1 else 0 end
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_unique = 1;
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_primary_key = 0;
|
||||
use " + database, tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (istmpatler == false)
|
||||
{
|
||||
sb.Append(sbalter).Append("\r\nuse " + database);
|
||||
if (sbalter.Length > 0)
|
||||
sb.Append(sbalter).Append("\r\nuse " + database);
|
||||
continue;
|
||||
}
|
||||
//创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名
|
||||
@ -337,12 +355,6 @@ use " + database, tboldname ?? tbname);
|
||||
sb.Append(",");
|
||||
idents = idents || tbcol.Attribute.IsIdentity == true;
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
@ -377,6 +389,20 @@ use " + database, tboldname ?? tbname);
|
||||
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
sb.Append("COMMIT;\r\n");
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
|
@ -267,24 +267,23 @@ use [{db}];
|
||||
select
|
||||
a.object_id 'Object_id'
|
||||
,c.name 'Column'
|
||||
,d.name 'Index_id'
|
||||
,b.name 'Index_id'
|
||||
,b.is_unique 'IsUnique'
|
||||
,b.is_primary_key 'IsPrimaryKey'
|
||||
,cast(case when b.type_desc = 'CLUSTERED' then 1 else 0 end as bit) 'IsClustered'
|
||||
,case when a.is_descending_key = 1 then 2 when a.is_descending_key = 0 then 1 else 0 end 'IsDesc'
|
||||
,case when a.is_descending_key = 1 then 1 else 0 end 'IsDesc'
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in ({loc8})
|
||||
where a.object_id in ({loc8}) and b.is_primary_key = 0
|
||||
;
|
||||
use [{olddatabase}];
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<int, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<int, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (object[] row in ds)
|
||||
{
|
||||
int object_id = int.Parse(string.Concat(row[0]));
|
||||
@ -293,26 +292,26 @@ use [{olddatabase}];
|
||||
bool is_unique = bool.Parse(string.Concat(row[3]));
|
||||
bool is_primary_key = bool.Parse(string.Concat(row[4]));
|
||||
bool is_clustered = bool.Parse(string.Concat(row[5]));
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
|
||||
if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue;
|
||||
DbColumnInfo loc9 = loc3[object_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(object_id, out loc10))
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(object_id, out loc10))
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (var object_id in indexColumns.Keys)
|
||||
@ -324,7 +323,7 @@ use [{olddatabase}];
|
||||
{
|
||||
foreach (var column in uniqueColumns[object_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[object_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -402,14 +401,14 @@ use [{olddatabase}];
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -109,7 +109,8 @@ namespace FreeSql.Oracle
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("execute immediate 'CREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("execute immediate 'CREATE TABLE ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(",");
|
||||
@ -122,14 +123,22 @@ namespace FreeSql.Oracle
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE (");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) \r\nLOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -223,29 +232,38 @@ where a.owner={{0}} and a.table_name={{1}}", tboldname ?? tbname);
|
||||
if (tbcol.Attribute.IsIdentity == true) seqcols.Add((tbcol, tbname, tbcol.Attribute.IsIdentity == true));
|
||||
if (string.IsNullOrEmpty(tbcol.Comment) == false) sbalter.Append("execute immediate 'COMMENT ON COLUMN ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbcol.Attribute.Name}")).Append(" IS ").Append(_commonUtils.FormatSql("{0}", tbcol.Comment ?? "").Replace("'", "''")).Append("';\r\n");
|
||||
}
|
||||
|
||||
CreateOracleFunction(_orm);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
c.column_name,
|
||||
c.constraint_name
|
||||
from
|
||||
all_constraints a,
|
||||
all_cons_columns c
|
||||
where
|
||||
a.constraint_name = c.constraint_name
|
||||
and a.owner = c.owner
|
||||
nvl(freesql_long_2_varchar(a.index_name, c.table_name, c.column_position), c.column_name),
|
||||
a.index_name,
|
||||
case when c.descend = 'DESC' then 1 else 0 end,
|
||||
case when a.uniqueness = 'UNIQUE' then 1 else 0 end
|
||||
from all_indexes a,
|
||||
all_ind_columns c
|
||||
where a.index_name = c.index_name
|
||||
and a.table_owner = c.table_owner
|
||||
and a.table_name = c.table_name
|
||||
and a.constraint_type in ('U')
|
||||
and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
and a.owner in ({0}) and a.table_name in ({1})
|
||||
and not exists(select 1 from all_constraints where constraint_name = a.index_name and constraint_type = 'P')", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]).Trim('"'), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) }).ToArray();
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => uk.Columns.Where(b => (a[3] == "1") == uk.IsUnique && string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append("';\r\n");
|
||||
sbalter.Append("execute immediate 'ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("execute immediate 'DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append("';\r\n");
|
||||
sbalter.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
}
|
||||
@ -276,12 +294,6 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE (");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) LOGGING \r\nNOCOMPRESS \r\nNOCACHE\r\n';\r\n");
|
||||
//备注
|
||||
@ -316,6 +328,20 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append("';\r\n");
|
||||
sb.Append("execute immediate 'DROP TABLE ").Append(tablename).Append("';\r\n");
|
||||
sb.Append("execute immediate 'ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append("';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("execute immediate 'CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(")';\r\n");
|
||||
}
|
||||
}
|
||||
Dictionary<string, bool> dicDeclare = new Dictionary<string, bool>();
|
||||
Action<string> dropSequence = seqname =>
|
||||
@ -408,5 +434,26 @@ and a.owner in ({0}) and a.table_name in ({1})", tboldname ?? tbname);
|
||||
sqlType += $"({data_length})";
|
||||
return sqlType;
|
||||
}
|
||||
internal static void CreateOracleFunction(IFreeSql fsql)
|
||||
{
|
||||
fsql.Ado.ExecuteNonQuery(CommandType.Text, @"
|
||||
CREATE OR REPLACE FUNCTION freesql_long_2_varchar (
|
||||
p_index_name IN user_ind_expressions.index_name%TYPE,
|
||||
p_table_name IN user_ind_expressions.table_name%TYPE,
|
||||
p_COLUMN_POSITION IN user_ind_expressions.table_name%TYPE)
|
||||
RETURN VARCHAR2
|
||||
AS
|
||||
l_COLUMN_EXPRESSION LONG;
|
||||
BEGIN
|
||||
SELECT COLUMN_EXPRESSION
|
||||
INTO l_COLUMN_EXPRESSION
|
||||
FROM user_ind_expressions
|
||||
WHERE index_name = p_index_name
|
||||
AND table_name = p_table_name
|
||||
AND COLUMN_POSITION = p_COLUMN_POSITION;
|
||||
|
||||
RETURN SUBSTR (l_COLUMN_EXPRESSION, 1, 4000);
|
||||
END;");
|
||||
}
|
||||
}
|
||||
}
|
@ -287,61 +287,59 @@ where a.owner in ({1}) and a.table_name in ({0})
|
||||
loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]);
|
||||
}
|
||||
|
||||
OracleCodeFirst.CreateOracleFunction(_orm);
|
||||
sql = string.Format(@"
|
||||
select
|
||||
a.owner || '.' || a.table_name,
|
||||
c.column_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,
|
||||
a.table_owner || '.' || a.table_name,
|
||||
nvl(freesql_long_2_varchar(a.index_name, c.table_name, c.column_position), c.column_name),
|
||||
c.index_name,
|
||||
case when a.uniqueness = 'UNIQUE' then 1 else 0 end,
|
||||
0,
|
||||
0
|
||||
from
|
||||
all_constraints a,
|
||||
all_cons_columns c
|
||||
where
|
||||
a.constraint_name = c.constraint_name
|
||||
and a.owner = c.owner
|
||||
0,
|
||||
case when c.descend = 'DESC' then 1 else 0 end,
|
||||
c.column_position
|
||||
from all_indexes a,
|
||||
all_ind_columns c
|
||||
where a.index_name = c.index_name
|
||||
and a.table_owner = c.table_owner
|
||||
and a.table_name = c.table_name
|
||||
and a.constraint_type in ('P', 'U')
|
||||
and a.owner in ({1}) and a.table_name in ({0})
|
||||
and a.table_owner in ({1}) and a.table_name in ({0})
|
||||
and not exists(select 1 from all_constraints where constraint_name = a.index_name and constraint_type = 'P')
|
||||
", loc8, databaseIn);
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (var row in ds)
|
||||
{
|
||||
string table_id = string.Concat(row[0]);
|
||||
string column = string.Concat(row[1]);
|
||||
string column = string.Concat(row[1]).Trim('"');
|
||||
string index_id = string.Concat(row[2]);
|
||||
bool is_unique = string.Concat(row[3]) == "1";
|
||||
bool is_primary_key = string.Concat(row[4]) == "1";
|
||||
bool is_clustered = string.Concat(row[5]) == "1";
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
if (database.Length == 1)
|
||||
{
|
||||
table_id = table_id.Substring(table_id.IndexOf('.') + 1);
|
||||
}
|
||||
if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue;
|
||||
var loc9 = loc3[table_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(table_id, out loc10))
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(table_id, out loc10))
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (string table_id in indexColumns.Keys)
|
||||
@ -353,7 +351,7 @@ and a.owner in ({1}) and a.table_name in ({0})
|
||||
{
|
||||
foreach (var column in uniqueColumns[table_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[table_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -441,14 +439,14 @@ and a.owner in ({1}) and a.table_name in ({0})
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -150,7 +150,8 @@ namespace FreeSql.PostgreSQL
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ").Append(tbcol.Attribute.DbType).Append(",");
|
||||
@ -162,14 +163,22 @@ namespace FreeSql.PostgreSQL
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) WITH (OIDS=FALSE);\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -275,23 +284,32 @@ where ns.nspname = {0} and c.relname = {1}", tboldname ?? tbname);
|
||||
var dsuksql = _commonUtils.FormatSql(@"
|
||||
select
|
||||
c.attname,
|
||||
b.relname
|
||||
b.relname,
|
||||
case when pg_index_column_has_property(b.oid, c.attnum, 'desc') = 't' then 1 else 0 end IsDesc,
|
||||
case when indisunique = 't' then 1 else 0 end IsUnique
|
||||
from pg_index a
|
||||
inner join pg_class b on b.oid = a.indexrelid
|
||||
inner join pg_attribute c on c.attnum > 0 and c.attrelid = b.oid
|
||||
inner join pg_namespace ns on ns.oid = b.relnamespace
|
||||
inner join pg_class d on d.oid = a.indrelid
|
||||
where ns.nspname in ({0}) and d.relname in ({1}) and a.indisunique = 't'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
where ns.nspname in ({0}) and d.relname in ({1}) and a.indisprimary = 'f'", tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => uk.Columns.Where(b => (a[3] == "1") == uk.IsUnique && string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
@ -325,12 +343,6 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) WITH (OIDS=FALSE);\r\n");
|
||||
//备注
|
||||
@ -362,6 +374,20 @@ where pg_namespace.nspname={0} and pg_class.relname={1} and pg_constraint.contyp
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName(tbname[1])).Append(";\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
foreach (var seqcol in seqcols)
|
||||
{
|
||||
|
@ -362,7 +362,7 @@ b.relname as index_id,
|
||||
case when a.indisunique then 1 else 0 end IsUnique,
|
||||
case when a.indisprimary then 1 else 0 end IsPrimary,
|
||||
case when a.indisclustered then 0 else 1 end IsClustered,
|
||||
0 IsDesc,
|
||||
case when pg_index_column_has_property(b.oid, c.attnum, 'desc') = 't' then 1 else 0 end IsDesc,
|
||||
a.indkey::text,
|
||||
c.attnum
|
||||
from pg_index a
|
||||
@ -370,13 +370,13 @@ inner join pg_class b on b.oid = a.indexrelid
|
||||
inner join pg_attribute c on c.attnum > 0 and c.attrelid = b.oid
|
||||
inner join pg_namespace ns on ns.oid = b.relnamespace
|
||||
inner join pg_class d on d.oid = a.indrelid
|
||||
where ns.nspname || '.' || d.relname in ({loc8})
|
||||
where ns.nspname || '.' || d.relname in ({loc8}) and a.indisprimary = 'f'
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (object[] row in ds)
|
||||
{
|
||||
var object_id = string.Concat(row[0]);
|
||||
@ -385,7 +385,7 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
var is_unique = string.Concat(row[3]) == "1";
|
||||
var is_primary_key = string.Concat(row[4]) == "1";
|
||||
var is_clustered = string.Concat(row[5]) == "1";
|
||||
var is_desc = int.Parse(string.Concat(row[6]));
|
||||
var is_desc = string.Concat(row[6]) == "1";
|
||||
var inkey = string.Concat(row[7]).Split(' ');
|
||||
var attnum = int.Parse(string.Concat(row[8]));
|
||||
attnum = int.Parse(inkey[attnum - 1]);
|
||||
@ -401,20 +401,20 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
var loc9 = loc3[object_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(object_id, out loc10))
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(object_id, out loc10))
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (var object_id in indexColumns.Keys)
|
||||
@ -426,7 +426,7 @@ where ns.nspname || '.' || d.relname in ({loc8})
|
||||
{
|
||||
foreach (var column in uniqueColumns[object_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[object_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -493,14 +493,14 @@ where ns.nspname || '.' || b.relname in ({loc8})
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -159,8 +159,9 @@ ELSE
|
||||
}
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建新表
|
||||
sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(" ( ");
|
||||
//创建表
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}");
|
||||
sb.Append("use ").Append(_commonUtils.QuoteSqlName(tbname[0])).Append(";\r\nCREATE TABLE ").Append(createTableName).Append(" ( ");
|
||||
var pkidx = 0;
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -180,13 +181,21 @@ ELSE
|
||||
}
|
||||
sb.Append(",");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(createTableName).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
@ -278,30 +287,39 @@ use " + database, tboldname ?? tbname);
|
||||
use [{0}];
|
||||
select
|
||||
c.name
|
||||
,d.name
|
||||
,b.name
|
||||
,case when a.is_descending_key = 1 then 1 else 0 end
|
||||
,case when b.is_unique = 1 then 1 else 0 end
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_unique = 1;
|
||||
where a.object_id in (object_id(N'[{1}].[{2}]')) and b.is_primary_key = 0;
|
||||
use " + database, tboldname ?? tbname);
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]) });
|
||||
foreach (var uk in tb.Uniques)
|
||||
var dsuk = _orm.Ado.ExecuteArray(CommandType.Text, dsuksql).Select(a => new[] { string.Concat(a[0]), string.Concat(a[1]), string.Concat(a[2]), string.Concat(a[3]) });
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
{
|
||||
if (dsukfind1.Any()) sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" DROP CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(";\r\n");
|
||||
sbalter.Append("ALTER TABLE ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}.{tbname[2]}")).Append(" ADD CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
if (dsukfind1.Any()) sbalter.Append("DROP INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append(";\r\n");
|
||||
sbalter.Append("CREATE ");
|
||||
if (uk.IsUnique) sbalter.Append("UNIQUE ");
|
||||
sbalter.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}.{tbname[2]}")).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sbalter.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sbalter.Append(" DESC");
|
||||
sbalter.Append(", ");
|
||||
}
|
||||
sbalter.Remove(sbalter.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
if (istmpatler == false)
|
||||
{
|
||||
sb.Append(sbalter).Append("\r\nuse " + database);
|
||||
if (sbalter.Length > 0)
|
||||
sb.Append(sbalter).Append("\r\nuse " + database);
|
||||
continue;
|
||||
}
|
||||
//创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名
|
||||
@ -340,12 +358,6 @@ use " + database, tboldname ?? tbname);
|
||||
sb.Append(",");
|
||||
idents = idents || tbcol.Attribute.IsIdentity == true;
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1).Append("\r\n);\r\n");
|
||||
//备注
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
@ -380,6 +392,20 @@ use " + database, tboldname ?? tbname);
|
||||
if (idents) sb.Append("SET IDENTITY_INSERT ").Append(tmptablename).Append(" OFF;\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("EXECUTE sp_rename N'").Append(tmptablename).Append("', N'").Append(tbname[2]).Append("', 'OBJECT';\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablename).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
sb.Append("COMMIT;\r\n");
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
|
@ -270,24 +270,23 @@ use [{db}];
|
||||
select
|
||||
a.object_id 'Object_id'
|
||||
,c.name 'Column'
|
||||
,d.name 'Index_id'
|
||||
,b.name 'Index_id'
|
||||
,b.is_unique 'IsUnique'
|
||||
,b.is_primary_key 'IsPrimaryKey'
|
||||
,cast(case when b.type_desc = 'CLUSTERED' then 1 else 0 end as bit) 'IsClustered'
|
||||
,case when a.is_descending_key = 1 then 2 when a.is_descending_key = 0 then 1 else 0 end 'IsDesc'
|
||||
,case when a.is_descending_key = 1 then 1 else 0 end 'IsDesc'
|
||||
from sys.index_columns a
|
||||
inner join sys.indexes b on b.object_id = a.object_id and b.index_id = a.index_id
|
||||
left join sys.columns c on c.object_id = a.object_id and c.column_id = a.column_id
|
||||
left join sys.key_constraints d on d.parent_object_id = b.object_id and d.unique_index_id = b.index_id
|
||||
where a.object_id in ({loc8})
|
||||
where a.object_id in ({loc8}) and b.is_primary_key = 0
|
||||
;
|
||||
use [{olddatabase}];
|
||||
";
|
||||
ds = _orm.Ado.ExecuteArray(CommandType.Text, sql);
|
||||
if (ds == null) return loc1;
|
||||
|
||||
var indexColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var uniqueColumns = new Dictionary<int, Dictionary<string, List<DbColumnInfo>>>();
|
||||
var indexColumns = new Dictionary<int, Dictionary<string, DbIndexInfo>>();
|
||||
var uniqueColumns = new Dictionary<int, Dictionary<string, DbIndexInfo>>();
|
||||
foreach (object[] row in ds)
|
||||
{
|
||||
int object_id = int.Parse(string.Concat(row[0]));
|
||||
@ -296,26 +295,26 @@ use [{olddatabase}];
|
||||
bool is_unique = bool.Parse(string.Concat(row[3]));
|
||||
bool is_primary_key = bool.Parse(string.Concat(row[4]));
|
||||
bool is_clustered = bool.Parse(string.Concat(row[5]));
|
||||
int is_desc = int.Parse(string.Concat(row[6]));
|
||||
bool is_desc = string.Concat(row[6]) == "1";
|
||||
|
||||
if (loc3.ContainsKey(object_id) == false || loc3[object_id].ContainsKey(column) == false) continue;
|
||||
DbColumnInfo loc9 = loc3[object_id][column];
|
||||
if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key;
|
||||
|
||||
Dictionary<string, List<DbColumnInfo>> loc10 = null;
|
||||
List<DbColumnInfo> loc11 = null;
|
||||
Dictionary<string, DbIndexInfo> loc10 = null;
|
||||
DbIndexInfo loc11 = null;
|
||||
if (!indexColumns.TryGetValue(object_id, out loc10))
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
indexColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
if (is_unique && !is_primary_key)
|
||||
{
|
||||
if (!uniqueColumns.TryGetValue(object_id, out loc10))
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, List<DbColumnInfo>>());
|
||||
uniqueColumns.Add(object_id, loc10 = new Dictionary<string, DbIndexInfo>());
|
||||
if (!loc10.TryGetValue(index_id, out loc11))
|
||||
loc10.Add(index_id, loc11 = new List<DbColumnInfo>());
|
||||
loc11.Add(loc9);
|
||||
loc10.Add(index_id, loc11 = new DbIndexInfo());
|
||||
loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc });
|
||||
}
|
||||
}
|
||||
foreach (var object_id in indexColumns.Keys)
|
||||
@ -327,7 +326,7 @@ use [{olddatabase}];
|
||||
{
|
||||
foreach (var column in uniqueColumns[object_id])
|
||||
{
|
||||
column.Value.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name));
|
||||
loc2[object_id].UniquesDict.Add(column.Key, column.Value);
|
||||
}
|
||||
}
|
||||
@ -405,14 +404,14 @@ use [{olddatabase}];
|
||||
}
|
||||
foreach (var loc4 in loc2.Values)
|
||||
{
|
||||
if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
{
|
||||
foreach (var loc5 in loc4.UniquesDict.First().Value)
|
||||
{
|
||||
loc5.IsPrimary = true;
|
||||
loc4.Primarys.Add(loc5);
|
||||
}
|
||||
}
|
||||
//if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0)
|
||||
//{
|
||||
// foreach (var loc5 in loc4.UniquesDict.First().Value.Columns)
|
||||
// {
|
||||
// loc5.Column.IsPrimary = true;
|
||||
// loc4.Primarys.Add(loc5.Column);
|
||||
// }
|
||||
//}
|
||||
loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name));
|
||||
loc4.Columns.Sort((c1, c2) =>
|
||||
{
|
||||
|
@ -99,7 +99,8 @@ namespace FreeSql.Sqlite
|
||||
if (tboldname == null)
|
||||
{
|
||||
//创建表
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(_commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}")).Append(" ( ");
|
||||
var createTableName = _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}");
|
||||
sb.Append("CREATE TABLE IF NOT EXISTS ").Append(createTableName).Append(" ( ");
|
||||
foreach (var tbcol in tb.ColumnsByPosition)
|
||||
{
|
||||
sb.Append(" \r\n ").Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(" ");
|
||||
@ -117,14 +118,22 @@ namespace FreeSql.Sqlite
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) \r\n;\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tbname[1]).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
//如果新表,旧表在一个模式下,直接修改表名
|
||||
@ -183,25 +192,26 @@ namespace FreeSql.Sqlite
|
||||
//添加列
|
||||
istmpatler = true;
|
||||
}
|
||||
var dsukMatches = _regexUK.Matches(dsql);
|
||||
var dsuk = new List<string[]>();
|
||||
foreach (Match dsukm in dsukMatches)
|
||||
var dbIndexes = _orm.Ado.ExecuteArray(CommandType.Text, $"PRAGMA {_commonUtils.QuoteSqlName(tbtmp[0])}.INDEX_LIST({_commonUtils.QuoteSqlName(tbtmp[1])})");
|
||||
foreach (var dbIndex in dbIndexes)
|
||||
{
|
||||
var dbsukmg2 = dsukm.Groups[2].Value.Split(',');
|
||||
if (dbsukmg2.Any() == false) continue;
|
||||
foreach (var dbfield in dbsukmg2)
|
||||
if (string.Concat(dbIndex[3]) == "pk") continue;
|
||||
var dbIndexesColumns = _orm.Ado.ExecuteArray(CommandType.Text, $"PRAGMA {_commonUtils.QuoteSqlName(tbtmp[0])}.INDEX_INFO({dbIndex[1]})");
|
||||
var dbIndexesSql = string.Concat(_orm.Ado.ExecuteScalar(CommandType.Text, $"SELECT sql FROM sqlite_master WHERE name = '{dbIndex[1]}'"));
|
||||
foreach (var dbcolumn in dbIndexesColumns)
|
||||
{
|
||||
dsuk.Add(new[] { Regex.Match(dbfield, @"""([^""]+)""").Groups[1].Value, dsukm.Groups[1].Value });
|
||||
var dbcolumnName = string.Concat(dbcolumn[2]);
|
||||
var isDesc = dbIndexesSql.IndexOf($@"{dbcolumnName}"" DESC", StringComparison.CurrentCultureIgnoreCase) == -1 ? "0" : "1";
|
||||
dsuk.Add(new[] { dbcolumnName, string.Concat(dbIndex[1]), isDesc, string.Concat(dbIndex[2]) }); ;
|
||||
}
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Key) || uk.Value.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Key, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Value.Count || dsukfind1.Where(a => uk.Value.Where(b => string.Compare(b.Attribute.Name, a[0], true) == 0).Any()).Count() != uk.Value.Count)
|
||||
{
|
||||
if (string.IsNullOrEmpty(uk.Name) || uk.Columns.Any() == false) continue;
|
||||
var dsukfind1 = dsuk.Where(a => string.Compare(a[1], uk.Name, true) == 0).ToArray();
|
||||
if (dsukfind1.Any() == false || dsukfind1.Length != uk.Columns.Length || dsukfind1.Where(a => (a[3] == "1") == uk.IsUnique && uk.Columns.Where(b => string.Compare(b.Column.Attribute.Name, a[0], true) == 0 && (a[2] == "1") == b.IsDesc).Any()).Count() != uk.Columns.Length)
|
||||
istmpatler = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (istmpatler == false)
|
||||
@ -212,6 +222,7 @@ namespace FreeSql.Sqlite
|
||||
|
||||
//创建临时表,数据导进临时表,然后删除原表,将临时表改名为原表名
|
||||
var tablename = tboldname == null ? _commonUtils.QuoteSqlName($"{tbname[0]}.{tbname[1]}") : _commonUtils.QuoteSqlName($"{tboldname[0]}.{tboldname[1]}");
|
||||
var tablenameOnlyTb = tboldname == null ? _commonUtils.QuoteSqlName(tbname[1]) : _commonUtils.QuoteSqlName(tboldname[1]);
|
||||
var tmptablename = _commonUtils.QuoteSqlName($"{tbname[0]}._FreeSqlTmp_{tbname[1]}");
|
||||
//创建临时表
|
||||
//创建表
|
||||
@ -234,12 +245,6 @@ namespace FreeSql.Sqlite
|
||||
foreach (var tbcol in tb.Primarys) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
foreach (var uk in tb.Uniques)
|
||||
{
|
||||
sb.Append(" \r\n CONSTRAINT ").Append(_commonUtils.QuoteSqlName(uk.Key)).Append(" UNIQUE(");
|
||||
foreach (var tbcol in uk.Value) sb.Append(_commonUtils.QuoteSqlName(tbcol.Attribute.Name)).Append(", ");
|
||||
sb.Remove(sb.Length - 2, 2).Append("),");
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("\r\n) \r\n;\r\n");
|
||||
sb.Append("INSERT INTO ").Append(tmptablename).Append(" (");
|
||||
@ -268,9 +273,22 @@ namespace FreeSql.Sqlite
|
||||
sb.Remove(sb.Length - 2, 2).Append(" FROM ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("DROP TABLE ").Append(tablename).Append(";\r\n");
|
||||
sb.Append("ALTER TABLE ").Append(tmptablename).Append(" RENAME TO ").Append(_commonUtils.QuoteSqlName($"{tbname[1]}")).Append(";\r\n");
|
||||
//创建表的索引
|
||||
foreach (var uk in tb.Indexes)
|
||||
{
|
||||
sb.Append("CREATE ");
|
||||
if (uk.IsUnique) sb.Append("UNIQUE ");
|
||||
sb.Append("INDEX ").Append(_commonUtils.QuoteSqlName(uk.Name)).Append(" ON ").Append(tablenameOnlyTb).Append("(");
|
||||
foreach (var tbcol in uk.Columns)
|
||||
{
|
||||
sb.Append(_commonUtils.QuoteSqlName(tbcol.Column.Attribute.Name));
|
||||
if (tbcol.IsDesc) sb.Append(" DESC");
|
||||
sb.Append(", ");
|
||||
}
|
||||
sb.Remove(sb.Length - 2, 2).Append(");\r\n");
|
||||
}
|
||||
}
|
||||
return sb.Length == 0 ? null : sb.ToString();
|
||||
}
|
||||
static Regex _regexUK = new Regex(@"CONSTRAINT\s*""([^""]+)""\s*UNIQUE\s*\(([^\)]+)\)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user