From 5929e13dca43a991ab13a9ec700fe570ce94e7de Mon Sep 17 00:00:00 2001 From: Simon G Date: Fri, 13 Nov 2020 17:00:27 +0100 Subject: [PATCH] - handle Keys --- GBase/GBaseTable.cs | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/GBase/GBaseTable.cs b/GBase/GBaseTable.cs index 4a20a1a..6571f69 100644 --- a/GBase/GBaseTable.cs +++ b/GBase/GBaseTable.cs @@ -10,6 +10,7 @@ using System.Threading; using System.Threading.Tasks; using GBase.Api; using GBase.Attributes; +using GBase.Exceptions; using GBase.Factories; using GBase.FileHandling.Factories; using GBase.Helpers; @@ -66,6 +67,18 @@ namespace GBase /// public List Entries { get; } + private int CurrentLastKey + { + get + { + T lastEntry = Entries.LastOrDefault(); + if (lastEntry == null) + return -1; + + return lastEntry.Key; + } + } + /// /// Initialize this @@ -83,11 +96,13 @@ namespace GBase //TODO: Init columns list depending on GBaseColumnAttributes set for this GBaseTable foreach (var property in type.GetProperties()) { - GBaseColumnAttribute gBaseColumnAttribute = property.GetCustomAttribute(); + GBaseColumnAttribute gBaseColumnAttribute = property.GetCustomAttribute() ?? + property.GetAttributeFromInheritedInterfaces(); + if (gBaseColumnAttribute == null) continue; - IGBaseColumn gBaseColumn = _gBaseColumnFactory.Create(property.Name, property.PropertyType); + IGBaseColumn gBaseColumn = _gBaseColumnFactory.Create(property.Name, property.PropertyType, gBaseColumnAttribute.IsKey); AddColumn(gBaseColumn); } @@ -102,7 +117,7 @@ namespace GBase T entry = new T(); List parameters = new List(); - foreach (var column in Columns) + foreach (var column in Columns.Where(c => !c.IsKey)) { using IPoolItem dataHandlerItem = await _dataHandlerPool.RequestDataHandler(this, false, cancellationToken); @@ -112,8 +127,18 @@ namespace GBase typeof(T), column.Type, file.File, column.Name, cancellationToken)); } + + IGBaseColumn keyColumn = Columns.FirstOrDefault(c => c.IsKey); + if (keyColumn == null) + throw new MissingKeyColumnException(); + + GBaseKey key = new GBaseKey(); + using (IPoolItem dataHandlerItem = await _dataHandlerPool.RequestDataHandler(this, false, cancellationToken)) + { + key.Key = await dataHandlerItem.Use().GetValue(file.File, keyColumn.Name, cancellationToken); + } - entry.Initialize(parameters); + entry.Initialize(key, parameters); file.Entry = entry; Entries.Add(entry); @@ -158,6 +183,13 @@ namespace GBase /// True if successful, false if not public async Task AddEntry(T entry, CancellationToken cancellationToken) { + entry.Key ??= new GBaseKey(); + + if (entry.Key != -1) + throw new InvalidKeyException("Key of entry is already set. Make sure it is -1 when initializing."); + + entry.Key.Key = CurrentLastKey + 1; //set next possible key + Entries.Add(entry); using IGBaseFile file = _fileHandler.CreateEntryFile(entry, this);