Commit 9d7801b7 authored by 潘栩锋's avatar 潘栩锋 🚴

添加 SQLITE 添加 index功能

parent ab1ec72c
...@@ -12,15 +12,15 @@ using System.Threading.Tasks; ...@@ -12,15 +12,15 @@ using System.Threading.Tasks;
namespace FLY.OBJComponents.Server namespace FLY.OBJComponents.Server
{ {
public class BufferError : BufferSQLite<FlyData_WarningHistory, DB_Error> public class BufferError : BufferSQLite<FlyData_WarningHistory, Db_Error>
{ {
public void Init(DBTable<DB_Error> dbTable) public void Init(DBTable<Db_Error> dbTable)
{ {
base.Init(dbTable, mapLc2Db, mapDb2Lc); base.Init(dbTable, mapLc2Db, mapDb2Lc);
} }
static DB_Error mapLc2Db(FlyData_WarningHistory lc) static Db_Error mapLc2Db(FlyData_WarningHistory lc)
{ {
return new DB_Error() return new Db_Error()
{ {
ID = lc.ID, ID = lc.ID,
Time = lc.Time, Time = lc.Time,
...@@ -29,7 +29,7 @@ namespace FLY.OBJComponents.Server ...@@ -29,7 +29,7 @@ namespace FLY.OBJComponents.Server
IsOn = lc.State == ERR_STATE.ON IsOn = lc.State == ERR_STATE.ON
}; };
} }
static FlyData_WarningHistory mapDb2Lc(DB_Error db) static FlyData_WarningHistory mapDb2Lc(Db_Error db)
{ {
return new FlyData_WarningHistory() return new FlyData_WarningHistory()
{ {
......
...@@ -13,15 +13,17 @@ namespace FLY.OBJComponents.Server.Model ...@@ -13,15 +13,17 @@ namespace FLY.OBJComponents.Server.Model
/// 异常记录 /// 异常记录
/// </summary> /// </summary>
[Table("Error")] [Table("Error")]
public class DB_Error:IDbBase public class Db_Error:IDbBase
{ {
[Key] [Key]
[Index]
[PropertyIndex(0)] [PropertyIndex(0)]
public Int64 ID { get; set; } public Int64 ID { get; set; }
/// <summary> /// <summary>
/// 发生的时间 /// 发生的时间
/// </summary> /// </summary>
[Index]
[PropertyIndex(1)] [PropertyIndex(1)]
public DateTime Time { get; set; } public DateTime Time { get; set; }
......
...@@ -10,6 +10,6 @@ namespace FLY.OBJComponents.Server.Model ...@@ -10,6 +10,6 @@ namespace FLY.OBJComponents.Server.Model
public interface IErrorDBModel public interface IErrorDBModel
{ {
SQLiteHelper sqliteHelper { get; } SQLiteHelper sqliteHelper { get; }
DBTable<DB_Error> TbError { get; } DBTable<Db_Error> TbError { get; }
} }
} }
...@@ -13,6 +13,7 @@ namespace FLY.Thick.Base.Common ...@@ -13,6 +13,7 @@ namespace FLY.Thick.Base.Common
{ {
static ERRNOs() static ERRNOs()
{ {
BASE_ERRNO_ONBOOT = new ERRNO() { Code = 250, Descrption = "系统启动" };
BASE_ERRNO_RINGTEST = new ERRNO() { Code = 1, Descrption = "报警测试" }; BASE_ERRNO_RINGTEST = new ERRNO() { Code = 1, Descrption = "报警测试" };
BASE_ERRNO_AD_MIN = new ERRNO() { Code = 2, Descrption = "AD值太小" }; BASE_ERRNO_AD_MIN = new ERRNO() { Code = 2, Descrption = "AD值太小" };
BASE_ERRNO_AD_MAX = new ERRNO() { Code = 3, Descrption = "AD值太大" }; BASE_ERRNO_AD_MAX = new ERRNO() { Code = 3, Descrption = "AD值太大" };
...@@ -34,11 +35,15 @@ namespace FLY.Thick.Base.Common ...@@ -34,11 +35,15 @@ namespace FLY.Thick.Base.Common
SYNC_ERRNO_FATAL = new ERRNO() { Code = 21, Descrption = "同步异常,致命错误 必须停止扫描" }; SYNC_ERRNO_FATAL = new ERRNO() { Code = 21, Descrption = "同步异常,致命错误 必须停止扫描" };
MEASURE_SYNC_ERRNO_FATAL = new ERRNO() { Code = 22, Descrption = "测量同步参数异常,致命错误 必须停止" }; MEASURE_SYNC_ERRNO_FATAL = new ERRNO() { Code = 22, Descrption = "测量同步参数异常,致命错误 必须停止" };
} }
#region 基础报警类型 #region 基础报警类型
/// <summary> /// <summary>
/// 系统启动
/// </summary>
public static ERRNO BASE_ERRNO_ONBOOT;
/// <summary>
/// 报警测试 /// 报警测试
/// </summary> /// </summary>
public static ERRNO BASE_ERRNO_RINGTEST; public static ERRNO BASE_ERRNO_RINGTEST;
...@@ -124,6 +129,8 @@ namespace FLY.Thick.Base.Common ...@@ -124,6 +129,8 @@ namespace FLY.Thick.Base.Common
/// 获取同步参数异常,致命错误 必须停止 /// 获取同步参数异常,致命错误 必须停止
/// </summary> /// </summary>
public static ERRNO MEASURE_SYNC_ERRNO_FATAL; public static ERRNO MEASURE_SYNC_ERRNO_FATAL;
} }
} }
...@@ -25,21 +25,18 @@ namespace SQLite ...@@ -25,21 +25,18 @@ namespace SQLite
freeID = value; freeID = value;
} }
} }
private string ddl;
public string DDL public string DDL { get; private set; }
{ public string INDEX { get; private set; }
get
{
return ddl;
}
}
public SQLiteHelper sqliteHelper; public SQLiteHelper sqliteHelper;
public DBTable() public DBTable()
{ {
TableName = SQLiteHelper.GetTableName(typeof(T)); TableName = SQLiteHelper.GetTableName(typeof(T));
ddl = SQLiteHelper.GetCreateTableCommandText(typeof(T)); DDL = SQLiteHelper.GetCreateTableCommandText(typeof(T));
INDEX = SQLiteHelper.GetCreateIndexCommandText(typeof(T));
} }
public void Init(SQLiteHelper sQLiteHelper) public void Init(SQLiteHelper sQLiteHelper)
{ {
...@@ -48,7 +45,7 @@ namespace SQLite ...@@ -48,7 +45,7 @@ namespace SQLite
public void Create() public void Create()
{ {
sqliteHelper.ExecuteNonQuery(ddl);// SQLiteHelper.GetCreateTableCommandText(typeof(T)));//, ArrayFieldTypeInfos.ToArray())); sqliteHelper.ExecuteNonQuery(DDL);
} }
public void Add(T t) public void Add(T t)
......
...@@ -17,6 +17,12 @@ namespace SQLite ...@@ -17,6 +17,12 @@ namespace SQLite
/// </summary> /// </summary>
string DDL { get; } string DDL { get; }
/// <summary>
/// 表的 INDEX, 只能有一个
/// </summary>
string INDEX { get; }
/// <summary> /// <summary>
/// 创建表 /// 创建表
/// </summary> /// </summary>
......
...@@ -148,6 +148,43 @@ namespace SQLite ...@@ -148,6 +148,43 @@ namespace SQLite
} }
} }
} }
//检查INDEX
Dictionary<string, string> indexs = new Dictionary<string, string>();
foreach (IDBTable tb in DbSet)
{
if(!string.IsNullOrEmpty(tb.INDEX))
indexs.Add(tb.TableName, tb.INDEX);
}
if (indexs.Count() > 0)
{
isVaild = sqliteHelper.IsIndexValid(indexs, out results);
if (!isVaild)//不合法
{
foreach (var kv in results)
{
switch (kv.Value)
{
case SQLiteHelper.IsTableValidResult.NotHere:
{
//直接创建表
sqliteHelper.ExecuteNonQuery(indexs[kv.Key]);
}
break;
case SQLiteHelper.IsTableValidResult.FormatErr:
{
//先删除INDEX,再创建
sqliteHelper.ExecuteNonQuery($"DROP INDEX {kv.Key}_INDEX");
sqliteHelper.ExecuteNonQuery(indexs[kv.Key]);
}
break;
}
}
}
}
//最后也要加载数据 //最后也要加载数据
Load(); Load();
return isVaild; return isVaild;
......
...@@ -123,7 +123,55 @@ namespace SQLite ...@@ -123,7 +123,55 @@ namespace SQLite
return type.Name; return type.Name;
} }
} }
static string GetCreateIndexCommandText_fieldText(Type type)
{
string total_fieldtext = "";
List<FieldTextIndex> fieldTexts = new List<FieldTextIndex>();
PropertyInfo[] propertyInfos = type.GetProperties();
foreach (var propertyInfo in propertyInfos)
{
//忽略
if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), false).Count() > 0)
continue;
if (!(propertyInfo.GetCustomAttributes(typeof(IndexAttribute), false).Count() > 0))
continue;//没有INDEX
FieldTextIndex fieldText = new FieldTextIndex();
fieldTexts.Add(fieldText);
PropertyIndexAttribute propertyIndex = propertyInfo.GetCustomAttribute(typeof(PropertyIndexAttribute)) as PropertyIndexAttribute;
if (propertyIndex != null)
fieldText.index = propertyIndex.Index;//默认index=0
SQLiteFieldTypeInfo fieldTypeInfo = FieldTypeInfo.Find((fti) => fti.PropertyType == propertyInfo.PropertyType);
fieldText.fieldtext = propertyInfo.Name;
}
if (fieldTexts.Count() == 0)
return null;
//从小到大排序
fieldTexts.Sort((fieldTextIndex0, fieldTextIndex1) =>
{
if (fieldTextIndex0.index < fieldTextIndex1.index)
return -1;
if (fieldTextIndex0.index > fieldTextIndex1.index)
return 1;
else
return 0;
});
for (int i = 0; i < fieldTexts.Count(); i++)
{
var fieldTextIndex = fieldTexts[i];
if (i != 0)
total_fieldtext += ",";
total_fieldtext += fieldTextIndex.fieldtext;
}
return total_fieldtext;
}
static string GetCreateTableCommandText_fieldText(Type type) static string GetCreateTableCommandText_fieldText(Type type)
{ {
...@@ -187,7 +235,18 @@ namespace SQLite ...@@ -187,7 +235,18 @@ namespace SQLite
string commandText = string.Format("CREATE TABLE {0} ({1})", tablename, fieldtext); string commandText = string.Format("CREATE TABLE {0} ({1})", tablename, fieldtext);
return commandText; return commandText;
} }
public static string GetCreateIndexCommandText(Type type)
{
//CREATE INDEX index_name
//on table_name(column1, column2);
string tablename = GetTableName(type);
string fieldtext = GetCreateIndexCommandText_fieldText(type);
if (string.IsNullOrEmpty(fieldtext))
return null;
string commandText = string.Format("CREATE INDEX {0}_INDEX ON {0} ({1})", tablename, fieldtext);
return commandText;
}
class FieldTextIndex class FieldTextIndex
{ {
public int index = 0; public int index = 0;
...@@ -693,6 +752,103 @@ namespace SQLite ...@@ -693,6 +752,103 @@ namespace SQLite
} }
return true; return true;
} }
public bool ParseINDEX(string INDEX, out string indexName, out string tableName, out string[] fieldNames)
{
indexName = null;
tableName = null;
fieldNames = null;
//CREATE TABLE boltmap(ID INTEGER PRIMARY KEY, MID INTEGER, RBegin INTEGER, REnd INTEGER)
Regex regex = new Regex(@"CREATE INDEX\s+(\w+)\s+ON\s+(\w+)\s+\((.+)\)");
Match match = regex.Match(INDEX);
if (!match.Success)
{
ErrorMsg = "不能匹配 CREATE INDEX 的格式";
return false;
}
indexName = match.Groups[1].Value;
tableName = match.Groups[2].Value;
string fields_sql = match.Groups[3].Value;
fieldNames = fields_sql.Split(',');
return true;
}
/// <summary>
/// 输入INDEXs 判断是否存在
/// </summary>
/// <param name="INDEXs">key=tablename, value=INDEX</param>
/// <returns></returns>
public bool IsIndexValid(Dictionary<string, string> INDEXs, out Dictionary<string, IsTableValidResult> results)
{
results = new Dictionary<string, IsTableValidResult>();
//检测 table 是否合法
DataTable data = ExecuteReader("SELECT tbl_name,sql FROM sqlite_master WHERE type = 'index'");
//任意一个表不对,或者不存在,都必须重建
foreach (var kv in INDEXs)
{
string tableName = kv.Key;
string createindex_sql = kv.Value;
var sqls = from r in data.AsEnumerable() where (string)r["tbl_name"] == tableName select r["sql"];
if (sqls.Count() == 0)
{
//不存在该表
ErrorMsg = $"sqlite_master 不能找到 tbl_name = '{tableName}' 的 sql";
results.Add(tableName, IsTableValidResult.NotHere);
continue;
}
string sql = (string)sqls.First();
if (sql == createindex_sql)
{
//完全一样
results.Add(tableName, IsTableValidResult.OK);
continue;
}
if (!ParseINDEX(createindex_sql, out string indexName0, out string tableName0, out string[] fieldNames0))
{
ErrorMsg = $"sqlite_master 找到 tbl_name = '{tableName}' 的 sql 不能解析";
results.Add(tableName, IsTableValidResult.FormatErr);
continue;
}
if (!ParseINDEX(sql, out string indexName2, out string tableName2, out string[] fieldNames2))
{
ErrorMsg = $"程序中 找到 tbl_name = '{tableName}' 的 sql 不能解析";
results.Add(tableName, IsTableValidResult.FormatErr);
continue;
}
if (tableName2 != tableName0) {
ErrorMsg = $"sqlite_master 找到 tbl_name = '{tableName}' 的 sql 不符合要求";
results.Add(tableName, IsTableValidResult.FormatErr);
continue;
}
//检查 fieldNames0,fieldNames 是否一致
if (fieldNames0.Except(fieldNames2).Count() != 0) {
ErrorMsg = $"sqlite_master 找到 tbl_name = '{tableName}' 的 sql 不符合要求";
results.Add(tableName, IsTableValidResult.FormatErr);
continue;
}
if (fieldNames2.Except(fieldNames0).Count() != 0)
{
ErrorMsg = $"sqlite_master 找到 tbl_name = '{tableName}' 的 sql 不符合要求";
results.Add(tableName, IsTableValidResult.FormatErr);
continue;
}
//虽然不一样,都也是合法的
results.Add(tableName, IsTableValidResult.OK);
}
return results.All(kv => kv.Value == IsTableValidResult.OK);
}
} }
public class SQLiteTableInfo public class SQLiteTableInfo
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment