-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathSingleFileTable.cs
More file actions
1123 lines (940 loc) · 35.7 KB
/
SingleFileTable.cs
File metadata and controls
1123 lines (940 loc) · 35.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
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
715
716
717
718
719
720
721
722
723
724
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
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
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
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
953
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
990
991
992
993
994
995
996
997
998
999
1000
// <copyright file="SingleFileTable.cs" company="MPCoreDeveloper">
// Copyright (c) 2025-2026 MPCoreDeveloper and GitHub Copilot. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
// </copyright>
namespace SharpCoreDB;
using SharpCoreDB.DataStructures;
using SharpCoreDB.Interfaces;
using SharpCoreDB.Optimizations;
using SharpCoreDB.Services;
using SharpCoreDB.Storage;
using SharpCoreDB.Storage.Hybrid;
using SharpCoreDB.Storage.Scdb;
using StorageModeHybrid = SharpCoreDB.Storage.Hybrid.StorageMode;using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Runtime.InteropServices;
/// <summary>
/// Table implementation for single-file storage.
/// Uses an in-memory cache with explicit flush to the storage provider.
/// ✅ CRITICAL FIX: Transaction-aware cache to support proper rollback semantics.
/// </summary>
public sealed class SingleFileTable(string tableName, IStorageProvider storageProvider) : ITable, ITableSchemaApplicator
{
private readonly IStorageProvider _storageProvider = storageProvider ?? throw new ArgumentNullException(nameof(storageProvider));
private readonly Lock _tableLock = new();
private readonly string _dataBlockName = $"table:{tableName}:data";
private List<Dictionary<string, object>> _rowCache = [];
private bool _cacheLoaded;
private bool _isDirty;
private long _nextId = 1;
// ✅ Transaction-aware cache snapshot for rollback support
private List<Dictionary<string, object>>? _transactionSnapshot;
private bool _isInTransaction;
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileTable"/> class from table metadata.
/// </summary>
/// <param name="tableName">Table name.</param>
/// <param name="storageProvider">Storage provider.</param>
/// <param name="metadata">Table metadata entry.</param>
public SingleFileTable(string tableName, IStorageProvider storageProvider, TableMetadataEntry metadata)
: this(tableName, storageProvider)
{
PrimaryKeyIndex = metadata.PrimaryKeyIndex;
LoadSchemaFromProvider(tableName);
// ✅ REMOVED: InitializeColumnMetadata() — LoadSchemaFromProvider now handles IsAuto/IsNotNull
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileTable"/> class with schema definition.
/// </summary>
/// <param name="tableName">Table name.</param>
/// <param name="columns">Column names.</param>
/// <param name="columnTypes">Column data types.</param>
/// <param name="storageProvider">Storage provider.</param>
public SingleFileTable(string tableName, List<string> columns, List<DataType> columnTypes, IStorageProvider storageProvider)
: this(tableName, storageProvider)
{
ArgumentNullException.ThrowIfNull(columns);
ArgumentNullException.ThrowIfNull(columnTypes);
Columns = columns;
ColumnTypes = columnTypes;
InitializeColumnMetadata();
}
/// <summary>
/// Initializes a new instance of the <see cref="SingleFileTable"/> class with full schema definition
/// including primary key, NOT NULL, and AUTOINCREMENT constraints.
/// </summary>
/// <param name="tableName">Table name.</param>
/// <param name="columns">Column names.</param>
/// <param name="columnTypes">Column data types.</param>
/// <param name="primaryKeyIndex">Index of the primary key column (-1 if none).</param>
/// <param name="isNotNull">NOT NULL constraint per column.</param>
/// <param name="isAuto">AUTOINCREMENT flag per column.</param>
/// <param name="storageProvider">Storage provider.</param>
public SingleFileTable(string tableName, List<string> columns, List<DataType> columnTypes,
int primaryKeyIndex, List<bool> isNotNull, List<bool> isAuto, IStorageProvider storageProvider)
: this(tableName, storageProvider)
{
ArgumentNullException.ThrowIfNull(columns);
ArgumentNullException.ThrowIfNull(columnTypes);
Columns = columns;
ColumnTypes = columnTypes;
PrimaryKeyIndex = primaryKeyIndex;
// Copy constraint lists
IsNotNull.Clear();
IsNotNull.AddRange(isNotNull);
IsAuto.Clear();
IsAuto.AddRange(isAuto);
InitializeColumnMetadata();
}
/// <inheritdoc />
public string Name { get; set; } = tableName;
/// <inheritdoc />
public List<string> Columns { get; set; } = [];
/// <inheritdoc />
public List<DataType> ColumnTypes { get; set; } = [];
/// <inheritdoc />
public string DataFile { get; set; } = storageProvider.RootPath;
/// <inheritdoc />
public int PrimaryKeyIndex { get; set; } = -1;
/// <inheritdoc />
public bool HasInternalRowId { get; set; }
/// <inheritdoc />
/// <remarks>Single-file tables store this for schema compatibility with the shared DDL path;
/// the actual value does not affect storage engine behaviour.</remarks>
public StorageModeHybrid StorageMode { get; set; } = StorageModeHybrid.Columnar;
/// <inheritdoc />
/// <remarks>Single-file tables do not use a standalone B-tree PK index;
/// the setter is accepted but the value is unused at runtime.</remarks>
public IIndex<string, long> Index { get; set; } = new NullIndex();
/// <inheritdoc />
public List<string?> DefaultExpressions { get; set; } = [];
/// <inheritdoc />
public List<string?> ColumnCheckExpressions { get; set; } = [];
/// <inheritdoc />
public List<string> TableCheckConstraints { get; set; } = [];
/// <inheritdoc />
public List<bool> IsAuto { get; set; } = [];
/// <inheritdoc />
public List<bool> IsNotNull { get; set; } = [];
/// <inheritdoc />
public List<object?> DefaultValues { get; set; } = [];
/// <inheritdoc />
public List<ForeignKeyConstraint> ForeignKeys { get; set; } = [];
/// <inheritdoc />
public List<List<string>> UniqueConstraints { get; set; } = [];
/// <inheritdoc />
public List<CollationType> ColumnCollations { get; set; } = [];
/// <inheritdoc />
public List<string?> ColumnLocaleNames { get; set; } = [];
/// <summary>
/// Gets or sets whether changes are automatically flushed to disk after each operation.
/// </summary>
public bool AutoFlush { get; set; } = true;
/// <inheritdoc />
public void Insert(Dictionary<string, object> row)
{
ArgumentNullException.ThrowIfNull(row);
EnsureCacheLoaded();
lock (_tableLock)
{
ApplyDefaults(row);
_rowCache.Add(row);
_isDirty = true;
}
// ✅ CRITICAL FIX: Only flush if not in transaction
if (AutoFlush && !_isInTransaction)
{
FlushCache();
}
}
/// <inheritdoc />
public long[] InsertBatch(List<Dictionary<string, object>> rows)
{
ArgumentNullException.ThrowIfNull(rows);
if (rows.Count == 0) return [];
EnsureCacheLoaded();
var positions = new long[rows.Count];
lock (_tableLock)
{
for (int i = 0; i < rows.Count; i++)
{
var row = rows[i];
ApplyDefaults(row);
_rowCache.Add(row);
positions[i] = _rowCache.Count - 1;
}
_isDirty = true;
}
// ✅ CRITICAL FIX: Only flush if not in transaction
if (AutoFlush && !_isInTransaction)
{
FlushCache();
}
return positions;
}
/// <inheritdoc />
public long[] InsertBatchFromBuffer(ReadOnlySpan<byte> encodedData, int rowCount)
{
if (rowCount < 0) throw new ArgumentOutOfRangeException(nameof(rowCount));
if (rowCount == 0) return [];
if (encodedData.IsEmpty) throw new ArgumentException("Encoded data buffer is empty", nameof(encodedData));
var decoder = new BinaryRowDecoder(Columns, ColumnTypes);
var rows = decoder.DecodeRows(encodedData, rowCount);
return InsertBatch(rows);
}
/// <inheritdoc />
public List<Dictionary<string, object>> Select(string? where = null, string? orderBy = null, bool asc = true)
=> Select(where, orderBy, asc, noEncrypt: false);
/// <inheritdoc />
public List<Dictionary<string, object>> Select(string? where, string? orderBy, bool asc, bool noEncrypt)
{
EnsureCacheLoaded();
// Strip leading WHERE keyword if present
var condition = where?.Trim();
if (condition is not null && condition.StartsWith("WHERE ", StringComparison.OrdinalIgnoreCase))
{
condition = condition[6..].Trim();
}
List<Dictionary<string, object>> results;
lock (_tableLock)
{
results = _rowCache.Select(row => new Dictionary<string, object>(row)).ToList();
}
if (!string.IsNullOrWhiteSpace(condition))
{
results = results.Where(row => EvaluateCondition(row, condition)).ToList();
}
if (!string.IsNullOrWhiteSpace(orderBy))
{
results = asc
? results.OrderBy(row => row.TryGetValue(orderBy, out var value) ? value : null).ToList()
: results.OrderByDescending(row => row.TryGetValue(orderBy, out var value) ? value : null).ToList();
}
return results;
}
/// <inheritdoc />
public void Update(string? where, Dictionary<string, object> updates)
{
ArgumentNullException.ThrowIfNull(updates);
EnsureCacheLoaded();
// Strip leading WHERE keyword if present
var condition = where?.Trim();
if (condition is not null && condition.StartsWith("WHERE ", StringComparison.OrdinalIgnoreCase))
{
condition = condition[6..].Trim();
}
lock (_tableLock)
{
foreach (var row in _rowCache)
{
if (string.IsNullOrWhiteSpace(condition) || EvaluateCondition(row, condition))
{
foreach (var update in updates)
{
row[update.Key] = update.Value;
}
_isDirty = true;
}
}
}
// ✅ CRITICAL FIX: Only flush if not in transaction
if (AutoFlush && _isDirty && !_isInTransaction)
{
FlushCache();
}
}
/// <summary>
/// Executes batch updates keyed by primary key value.
/// </summary>
/// <param name="updates">Dictionary of primary key to update values.</param>
public void UpdateBatch(Dictionary<object, Dictionary<string, object>> updates)
{
ArgumentNullException.ThrowIfNull(updates);
EnsureCacheLoaded();
if (PrimaryKeyIndex < 0) return;
var pkColumn = Columns[PrimaryKeyIndex];
lock (_tableLock)
{
foreach (var row in _rowCache)
{
if (!row.TryGetValue(pkColumn, out var pkValue) || pkValue is null)
{
continue;
}
if (!updates.TryGetValue(pkValue, out var rowUpdates))
{
continue;
}
foreach (var update in rowUpdates)
{
row[update.Key] = update.Value;
}
_isDirty = true;
}
}
// ✅ CRITICAL FIX: Only flush if not in transaction
if (AutoFlush && _isDirty && !_isInTransaction)
{
FlushCache();
}
}
/// <inheritdoc />
public void Delete(string? where)
{
EnsureCacheLoaded();
// Strip leading WHERE keyword if present
var condition = where?.Trim();
if (condition is not null && condition.StartsWith("WHERE ", StringComparison.OrdinalIgnoreCase))
{
condition = condition[6..].Trim();
}
lock (_tableLock)
{
if (string.IsNullOrWhiteSpace(condition))
{
_rowCache.Clear();
}
else
{
_rowCache.RemoveAll(row => EvaluateCondition(row, condition));
}
_isDirty = true;
}
// ✅ CRITICAL FIX: Only flush if not in transaction
if (AutoFlush && !_isInTransaction)
{
FlushCache();
}
}
/// <inheritdoc />
public Dictionary<string, object>? FindByPrimaryKey(object key) => null;
/// <inheritdoc />
public List<Dictionary<string, object>> FindByIndex(string column, object value) => [];
/// <inheritdoc />
public bool UpdateByPrimaryKey(object key, Dictionary<string, object> updates) => false;
/// <inheritdoc />
public bool DeleteByPrimaryKey(object key) => false;
/// <summary>
/// Flushes the in-memory row cache to the storage provider.
/// </summary>
public void FlushCache()
{
if (!_isDirty)
{
return;
}
List<Dictionary<string, object?>> serializableRows;
lock (_tableLock)
{
serializableRows = _rowCache.Select(ToSerializableRow).ToList();
_isDirty = false;
}
// Serialize to byte array to get exact length
var jsonBytes = JsonSerializer.SerializeToUtf8Bytes(serializableRows);
// Write using WriteBlockAsync to properly track data length
_storageProvider.WriteBlockAsync(_dataBlockName, jsonBytes).GetAwaiter().GetResult();
}
/// <summary>
/// Forces a reload of the row cache from storage, discarding any in-memory state.
/// This is used after transaction commit/rollback to ensure queries see the persisted state.
/// </summary>
public void ReloadFromStorage()
{
lock (_tableLock)
{
_cacheLoaded = false;
_rowCache.Clear();
_isDirty = false;
EnsureCacheLoaded();
}
}
/// <inheritdoc />
public void CreateHashIndex(string columnName) { }
/// <inheritdoc />
public void CreateHashIndex(string indexName, string columnName, bool isUnique = false) { }
/// <inheritdoc />
public bool HasHashIndex(string columnName) => false;
/// <inheritdoc />
public (int UniqueKeys, int TotalRows, double AvgRowsPerKey)? GetHashIndexStatistics(string columnName) => null;
/// <inheritdoc />
public void IncrementColumnUsage(string columnName)
{
if (string.IsNullOrWhiteSpace(columnName)) return;
_columnUsage[columnName] = _columnUsage.TryGetValue(columnName, out var count) ? count + 1 : 1;
}
/// <inheritdoc />
public IReadOnlyDictionary<string, long> GetColumnUsage() => new Dictionary<string, long>(_columnUsage);
/// <inheritdoc />
public void TrackAllColumnsUsage()
{
foreach (var column in Columns)
{
IncrementColumnUsage(column);
}
}
/// <inheritdoc />
public void TrackColumnUsage(string columnName) => IncrementColumnUsage(columnName);
/// <inheritdoc />
public bool RemoveHashIndex(string columnName) => false;
/// <inheritdoc />
public void ClearAllIndexes() { }
/// <inheritdoc />
public long GetCachedRowCount() => _rowCache.Count;
/// <inheritdoc />
public void RefreshRowCount() { }
/// <inheritdoc />
public void CreateBTreeIndex(string columnName) { }
/// <inheritdoc />
public void CreateBTreeIndex(string indexName, string columnName, bool isUnique = false) { }
/// <inheritdoc />
public bool HasBTreeIndex(string columnName) => false;
/// <inheritdoc />
public bool RemoveBTreeIndex(string columnName) => false;
/// <inheritdoc />
public void SetDatabase(Database database) { }
private readonly Dictionary<string, long> _columnUsage = new(StringComparer.OrdinalIgnoreCase);
private void EnsureCacheLoaded()
{
if (_cacheLoaded)
{
return;
}
lock (_tableLock)
{
if (_cacheLoaded)
{
return;
}
using var stream = _storageProvider.GetReadStream(_dataBlockName);
if (stream is null)
{
_rowCache = [];
_cacheLoaded = true;
return;
}
// Read the stream into bytes and trim trailing null bytes
using var memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
var jsonBytes = memoryStream.ToArray();
// Trim trailing null bytes
var endIndex = jsonBytes.Length;
while (endIndex > 0 && jsonBytes[endIndex - 1] == 0)
{
endIndex--;
}
if (endIndex == 0)
{
_rowCache = [];
_cacheLoaded = true;
return;
}
var trimmedJsonBytes = jsonBytes.AsSpan(0, endIndex);
var rows = JsonSerializer.Deserialize<List<Dictionary<string, object?>>>(trimmedJsonBytes);
_rowCache = rows?.Select(FromSerializableRow).ToList() ?? [];
_cacheLoaded = true;
}
}
private void LoadSchemaFromProvider(string tableName)
{
if (_storageProvider is not SingleFileStorageProvider provider)
{
return;
}
var columnDefs = provider.TableDirectoryManager.GetColumnDefinitions(tableName);
var columns = new List<string>(columnDefs.Count);
var types = new List<DataType>(columnDefs.Count);
var isAuto = new List<bool>(columnDefs.Count);
var isNotNull = new List<bool>(columnDefs.Count);
foreach (var entry in columnDefs)
{
columns.Add(GetColumnName(entry));
types.Add((DataType)entry.DataType);
isAuto.Add((entry.Flags & (uint)ColumnFlags.AutoIncrement) != 0);
isNotNull.Add((entry.Flags & (uint)ColumnFlags.NotNull) != 0);
if ((entry.Flags & (uint)ColumnFlags.PrimaryKey) != 0)
{
PrimaryKeyIndex = columns.Count - 1;
}
}
Columns = columns;
ColumnTypes = types;
IsAuto = isAuto;
IsNotNull = isNotNull;
}
private void InitializeColumnMetadata()
{
IsAuto.Clear();
IsNotNull.Clear();
DefaultValues.Clear();
ColumnCollations.Clear();
ColumnLocaleNames.Clear();
for (int i = 0; i < Columns.Count; i++)
{
IsAuto.Add(false);
IsNotNull.Add(false);
DefaultValues.Add(null);
ColumnCollations.Add(CollationType.Binary);
ColumnLocaleNames.Add(null);
}
}
/// <summary>
/// ✅ CRITICAL FIX: Begins a table-level transaction by creating a snapshot of the current cache.
/// This allows rollback to restore the pre-transaction state.
/// </summary>
internal void BeginTransaction()
{
lock (_tableLock)
{
if (_isInTransaction)
{
throw new InvalidOperationException($"Table {Name} is already in a transaction");
}
EnsureCacheLoaded();
// Deep copy the cache so rollback can restore the exact state
_transactionSnapshot = _rowCache.Select(row => new Dictionary<string, object>(row)).ToList();
_isInTransaction = true;
}
}
/// <summary>
/// ✅ CRITICAL FIX: Commits the transaction by flushing changes to storage and clearing the snapshot.
/// </summary>
internal void CommitTransaction()
{
lock (_tableLock)
{
if (!_isInTransaction)
{
throw new InvalidOperationException($"Table {Name} is not in a transaction");
}
// Flush all pending changes to storage
if (_isDirty)
{
FlushCache();
}
_transactionSnapshot = null;
_isInTransaction = false;
}
}
/// <summary>
/// ✅ CRITICAL FIX: Rolls back the transaction by restoring the cache from the snapshot.
/// </summary>
internal void RollbackTransaction()
{
lock (_tableLock)
{
if (!_isInTransaction)
{
throw new InvalidOperationException($"Table {Name} is not in a transaction");
}
// Restore the cache to the snapshot state
if (_transactionSnapshot is not null)
{
_rowCache = _transactionSnapshot.Select(row => new Dictionary<string, object>(row)).ToList();
}
_transactionSnapshot = null;
_isInTransaction = false;
_isDirty = false; // Clear dirty flag since we discarded changes
}
}
private void ApplyDefaults(Dictionary<string, object> row)
{
for (int i = 0; i < Columns.Count; i++)
{
var col = Columns[i];
if (!row.ContainsKey(col))
{
// Check IsAuto flag, with fallback to PrimaryKeyIndex for AUTO PK columns
bool shouldAuto = (IsAuto.Count > i && IsAuto[i]) ||
(i == PrimaryKeyIndex && PrimaryKeyIndex >= 0);
if (shouldAuto)
{
row[col] = GenerateAutoValue(ColumnTypes[i]);
}
else if (DefaultValues.Count > i)
{
row[col] = DefaultValues[i] ?? DBNull.Value;
}
else
{
row[col] = DBNull.Value;
}
}
}
}
private object GenerateAutoValue(DataType type)
{
var nextValue = _nextId++;
return type switch
{
DataType.Integer => (int)nextValue,
DataType.Long => nextValue,
_ => nextValue
};
}
/// <inheritdoc />
public void Flush() => FlushCache();
/// <inheritdoc />
/// <remarks>No-op for single-file tables: the storage provider handles all I/O.</remarks>
public void InitializeStorageEngine() { }
/// <inheritdoc />
/// <remarks>Single-file tables have no named index registry; always returns false.</remarks>
public bool HasIndex(string nameOrColumn) => false;
/// <inheritdoc />
/// <remarks>
/// Applies a DDL-parsed schema to this single-file table.
/// The data file path and storage-engine-specific fields (StorageMode, Index) are
/// stored for schema completeness but do not affect runtime behaviour since
/// the storage provider manages all persistence.
/// </remarks>
public void ApplySchema(TableSchemaDefinition schema)
{
ArgumentNullException.ThrowIfNull(schema);
Columns = schema.Columns;
ColumnTypes = schema.ColumnTypes;
IsAuto = schema.IsAuto;
PrimaryKeyIndex = schema.PrimaryKeyIndex;
HasInternalRowId = schema.HasInternalRowId;
DataFile = schema.DataFilePath;
StorageMode = schema.StorageMode;
IsNotNull = schema.IsNotNull;
DefaultValues = schema.DefaultValues;
UniqueConstraints = schema.UniqueConstraints;
ForeignKeys = schema.ForeignKeys;
DefaultExpressions = schema.DefaultExpressions;
ColumnCheckExpressions = schema.ColumnCheckExpressions;
TableCheckConstraints = schema.TableCheckConstraints;
ColumnCollations = schema.ColumnCollations;
ColumnLocaleNames = schema.ColumnLocaleNames;
}
/// <inheritdoc />
public void AddColumn(ColumnDefinition columnDef)
{
ArgumentNullException.ThrowIfNull(columnDef);
var dataType = ParseDataType(columnDef.DataType);
Columns.Add(columnDef.Name);
ColumnTypes.Add(dataType);
IsAuto.Add(columnDef.IsAutoIncrement);
IsNotNull.Add(columnDef.IsNotNull);
DefaultValues.Add(columnDef.DefaultValue);
ColumnCollations.Add(columnDef.Collation);
ColumnLocaleNames.Add(columnDef.LocaleName);
if (columnDef.IsPrimaryKey)
{
PrimaryKeyIndex = Columns.Count - 1;
}
if (columnDef.IsUnique)
{
UniqueConstraints.Add([columnDef.Name]);
}
_isDirty = true;
if (AutoFlush)
{
FlushCache();
}
}
/// <inheritdoc />
public void DropColumn(string columnName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(columnName);
EnsureCacheLoaded();
lock (_tableLock)
{
var idx = Columns.FindIndex(c => c.Equals(columnName, StringComparison.OrdinalIgnoreCase));
if (idx < 0)
throw new InvalidOperationException($"Column '{columnName}' does not exist in table '{Name}'.");
// Cannot drop the primary key column
if (idx == PrimaryKeyIndex)
throw new InvalidOperationException($"Cannot drop primary key column '{columnName}'.");
// Update schema lists
Columns.RemoveAt(idx);
ColumnTypes.RemoveAt(idx);
if (idx < IsAuto.Count) IsAuto.RemoveAt(idx);
if (idx < IsNotNull.Count) IsNotNull.RemoveAt(idx);
if (idx < DefaultValues.Count) DefaultValues.RemoveAt(idx);
if (idx < DefaultExpressions.Count) DefaultExpressions.RemoveAt(idx);
if (idx < ColumnCheckExpressions.Count) ColumnCheckExpressions.RemoveAt(idx);
if (idx < ColumnCollations.Count) ColumnCollations.RemoveAt(idx);
if (idx < ColumnLocaleNames.Count) ColumnLocaleNames.RemoveAt(idx);
// Adjust primary key index
if (PrimaryKeyIndex > idx)
PrimaryKeyIndex--;
// Remove the column from all cached rows
foreach (var row in _rowCache)
{
var actualKey = row.Keys.FirstOrDefault(k => k.Equals(columnName, StringComparison.OrdinalIgnoreCase));
if (actualKey is not null)
row.Remove(actualKey);
}
// Remove from unique constraints
UniqueConstraints.RemoveAll(uc => uc.Any(c => c.Equals(columnName, StringComparison.OrdinalIgnoreCase)));
// Remove from foreign keys
ForeignKeys.RemoveAll(fk => fk.ColumnName.Equals(columnName, StringComparison.OrdinalIgnoreCase));
_isDirty = true;
}
if (AutoFlush)
FlushCache();
}
/// <inheritdoc />
public void RenameColumn(string oldName, string newName)
{
ArgumentException.ThrowIfNullOrWhiteSpace(oldName);
ArgumentException.ThrowIfNullOrWhiteSpace(newName);
EnsureCacheLoaded();
lock (_tableLock)
{
var idx = Columns.FindIndex(c => c.Equals(oldName, StringComparison.OrdinalIgnoreCase));
if (idx < 0)
throw new InvalidOperationException($"Column '{oldName}' does not exist in table '{Name}'.");
if (Columns.Any(c => c.Equals(newName, StringComparison.OrdinalIgnoreCase)))
throw new InvalidOperationException($"Column '{newName}' already exists in table '{Name}'.");
Columns[idx] = newName;
// Rename key in all cached rows
foreach (var row in _rowCache)
{
var actualKey = row.Keys.FirstOrDefault(k => k.Equals(oldName, StringComparison.OrdinalIgnoreCase));
if (actualKey is not null)
{
var val = row[actualKey];
row.Remove(actualKey);
row[newName] = val;
}
}
// Update unique constraints
foreach (var uc in UniqueConstraints)
{
for (int i = 0; i < uc.Count; i++)
if (uc[i].Equals(oldName, StringComparison.OrdinalIgnoreCase))
uc[i] = newName;
}
// Update foreign keys
foreach (var fk in ForeignKeys.Where(fk => fk.ColumnName.Equals(oldName, StringComparison.OrdinalIgnoreCase)))
fk.ColumnName = newName;
_isDirty = true;
}
if (AutoFlush)
FlushCache();
}
/// <inheritdoc />
public void SetMetadata(string key, object value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
ArgumentNullException.ThrowIfNull(value);
_metadata[key] = value;
}
/// <inheritdoc />
public object? GetMetadata(string key)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
return _metadata.TryGetValue(key, out var value) ? value : null;
}
/// <inheritdoc />
public bool RemoveMetadata(string key)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
return _metadata.Remove(key);
}
private readonly Dictionary<string, object> _metadata = new(StringComparer.OrdinalIgnoreCase);
private static DataType ParseDataType(string typeName)
=> typeName.ToUpperInvariant() switch
{
"INT" or "INTEGER" => DataType.Integer,
"LONG" or "BIGINT" => DataType.Long,
"REAL" or "FLOAT" or "DOUBLE" => DataType.Real,
"DECIMAL" or "NUMERIC" => DataType.Decimal,
"DATETIME" or "DATE" => DataType.DateTime,
"BOOL" or "BOOLEAN" => DataType.Boolean,
"BLOB" => DataType.Blob,
"GUID" => DataType.Guid,
"ULID" => DataType.Ulid,
_ => DataType.String
};
private static string GetColumnName(ColumnDefinitionEntry entry)
{
unsafe
{
ref var start = ref entry.ColumnName[0];
var span = MemoryMarshal.CreateReadOnlySpan(ref start, ColumnDefinitionEntry.MAX_COLUMN_NAME_LENGTH + 1);
var nullIndex = span.IndexOf((byte)0);
if (nullIndex >= 0)
{
span = span[..nullIndex];
}
return Encoding.UTF8.GetString(span);
}
}
private static bool EvaluateCondition(Dictionary<string, object> row, string condition)
{
var parts = condition.Split([" AND ", " and "], StringSplitOptions.RemoveEmptyEntries);
foreach (var part in parts)
{
if (!EvaluateSingleCondition(row, part.Trim()))
{
return false;
}
}
return true;
}
private static bool EvaluateSingleCondition(Dictionary<string, object> row, string condition)
{
var operators = new[] { ">=", "<=", "!=", "<>", "=", ">", "<" };
string? op = null;
int opIndex = -1;
foreach (var testOp in operators)
{
opIndex = condition.IndexOf(testOp, StringComparison.Ordinal);
if (opIndex >= 0)
{
op = testOp;
break;
}
}
if (op == null || opIndex < 0)
{
return true;
}
var columnName = condition[..opIndex].Trim();
var valueStr = condition[(opIndex + op.Length)..].Trim();
if (!row.TryGetValue(columnName, out var rowValue))
{
return false;
}
if ((valueStr.StartsWith('\'') && valueStr.EndsWith('\'')) ||
(valueStr.StartsWith('"') && valueStr.EndsWith('"')))
{
valueStr = valueStr[1..^1];
}
if (rowValue is int intVal && int.TryParse(valueStr, out var intCompare))
{
return op switch
{
"=" => intVal == intCompare,
"!=" or "<>" => intVal != intCompare,
">" => intVal > intCompare,
"<" => intVal < intCompare,
">=" => intVal >= intCompare,
"<=" => intVal <= intCompare,
_ => true
};
}
if (rowValue is long longVal && long.TryParse(valueStr, out var longCompare))
{
return op switch
{
"=" => longVal == longCompare,
"!=" or "<>" => longVal != longCompare,
">" => longVal > longCompare,
"<" => longVal < longCompare,
">=" => longVal >= longCompare,