diff --git a/Apewer.Source/Source/SqlClient.cs b/Apewer.Source/Source/SqlClient.cs index c300353..9393f11 100644 --- a/Apewer.Source/Source/SqlClient.cs +++ b/Apewer.Source/Source/SqlClient.cs @@ -115,7 +115,6 @@ namespace Apewer.Source // 找出新列。 var newColumns = new List(); - var newPrimaryKey = new List(); foreach (var column in structure.Columns) { // 检查 Independent 特性。 @@ -326,7 +325,7 @@ namespace Apewer.Source } /// 获取列信息。 - public ColumnInfo[] ColumnsInfo(string tableName) + public virtual ColumnInfo[] ColumnsInfo(string tableName) { if (tableName.IsEmpty()) throw new ArgumentNullException(nameof(tableName)); var sql = $"select name, xtype, length from syscolumns where id = object_id('{tableName}') "; @@ -345,11 +344,47 @@ namespace Apewer.Source } } + /// 创建索引。 + /// 索引名称已存在或无索引字段时,不抛出异常。 + public virtual string Initialize(TableIndex index) + { + if (index == null) + { + if (ThrowAdoException) throw new ArgumentNullException(nameof(index)); + return $"参数 {nameof(index)} 无效。"; + } + + // 查询索引是否存在,若存在则直接退出。 + var sql1 = "select distinct i.name from sys.indexes i left join sys.all_objects o on i.object_id = o.object_id where i.name is not null and o.type = 'U' and i.is_primary_key = 0 and i.is_unique = 0"; + var names = this.Column(sql1, false); + var exist = names.Find(x => string.Equals(x, index.Name, StringComparison.CurrentCultureIgnoreCase)); + if (exist.NotEmpty()) return $"索引已存在。"; + + // 执行创建。 + var fields = new List(); + foreach (var field in index.Fields) + { + if (field.Order == Order.Ascend) fields.Add($"[{field.Column.Field}]"); + else fields.Add($"[{field.Column.Field}] desc"); + } + if (fields.IsEmpty()) return "无索引字段。"; + + var sql2 = $"create index {index.Name} on [{index.Table.Name}] ({fields.Join(", ")})"; + var execute = Execute(sql2); + if (!execute.Success) + { + if (ThrowAdoException) throw new SqlException(execute.Message); + return execute.Message; + } + + return null; + } + /// 批量插入,必须在 DataTable 中指定表名,或指定 tableName 参数。 /// /// /// - public void BulkCopy(DataTable table, string tableName = null) + public virtual void BulkCopy(DataTable table, string tableName = null) { // 检查 table 参数。 if (table == null) throw new ArgumentNullException(nameof(table)); @@ -389,7 +424,7 @@ namespace Apewer.Source /// 数据库名称。 /// 日志文件的最大 MB 数,指定非正数将不限制增长。 /// 成功时候返回 NULL 值,失败时返回错误信息。 - public string CreateStore(string name, int logMaxSizeMB = 1024) + public virtual string CreateStore(string name, int logMaxSizeMB = 1024) { var store = name.Escape().ToTrim(); if (store.IsEmpty()) return "创建失败:未指定数据库名称。";