Files

31 lines
1.9 KiB
C#

// Read-only DBCD exporter: supports sparse rows, copies, relationships and exact float bits.
using System.Text.Json;
using DBCD; using DBCD.IO; using DBCD.Providers;
static object Value(object value) {
if (value is float f) return new Dictionary<string, uint>{{"f32_bits",BitConverter.SingleToUInt32Bits(f)}};
if (value is Array a) return a.Cast<object>().Select(Value).ToArray();
return value;
}
var requests=JsonSerializer.Deserialize<Dictionary<string,int[]>>(File.ReadAllText(args[2]))!;
Directory.CreateDirectory(args[3]);
var report=new Dictionary<string,object>();
foreach(var (name,ids) in requests.OrderBy(kv=>kv.Key)) {
if(!System.Text.RegularExpressions.Regex.IsMatch(name,"^[A-Za-z][A-Za-z0-9_]+$")) throw new Exception("Invalid table name");
try {
var provider=new DBCD.DBCD(new FilesystemDBCProvider(args[0]),new FilesystemDBDProvider(args[1]));
var storage=provider.Load(name,"1.60.1.70334",Locale.EnUS);
int encrypted=storage.GetEncryptedSections().Values.Sum();
if(encrypted!=0) throw new Exception($"Unresolved encrypted rows: {encrypted}");
var rows=storage.ToDictionary();int found=0;
using(var output=new StreamWriter(Path.Combine(args[3],name+".jsonl"))) {
foreach(int id in (ids.Length==1 && ids[0]==-1 ? rows.Keys : ids.AsEnumerable()).Distinct().OrderBy(id=>id)) if(rows.TryGetValue(id,out var row)) {
var fields=row.GetDynamicMemberNames().ToDictionary(field=>field,field=>Value(row[field]));
output.WriteLine(JsonSerializer.Serialize(new {id,fields}));found++;
}
}
report[name]=new {count=storage.Count,selected=found,encryptedRows=encrypted};
} catch(Exception error) { report[name]=new {error=error.GetType().Name+": "+error.Message.Split('\n')[0]}; }
}
File.WriteAllText(Path.Combine(args[3],"reader.json"),JsonSerializer.Serialize(report));
Console.WriteLine($"Read-only DB2 export: {report.Count} tables");