refactor: Automatically add id column in BlueTableSchemaBuilder

This commit is contained in:
John Colvin committed 2025-11-19 00:36:56 -05:00
1 parent 12c6b367f4
commit aa740e786c
1 file changed
+18 -9
@@ -6,30 +6,39 @@ using BCG;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public class BlueTableSchemaBuilder : IEnumerable<(string, Type)> {
readonly string? tableName;
readonly List<(string Name, Type Type)> colDefs = new();
readonly bool autoAddId;
public BlueTableSchemaBuilder(string? tableName = null) =>
public BlueTableSchemaBuilder(string? tableName = null, bool autoAddId = true) {
this.tableName = tableName;
this.autoAddId = autoAddId;
}
public void Add((string Name, Type Type) tup) =>
Add(tup.Name, tup.Type);
colDefs.Add(tup);
public void Add<T>(string Name) =>
colDefs.Add((Name, typeof(T)));
public void Add<T>(string name) =>
colDefs.Add((name, typeof(T)));
public void Add(string Name, Type Type) =>
colDefs.Add((Name, Type));
public void Add(string name, Type type) =>
colDefs.Add((name, type));
public IEnumerator<(string, Type)> GetEnumerator() =>
colDefs.GetEnumerator();
public IBlueTableSchema ToSchema(string? tableName = null) {
var colInfos = new ColumnInfo[colDefs.Count];
for (int i = 0; i < colInfos.Length; i++) {
colInfos[i] = new(colDefs[i].Name, i, colDefs[i].Type);
bool prependIdCol = autoAddId && !colDefs.Any(c => c.Name == "id");
int offset = prependIdCol ? 1 : 0;
var colInfos = new ColumnInfo[colDefs.Count + offset];
if (prependIdCol) {
colInfos[0] = new("id", 0, typeof(int));
}
for (int i = 0; i < colDefs.Count; i++) {
colInfos[i + offset] = new(colDefs[i].Name, i + offset, colDefs[i].Type);
}
return new BlueTableSchema(colInfos, tableName ?? this.tableName);
}