Add: ファストマージ機能を追加

This commit is contained in:
Sakurai Ryota 2024-08-12 16:35:58 +09:00
parent d9e3e7bf3b
commit b7d9c4ea70
3 changed files with 60 additions and 5 deletions

8
IO/FastMergeType.cs Normal file
View File

@ -0,0 +1,8 @@
namespace DevJsonDB.IO;
public enum FastMergeType
{
None = 0,
Add = 2,
Remove = 4,
}

View File

@ -8,11 +8,13 @@ public class LocalStore<T> : IStore<T>
private static Encoding DefaultEncoding = Encoding.UTF8;
private string filePath;
private List<T> items;
private bool autoCommit;
public LocalStore(string filePath)
public LocalStore(string filePath, bool autoCommit)
{
this.filePath = filePath;
this.items = new List<T>();
this.autoCommit = autoCommit;
this.InitDatabase();
}
@ -32,10 +34,15 @@ public class LocalStore<T> : IStore<T>
fs.Seek(0, SeekOrigin.Begin);
fs.SetLength(0);
foreach (T item in this.items)
for (int i = 0 ; i < items.Count; i++)
{
T item = items[i];
string json = JsonSerializer.Serialize<T>(item);
writer.WriteLine(json);
writer.Write(json);
if (i != items.Count - 1)
{
writer.Write("\n");
}
}
}
}
@ -53,6 +60,7 @@ public class LocalStore<T> : IStore<T>
}
this.items.Add(item);
this.AutoCommit(FastMergeType.Add);
return true;
}
@ -63,7 +71,9 @@ public class LocalStore<T> : IStore<T>
public bool Remove(T item)
{
return this.items.Remove(item);
bool ret = this.items.Remove(item);
this.AutoCommit(FastMergeType.Remove);
return ret;
}
public IEnumerable<T> GetValues()
@ -71,6 +81,43 @@ public class LocalStore<T> : IStore<T>
return this.items.ToList();
}
private void AutoCommit(FastMergeType mergeType)
{
if (!this.autoCommit) return;
try
{
// Fast-Merge
switch (mergeType)
{
case FastMergeType.Add:
{
using (FileStream fs = new FileStream(this.filePath, FileMode.Append))
using (StreamWriter writer = new StreamWriter(fs, DefaultEncoding))
{
T lastItem = this.items.ElementAt(this.items.Count() - 1);
string json = JsonSerializer.Serialize<T>(lastItem);
if (fs.Length > 0)
{
writer.Write("\n");
}
writer.Write(json);
}
break;
}
case FastMergeType.Remove:
{
this.Commit();
break;
}
}
}
catch (Exception ex)
{
throw new JsonDBException(ex.Message, ex);
}
}
private void InitDatabase()
{
try

View File

@ -6,7 +6,7 @@ public static class JsonDBFactory
{
public static JsonDB<T> CreateDB<T>(string filePath)
{
IStore<T> store = new LocalStore<T>(filePath);
IStore<T> store = new LocalStore<T>(filePath, true);
return new JsonDB<T>(store);
}
}