LiteDB icon indicating copy to clipboard operation
LiteDB copied to clipboard

Cause I guess maybe it's inserted into the database table column contains null values, lead to find there was a problem or delete

Open pongor8 opened this issue 9 years ago • 9 comments

Hello, I'm using is 1.0.4.0 version I found a problem bothering me for a long time, thousands of users to use the database of the client, the total is 1 ‰ database, speaking, reading and writing mistakes, even lead to death cycle. Cause I guess maybe it's inserted into the database table column contains null values, lead to find there was a problem or delete. Issue log is as follows:

method:Contains messge: Value cannot be null.Parameter name: value stackTrace: at LiteDB.Query.Contains(String field, String value) at LiteDB.QueryVisitor1.VisitExpression(Expression expr) at LiteDB.QueryVisitor1.VisitExpression(Expression expr) at LiteDB.QueryVisitor1.Visit(Expression predicate) at LiteDB.LiteCollection1.Find(Expression1 predicate, Int32 skip, Int32 limit) at DrugCodeTrace.Core.Mongo.DB.Find[T](Expression1 selector)

method:ToList messge: Value cannot be null.Parameter name: source stackTrace: at System.Linq.Enumerable.ToList[TSource](IEnumerable1 source) at DrugCodeTrace.DAL.RelationCompanyExport.QueryReleationCompany(Expression1 predicate) at DrugCodeTrace.BLL.RelationCompany.QueryReleationCompany(Expression`1 predicate) at DrugCodeTrace.UC.InfoManagement.ContentDocument.ContentDocument.autoEnts_PatternChanged(Object sender, AutoCompleteArgs args) at DrugCodeTrace.FrameWorkControl.AutoComplete.<_interval_Elapsed>b__0() at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs) at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

method:AddNode message: Index was outside the bounds of the array. stackTrace: at LiteDB.IndexService.AddNode(CollectionIndex index, BsonValue key, Byte level) at LiteDB.IndexService.AddNode(CollectionIndex index, BsonValue key) at LiteDB.LiteCollection1.EnsureIndex(String field, IndexOptions options) at LiteDB.LiteCollection1.EnsureIndex(String field, Boolean unique) at LiteDB.Query.Run[T](LiteCollection1 collection) at LiteDB.QueryOr.Run[T](LiteCollection1 collection) at LiteDB.LiteCollection1.<Find>d__9.MoveNext() at System.Linq.Enumerable.Count[TSource](IEnumerable1 source) at lambda_method(Closure ) at System.Linq.EnumerableExecutor1.Execute() at System.Linq.EnumerableQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression) at System.Linq.Queryable.Count[TSource](IQueryable1 source) at DrugCodeTrace.Core.Mongo.DB.Find[T](Expression1 selector)

method:Delete message: The given key was not present in the dictionary. stackTrace: at LiteDB.LiteCollection1.Delete(Query query) at LiteDB.LiteCollection1.Delete(Expression1 predicate) at DrugCodeTrace.Core.Mongo.DB.Delete[T](Expression1 selector)

method:Read7BitEncodedInt message: Too many bytes in what should have been a 7 bit encoded Int32. stackTrace: at System.IO.BinaryReader.Read7BitEncodedInt() at System.IO.BinaryReader.ReadString() at LiteDB.CollectionPage.ReadContent(BinaryReader reader) at LiteDB.DiskService.<>c__DisplayClass11.<ReadPage>b__0() at LiteDB.DiskService.TryExec(TimeSpan timeout, Action action) at LiteDB.DiskService.ReadPage[T](UInt32 pageID) at LiteDB.PageService.GetPage[T](UInt32 pageID) at LiteDB.PageService.<GetSeqPages>d__01.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate) at LiteDB.CollectionService.Get(String name) at LiteDB.LiteDatabase.CollectionExists(String name) at DrugCodeTrace.Core.Mongo.DB.Find[T](Expression`1 selector)

pongor8 avatar Nov 23 '17 09:11 pongor8

Well, if you are using 1.0.4 you are note using tread-safe, so it's not possible share your LiteDatabase instance with multiple threads. Did you have a single database or multiple databases (on per user)?

mbdavid avatar Nov 24 '17 21:11 mbdavid

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;
using CodeTrace.Entity;
using LiteDB;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Diagnostics;

namespace CodeTrace.Core
{
    public partial class NoSql
    {
        public static bool AddRecord<T>(T obj) where T : class,new()
        {
            return Insert<T>(obj);
        }

        public static bool AddRecord<T>(List<T> listObj) where T : class,new()
        {
            return Insert<T>(listObj);
        }

        public static bool Insert<T>(T obj) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                db.Insert<T>(obj);
                return true;
            }
        }

        /// <summary>
        /// 插入对象列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public static bool Insert<T>(List<T> Listobj) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                db.Insert<T>(Listobj);
                return true;
            }
        }

        /// <summary>
        /// 更新对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filter"></param>
        public static void Update<T>(Expression<Func<T, bool>> selector, Expression<Func<T, T>> member, T newobj) where T : class,new()
        {
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filter"></param>
        public static bool Delete<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                db.Delete<T>(selector);
                return true;
            }
        }

        /// <summary>
        /// 全更新,发送整个对象更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public static void Save<T>(T obj) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                db.Save<T>(obj);
            }
        }

        /// <summary>
        /// 查询符合条件的列表,分页及排序可在返回结果中操作
        /// </summary>
        /// <typeparam name="T">要查询的类</typeparam>
        /// <param name="selector">过滤条件</param>
        /// <returns></returns>
        public static IQueryable<T> Query<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.Find<T>(selector);
            }
        }

        public static IQueryable<T> Query<T>(BsonArray array,string fieldName) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.Find<T>(array,fieldName);
            }
        }

        /// <summary>
        /// 查询表里是否存在数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static bool IsExistsData<T>() where T:class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.IsExistsData<T>();
            }
        }

        public static bool IsExistsData<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.IsExistsData<T>(selector);
            }
        }

        /// <summary>
        /// 查询符合条件的列表,分页及排序可在返回结果中操作
        /// </summary>
        /// <typeparam name="T">要查询的类</typeparam>
        /// <param name="selector">过滤条件</param>
        /// <returns></returns>
        public static IQueryable<T> Select<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.Find<T>(selector);
            }
        }

        /// <summary>
        /// 查询符合条件的列表,分页及排序可在返回结果中操作
        /// </summary>
        /// <typeparam name="T">要查询的类</typeparam>
        /// <param name="selector">过滤条件</param>
        /// <returns></returns>
        public static IEnumerable<T> SelectAll<T>() where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.FindAll<T>();
            }
        }

        /// <summary>
        /// 按照输入条件查找第一个符合条件的元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selector"></param>
        /// <returns></returns>
        public static T FindOne<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                return db.FindOne<T>(selector);
            }
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filter"></param>
        public static void DeleteAll<T>() where T : class,new()
        {
            using (Mongo.DB db = new Mongo.DB())
            {
                db.DeleteAll<T>();
            }
        }
    }
}

namespace CodeTrace.Core.Mongo
{
    public class DB : IDisposable
    {
        LiteDatabase db = null;
        public DB()
        {
            try
            {
                if (!System.IO.Directory.Exists("C:\\ProgramData\\CodeTraceData\\"))
                    System.IO.Directory.CreateDirectory("C:\\ProgramData\\CodeTraceData\\");

                string databasePath = @"C:\\ProgramData\\CodeTraceData\\" + SettingModel.Setting.OperIcCode + ".db";
                CleanupJournal(databasePath);

                if (db == null)
                    db = new LiteDatabase(databasePath);
            }
            catch (Exception ex)
            {
                ex.HandleException();
            }
        }

        private void CleanupJournal(string databasePath)
        {
            var file = databasePath.Replace(".db", "-journal.db");
            if (File.Exists(file))
                File.Delete(file);
        }

        public void Insert<T>(T obj) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                //获取 customers 集合,如果没有会创建,相当于表
                db.GetCollection<T>(typeName).Insert(obj);
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
            }
        }

        /// <summary>
        /// 插入对象列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public void Insert<T>(List<T> Listobj) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                db.GetCollection<T>(typeName).InsertBulk(Listobj);
                //db.GetCollection<T>(typeName).Insert(Listobj);
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
            }
        }

        /// <summary>
        /// 更新,发送整个对象更新
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        public void Save<T>(T obj) where T : class,new()
        {
            db.GetCollection<T>(ConvertInsertTypeName(typeof(T).ToString())).Insert(obj);
        }

        /// <summary>
        /// 删除对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filter"></param>
        public void Delete<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                var col = db.GetCollection<T>(typeName);
                if (db.CollectionExists(typeName))
                {
                    if (selector.Body.ToString() == "True")
                        col.DropIndex(typeName);
                    else
                        col.Delete(selector);
                }
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
            }
        }

        /// <summary>
        /// 清空对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filter"></param>
        public void DeleteAll<T>() where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                var col = db.GetCollection<T>(typeName);
                col.DropIndex(typeName);
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
            }
        }

        public IEnumerable<T> FindAll<T>() where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                var col = db.GetCollection<T>(typeName);
                return col.FindAll();
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
                return null;
            }
        }

        /// <summary>
        /// 按照输入条件查找第一个符合条件的元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="selector"></param>
        /// <returns></returns>
        public T FindOne<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            var col = db.GetCollection<T>(typeName);
            if (!db.CollectionExists(typeName))
            {
                return null;
            }
            return col.FindOne(selector);
        }

        public IQueryable<T> Find<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                List<T> _t = new List<T>();
                if (!db.CollectionExists(typeName))
                    return Queryable.AsQueryable<T>(_t);

                var col = db.GetCollection<T>(typeName);
                if (selector.Body.ToString() == "True")
                    return col.FindAll().ToList().AsQueryable();
                var results = col.Find(selector).AsQueryable();
                if (results == null || results.Count() < 1)
                    return Queryable.AsQueryable<T>(_t);
                return results.DefaultIfEmpty();
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
                return null;
            }
        }

        public IQueryable<T> Find<T>(BsonArray array,string fieldName) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                List<T> _t = new List<T>();
                if (!db.CollectionExists(typeName))
                    return Queryable.AsQueryable<T>(_t);

                var col = db.GetCollection<T>(typeName);
                var results = col.Find(Query.In(fieldName, array)).AsQueryable();
                if (results == null || results.Count() < 1)
                    return Queryable.AsQueryable<T>(_t);
                return results.DefaultIfEmpty();
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
                return null;
            }
        }

        public bool IsExistsData<T>() where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                List<T> _t = new List<T>();
                if (!db.CollectionExists(typeName))
                    return false;

                var col = db.GetCollection<T>(typeName);
                int count = col.Count(Query.All(1));
                if (count > 0)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
                return false;
            }
        }

        public bool IsExistsData<T>(Expression<Func<T, bool>> selector) where T : class,new()
        {
            string typeName = ConvertInsertTypeName(typeof(T).ToString());
            try
            {
                List<T> _t = new List<T>();
                if (!db.CollectionExists(typeName))
                    return false;

                var col = db.GetCollection<T>(typeName);
                int count = col.Count(selector);
                if (count > 0)
                    return true;
                return false;
            }
            catch (Exception ex)
            {
                ex.HandleException();
                LiteDbRenameCollection(db, typeName);
                return false;
            }
        }

        public void Dispose()
        {
            //db.Dispose();
        }

        public static void Init() { }

        public static void ReStart() { }

        private string ConvertInsertTypeName(string source)
        {
            switch (source)
            {
                case "CodeTrace.Entity.Models.EntPartner.EntPartnerUseStatistics"://往来单位
                    return "EntPartner_UseStatis";
                case "CodeTrace.Entity.Models.EntPartner.EntPartnerList"://往来单位更新
                    return "EntPartner_EntPartners";
                case "CodeTrace.Entity.Models.EntPartner.entDicts":
                    return "EntPartner_entDicts";
                case "CodeTrace.Entity.Models.DictRegion.DictRegionList"://行政区域更新
                    return "DictRegion_DictRegions";
                case "CodeTrace.Entity.Models.PhysicsName.PhysicNameList"://药品通用名更新
                    return "PhysicsName_PhysicsNames";
                case "CodeTrace.Entity.Models.DictList.DictCodeList"://数据字典更新
                    return "DictList_DictCodes";
                case "CodeTrace.Entity.Models.DictList.DictCodeTypeList"://数据字典类型更新
                    return "DictList_DictCodeTypes";
                case "CodeTrace.Entity.Models.EntInfo.Produceentdicttype"://生产厂商更新
                    return "EntInfo_Produceentdicttype";
                case "CodeTrace.Entity.Models.PhysicCategory.Product"://经营范围更新
                    return "PhysicCategory_Product";
                case "CodeTrace.Entity.Models.PhysicCategory.PhysicCategoryList"://药品目录列表
                    return "PhysicCategory_PhyCates";
                case "CodeTrace.Entity.Models.CodeUsedInfo.CodeUsedInfoLists"://药品基本信息查询
                    return "UsedInfo_CodeUsedInfoLists";

                case "CodeTrace.Entity.Models.InOrOutStoreUpload.PurchaseSaleReturnDocumnet.Document"://入出库
                    return "IO_SaleReturn";
                case "CodeTrace.Entity.Models.CodeRelation.CheckRelationFile.Document"://关联关系上传
                    return "Relation_Upload";

                case "CodeTrace.Entity.Models.DGColumnDisplayOrder"://DataGrid列索引
                    return "DGColumnDisplayOrder";
                case "CodeTrace.Entity.Models.InOrOutStoreUpload.PurchaseSaleReturnDocumnet.UploadedFiles"://DataGrid列索引
                    return "IO_UploadedFiles";
                default:
                    {
                        System.IO.File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "//NoDifTable.txt", source + "\r\n");
                        return "EmptyTableName";
                    }
            }
        }

        private void LiteDbRenameCollection(LiteDatabase db, string typeName)
        {
            switch (typeName)
            {
                case "IO_SaleReturn":
                    db.RenameCollection(typeName, "IO" + DateTime.Now.ToString("yyyyMMddhhmmss"));
                    break;
                case "Relation_Upload":
                    db.RenameCollection(typeName, "R" + DateTime.Now.ToString("yyyyMMddhhmmss"));
                    break;
                case "IO_UploadedFiles":
                    db.RenameCollection(typeName, "IO_UploadedFiles" + DateTime.Now.ToString("yyyyMMddhhmmss"));
                    break;
                default:
                    db.RenameCollection(typeName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    break;
            }
        }
    }
}

pongor8 avatar Nov 27 '17 03:11 pongor8

Ok, reading your code there is no problem with thread safe. You always create a new instance of database.

There is any similar environment to compare? Like same OS/Version? NTFS? .. It's a desktop app?

Also, I saw some inconsistency in your DB class

  • You are deleting -journal file. There is any issue with that?
  • In some cases your are droping index, not collection (like in DeleteAll).

Did you think in upgrade to lastest LiteDB version? This 1.x is quite old and much of bugs in this version was fixed in new versions.

mbdavid avatar Nov 27 '17 23:11 mbdavid

First of all, thank you very much for reply and help!Take up your precious time, thank you very much! 1, delete files - journal, because sometimes some users residues have this file, cannot use LiteDB again 2, I am in the desktop app applications, the operating system is Windows xp sp3 and above version, such as Windows 7, win10 3, I imagine upgrade to the latest v4.0 release version, but I existing user database, all data needs to be clear, to establish a new database, because the new version doesn't seem to have backward compatibility

I tried a new demo 1, fields, purposely column for a very long string 2, deliberately opened several threads at the same time insert, delete, select, and still there is no problem, up to "not add object references to the object instance" So, based on the existing version, can I have a better way to find out the problem?Because of the existing problems can't reproduce, and repetition. In addition, my desktop app has reached more than 6000 users, if after I updated to the new v4.0, will trigger a new unknown problem?Let users are not satisfied with our products said?

pongor8 avatar Nov 28 '17 01:11 pongor8

Hi @pongor8, there is no direct upgrade database from v1 to v4. To migrate your data you will need a console app using LiteDB v1 and v4, generation json file from v1 and importing in v4. But I understand your case: upgrade 6000 is not a easy job, can cause unknown problems...

In your case, to avoid concurrency problems, I can recommend you to keeps database opened always (do not open/close each operation). Re-use same LiteDatabase instance... BUT, very important: you must lock each database operation (insert/update/delete/find/...) (in find, don't forgot to use ToList() to get all documents).

Using C# locks are much better than lock by file (as LiteDB uses in v1). It's faster and has no NTFS/Operation system to communicate with.

mbdavid avatar Dec 01 '17 18:12 mbdavid

Hello teacher @mbdavid, I decided to use the latest version of the v4.0 release, each user of the local database data can be removed, the local data is only used for temporary storage, merely reduces the user experience. In addition, ask a few questions: 1, I existing code can be used directly?Such as existing, I each operation (add, delete, update, select) use to create an instance of using destroyed automatically after completion (if using) 2, I need to use a thread safe way?Create an instance only as you suggest, don't have to be destroyed, and use the lock with each operation to ensure that safety?

pongor8 avatar Dec 04 '17 01:12 pongor8

Hi @pongor8, almost all method are the same in v4. There are few differences like:

  • Always use EnsureIndex to create your indexes. In v1-3, LiteDB auto-create indexes if not exists. In v4 you need use EnsureIndex. You can see some examples here: https://github.com/mbdavid/LiteDB/issues/789
  • If your application are single process, use single instance in Exclusive mode (see connection string). That's faster way to read/write data in LiteDB. But, you can't open datafile in any other process (like shell tool) until you close your datafile.
  • Using this way, keeps your LiteDatabase instance in a single place and re-use it all times.

But if you want keeps your code as same, there is no problem. Simple operations like open/close/insert/update/delete/find keeps the same.

mbdavid avatar Dec 04 '17 20:12 mbdavid

OK, thank the teacher for help.

pongor8 avatar Dec 05 '17 03:12 pongor8

Hi! With the objective of organizing our issues, we are closing old unsolved issues. Please check the latest version of LiteDB and open a new issue if your problem/question/suggestion still applies. Thanks!

lbnascimento avatar Feb 06 '20 17:02 lbnascimento