-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCompositeTypeCache.cs
More file actions
406 lines (357 loc) · 14.4 KB
/
Copy pathCompositeTypeCache.cs
File metadata and controls
406 lines (357 loc) · 14.4 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
using System.Collections.Concurrent;
using Npgsql;
namespace NpgsqlRest;
/// <summary>
/// Metadata for a composite type including field names, types, and nested composite info.
/// </summary>
public class CompositeTypeMetadata
{
/// <summary>
/// Fully qualified type name, e.g., "public.my_type"
/// </summary>
public required string TypeName { get; init; }
/// <summary>
/// Field names in order, e.g., ["id", "name", "nested_val"]
/// </summary>
public required string[] FieldNames { get; init; }
/// <summary>
/// Field type names in order, e.g., ["integer", "text", "public.inner_type"]
/// </summary>
public required string[] FieldTypeNames { get; init; }
/// <summary>
/// Converted field names using the name converter
/// </summary>
public string[]? ConvertedFieldNames { get; set; }
/// <summary>
/// Type descriptors for each field
/// </summary>
public TypeDescriptor[]? FieldDescriptors { get; set; }
/// <summary>
/// For each field, if it's a composite type, contains its metadata; null otherwise
/// </summary>
public CompositeTypeMetadata?[]? NestedFieldTypes { get; set; }
/// <summary>
/// For each field, true if the field is an array type
/// </summary>
public required bool[] IsArrayField { get; init; }
/// <summary>
/// For each field that is an array of composites, contains the element type metadata
/// </summary>
public CompositeTypeMetadata?[]? ArrayElementTypes { get; set; }
}
/// <summary>
/// Thread-safe cache for composite type metadata.
/// Used to resolve nested composite types for deep JSON serialization.
/// </summary>
public static class CompositeTypeCache
{
private static readonly ConcurrentDictionary<string, CompositeTypeMetadata> _cache = new(StringComparer.Ordinal);
private static readonly object _initLock = new();
private static volatile bool _initialized = false;
private static Func<string, string?>? _nameConverter;
/// <summary>
/// SQL query to fetch all composite types and their fields.
/// </summary>
private const string TypeQuery = """
select
(quote_ident(n.nspname) || '.' || quote_ident(t.typname))::regtype::text as type_name,
a.attnum as field_pos,
a.attname as field_name,
pg_catalog.format_type(a.atttypid, a.atttypmod) as field_type,
ft.typrelid <> 0 as is_field_composite,
a.atttypid = any(array(select oid from pg_type where typelem <> 0)) as is_array,
case
when ft.typelem <> 0 then
(select eft.typrelid <> 0
from pg_catalog.pg_type eft
where eft.oid = ft.typelem)
else false
end as is_array_of_composite
from pg_catalog.pg_type t
join pg_catalog.pg_namespace n on n.oid = t.typnamespace
join pg_catalog.pg_class c on t.typrelid = c.oid and c.relkind in ('r', 'c')
join pg_catalog.pg_attribute a on t.typrelid = a.attrelid
and a.attisdropped is false and a.attnum > 0
left join pg_catalog.pg_type ft on a.atttypid = ft.oid
where n.nspname not like 'pg_%'
and n.nspname <> 'information_schema'
and has_schema_privilege(current_user, n.nspname, 'USAGE')
order by type_name, field_pos
""";
/// <summary>
/// Initialize the composite type cache from the database.
/// Thread-safe and idempotent - only loads once.
/// </summary>
/// <param name="connection">Open database connection</param>
/// <param name="nameConverter">Name converter function for field names</param>
public static void Initialize(NpgsqlConnection connection, Func<string, string?>? nameConverter = null)
{
if (_initialized) return;
lock (_initLock)
{
if (_initialized) return;
_nameConverter = nameConverter;
LoadAllCompositeTypes(connection);
ResolveNestedTypes();
_initialized = true;
}
}
/// <summary>
/// Clear the cache. Useful for testing or when schema changes.
/// </summary>
public static void Clear()
{
lock (_initLock)
{
_cache.Clear();
_initialized = false;
_nameConverter = null;
}
}
/// <summary>
/// Check if the cache is initialized.
/// </summary>
public static bool IsInitialized => _initialized;
/// <summary>
/// Get metadata for a composite type by name.
/// </summary>
/// <param name="typeName">Type name (e.g., "public.my_type" or "my_type")</param>
/// <returns>Composite type metadata, or null if not a composite type</returns>
public static CompositeTypeMetadata? GetType(string? typeName)
{
if (string.IsNullOrEmpty(typeName)) return null;
return FindInCache(typeName);
}
/// <summary>
/// Get metadata for the element type of an array of composites.
/// </summary>
/// <param name="arrayTypeName">Array type name (e.g., "public.my_type[]")</param>
/// <returns>Element composite type metadata, or null if not an array of composites</returns>
public static CompositeTypeMetadata? GetArrayElementType(string? arrayTypeName)
{
if (string.IsNullOrEmpty(arrayTypeName)) return null;
// Strip array suffix(es) - handles both [] and [][] etc.
var elementTypeName = arrayTypeName;
while (elementTypeName.EndsWith("[]", StringComparison.Ordinal))
{
elementTypeName = elementTypeName[..^2];
}
return GetType(elementTypeName);
}
/// <summary>
/// Resolve composite type metadata for a TypeDescriptor.
/// Sets CompositeFieldNames/CompositeFieldDescriptors if the type is a composite,
/// or ArrayCompositeFieldNames/ArrayCompositeFieldDescriptors if it's an array of composites.
/// Can be called from plugins since TypeDescriptor setters are internal.
/// </summary>
/// <param name="descriptor">The TypeDescriptor to resolve</param>
/// <returns>True if the descriptor was resolved as a composite or array of composites</returns>
public static bool ResolveTypeDescriptor(TypeDescriptor descriptor)
{
var compositeMetadata = GetType(descriptor.OriginalType);
if (compositeMetadata != null)
{
descriptor.CompositeFieldNames = compositeMetadata.ConvertedFieldNames;
descriptor.CompositeFieldDescriptors = compositeMetadata.FieldDescriptors;
return true;
}
if (descriptor.IsArray)
{
var elementMetadata = GetArrayElementType(descriptor.OriginalType);
if (elementMetadata != null)
{
descriptor.ArrayCompositeFieldNames = elementMetadata.ConvertedFieldNames;
descriptor.ArrayCompositeFieldDescriptors = elementMetadata.FieldDescriptors;
return true;
}
}
return false;
}
/// <summary>
/// Normalize type name by removing quotes and handling schema prefixes.
/// </summary>
private static string NormalizeTypeName(string typeName)
{
// Remove surrounding quotes if present
var result = typeName.Trim();
if (result.StartsWith('"') && result.EndsWith('"'))
{
result = result[1..^1];
}
// Handle quoted identifiers within the name
result = result.Replace("\"", "");
return result;
}
/// <summary>
/// Try to find a type in the cache, also trying without schema prefix.
/// PostgreSQL regtype::text omits the public schema, but other sources may include it.
/// </summary>
private static CompositeTypeMetadata? FindInCache(string typeName)
{
var normalized = NormalizeTypeName(typeName);
if (_cache.TryGetValue(normalized, out var result))
{
return result;
}
// Try stripping schema prefix (e.g., "public.my_type" → "my_type")
int dotIndex = normalized.IndexOf('.');
if (dotIndex >= 0)
{
var withoutSchema = normalized[(dotIndex + 1)..];
if (_cache.TryGetValue(withoutSchema, out result))
{
return result;
}
}
return null;
}
/// <summary>
/// Load all composite types from the database into the cache.
/// </summary>
private static void LoadAllCompositeTypes(NpgsqlConnection connection)
{
using var command = connection.CreateCommand();
command.CommandText = TypeQuery;
command.LogCommand(nameof(CompositeTypeCache));
using var reader = command.ExecuteReader();
// Group rows by type name to build metadata
string? currentTypeName = null;
var fieldNames = new List<string>();
var fieldTypes = new List<string>();
var isArrayField = new List<bool>();
var isFieldComposite = new List<bool>();
var isArrayOfComposite = new List<bool>();
while (reader.Read())
{
var typeName = reader.GetString(0);
// If we've moved to a new type, save the previous one
if (currentTypeName != null && typeName != currentTypeName)
{
SaveTypeMetadata(currentTypeName, fieldNames, fieldTypes, isArrayField, isFieldComposite, isArrayOfComposite);
fieldNames.Clear();
fieldTypes.Clear();
isArrayField.Clear();
isFieldComposite.Clear();
isArrayOfComposite.Clear();
}
currentTypeName = typeName;
fieldNames.Add(reader.GetString(2));
fieldTypes.Add(reader.GetString(3));
isArrayField.Add(reader.GetBoolean(5));
isFieldComposite.Add(reader.GetBoolean(4));
isArrayOfComposite.Add(reader.GetBoolean(6));
}
// Don't forget the last type
if (currentTypeName != null)
{
SaveTypeMetadata(currentTypeName, fieldNames, fieldTypes, isArrayField, isFieldComposite, isArrayOfComposite);
}
}
/// <summary>
/// Save a single type's metadata to the cache.
/// </summary>
private static void SaveTypeMetadata(
string typeName,
List<string> fieldNames,
List<string> fieldTypes,
List<bool> isArrayField,
List<bool> isFieldComposite,
List<bool> isArrayOfComposite)
{
var fieldNamesArray = fieldNames.ToArray();
var fieldTypesArray = fieldTypes.ToArray();
var count = fieldNamesArray.Length;
// Apply name converter
var convertedNames = new string[count];
for (var i = 0; i < count; i++)
{
convertedNames[i] = _nameConverter?.Invoke(fieldNamesArray[i]) ?? fieldNamesArray[i];
}
// Create type descriptors for each field
var descriptors = new TypeDescriptor[count];
for (var i = 0; i < count; i++)
{
descriptors[i] = new TypeDescriptor(fieldTypesArray[i]);
}
var metadata = new CompositeTypeMetadata
{
TypeName = typeName,
FieldNames = fieldNamesArray,
FieldTypeNames = fieldTypesArray,
ConvertedFieldNames = convertedNames,
FieldDescriptors = descriptors,
IsArrayField = isArrayField.ToArray(),
// These will be populated in ResolveNestedTypes()
NestedFieldTypes = new CompositeTypeMetadata?[count],
ArrayElementTypes = new CompositeTypeMetadata?[count]
};
var normalizedName = NormalizeTypeName(typeName);
_cache[normalizedName] = metadata;
}
/// <summary>
/// After all types are loaded, resolve nested type references.
/// Uses cycle detection to handle self-referencing types.
/// </summary>
private static void ResolveNestedTypes()
{
foreach (var metadata in _cache.Values)
{
var visited = new HashSet<string>(StringComparer.Ordinal);
ResolveNestedTypesForType(metadata, visited);
}
}
/// <summary>
/// Recursively resolve nested types for a single type.
/// </summary>
private static void ResolveNestedTypesForType(CompositeTypeMetadata metadata, HashSet<string> visited)
{
// Cycle detection
var normalizedName = NormalizeTypeName(metadata.TypeName);
if (!visited.Add(normalizedName))
{
return; // Already processing this type - circular reference
}
try
{
for (var i = 0; i < metadata.FieldTypeNames.Length; i++)
{
var fieldType = metadata.FieldTypeNames[i];
// Check if this field is a composite type
var nestedType = GetType(fieldType);
if (nestedType != null)
{
metadata.NestedFieldTypes![i] = nestedType;
// Also set the nested info on the TypeDescriptor
if (metadata.FieldDescriptors != null)
{
metadata.FieldDescriptors[i].CompositeFieldNames = nestedType.ConvertedFieldNames;
metadata.FieldDescriptors[i].CompositeFieldDescriptors = nestedType.FieldDescriptors;
}
// Recursively resolve (with cycle detection)
ResolveNestedTypesForType(nestedType, visited);
}
// Check if this field is an array of composites
if (metadata.IsArrayField[i])
{
var elementType = GetArrayElementType(fieldType);
if (elementType != null)
{
metadata.ArrayElementTypes![i] = elementType;
// Also set the array composite info on the TypeDescriptor
if (metadata.FieldDescriptors != null)
{
metadata.FieldDescriptors[i].ArrayCompositeFieldNames = elementType.ConvertedFieldNames;
metadata.FieldDescriptors[i].ArrayCompositeFieldDescriptors = elementType.FieldDescriptors;
}
// Recursively resolve the element type
ResolveNestedTypesForType(elementType, visited);
}
}
}
}
finally
{
visited.Remove(normalizedName);
}
}
}