Skip to content

Support span based collations comparison functions in Sqlite #35236

@hahn-kev

Description

@hahn-kev

Sqlite supports creating custom collations via SqliteConnection.CreateCollation

public virtual void CreateCollation(string name, Comparison<string>? comparison)

this calls sqlite3_create_collation, however this function allocates strings for every comparison.

I'd like to have a function which works with spans, there's already the function sqlite3__create_collation_utf8 which exposes the span based API we just need to wire it up. I'm happy to contribute a PR if it would be accepted.

private void CreateSpanCollation<T>(SqliteConnection connection,
    string name, T state,
    Func<T, ReadOnlySpan<char>, ReadOnlySpan<char>, int> compare)
{
    if (connection.State != ConnectionState.Open)
        throw new InvalidOperationException("Unable to create custom collation Connection must be open.");
    var rc = SQLitePCL.raw.sqlite3__create_collation_utf8(connection.Handle,
        name,
        Tuple.Create(state, compare),
        static (s, x, y) =>
        {
            var (state, compare) = (Tuple<T, Func<T, ReadOnlySpan<char>, ReadOnlySpan<char>, int>>) s;
            Span<char> xSpan = stackalloc char[Encoding.UTF8.GetCharCount(x)];
            Span<char> ySpan = stackalloc char[Encoding.UTF8.GetCharCount(y)];
            Encoding.UTF8.GetChars(x, xSpan);
            Encoding.UTF8.GetChars(y, ySpan);

            return compare(state, xSpan, ySpan);
        });
    SqliteException.ThrowExceptionForRC(rc, connection.Handle);
}

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions