{{ message }}
forked from NpgsqlRest/NpgsqlRest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSqlFileSource.cs
More file actions
864 lines (776 loc) · 36.4 KB
/
Copy pathSqlFileSource.cs
File metadata and controls
864 lines (776 loc) · 36.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
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
using System.Text.RegularExpressions;
using Npgsql;
using NpgsqlRest.HttpClientType;
namespace NpgsqlRest.SqlFileSource;
/// <summary>
/// Routine source that scans SQL files matching a glob pattern and generates REST API endpoints.
/// Each SQL file must contain exactly one statement (multi-statement support planned for a future version).
/// </summary>
public class SqlFileSource(SqlFileSourceOptions options) : IEndpointSource
{
private const string UnnamedColumnPrefix = "column";
public CommentsMode? CommentsMode { get; set; } = options.CommentsMode; // Always has a value from options default
public bool NestedJsonForCompositeTypes { get; set; } = false;
public IEnumerable<(Routine, IRoutineSourceParameterFormatter)> Read(
IServiceProvider? serviceProvider,
RetryStrategy? retryStrategy)
{
if (string.IsNullOrEmpty(options.FilePattern))
{
yield break;
}
var files = FindMatchingFiles(options.FilePattern, options.SkipPattern).ToArray();
if (files.Length == 0)
{
NpgsqlRestOptions.Logger?.LogWarning("SqlFileSource: No SQL files found matching pattern \"{FilePattern}\"", options.FilePattern);
yield break;
}
// Compute the base directory from the file pattern for subdirectory-as-schema resolution
var baseDir = GetBaseDirectory(options.FilePattern);
// Open a single connection for all Describe calls — same as RoutineSource and CrudSource
NpgsqlConnection? connection = null;
bool shouldDispose = true;
try
{
NpgsqlRestOptions.Options.CreateAndOpenSourceConnection(serviceProvider, ref connection, ref shouldDispose, nameof(SqlFileSource));
if (connection is null)
{
yield break;
}
var nameConverter = NpgsqlRestOptions.Options.NameConverter;
// Initialize composite type cache for custom type column resolution
CompositeTypeCache.Initialize(connection, nameConverter);
foreach (var filePath in files)
{
(Routine, IRoutineSourceParameterFormatter)? result = null;
try
{
result = ProcessFile(filePath, baseDir, connection, nameConverter, options);
}
catch (Exception ex)
{
NpgsqlRestOptions.Logger?.LogError("SqlFileSource: Error processing file {FilePath}: {Error}", filePath, ex.Message);
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
}
if (result is not null)
{
yield return result.Value;
}
}
}
finally
{
if (shouldDispose && connection is not null)
{
connection.Dispose();
}
}
}
private static (Routine, IRoutineSourceParameterFormatter)? ProcessFile(
string filePath,
string baseDir,
NpgsqlConnection connection,
Func<string?, string?> nameConverter,
SqlFileSourceOptions options)
{
var content = File.ReadAllText(filePath);
var parseResult = SqlFileParser.Parse(content, options.CommentScope);
// When CommentsMode gates endpoint creation (OnlyAnnotated, or its back-compat alias
// OnlyWithHttpTag), skip files without an HTTP tag BEFORE attempting to describe — avoids
// errors on non-endpoint SQL files (migrations, utility scripts, etc.). A file whose comment
// carries a plugin endpoint-requesting annotation (e.g. a bare `mcp` — an MCP-only tool) is an
// endpoint candidate too, so it passes the gate; the check stays textual and cheap, so scripts
// with neither are never described.
if (options.CommentsMode is NpgsqlRest.CommentsMode.OnlyWithHttpTag or NpgsqlRest.CommentsMode.OnlyAnnotated
&& !HasHttpTag(parseResult.Comment)
&& !HasEndpointRequestingAnnotation(parseResult.Comment))
{
return null;
}
// Check for parse errors
if (parseResult.Errors.Count > 0)
{
foreach (var error in parseResult.Errors)
{
NpgsqlRestOptions.Logger?.LogError("SqlFileSource: {FilePath}: {Error}", filePath, error);
}
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
return null;
}
if (parseResult.Statements.Count == 0)
{
return null;
}
// Named-parameter (:name) rewrite: placeholders become native $N before Describe/execution
// (PostgreSQL never sees the :name form); the names flow into parameter ActualName, so the API
// name — and claim mappings — come from the placeholder itself. Same name = same parameter,
// file-wide. Mixing $N and :name in one file is ambiguous and rejected.
var namedParams = SqlFileParser.RewriteNamedParameters(parseResult.Statements);
if (namedParams.HasNamed && namedParams.HasPositional)
{
NpgsqlRestOptions.Logger?.LogError(
"SqlFileSource: {FilePath}: mixing positional ($N) and named (:name) parameters in the same file is not supported — use one style.",
filePath);
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
return null;
}
IReadOnlyList<string>? namedList = namedParams.HasNamed ? namedParams.Names : null;
bool isMultiCommand = parseResult.Statements.Count > 1;
// Check @param annotations for HTTP client type parameters (single composite, no SQL rewriting)
Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>? httpTypeParams = null;
if (NpgsqlRestOptions.Options.HttpClientOptions.Enabled && HttpClientTypes.Definitions.Count > 0)
{
httpTypeParams = DetectHttpTypeParams(parseResult.Comment, connection, namedList);
}
// Check @param annotations for non-HTTP composite type parameters (single composite, no SQL rewriting)
var compositeTypeParams = DetectCompositeTypeParams(parseResult.Comment, connection, httpTypeParams, namedList);
// Describe each statement individually and merge parameters
int mergedMaxParam = 0;
var paramTypesByIndex = new Dictionary<int, string>(); // $N index → type name
var commandDescribes = new List<DescribeResult>();
var paramTypeHints = SqlFileParser.ExtractParamTypeHints(parseResult.Comment, namedList);
for (int stmtIndex = 0; stmtIndex < parseResult.Statements.Count; stmtIndex++)
{
var stmt = parseResult.Statements[stmtIndex];
int stmtParamCount = SqlFileDescriber.FindMaxParamIndex(stmt);
if (stmtParamCount > mergedMaxParam) mergedMaxParam = stmtParamCount;
// @returns type_name | void — skip Describe entirely
if (parseResult.ReturnsTypeOverrides.TryGetValue(stmtIndex, out var returnsTypeName))
{
// @returns void — skip Describe, no columns (void command)
if (string.Equals(returnsTypeName, "void", StringComparison.OrdinalIgnoreCase))
{
commandDescribes.Add(new DescribeResult { Columns = [] });
continue;
}
// Check if it's a known scalar type
var scalarDescriptor = new TypeDescriptor(returnsTypeName);
if (scalarDescriptor.DbType != NpgsqlTypes.NpgsqlDbType.Unknown)
{
// @returns scalar_type — single column with the given type
commandDescribes.Add(new DescribeResult
{
Columns = [new ColumnInfo { Name = returnsTypeName, DataTypeName = returnsTypeName }]
});
continue;
}
// Check if it's a known composite type
var compositeType = CompositeTypeCache.GetType(returnsTypeName);
if (compositeType is not null)
{
var returnsCols = new ColumnInfo[compositeType.FieldNames.Length];
for (int fi = 0; fi < compositeType.FieldNames.Length; fi++)
{
returnsCols[fi] = new ColumnInfo
{
Name = compositeType.FieldNames[fi],
DataTypeName = compositeType.FieldTypeNames[fi],
};
}
commandDescribes.Add(new DescribeResult { Columns = returnsCols });
continue;
}
var error = $"@returns type '{returnsTypeName}' is not a recognized PostgreSQL type or composite type.";
NpgsqlRestOptions.Logger?.LogError("SqlFileSource: {FilePath}: {Error}", filePath, error);
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
return null;
}
var describeResult = SqlFileDescriber.Describe(connection, stmt, stmtParamCount, paramTypeHints);
if (describeResult.HasError)
{
NpgsqlRestOptions.Logger?.LogError("SqlFileSource: {FilePath}:\n{Error}", filePath, describeResult.Error);
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
return null;
}
commandDescribes.Add(describeResult);
// Merge parameter types — if same $N has different types across statements, error
if (describeResult.ParameterTypes is not null)
{
for (int i = 0; i < describeResult.ParameterTypes.Length; i++)
{
var pType = describeResult.ParameterTypes[i];
if (pType == "unknown") continue;
if (paramTypesByIndex.TryGetValue(i, out var existing))
{
if (existing != "unknown" && existing != pType)
{
var error = $"Parameter ${i + 1} has conflicting types across statements: '{existing}' vs '{pType}'. Use @param annotation to override.";
NpgsqlRestOptions.Logger?.LogError("SqlFileSource: {FilePath}: {Error}", filePath, error);
if (options.ErrorMode == ParseErrorMode.Exit)
{
NpgsqlRestOptions.Logger?.LogCritical("SqlFileSource: Exiting due to SQL file error. Set ErrorMode to Skip to continue past errors.");
Environment.Exit(1);
}
return null;
}
}
else
{
paramTypesByIndex[i] = pType;
}
}
}
}
// Build merged parameters (real SQL params + virtual params from @define_param)
var virtualParams = parseResult.VirtualParams;
var totalParamCount = mergedMaxParam + virtualParams.Count;
var parameters = new NpgsqlRestParameter[totalParamCount];
for (int i = 0; i < mergedMaxParam; i++)
{
var typeName = paramTypesByIndex.GetValueOrDefault(i, "unknown");
// Named (:name) placeholder for this ordinal, when the file uses them.
string? placeholderName = namedList is not null && i < namedList.Count ? namedList[i] : null;
string? customType = null;
string? customTypeName = null;
short? customTypePosition = null;
string? originalParameterName = null;
string convertedName;
// HTTP custom type params: single composite parameter, no expansion
if (httpTypeParams is not null && httpTypeParams.TryGetValue(i, out var httpParam))
{
customType = httpParam.TypeName;
originalParameterName = $"${i + 1}";
convertedName = httpParam.ParamName;
typeName = "text"; // composite sent as text representation
}
// Non-HTTP composite type params: single composite parameter, no expansion
else if (compositeTypeParams is not null && compositeTypeParams.TryGetValue(i, out var compositeParam))
{
originalParameterName = $"${i + 1}";
convertedName = compositeParam.ParamName;
typeName = "text"; // composite sent as text representation
}
else
{
// Named placeholders get their API name from the placeholder itself, through the same
// NameConverter routine parameters use (:user_id → userId); positional stay "$N".
convertedName = placeholderName is not null
? nameConverter(placeholderName) ?? placeholderName
: $"${i + 1}";
}
var typeDescriptor = new TypeDescriptor(
typeName,
hasDefault: customType is not null,
customType: customType,
customTypePosition: customTypePosition,
originalParameterName: originalParameterName,
customTypeName: customTypeName);
var positionalName = placeholderName ?? $"${i + 1}";
var param = new NpgsqlRestParameter(
ordinal: i,
convertedName: convertedName,
actualName: positionalName,
typeDescriptor: typeDescriptor);
// HTTP type params need a default value so they're added to command.Parameters
// (otherwise HasDefault=true + no DefaultValue causes the parameter to be skipped)
if (httpTypeParams is not null && httpTypeParams.TryGetValue(i, out var httpParamForFields))
{
param.DefaultValue = DBNull.Value;
param.CompositeFieldNames = httpParamForFields.FieldNames;
}
parameters[i] = param;
}
// Add virtual parameters — exist for HTTP matching and claim mapping, not bound to PostgreSQL
for (int i = 0; i < virtualParams.Count; i++)
{
var vp = virtualParams[i];
var vpType = vp.Type ?? "text";
parameters[mergedMaxParam + i] = new NpgsqlRestParameter(
ordinal: mergedMaxParam + i,
convertedName: vp.Name,
actualName: vp.Name,
typeDescriptor: new TypeDescriptor(vpType, hasDefault: true))
{
IsVirtual = true
};
}
// For single-command: use first describe's columns
// For multi-command: use first non-void describe's columns as the Routine columns
// (individual command columns stored in MultiCommandInfo)
var primaryDescribe = commandDescribes[0];
var columns = primaryDescribe.Columns ?? [];
var columnCount = columns.Length;
var originalColumnNames = new string[columnCount];
var columnNames = new string[columnCount];
var columnTypeDescriptors = new TypeDescriptor[columnCount];
Dictionary<int, (string[] FieldNames, TypeDescriptor[] FieldDescriptors)>? arrayCompositeColumnInfo = null;
var usedColumnNames = new HashSet<string>(StringComparer.Ordinal);
for (int i = 0; i < columnCount; i++)
{
var colName = columns[i].Name;
// Replace unnamed/duplicate columns with unique names (column1, column2, ...)
if (colName == "?column?" || !usedColumnNames.Add(colName))
{
colName = string.Concat(UnnamedColumnPrefix, (i + 1).ToString());
}
originalColumnNames[i] = colName;
columnNames[i] = nameConverter(colName) ?? colName;
columnTypeDescriptors[i] = new TypeDescriptor(columns[i].DataTypeName);
ResolveCompositeType(columnTypeDescriptors[i]);
if (columnTypeDescriptors[i].IsArrayOfCompositeType &&
columnTypeDescriptors[i].ArrayCompositeFieldNames is not null &&
columnTypeDescriptors[i].ArrayCompositeFieldDescriptors is not null)
{
arrayCompositeColumnInfo ??= new();
arrayCompositeColumnInfo[i] = (
columnTypeDescriptors[i].ArrayCompositeFieldNames!,
columnTypeDescriptors[i].ArrayCompositeFieldDescriptors!);
}
}
var jsonColumnNames = new string[columnCount];
for (int i = 0; i < columnCount; i++)
{
jsonColumnNames[i] = PgConverters.SerializeString(columnNames[i]);
}
// Build multi-command info if needed
MultiCommandInfo[]? multiCommandInfo = null;
if (isMultiCommand)
{
multiCommandInfo = new MultiCommandInfo[commandDescribes.Count];
int resultCounter = 0; // Only incremented for non-skipped commands
for (int ci = 0; ci < commandDescribes.Count; ci++)
{
var cmdCols = commandDescribes[ci].Columns ?? [];
var cmdColNames = new string[cmdCols.Length];
var cmdJsonColNames = new string[cmdCols.Length];
var cmdColDescriptors = new TypeDescriptor[cmdCols.Length];
for (int j = 0; j < cmdCols.Length; j++)
{
cmdColNames[j] = nameConverter(cmdCols[j].Name) ?? cmdCols[j].Name;
cmdJsonColNames[j] = PgConverters.SerializeString(cmdColNames[j]);
cmdColDescriptors[j] = new TypeDescriptor(cmdCols[j].DataTypeName);
ResolveCompositeType(cmdColDescriptors[j]);
}
// Determine if this command should be skipped
bool isSkipped = parseResult.SkipCommands.Contains(ci) ||
(options.SkipNonQueryCommands && IsNonQueryCommand(parseResult.Statements[ci]));
// Result name: only assign meaningful names to non-skipped commands
string resultName;
if (isSkipped)
{
resultName = "";
}
else
{
resultCounter++;
if (parseResult.PositionalResultNames.TryGetValue(ci, out var positionalName))
{
resultName = positionalName;
NpgsqlRestOptions.Logger?.LogDebug(
"SqlFileSource: {FilePath} result{Index} renamed to \"{Name}\" by positional @result annotation",
filePath, resultCounter, positionalName);
}
else
{
resultName = string.Concat(options.ResultPrefix, resultCounter.ToString());
}
}
multiCommandInfo[ci] = new MultiCommandInfo
{
Name = resultName,
JsonName = isSkipped ? "" : PgConverters.SerializeString(resultName),
Statement = parseResult.Statements[ci],
ParamCount = SqlFileDescriber.FindMaxParamIndex(parseResult.Statements[ci]),
ColumnCount = cmdCols.Length,
ColumnNames = cmdColNames,
JsonColumnNames = cmdJsonColNames,
ColumnTypeDescriptors = cmdColDescriptors,
ReturnsUnnamedSet = options.UnnamedSingleColumnSet && cmdCols.Length == 1
&& !cmdColDescriptors[0].IsCompositeType,
IsSingle = parseResult.SingleCommands.Contains(ci),
IsSkipped = isSkipped,
};
}
}
// Multi-command is never void — always returns JSON object (with nulls for void commands)
bool isVoid = !isMultiCommand && columnCount == 0;
var fileName = Path.GetFileNameWithoutExtension(filePath);
var routine = new Routine
{
Type = RoutineType.SqlFile,
Schema = "public",
Name = fileName,
Comment = string.IsNullOrEmpty(parseResult.Comment) ? null : parseResult.Comment,
IsStrict = false,
CrudType = parseResult.AutoHttpMethod switch
{
Method.PUT => CrudType.Insert,
Method.POST => CrudType.Update,
Method.DELETE => CrudType.Delete,
_ => CrudType.Select,
},
ReturnsRecordType = false,
ReturnsSet = !isVoid,
ColumnCount = columnCount,
OriginalColumnNames = originalColumnNames,
ColumnNames = columnNames,
JsonColumnNames = jsonColumnNames,
ColumnsTypeDescriptor = columnTypeDescriptors,
ReturnsUnnamedSet = options.UnnamedSingleColumnSet && columnCount == 1 && !isMultiCommand
&& !columnTypeDescriptors[0].IsCompositeType,
IsVoid = isVoid,
ParamCount = totalParamCount,
Parameters = parameters,
ParamsHash = [.. parameters.Select(p => p.ConvertedName)],
OriginalParamsHash = [.. parameters.Select(p => p.ActualName)],
Expression = parseResult.Statements[0], // first statement for display/logging; batch uses individual statements
FullDefinition = $"-- SQL file: {filePath}",
SimpleDefinition = $"SQL file: {filePath}",
FormatUrlPattern = null,
Tags = null,
EndpointHandler = null,
Metadata = DeriveTsClientModule(filePath, baseDir),
};
if (arrayCompositeColumnInfo is not null)
{
routine.ArrayCompositeColumnInfo = arrayCompositeColumnInfo;
}
if (multiCommandInfo is not null)
{
routine.MultiCommandInfo = multiCommandInfo;
routine.LogCommandText = options.LogCommandText;
}
return (routine, SqlFileParameterFormatter.Instance);
}
/// <summary>
/// Resolve composite type metadata for a column TypeDescriptor.
/// Delegates to CompositeTypeCache.ResolveTypeDescriptor which can set internal properties.
/// </summary>
private static void ResolveCompositeType(TypeDescriptor descriptor)
{
CompositeTypeCache.ResolveTypeDescriptor(descriptor);
}
/// <summary>
/// Collect typed @param annotations as (0-based index, API param name, type name) tuples.
/// Positional form: @param $N name type. Named form (only for files using :name placeholders):
/// @param :name type — the API name comes from the placeholder itself, through the NameConverter.
/// </summary>
private static List<(int ParamIndex, string ParamName, string TypeName)> CollectTypedParamAnnotations(
string comment, IReadOnlyList<string>? namedParams)
{
List<(int, string, string)> annotations = [];
foreach (Match match in Regex.Matches(comment, @"@param\s+\$(\d+)\s+(\w+)\s+(\S+)", RegexOptions.IgnoreCase))
{
annotations.Add((int.Parse(match.Groups[1].Value) - 1, match.Groups[2].Value, match.Groups[3].Value));
}
if (namedParams is not null)
{
foreach (Match match in Regex.Matches(comment, @"@param\s+:(\w+)\s+(\S+)", RegexOptions.IgnoreCase))
{
var name = match.Groups[1].Value;
var paramIndex = SqlFileParser.IndexOfName(namedParams, name);
if (paramIndex < 0)
{
continue;
}
var paramName = NpgsqlRestOptions.Options.NameConverter(name) ?? name;
annotations.Add((paramIndex, paramName, match.Groups[2].Value));
}
}
return annotations;
}
/// <summary>
/// Scan @param annotations in the comment for HTTP client type parameters.
/// Returns null if no HTTP types found, otherwise a dictionary keyed by 0-based param index.
/// </summary>
private static Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>?
DetectHttpTypeParams(string comment, NpgsqlConnection connection, IReadOnlyList<string>? namedParams)
{
Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>? result = null;
foreach (var (paramIndex, paramName, typeName) in CollectTypedParamAnnotations(comment, namedParams))
{
// Check if this type is an HTTP client type (try with and without public. prefix)
string? resolvedTypeName = null;
if (HttpClientTypes.Definitions.ContainsKey(typeName))
{
resolvedTypeName = typeName;
}
else if (HttpClientTypes.Definitions.ContainsKey($"public.{typeName}"))
{
resolvedTypeName = $"public.{typeName}";
}
if (resolvedTypeName is null)
{
continue;
}
// Query composite type fields from pg_catalog
var (fieldNames, fieldTypes) = QueryCompositeFields(connection, typeName);
if (fieldNames.Length == 0)
{
continue;
}
result ??= new();
result[paramIndex] = (resolvedTypeName, paramName, fieldNames, fieldTypes);
}
return result;
}
/// <summary>
/// Query composite type field names and types from pg_catalog.
/// </summary>
private static (string[] FieldNames, string[] FieldTypes) QueryCompositeFields(NpgsqlConnection connection, string typeName)
{
using var cmd = connection.CreateCommand();
// Handle schema-qualified names
var parts = typeName.Split('.');
var schema = parts.Length > 1 ? parts[0] : "public";
var name = parts.Length > 1 ? parts[1] : parts[0];
cmd.CommandText = @"
select a.attname, format_type(a.atttypid, a.atttypmod)
from pg_catalog.pg_attribute a
join pg_catalog.pg_type t on a.attrelid = t.typrelid
join pg_catalog.pg_namespace n on t.typnamespace = n.oid
where t.typname = $1 and n.nspname = $2
and a.attnum > 0 and not a.attisdropped
order by a.attnum";
cmd.Parameters.AddWithValue(name);
cmd.Parameters.AddWithValue(schema);
cmd.LogCommand(nameof(SqlFileSource));
var fieldNames = new List<string>();
var fieldTypes = new List<string>();
using var reader = cmd.ExecuteReader();
while (reader.Read())
{
fieldNames.Add(reader.GetString(0));
fieldTypes.Add(reader.GetString(1));
}
return (fieldNames.ToArray(), fieldTypes.ToArray());
}
/// <summary>
/// Detect @param annotations with composite types that are NOT HTTP client types.
/// These are client-sent composite parameters that need ROW() expansion.
/// </summary>
private static Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>?
DetectCompositeTypeParams(
string comment,
NpgsqlConnection connection,
Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>? httpTypeParams,
IReadOnlyList<string>? namedParams)
{
Dictionary<int, (string TypeName, string ParamName, string[] FieldNames, string[] FieldTypes)>? result = null;
foreach (var (paramIndex, paramName, typeName) in CollectTypedParamAnnotations(comment, namedParams))
{
// Skip if already detected as HTTP type
if (httpTypeParams is not null && httpTypeParams.ContainsKey(paramIndex))
{
continue;
}
// Check if this type is a known composite type
if (CompositeTypeCache.GetType(typeName) is null)
{
continue;
}
// Query composite type fields from pg_catalog
var (fieldNames, fieldTypes) = QueryCompositeFields(connection, typeName);
if (fieldNames.Length == 0)
{
continue;
}
result ??= new();
result[paramIndex] = (typeName, paramName, fieldNames, fieldTypes);
}
return result;
}
/// <summary>
/// Find files matching the glob pattern. Splits the pattern into a base directory
/// and a file pattern, then lazily enumerates matching files.
/// </summary>
internal static IEnumerable<string> FindMatchingFiles(string filePattern, string? skipPattern = null)
{
// Find the base directory (everything before the first wildcard)
int firstWildcard = filePattern.IndexOfAny(['*', '?']);
if (firstWildcard < 0)
{
// No wildcards — treat as exact file path
if (File.Exists(filePattern))
{
yield return Path.GetFullPath(filePattern);
}
yield break;
}
// Find the last / before the first wildcard to get the base directory
int lastSlash = filePattern.LastIndexOf('/', firstWildcard);
string baseDir;
string pattern;
if (lastSlash >= 0)
{
baseDir = filePattern[..lastSlash];
pattern = filePattern;
}
else
{
baseDir = ".";
pattern = filePattern;
}
if (!Directory.Exists(baseDir))
{
yield break;
}
// Lazily enumerate files and filter with IsPatternMatch
bool isRecursive = filePattern.Contains("**");
var searchOption = isRecursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
bool hasSkip = !string.IsNullOrEmpty(skipPattern);
foreach (var file in Directory.EnumerateFiles(baseDir, "*", searchOption))
{
var normalizedFile = file.Replace('\\', '/');
if (Parser.IsPatternMatch(normalizedFile, pattern)
&& !(hasSkip && Parser.IsPatternMatch(normalizedFile, skipPattern!)))
{
yield return file;
}
}
}
/// <summary>
/// Keywords for non-query commands that produce no meaningful result in multi-command responses.
/// </summary>
private static readonly HashSet<string> NonQueryKeywords = new(StringComparer.OrdinalIgnoreCase)
{
"BEGIN", "COMMIT", "END", "ROLLBACK", "SAVEPOINT", "RELEASE",
"SET", "RESET", "DISCARD", "LOCK", "LISTEN", "NOTIFY", "DEALLOCATE"
};
/// <summary>
/// Check if a statement is a non-query command (transaction control, session, DO block, etc.)
/// that should be skipped from multi-command results.
/// </summary>
private static bool IsNonQueryCommand(string statement)
{
var trimmed = statement.AsSpan().TrimStart();
int end = 0;
while (end < trimmed.Length && char.IsLetter(trimmed[end]))
end++;
if (end == 0) return false;
var keyword = trimmed[..end].ToString();
// DO blocks: must be followed by whitespace or $ (to avoid matching identifiers starting with DO)
if (string.Equals(keyword, "DO", StringComparison.OrdinalIgnoreCase))
{
return end >= trimmed.Length || char.IsWhiteSpace(trimmed[end]) || trimmed[end] == '$';
}
return NonQueryKeywords.Contains(keyword);
}
/// <summary>
/// Extract the base directory from a file pattern (everything before the first wildcard).
/// Returns the full path of the base directory.
/// </summary>
private static string GetBaseDirectory(string filePattern)
{
int firstWildcard = filePattern.IndexOfAny(['*', '?']);
if (firstWildcard < 0)
{
return Path.GetFullPath(Path.GetDirectoryName(filePattern) ?? ".");
}
int lastSlash = filePattern.LastIndexOf('/', firstWildcard);
return Path.GetFullPath(lastSlash >= 0 ? filePattern[..lastSlash] : ".");
}
/// <summary>
/// Check whether the parsed comment contains an HTTP tag (a line starting with "http").
/// Mirrors the detection logic in DefaultCommentParser.
/// </summary>
private static bool HasHttpTag(string comment)
{
if (string.IsNullOrEmpty(comment))
{
return false;
}
foreach (var line in comment.Split('\n'))
{
var trimmed = line.Trim();
if (trimmed.Length >= 4 &&
trimmed.StartsWith("http", StringComparison.OrdinalIgnoreCase) &&
(trimmed.Length == 4 || trimmed[4] == ' ' || trimmed[4] == '\t'))
{
return true;
}
}
return false;
}
/// <summary>
/// Check whether the parsed comment contains a plugin endpoint-requesting annotation — a line whose
/// first word (optional <c>@</c> prefix stripped) matches a keyword any registered
/// <see cref="IEndpointCreateHandler"/> advertises via
/// <see cref="IEndpointCreateHandler.EndpointRequestingAnnotations"/> (e.g. a bare <c>mcp</c>).
/// Such a file is an endpoint candidate (an MCP-only tool) even without an HTTP tag.
/// </summary>
private static bool HasEndpointRequestingAnnotation(string comment)
{
if (string.IsNullOrEmpty(comment))
{
return false;
}
var handlers = NpgsqlRestOptions.Options?.EndpointCreateHandlers;
if (handlers is null)
{
return false;
}
foreach (var line in comment.Split('\n'))
{
var trimmed = line.Trim();
if (trimmed.Length == 0)
{
continue;
}
var span = trimmed.AsSpan();
if (span[0] == '@')
{
span = span[1..];
}
var wordEnd = span.IndexOfAny(' ', '\t');
var word = wordEnd < 0 ? span : span[..wordEnd];
if (word.Length == 0)
{
continue;
}
foreach (var handler in handlers)
{
foreach (var key in handler.EndpointRequestingAnnotations)
{
if (word.Equals(key, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
}
return false;
}
/// <summary>
/// Derive a module name from the file's position relative to the base scan directory.
/// Stored in Routine.Metadata as the raw directory name.
/// - sql/get-order.sql → "sql" (base dir name)
/// - sql/orders/get-order.sql → "orders" (first subdirectory)
/// - sql/my_orders/get-order.sql → "my_orders"
/// </summary>
private static string? DeriveTsClientModule(string filePath, string baseDir)
{
var fullPath = Path.GetFullPath(filePath);
var fullBase = Path.GetFullPath(baseDir);
var fileDir = Path.GetDirectoryName(fullPath) ?? fullBase;
var relative = Path.GetRelativePath(fullBase, fileDir).Replace('\\', '/');
if (relative == ".")
{
// File is directly in the base directory — use the base dir name
return Path.GetFileName(fullBase) ?? "sql";
}
// Use the first subdirectory segment
var firstSlash = relative.IndexOf('/');
return firstSlash >= 0 ? relative[..firstSlash] : relative;
}
}
You can’t perform that action at this time.
