/
NpgsqlTsQuery.cs
744 lines (651 loc) · 22 KB
/
NpgsqlTsQuery.cs
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
using System;
using System.Collections.Generic;
using System.Text;
#pragma warning disable CA1034
// ReSharper disable once CheckNamespace
namespace NpgsqlTypes;
/// <summary>
/// Represents a PostgreSQL tsquery. This is the base class for the
/// lexeme, not, or, and, and "followed by" nodes.
/// </summary>
public abstract class NpgsqlTsQuery : IEquatable<NpgsqlTsQuery>
{
/// <summary>
/// Node kind
/// </summary>
public NodeKind Kind { get; }
/// <summary>
/// NodeKind
/// </summary>
public enum NodeKind
{
/// <summary>
/// Represents the empty tsquery. Should only be used at top level.
/// </summary>
Empty = -1,
/// <summary>
/// Lexeme
/// </summary>
Lexeme = 0,
/// <summary>
/// Not operator
/// </summary>
Not = 1,
/// <summary>
/// And operator
/// </summary>
And = 2,
/// <summary>
/// Or operator
/// </summary>
Or = 3,
/// <summary>
/// "Followed by" operator
/// </summary>
Phrase = 4
}
/// <summary>
/// Constructs an <see cref="NpgsqlTsQuery"/>.
/// </summary>
/// <param name="kind"></param>
protected NpgsqlTsQuery(NodeKind kind) => Kind = kind;
/// <summary>
/// Writes the tsquery in PostgreSQL's text format.
/// </summary>
public void Write(StringBuilder stringBuilder) => WriteCore(stringBuilder, true);
internal abstract void WriteCore(StringBuilder sb, bool first = false);
/// <summary>
/// Writes the tsquery in PostgreSQL's text format.
/// </summary>
public override string ToString()
{
var sb = new StringBuilder();
Write(sb);
return sb.ToString();
}
/// <summary>
/// Parses a tsquery in PostgreSQL's text format.
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static NpgsqlTsQuery Parse(string value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var valStack = new Stack<NpgsqlTsQuery>();
var opStack = new Stack<NpgsqlTsQueryOperator>();
var sb = new StringBuilder();
var pos = 0;
var expectingBinOp = false;
short lastFollowedByOpDistance = -1;
NextToken:
if (pos >= value.Length)
goto Finish;
var ch = value[pos++];
if (ch == '\'')
goto WaitEndComplex;
if ((ch == ')' || ch == '|' || ch == '&') && !expectingBinOp || (ch == '(' || ch == '!') && expectingBinOp)
throw new FormatException("Syntax error in tsquery. Unexpected token.");
if (ch == '<')
{
var endOfOperatorConsumed = false;
var sbCurrentLength = sb.Length;
while (pos < value.Length)
{
var c = value[pos++];
if (c == '>')
{
endOfOperatorConsumed = true;
break;
}
sb.Append(c);
}
if (sb.Length == sbCurrentLength || !endOfOperatorConsumed)
throw new FormatException("Syntax error in tsquery. Malformed 'followed by' operator.");
var followedByOpDistanceString = sb.ToString(sbCurrentLength, sb.Length - sbCurrentLength);
if (followedByOpDistanceString == "-")
{
lastFollowedByOpDistance = 1;
}
else if (!short.TryParse(followedByOpDistanceString, out lastFollowedByOpDistance)
|| lastFollowedByOpDistance < 0)
{
throw new FormatException("Syntax error in tsquery. Malformed distance in 'followed by' operator.");
}
sb.Length -= followedByOpDistanceString.Length;
}
if (ch == '(' || ch == '!' || ch == '&' || ch == '<')
{
opStack.Push(new NpgsqlTsQueryOperator(ch, lastFollowedByOpDistance));
expectingBinOp = false;
lastFollowedByOpDistance = 0;
goto NextToken;
}
if (ch == '|')
{
if (opStack.Count > 0 && opStack.Peek() == '|')
{
if (valStack.Count < 2)
throw new FormatException("Syntax error in tsquery");
var right = valStack.Pop();
var left = valStack.Pop();
valStack.Push(new NpgsqlTsQueryOr(left, right));
// Implicit pop and repush |
}
else
opStack.Push('|');
expectingBinOp = false;
goto NextToken;
}
if (ch == ')')
{
while (opStack.Count > 0 && opStack.Peek() != '(')
{
if (valStack.Count < 2 || opStack.Peek() == '!')
throw new FormatException("Syntax error in tsquery");
var right = valStack.Pop();
var left = valStack.Pop();
var tsOp = opStack.Pop();
valStack.Push((char)tsOp switch
{
'&' => new NpgsqlTsQueryAnd(left, right),
'|' => new NpgsqlTsQueryOr(left, right),
'<' => new NpgsqlTsQueryFollowedBy(left, tsOp.FollowedByDistance, right),
_ => throw new FormatException("Syntax error in tsquery")
});
}
if (opStack.Count == 0)
throw new FormatException("Syntax error in tsquery: closing parenthesis without an opening parenthesis");
opStack.Pop();
goto PushedVal;
}
if (ch == ':')
throw new FormatException("Unexpected : while parsing tsquery");
if (char.IsWhiteSpace(ch))
goto NextToken;
pos--;
if (expectingBinOp)
throw new FormatException("Unexpected lexeme while parsing tsquery");
// Proceed to WaitEnd
WaitEnd:
if (pos >= value.Length || char.IsWhiteSpace(ch = value[pos]) || ch == '!' || ch == '&' || ch == '|' || ch == '(' || ch == ')')
{
valStack.Push(new NpgsqlTsQueryLexeme(sb.ToString()));
goto PushedVal;
}
pos++;
if (ch == ':')
{
valStack.Push(new NpgsqlTsQueryLexeme(sb.ToString()));
sb.Clear();
goto InWeightInfo;
}
if (ch == '\\')
{
if (pos >= value.Length)
throw new FormatException(@"Unexpected \ in end of value");
ch = value[pos++];
}
sb.Append(ch);
goto WaitEnd;
WaitEndComplex:
if (pos >= value.Length)
throw new FormatException("Missing terminating ' in string literal");
ch = value[pos++];
if (ch == '\'')
{
if (pos < value.Length && value[pos] == '\'')
{
ch = '\'';
pos++;
}
else
{
valStack.Push(new NpgsqlTsQueryLexeme(sb.ToString()));
if (pos < value.Length && value[pos] == ':')
{
pos++;
goto InWeightInfo;
}
goto PushedVal;
}
}
if (ch == '\\')
{
if (pos >= value.Length)
throw new FormatException(@"Unexpected \ in end of value");
ch = value[pos++];
}
sb.Append(ch);
goto WaitEndComplex;
InWeightInfo:
if (pos >= value.Length)
goto Finish;
ch = value[pos];
switch (ch)
{
case '*':
((NpgsqlTsQueryLexeme)valStack.Peek()).IsPrefixSearch = true;
break;
case 'a' or 'A':
((NpgsqlTsQueryLexeme)valStack.Peek()).Weights |= NpgsqlTsQueryLexeme.Weight.A;
break;
case 'b' or 'B':
((NpgsqlTsQueryLexeme)valStack.Peek()).Weights |= NpgsqlTsQueryLexeme.Weight.B;
break;
case 'c' or 'C':
((NpgsqlTsQueryLexeme)valStack.Peek()).Weights |= NpgsqlTsQueryLexeme.Weight.C;
break;
case 'd' or 'D':
((NpgsqlTsQueryLexeme)valStack.Peek()).Weights |= NpgsqlTsQueryLexeme.Weight.D;
break;
default:
goto PushedVal;
}
pos++;
goto InWeightInfo;
PushedVal:
sb.Clear();
var processTightBindingOperator = true;
while (opStack.Count > 0 && processTightBindingOperator)
{
var tsOp = opStack.Peek();
switch (tsOp)
{
case '&':
if (valStack.Count < 2)
throw new FormatException("Syntax error in tsquery");
var andRight = valStack.Pop();
var andLeft = valStack.Pop();
valStack.Push(new NpgsqlTsQueryAnd(andLeft, andRight));
opStack.Pop();
break;
case '!':
if (valStack.Count == 0)
throw new FormatException("Syntax error in tsquery");
valStack.Push(new NpgsqlTsQueryNot(valStack.Pop()));
opStack.Pop();
break;
case '<':
if (valStack.Count < 2)
throw new FormatException("Syntax error in tsquery");
var followedByRight = valStack.Pop();
var followedByLeft = valStack.Pop();
valStack.Push(
new NpgsqlTsQueryFollowedBy(
followedByLeft,
tsOp.FollowedByDistance,
followedByRight));
opStack.Pop();
break;
default:
processTightBindingOperator = false;
break;
}
}
expectingBinOp = true;
goto NextToken;
Finish:
while (opStack.Count > 0)
{
if (valStack.Count < 2)
throw new FormatException("Syntax error in tsquery");
var right = valStack.Pop();
var left = valStack.Pop();
var tsOp = opStack.Pop();
var query = (char)tsOp switch
{
'&' => (NpgsqlTsQuery)new NpgsqlTsQueryAnd(left, right),
'|' => new NpgsqlTsQueryOr(left, right),
'<' => new NpgsqlTsQueryFollowedBy(left, tsOp.FollowedByDistance, right),
_ => throw new FormatException("Syntax error in tsquery")
};
valStack.Push(query);
}
if (valStack.Count != 1)
throw new FormatException("Syntax error in tsquery");
return valStack.Pop();
}
/// <inheritdoc/>
public override int GetHashCode()
=> throw new NotSupportedException("Must be overridden");
/// <inheritdoc/>
public override bool Equals(object? obj)
=> obj is NpgsqlTsQuery query && query.Equals(this);
/// <summary>
/// Returns a value indicating whether this instance and a specified <see cref="NpgsqlTsQuery"/> object represent the same value.
/// </summary>
/// <param name="other">An object to compare to this instance.</param>
/// <returns><see langword="true"/> if g is equal to this instance; otherwise, <see langword="false"/>.</returns>
public abstract bool Equals(NpgsqlTsQuery? other);
/// <summary>
/// Indicates whether the values of two specified <see cref="NpgsqlTsQuery"/> objects are equal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns><see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are equal; otherwise, <see langword="false"/>.</returns>
public static bool operator ==(NpgsqlTsQuery? left, NpgsqlTsQuery? right)
=> left is null ? right is null : left.Equals(right);
/// <summary>
/// Indicates whether the values of two specified <see cref="NpgsqlTsQuery"/> objects are not equal.
/// </summary>
/// <param name="left">The first object to compare.</param>
/// <param name="right">The second object to compare.</param>
/// <returns><see langword="true"/> if <paramref name="left"/> and <paramref name="right"/> are not equal; otherwise, <see langword="false"/>.</returns>
public static bool operator !=(NpgsqlTsQuery? left, NpgsqlTsQuery? right)
=> left is null ? right is not null : !left.Equals(right);
}
readonly struct NpgsqlTsQueryOperator
{
public readonly char Char;
public readonly short FollowedByDistance;
public NpgsqlTsQueryOperator(char character, short followedByDistance)
{
Char = character;
FollowedByDistance = followedByDistance;
}
public static implicit operator NpgsqlTsQueryOperator(char c) => new(c, 0);
public static implicit operator char(NpgsqlTsQueryOperator o) => o.Char;
}
/// <summary>
/// TsQuery Lexeme node.
/// </summary>
public sealed class NpgsqlTsQueryLexeme : NpgsqlTsQuery
{
string _text;
/// <summary>
/// Lexeme text.
/// </summary>
public string Text
{
get => _text;
set
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("Text is null or empty string", nameof(value));
_text = value;
}
}
Weight _weights;
/// <summary>
/// Weights is a bitmask of the Weight enum.
/// </summary>
public Weight Weights
{
get => _weights;
set
{
if (((byte)value >> 4) != 0)
throw new ArgumentOutOfRangeException(nameof(value), "Illegal weights");
_weights = value;
}
}
/// <summary>
/// Prefix search.
/// </summary>
public bool IsPrefixSearch { get; set; }
/// <summary>
/// Creates a tsquery lexeme with only lexeme text.
/// </summary>
/// <param name="text">Lexeme text.</param>
public NpgsqlTsQueryLexeme(string text) : this(text, Weight.None, false) { }
/// <summary>
/// Creates a tsquery lexeme with lexeme text and weights.
/// </summary>
/// <param name="text">Lexeme text.</param>
/// <param name="weights">Bitmask of enum Weight.</param>
public NpgsqlTsQueryLexeme(string text, Weight weights) : this(text, weights, false) { }
/// <summary>
/// Creates a tsquery lexeme with lexeme text, weights and prefix search flag.
/// </summary>
/// <param name="text">Lexeme text.</param>
/// <param name="weights">Bitmask of enum Weight.</param>
/// <param name="isPrefixSearch">Is prefix search?</param>
public NpgsqlTsQueryLexeme(string text, Weight weights, bool isPrefixSearch)
: base(NodeKind.Lexeme)
{
_text = text;
Weights = weights;
IsPrefixSearch = isPrefixSearch;
}
/// <summary>
/// Weight enum, can be OR'ed together.
/// </summary>
#pragma warning disable CA1714
[Flags]
public enum Weight
#pragma warning restore CA1714
{
/// <summary>
/// None
/// </summary>
None = 0,
/// <summary>
/// D
/// </summary>
D = 1,
/// <summary>
/// C
/// </summary>
C = 2,
/// <summary>
/// B
/// </summary>
B = 4,
/// <summary>
/// A
/// </summary>
A = 8
}
internal override void WriteCore(StringBuilder sb, bool first = false)
{
sb.Append('\'').Append(Text.Replace(@"\", @"\\").Replace("'", "''")).Append('\'');
if (IsPrefixSearch || Weights != Weight.None)
sb.Append(':');
if (IsPrefixSearch)
sb.Append('*');
if ((Weights & Weight.A) != Weight.None)
sb.Append('A');
if ((Weights & Weight.B) != Weight.None)
sb.Append('B');
if ((Weights & Weight.C) != Weight.None)
sb.Append('C');
if ((Weights & Weight.D) != Weight.None)
sb.Append('D');
}
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryLexeme lexeme &&
lexeme.Text == Text &&
lexeme.Weights == Weights &&
lexeme.IsPrefixSearch == IsPrefixSearch;
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(Text, Weights, IsPrefixSearch);
}
/// <summary>
/// TsQuery Not node.
/// </summary>
public sealed class NpgsqlTsQueryNot : NpgsqlTsQuery
{
/// <summary>
/// Child node
/// </summary>
public NpgsqlTsQuery Child { get; set; }
/// <summary>
/// Creates a not operator, with a given child node.
/// </summary>
/// <param name="child"></param>
public NpgsqlTsQueryNot(NpgsqlTsQuery child)
: base(NodeKind.Not)
{
Child = child;
}
internal override void WriteCore(StringBuilder sb, bool first = false)
{
sb.Append('!');
if (Child == null)
{
sb.Append("''");
}
else
{
if (Child.Kind != NodeKind.Lexeme)
sb.Append("( ");
Child.WriteCore(sb, true);
if (Child.Kind != NodeKind.Lexeme)
sb.Append(" )");
}
}
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryNot not && not.Child == Child;
/// <inheritdoc/>
public override int GetHashCode()
=> Child?.GetHashCode() ?? 0;
}
/// <summary>
/// Base class for TsQuery binary operators (& and |).
/// </summary>
public abstract class NpgsqlTsQueryBinOp : NpgsqlTsQuery
{
/// <summary>
/// Left child
/// </summary>
public NpgsqlTsQuery Left { get; set; }
/// <summary>
/// Right child
/// </summary>
public NpgsqlTsQuery Right { get; set; }
/// <summary>
/// Constructs a <see cref="NpgsqlTsQueryBinOp"/>.
/// </summary>
protected NpgsqlTsQueryBinOp(NodeKind kind, NpgsqlTsQuery left, NpgsqlTsQuery right)
: base(kind)
{
Left = left;
Right = right;
}
}
/// <summary>
/// TsQuery And node.
/// </summary>
public sealed class NpgsqlTsQueryAnd : NpgsqlTsQueryBinOp
{
/// <summary>
/// Creates an and operator, with two given child nodes.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
public NpgsqlTsQueryAnd(NpgsqlTsQuery left, NpgsqlTsQuery right)
: base(NodeKind.And, left, right) {}
internal override void WriteCore(StringBuilder sb, bool first = false)
{
Left.WriteCore(sb);
sb.Append(" & ");
Right.WriteCore(sb);
}
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryAnd and && and.Left == Left && and.Right == Right;
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(Left, Right);
}
/// <summary>
/// TsQuery Or Node.
/// </summary>
public sealed class NpgsqlTsQueryOr : NpgsqlTsQueryBinOp
{
/// <summary>
/// Creates an or operator, with two given child nodes.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
public NpgsqlTsQueryOr(NpgsqlTsQuery left, NpgsqlTsQuery right)
: base(NodeKind.Or, left, right) {}
internal override void WriteCore(StringBuilder sb, bool first = false)
{
// TODO: Figure out the nullability strategy here
if (!first)
sb.Append("( ");
Left.WriteCore(sb);
sb.Append(" | ");
Right.WriteCore(sb);
if (!first)
sb.Append(" )");
}
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryOr or && or.Left == Left && or.Right == Right;
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(Left, Right);
}
/// <summary>
/// TsQuery "Followed by" Node.
/// </summary>
public sealed class NpgsqlTsQueryFollowedBy : NpgsqlTsQueryBinOp
{
/// <summary>
/// The distance between the 2 nodes, in lexemes.
/// </summary>
public short Distance { get; set; }
/// <summary>
/// Creates a "followed by" operator, specifying 2 child nodes and the
/// distance between them in lexemes.
/// </summary>
/// <param name="left"></param>
/// <param name="distance"></param>
/// <param name="right"></param>
public NpgsqlTsQueryFollowedBy(
NpgsqlTsQuery left,
short distance,
NpgsqlTsQuery right)
: base(NodeKind.Phrase, left, right)
{
if (distance < 0)
throw new ArgumentOutOfRangeException(nameof(distance));
Distance = distance;
}
internal override void WriteCore(StringBuilder sb, bool first = false)
{
// TODO: Figure out the nullability strategy here
if (!first)
sb.Append("( ");
Left.WriteCore(sb);
sb.Append(" <");
if (Distance == 1) sb.Append("-");
else sb.Append(Distance);
sb.Append("> ");
Right.WriteCore(sb);
if (!first)
sb.Append(" )");
}
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryFollowedBy followedBy &&
followedBy.Left == Left &&
followedBy.Right == Right &&
followedBy.Distance == Distance;
/// <inheritdoc/>
public override int GetHashCode()
=> HashCode.Combine(Left, Right, Distance);
}
/// <summary>
/// Represents an empty tsquery. Shold only be used as top node.
/// </summary>
public sealed class NpgsqlTsQueryEmpty : NpgsqlTsQuery
{
/// <summary>
/// Creates a tsquery that represents an empty query. Should not be used as child node.
/// </summary>
public NpgsqlTsQueryEmpty() : base(NodeKind.Empty) {}
internal override void WriteCore(StringBuilder sb, bool first = false) { }
/// <inheritdoc/>
public override bool Equals(NpgsqlTsQuery? other)
=> other is NpgsqlTsQueryEmpty;
/// <inheritdoc/>
public override int GetHashCode()
=> Kind.GetHashCode();
}