Skip to content

Commit cba24c7

Browse files
Fix ORDER BY type comparison with custom comparer
Co-authored-by: MPCoreDeveloper <37024522+MPCoreDeveloper@users.noreply.github.com>
1 parent 8bd6484 commit cba24c7

File tree

2 files changed

+27
-2
lines changed

2 files changed

+27
-2
lines changed

SharpCoreDB.Tests/IndexTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,7 +197,7 @@ public void HashIndex_UpdateOperations_MaintainConsistency()
197197

198198
// Act - Update status
199199
var updatedRow = new Dictionary<string, object> { { "id", 1 }, { "status", "inactive" }, { "name", "Item1" } };
200-
index.Remove(rows[0]);
200+
index.Remove(rows[0], 0);
201201
index.Add(updatedRow, 0);
202202

203203
// Assert - Index should reflect changes

SharpCoreDB/DataStructures/Table.cs

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,10 +228,35 @@ private List<Dictionary<string, object>> SelectInternal(string? where, string? o
228228
{
229229
var idx = this.Columns.IndexOf(orderBy);
230230
if (idx >= 0)
231-
results = asc ? results.OrderBy(r => r[this.Columns[idx]]).ToList() : results.OrderByDescending(r => r[this.Columns[idx]]).ToList();
231+
{
232+
var columnName = this.Columns[idx];
233+
// Use Comparer<object>.Default which handles type mismatches gracefully
234+
results = asc
235+
? results.OrderBy(r => r[columnName], Comparer<object>.Create((a, b) => CompareObjects(a, b))).ToList()
236+
: results.OrderByDescending(r => r[columnName], Comparer<object>.Create((a, b) => CompareObjects(a, b))).ToList();
237+
}
232238
}
233239
return results;
234240
}
241+
242+
private static int CompareObjects(object? a, object? b)
243+
{
244+
// Handle nulls
245+
if (a == null && b == null) return 0;
246+
if (a == null) return -1;
247+
if (b == null) return 1;
248+
249+
// If same type, use default comparison
250+
if (a.GetType() == b.GetType())
251+
{
252+
if (a is IComparable ca)
253+
return ca.CompareTo(b);
254+
return 0;
255+
}
256+
257+
// Different types - compare as strings
258+
return string.Compare(a.ToString(), b.ToString(), StringComparison.Ordinal);
259+
}
235260

236261
/// <summary>
237262
/// SIMD-accelerated row scanning for full table scans.

0 commit comments

Comments
 (0)