SQLiteHelper.cs 35.6 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1
using System;
2
using System.Collections.Concurrent;
潘栩锋's avatar
潘栩锋 committed
3 4 5 6 7 8 9 10
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Reflection;
using System.Text;
11
using System.Text.RegularExpressions;
12
using System.Threading.Tasks;
潘栩锋's avatar
潘栩锋 committed
13

14
namespace SQLite
潘栩锋's avatar
潘栩锋 committed
15 16 17
{
    public class SQLiteHelper
    {
潘栩锋's avatar
潘栩锋 committed
18
        static NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
潘栩锋's avatar
潘栩锋 committed
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
        #region 静态操作
        public class SQLiteFieldTypeInfo
        {
            /// <summary>
            /// sqlite field 类型
            /// </summary>
            public string FieldType { get; set; }
            /// <summary>
            /// C# 类型
            /// </summary>
            public Type PropertyType { get; set; }

            /// <summary>
            /// C# 类型转 sqlite 字符串
            /// </summary>
            public Func<object, string> PtoS { get; set; } = DefaultToS;

            public Func<object, object> StoP { get; set; } = DefaultToP;

            public static string DefaultToS(object obj)
            {
                return obj.ToString();
            }

            public static object DefaultToP(object obj)
            {
                return obj;
            }

            public SQLiteFieldTypeInfo(string fieldtype, Type propertytype)
            {
                FieldType = fieldtype;
                PropertyType = propertytype;
            }
            public SQLiteFieldTypeInfo(string fieldtype, Type propertytype, Func<object, string> ptos, Func<object, object> stop)
            {
                FieldType = fieldtype;
                PropertyType = propertytype;
                PtoS = ptos;
                StoP = stop;

            }


        }
        public static List<SQLiteFieldTypeInfo> FieldTypeInfo { get; set; }


        static SQLiteHelper()
        {

            FieldTypeInfo = new List<SQLiteFieldTypeInfo>
            {
                new SQLiteFieldTypeInfo("INTEGER",typeof(int),
                        SQLiteFieldTypeInfo.DefaultToS,
                        (obj)=>{
                            return Convert.ToInt32(obj);
                        }
                    ),
                new SQLiteFieldTypeInfo("INTEGER",typeof(Int64)),
                new SQLiteFieldTypeInfo("BOOLEAN",typeof(bool)),
                new SQLiteFieldTypeInfo("DOUBLE",typeof(double),
81
                        (obj)=>((double)obj).ToStringOfSQLiteFieldType(),
潘栩锋's avatar
潘栩锋 committed
82 83 84 85 86 87 88
                        (obj)=>{
                            if(obj == DBNull.Value)
                                return double.NaN;
                            else
                                return obj;
                        }
                     ),
89
                new SQLiteFieldTypeInfo("TEXT",typeof(string),
90
                        (obj)=>((string)obj).ToStringOfSQLiteFieldType(),
潘栩锋's avatar
潘栩锋 committed
91 92 93
                        SQLiteFieldTypeInfo.DefaultToP
                     ),
                new SQLiteFieldTypeInfo("DATETIME",typeof(DateTime),
94
                        (obj)=>((DateTime)obj).ToStringOfSQLiteFieldType(),
潘栩锋's avatar
潘栩锋 committed
95 96 97 98 99
                        SQLiteFieldTypeInfo.DefaultToP
                     )
            };
        }

100 101 102 103 104 105 106 107 108 109 110 111
        public static SQLiteFieldTypeInfo GetFieldTypeInfo(string fieldtype)
        {
            var ftis = from fti in FieldTypeInfo where fti.FieldType == fieldtype select fti;
            if (ftis.Count() > 0)
            {
                return ftis.First();
            }
            else
            {
                return null;
            }
        }
潘栩锋's avatar
潘栩锋 committed
112 113 114 115 116 117 118 119 120 121 122 123 124 125


        public static string GetTableName(Type type)
        {
            var attributes = type.GetCustomAttributes(typeof(TableAttribute), false);
            if (attributes.Count() > 0)
            {
                return ((TableAttribute)attributes.First()).Name;
            }
            else
            {
                return type.Name;
            }
        }
126 127 128 129 130 131 132 133 134 135 136 137
        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;
潘栩锋's avatar
潘栩锋 committed
138

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
                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;
        }
175
        static string GetCreateTableCommandText_fieldText(Type type)
潘栩锋's avatar
潘栩锋 committed
176
        {
177 178 179 180

            string total_fieldtext = "";
            List<FieldTextIndex> fieldTexts = new List<FieldTextIndex>();

潘栩锋's avatar
潘栩锋 committed
181 182 183
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
潘栩锋's avatar
潘栩锋 committed
184 185 186 187
                //忽略
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), false).Count() > 0)
                    continue;

188 189 190 191 192 193
                FieldTextIndex fieldText = new FieldTextIndex();
                fieldTexts.Add(fieldText);
                PropertyIndexAttribute propertyIndex = propertyInfo.GetCustomAttribute(typeof(PropertyIndexAttribute)) as PropertyIndexAttribute;
                if (propertyIndex != null)
                    fieldText.index = propertyIndex.Index;//默认index=0

194 195 196
                SQLiteFieldTypeInfo fieldTypeInfo = FieldTypeInfo.Find((fti) => fti.PropertyType == propertyInfo.PropertyType);
                string text = "";
                text += string.Format("{0} {1}", propertyInfo.Name, fieldTypeInfo.FieldType);
潘栩锋's avatar
潘栩锋 committed
197

198 199 200 201 202
                //主键
                if (propertyInfo.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0)
                    text += " PRIMARY KEY";
                fieldText.fieldtext = text;
                
潘栩锋's avatar
潘栩锋 committed
203
            }
204 205 206 207 208 209 210 211 212 213
            //从小到大排序
            fieldTexts.Sort((fieldTextIndex0, fieldTextIndex1) =>
            {
                if (fieldTextIndex0.index < fieldTextIndex1.index)
                    return -1;
                if (fieldTextIndex0.index > fieldTextIndex1.index)
                    return 1;
                else
                    return 0;
            });
214

215 216 217 218 219 220 221 222
            for (int i = 0; i < fieldTexts.Count(); i++)
            {
                var fieldTextIndex = fieldTexts[i];
                if (i != 0)
                    total_fieldtext += ",";
                total_fieldtext += fieldTextIndex.fieldtext;
            }
            return total_fieldtext;
223
        }
224
        public static string GetCreateTableCommandText(Type type)
225 226 227 228 229 230 231 232 233
        {
            //CREATE TABLE table_name(
            //column1 datatype  PRIMARY KEY,
            //column2 datatype,
            //   column3 datatype,
            //   .....
            //   columnN datatype,
            //)
            string tablename = GetTableName(type);
234
            string fieldtext = GetCreateTableCommandText_fieldText(type);
潘栩锋's avatar
潘栩锋 committed
235 236 237
            string commandText = string.Format("CREATE TABLE {0} ({1})", tablename, fieldtext);
            return commandText;
        }
238 239 240 241 242
        public static string GetCreateIndexCommandText(Type type)
        {
            //CREATE INDEX index_name
            //on table_name(column1, column2);
            string tablename = GetTableName(type);
潘栩锋's avatar
潘栩锋 committed
243

244 245 246 247 248 249
            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;
        }
250 251 252 253 254
        class FieldTextIndex
        {
            public int index = 0;
            public string fieldtext = "";
        }
255 256
        static string GetInsertCommandText_fieldText(object cell)
        {
潘栩锋's avatar
潘栩锋 committed
257
            Type type = cell.GetType();
258 259 260
            string total_fieldtext = "";
            List<FieldTextIndex> fieldTexts = new List<FieldTextIndex>();

潘栩锋's avatar
潘栩锋 committed
261 262 263
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
潘栩锋's avatar
潘栩锋 committed
264 265 266
                //忽略
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), false).Count() > 0)
                    continue;
267 268 269 270 271
                FieldTextIndex fieldText = new FieldTextIndex();
                fieldTexts.Add(fieldText);
                PropertyIndexAttribute propertyIndex = propertyInfo.GetCustomAttribute(typeof(PropertyIndexAttribute)) as PropertyIndexAttribute;
                if (propertyIndex != null)
                    fieldText.index = propertyIndex.Index;//默认index=0
潘栩锋's avatar
潘栩锋 committed
272

273 274
                object o = propertyInfo.GetValue(cell, null);

275
                SQLiteFieldTypeInfo fieldTypeInfo = FieldTypeInfo.Find((fti) => fti.PropertyType == propertyInfo.PropertyType);
276

277 278
                fieldText.fieldtext = fieldTypeInfo.PtoS(o);
                
潘栩锋's avatar
潘栩锋 committed
279
            }
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

            //从小到大排序
            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;
300 301 302 303 304 305 306 307 308
        }
        public static string GetInsertCommandText(object cell)
        {
            //不用
            //INSERT INTO TABLE_NAME[(column1, column2, column3,...columnN)]
            //VALUES(value1, value2, value3,...valueN);

            //使用
            //INSERT INTO TABLE_NAME VALUES(value1, value2, value3,...valueN);
潘栩锋's avatar
潘栩锋 committed
309

310 311 312
            Type type = cell.GetType();
            string tablename = GetTableName(type);
            string fieldtext = GetInsertCommandText_fieldText(cell);
潘栩锋's avatar
潘栩锋 committed
313 314 315
            string commandText = string.Format("INSERT INTO {0} VALUES({1})", tablename, fieldtext);
            return commandText;
        }
潘栩锋's avatar
潘栩锋 committed
316

317 318

        static string GetUpdateCommandText_fieldText(object cell)
潘栩锋's avatar
潘栩锋 committed
319 320 321 322 323 324 325 326 327 328 329 330
        {
            //UPDATE table_name
            //SET column1 = value1, column2 = value2...., columnN = valueN
            //WHERE[condition];

            Type type = cell.GetType();
            string tablename = GetTableName(type);

            string fieldtext = "";
            PropertyInfo[] propertyInfos = type.GetProperties();
            foreach (var propertyInfo in propertyInfos)
            {
潘栩锋's avatar
潘栩锋 committed
331 332 333 334
                //忽略
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), false).Count() > 0)
                    continue;

潘栩锋's avatar
潘栩锋 committed
335 336 337 338 339
                if (fieldtext != "")
                {
                    fieldtext += ",";
                }

340 341
                object o = propertyInfo.GetValue(cell, null);

潘栩锋's avatar
潘栩锋 committed
342

343
                SQLiteFieldTypeInfo fieldTypeInfo = FieldTypeInfo.Find((fti) => fti.PropertyType == propertyInfo.PropertyType);
潘栩锋's avatar
潘栩锋 committed
344 345


346 347
                fieldtext += string.Format("{0} = {1}", propertyInfo.Name, fieldTypeInfo.PtoS(o));
                
潘栩锋's avatar
潘栩锋 committed
348 349
            }

350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
            return fieldtext;
        }
        /// <summary>
        /// condition 为 "WHERE ......"
        /// </summary>
        /// <param name="cell"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public static string GetUpdateCommandText(object cell, string condition)
        {
            //UPDATE table_name
            //SET column1 = value1, column2 = value2...., columnN = valueN
            //WHERE[condition];

            Type type = cell.GetType();
            string tablename = GetTableName(type);
            string fieldtext = GetUpdateCommandText_fieldText(cell);
            string commandText = $"UPDATE {tablename} SET {fieldtext}";

            if (!string.IsNullOrEmpty(condition))
                commandText += $" {condition}";

潘栩锋's avatar
潘栩锋 committed
372 373 374
            return commandText;
        }

375
        public static List<T> ToObjs<T>(DataTable dataTable)
潘栩锋's avatar
潘栩锋 committed
376 377 378 379 380
            where T : new()
        {
            List<T> list = new List<T>();
            foreach (DataRow dataRow in dataTable.Rows)
            {
381
                list.Add(ToObj<T>(dataRow));
潘栩锋's avatar
潘栩锋 committed
382 383 384 385
            }
            return list;
        }

386
        static void SetObj(object t, DataRow dataRow)
潘栩锋's avatar
潘栩锋 committed
387
        {
388 389
            Type type = t.GetType();

潘栩锋's avatar
潘栩锋 committed
390
            PropertyInfo[] propertyInfos = type.GetProperties();
391

潘栩锋's avatar
潘栩锋 committed
392 393
            foreach (var propertyInfo in propertyInfos)
            {
394 395 396 397
                //忽略
                if (propertyInfo.GetCustomAttributes(typeof(IgnoreAttribute), false).Count() > 0)
                    continue;

潘栩锋's avatar
潘栩锋 committed
398
                Type ptype = propertyInfo.PropertyType;
399

400 401 402 403
                SQLiteFieldTypeInfo fieldTypeInfo = FieldTypeInfo.Find((fti) => fti.PropertyType == ptype);
                object o = fieldTypeInfo.StoP(dataRow[propertyInfo.Name]);
                propertyInfo.SetValue(t, o, null);
                
潘栩锋's avatar
潘栩锋 committed
404
            }
405
        }
406
        public static T ToObj<T>(DataRow dataRow)
407 408 409
            where T : new()
        {
            T t = new T();
410
            SetObj(t, dataRow);
潘栩锋's avatar
潘栩锋 committed
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
            return t;
        }

        #endregion


        public string ConnectionString;
        /// <summary> 
        /// 查询数据库中的所有数据类型信息。
        /// </summary> 
        /// <returns></returns> 
        /// <exception cref="Exception"></exception>
        public DataTable ExecuteReader(string sql)
        {
            DataTable data;
潘栩锋's avatar
潘栩锋 committed
426
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
潘栩锋's avatar
潘栩锋 committed
427
            {
潘栩锋's avatar
潘栩锋 committed
428 429 430 431 432 433 434 435 436 437
                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    connection.Open();
                    command.CommandText = sql;
                    // 开始读取
                    SQLiteDataAdapter adapter = new SQLiteDataAdapter(command);
                    data = new DataTable();
                    adapter.Fill(data);
                    connection.Close();
                }
438

潘栩锋's avatar
潘栩锋 committed
439 440 441 442 443 444 445 446 447 448
            }
            return data;
        }
        /// <summary> 
        /// 对SQLite数据库执行增删改操作,返回受影响的行数。 
        /// </summary> 
        /// <param name="sql">要执行的增删改的SQL语句。</param> 
        /// <param name="parameters">执行增删改语句所需要的参数,参数必须以它们在SQL语句中的顺序为准。</param> 
        /// <returns></returns> 
        /// <exception cref="Exception"></exception>
449
        public int ExecuteNonQuery(string sql)
潘栩锋's avatar
潘栩锋 committed
450
        {
451
            int ret = 0;
潘栩锋's avatar
潘栩锋 committed
452 453 454 455 456 457
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    connection.Open();
                    command.CommandText = sql;
458
                    ret = command.ExecuteNonQuery();
潘栩锋's avatar
潘栩锋 committed
459
                    connection.Close();
潘栩锋's avatar
潘栩锋 committed
460 461
                }
            }
462 463
            return ret;

潘栩锋's avatar
潘栩锋 committed
464 465
        }

潘栩锋's avatar
潘栩锋 committed
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486

        /// <summary>
        ///     
        /// </summary>
        /// <param name="sql"></param>
        /// <returns>The first column of the first row of the first resultset from the query.</returns>
        public object ExecuteScalar(string sql)
        {
            object obj = null;
            using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
            {
                using (SQLiteCommand command = new SQLiteCommand(connection))
                {
                    connection.Open();
                    command.CommandText = sql;
                    obj = command.ExecuteScalar();
                    connection.Close();
                }
            }
            return obj;
        }
潘栩锋's avatar
潘栩锋 committed
487 488 489 490 491 492 493
        /// <summary>
        /// 多行执行
        /// </summary>
        /// <param name="queryList"></param>
        /// <returns></returns>
        public bool QueryTran(IEnumerable<string> queryList)
        {
494
            if (isHoldQueryTran)
潘栩锋's avatar
潘栩锋 committed
495
            {
496 497 498 499 500 501
                holdQueryList.AddRange(queryList);
                return true;
            }
            else
            {
                using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
潘栩锋's avatar
潘栩锋 committed
502
                {
503
                    using (SQLiteCommand command = new SQLiteCommand(connection))
潘栩锋's avatar
潘栩锋 committed
504
                    {
505 506 507 508 509
                        connection.Open();

                        SQLiteTransaction tran = connection.BeginTransaction();
                        bool check = false;
                        try
潘栩锋's avatar
潘栩锋 committed
510
                        {
511 512 513 514 515 516 517
                            foreach (string item in queryList)
                            {
                                command.CommandText = item;
                                command.ExecuteNonQuery();
                            }
                            tran.Commit();
                            check = true;
潘栩锋's avatar
潘栩锋 committed
518
                        }
519 520 521 522
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            check = false;
潘栩锋's avatar
潘栩锋 committed
523
                            logger.Error(ex, Newtonsoft.Json.JsonConvert.SerializeObject(queryList));
524 525 526 527 528 529 530
                            throw ex;
                        }
                        finally
                        {
                            connection.Close();
                        }
                        return check;
潘栩锋's avatar
潘栩锋 committed
531 532 533 534
                    }
                }
            }

535
        }
潘栩锋's avatar
潘栩锋 committed
536

537 538 539 540 541 542 543 544 545 546
        /// <summary>
        /// 异步
        /// </summary>
        /// <param name="queryList"></param>
        /// <returns></returns>
        public void QueryTranAsync(IEnumerable<string> queryList)
        {
            new Task((obj) => {
                var _sqls = obj as IEnumerable<string>;
                QueryTran(_sqls);
547
            }, queryList).Start(Scheduler);
潘栩锋's avatar
潘栩锋 committed
548
        }
549
        TaskScheduler Scheduler { get; } = new StepByStepTaskScheduler();
潘栩锋's avatar
潘栩锋 committed
550

551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        List<string> holdQueryList = new List<string>();
        bool isHoldQueryTran = false;
        public void HoldQueryTran()
        {
            isHoldQueryTran = true;
        }
        public bool ReleaseQueryTran()
        {
            if (holdQueryList.Count() > 0)
            {
                using (SQLiteConnection connection = new SQLiteConnection(ConnectionString))
                {
                    using (SQLiteCommand command = new SQLiteCommand(connection))
                    {
                        connection.Open();

                        SQLiteTransaction tran = connection.BeginTransaction();
                        bool check = false;
                        try
                        {
                            foreach (string item in holdQueryList)
                            {
                                command.CommandText = item;
                                command.ExecuteNonQuery();
                            }
                            tran.Commit();
                            check = true;
                        }
                        catch (Exception ex)
                        {
                            tran.Rollback();
                            check = false;
                            throw ex;
                        }
                        finally
                        {
                            holdQueryList.Clear();
                            connection.Close();
                            isHoldQueryTran = false;
                        }
                        return check;
                    }
                }
            }
            isHoldQueryTran = false;
            return true;
        }
598 599 600 601
        /// <summary>
        /// 出错代码
        /// </summary>
        public string ErrorMsg { get; set; }
潘栩锋's avatar
潘栩锋 committed
602 603 604 605 606
        /// <summary>
        /// 输入DDLs 判断这些table都是否合法
        /// </summary>
        /// <param name="DDLs">key=tablename, value=DDL</param>
        /// <returns></returns>
607
        public bool IsTableValid(Dictionary<string, string> DDLs)
潘栩锋's avatar
潘栩锋 committed
608 609 610 611 612 613 614 615 616 617 618
        {

            //检测 table 是否合法
            DataTable data = ExecuteReader("SELECT name,sql FROM sqlite_master WHERE type = 'table'");

            //任意一个表不对,或者不存在,都必须重建
            bool isVaild = true;
            foreach (var kv in DDLs)
            {
                string tablename = kv.Key;
                string createtable_sql = kv.Value;
619

潘栩锋's avatar
潘栩锋 committed
620 621 622 623
                var sqls = from r in data.AsEnumerable() where (string)r["name"] == tablename select r["sql"];
                if (sqls.Count() == 0)
                {
                    //不存在该表,创建
潘栩锋's avatar
潘栩锋 committed
624
                    ErrorMsg = $"sqlite_master 不能找到 name = '{tablename}' 的 sql";
潘栩锋's avatar
潘栩锋 committed
625 626 627 628 629 630 631 632
                    isVaild = false;
                    break;
                }
                else
                {
                    string sql = (string)sqls.First();
                    if (sql != createtable_sql)
                    {
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
                        if (!GetTableInfoFromDDL(sql, out SQLiteTableInfo tableInfo0))
                        {
                            ErrorMsg = $"sqlite_master 找到 name = '{tablename}' 的 sql 不能解析";
                            isVaild = false;
                            break;
                        }
                        if (!GetTableInfoFromDDL(createtable_sql, out SQLiteTableInfo tableInfo1))
                        {
                            ErrorMsg = $"程序中 name = '{tablename}' 的 sql 不能解析";
                            isVaild = false;
                            break;
                        }

                        if (!tableInfo0.Equals(tableInfo1))
                        {
                            ErrorMsg = $"sqlite_master 找到 name = '{tablename}' 的 sql 不符合要求, " + tableInfo0.ErrorMsg;
                            isVaild = false;
                            break;
                        }
潘栩锋's avatar
潘栩锋 committed
652 653 654 655 656
                    }
                }
            }
            return isVaild;
        }
657

658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714
        public enum IsTableValidResult
        {
            OK,
            NotHere,
            FormatErr
        }
        /// <summary>
        /// 输入DDLs 判断这些table都是否合法
        /// </summary>
        /// <param name="DDLs">key=tablename, value=DDL</param>
        /// <returns></returns>
        public bool IsTableValid(Dictionary<string, string> DDLs,out Dictionary<string,IsTableValidResult> results)
        {
            results = new Dictionary<string, IsTableValidResult>();
            //检测 table 是否合法
            DataTable data = ExecuteReader("SELECT name,sql FROM sqlite_master WHERE type = 'table'");

            //任意一个表不对,或者不存在,都必须重建
            foreach (var kv in DDLs)
            {
                string tablename = kv.Key;
                string createtable_sql = kv.Value;

                var sqls = from r in data.AsEnumerable() where (string)r["name"] == tablename select r["sql"];
                if (sqls.Count() == 0)
                {
                    //不存在该表
                    ErrorMsg = $"sqlite_master 不能找到 name = '{tablename}' 的 sql";
                    results.Add(tablename, IsTableValidResult.NotHere);
                    continue;
                }

                string sql = (string)sqls.First();
                if (sql == createtable_sql)
                {
                    //完全一样
                    results.Add(tablename, IsTableValidResult.OK);
                    continue;
                }

                if (!GetTableInfoFromDDL(sql, out SQLiteTableInfo tableInfo0))
                {
                    ErrorMsg = $"sqlite_master 找到 name = '{tablename}' 的 sql 不能解析";
                    results.Add(tablename, IsTableValidResult.FormatErr);
                    continue;
                }

                if (!GetTableInfoFromDDL(createtable_sql, out SQLiteTableInfo tableInfo1))
                {
                    ErrorMsg = $"程序中 name = '{tablename}' 的 sql 不能解析";
                    results.Add(tablename, IsTableValidResult.FormatErr);
                    continue;
                }

                if (!tableInfo0.Equals(tableInfo1))
                {
                    ErrorMsg = $"sqlite_master 找到 name = '{tablename}' 的 sql 不符合要求, " + tableInfo0.ErrorMsg;
715
                    results.Add(tablename, IsTableValidResult.FormatErr);
716 717 718 719 720 721 722 723 724
                    continue;
                }

                //虽然不一样,都也是合法的
                results.Add(tablename, IsTableValidResult.OK);
            }

            return results.All(kv => kv.Value == IsTableValidResult.OK);
        }
725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
        public bool GetTableInfoFromDDL(string DDL, out SQLiteTableInfo tableInfo)
        {
            tableInfo = null;
            Regex regex_key = new Regex(@"PRIMARY KEY");
            //CREATE TABLE boltmap(ID INTEGER PRIMARY KEY, MID INTEGER, RBegin INTEGER, REnd INTEGER)
            Regex regex = new Regex(@"CREATE TABLE\s+(\w+)\s+\((.+)\)");
            Match match = regex.Match(DDL);
            if (!match.Success)
            {
                ErrorMsg = "不能匹配 CREATE TABLE 的格式";
                return false;
            }
            tableInfo = new SQLiteTableInfo();
            tableInfo.Name = match.Groups[1].Value;

            string fields_sql = match.Groups[2].Value;
            string[] fields_str = fields_sql.Split(',');
            foreach (string str in fields_str)
            {
                SQLiteFieldInfo fieldInfo = new SQLiteFieldInfo();
                string str1 = str.Trim();
                string[] ss = str1.Split(' ');
                if (ss.Length < 2)
                {
                    ErrorMsg = $"{str1} 格式出错";
                    return false;
                }
                fieldInfo.Name = ss[0];
                fieldInfo.Type = ss[1];
                if (regex_key.IsMatch(str1))
                    fieldInfo.IsKey = true;
                tableInfo.FieldInfos.Add(fieldInfo);
            }
            return true;
        }
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856

        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);
        }
857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923
    }

    public class SQLiteTableInfo
    {
        /// <summary>
        /// 名称
        /// </summary>
        public string Name;
        public List<SQLiteFieldInfo> FieldInfos = new List<SQLiteFieldInfo>();
        public override bool Equals(object obj)
        {
            SQLiteTableInfo tableinfo = obj as SQLiteTableInfo;
            if (tableinfo.Name != Name)
            {
                ErrorMsg = $"名称不相等 期待.{tableinfo.Name}!=数据库.{Name}";
                return false;
            }
            if (tableinfo.FieldInfos.Count() != FieldInfos.Count())
            {
                ErrorMsg = $"field 数量不同 期待.{tableinfo.FieldInfos.Count()}!=数据库.{FieldInfos.Count()}";
                return false;
            }
            for (int i = 0; i < FieldInfos.Count(); i++)
            {
                if (!FieldInfos[i].Equals(tableinfo.FieldInfos[i]))
                {
                    ErrorMsg = $"field 不同 期待.({tableinfo.FieldInfos[i]})!=数据库.({FieldInfos[i]})";
                    return false;
                }
            }
            ErrorMsg = "OK";
            return true;
        }
        public string ErrorMsg { get; set; }
    }
    public class SQLiteFieldInfo
    {
        /// <summary>
        /// 类型
        /// </summary>
        public string Type;
        /// <summary>
        /// 名称
        /// </summary>
        public string Name;
        /// <summary>
        /// 是主键?
        /// </summary>
        public bool IsKey;
        public override bool Equals(object obj)
        {
            SQLiteFieldInfo fieldInfo = obj as SQLiteFieldInfo;
            if (Type != fieldInfo.Type)
                return false;
            if (Name != fieldInfo.Name)
                return false;
            if (IsKey != fieldInfo.IsKey)
                return false;
            return true;
        }
        public override string ToString()
        {
            string s = $"{Name} As {Type}";
            if (IsKey)
                s += " IsKey";
            return s;
        }
潘栩锋's avatar
潘栩锋 committed
924
    }
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952

    public static class SQLiteFieldTypeExtern
    {
        public static string ToStringOfSQLiteFieldType(this DateTime dt)
        {
            return $"'{dt:yyyy-MM-dd HH:mm:ss.fff}'";
        }
        public static string ToStringOfSQLiteFieldType(this string str)
        {
            return $"'{str}'";
        }
        public static string ToStringOfSQLiteFieldType(this double d)
        {
            if (double.IsNaN(d))
                return "NULL";
            else return d.ToString();
        }
    }


    public class StepByStepTaskScheduler : TaskScheduler
    {
        public static new TaskScheduler Current { get; } = new StepByStepTaskScheduler();
        public static new TaskScheduler Default { get; } = Current;

        public static StepByStepTaskScheduler Instance { get; } = (StepByStepTaskScheduler)Current;
        private readonly BlockingCollection<Task> m_queue = new BlockingCollection<Task>();

953
        public StepByStepTaskScheduler()
954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989
        {
            //Thread thread = new Thread(Run);
            //thread.IsBackground = true;//设为为后台线程,当主线程结束时线程自动结束
            //thread.Start();
            Task.Factory.StartNew(Run);
        }

        private void Run()
        {
            //Console.WriteLine($"MyTaskScheduler, ThreadID: {Thread.CurrentThread.ManagedThreadId}");
            Task t;
            while (m_queue.TryTake(out t, System.Threading.Timeout.Infinite))
            {
                TryExecuteTask(t);//在当前线程执行Task
            }
        }

        protected override IEnumerable<Task> GetScheduledTasks()
        {
            return m_queue;
        }
        public BlockingCollection<Task> ScheduledTasks
        {
            get { return m_queue; }
        }
        protected override void QueueTask(Task task)
        {
            m_queue.Add(task);//t.Start(MyTaskScheduler.Current)时,将Task加入到队列中
        }

        //当执行该函数时,程序正在尝试以同步的方式执行Task代码
        protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
        {
            return false;
        }
    }
潘栩锋's avatar
潘栩锋 committed
990
}