|
| 1 | +using System.Data.Common; |
| 2 | +using System.Globalization; |
| 3 | +using System.Runtime.CompilerServices; |
| 4 | +using System.Text; |
| 5 | +using Microsoft.Data.Sqlite; |
| 6 | +using Microsoft.EntityFrameworkCore.Diagnostics; |
| 7 | +using MiniLcm.Culture; |
| 8 | + |
| 9 | +namespace LcmCrdt.Data; |
| 10 | + |
| 11 | +public class CustomSqliteFunctionInterceptor : IDbConnectionInterceptor |
| 12 | +{ |
| 13 | + public const string ContainsFunction = "contains"; |
| 14 | + |
| 15 | + public void ConnectionOpened(DbConnection connection, ConnectionEndEventData eventData) |
| 16 | + { |
| 17 | + var sqliteConnection = (SqliteConnection)connection; |
| 18 | + //creates a new function that can be used in queries |
| 19 | + sqliteConnection.CreateFunction(ContainsFunction, |
| 20 | + //in sqlite strings are byte arrays, so we can avoid allocating strings by using spans |
| 21 | + (byte[]? str, byte[]? value) => |
| 22 | + { |
| 23 | + if (str is null || value is null) return false; |
| 24 | + |
| 25 | + Span<char> source = stackalloc char[Encoding.UTF8.GetCharCount(str)]; |
| 26 | + Span<char> search = stackalloc char[Encoding.UTF8.GetCharCount(value)]; |
| 27 | + Encoding.UTF8.GetChars(str, source); |
| 28 | + Encoding.UTF8.GetChars(value, search); |
| 29 | + return CultureInfo.InvariantCulture.CompareInfo.IndexOf(source, |
| 30 | + search, |
| 31 | + ContainsDiacritic(search) |
| 32 | + ? CompareOptions.IgnoreCase |
| 33 | + : CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase |
| 34 | + ) >= 0; |
| 35 | + }); |
| 36 | + } |
| 37 | + |
| 38 | + private static bool ContainsDiacritic(in ReadOnlySpan<char> value) |
| 39 | + { |
| 40 | + bool hasAccent = false; |
| 41 | + //todo we could maybe get rid of this normalization step if the text is already normalized |
| 42 | + //that would mean we could just iterate the value here rather than creating a new string |
| 43 | + foreach (var ch in new string(value).Normalize(NormalizationForm.FormD)) |
| 44 | + { |
| 45 | + if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.NonSpacingMark) |
| 46 | + { |
| 47 | + hasAccent = true; |
| 48 | + break; |
| 49 | + } |
| 50 | + } |
| 51 | + return hasAccent; |
| 52 | + } |
| 53 | + |
| 54 | + public Task ConnectionOpenedAsync(DbConnection connection, |
| 55 | + ConnectionEndEventData eventData, |
| 56 | + CancellationToken cancellationToken = new CancellationToken()) |
| 57 | + { |
| 58 | + ConnectionOpened(connection, eventData); |
| 59 | + return Task.CompletedTask; |
| 60 | + } |
| 61 | +} |
0 commit comments