Skip to content

linq2db integration: silent query failures, incorrect key lookups, mapping loss, and shared DI connections #506

Done

Description

@CastleSoft

Summary

The linq2db integration has several correctness and lifecycle issues, including silent query failures, primary-key lookups returning the wrong row, discarded configuration, and user mapping schemas being replaced.

The underlying provider pairing fixed in 2.1.3 (#497) appears correct:

  • linq2db's SQLite dialect generates the SQL.
  • SharpCoreDB executes it through SharpCoreDBConnection, configured by SharpCoreDBDataConnection.CreateProviderAndConnection.
  • Bulk copy is forced to MultipleRows, avoiding Microsoft.Data.Sqlite's native bulk-copy path.

Most of the issues below are in the surrounding integration code, although the highest-impact issue appears to be in the engine's evaluation of scalar functions against columns.

Confirmed defects

1. Scalar functions applied to columns do not work

Severity: Critical — silent incorrect query results

Probe results:

SELECT upper(at) FROM T;
-- Actual: '1' (the id column, unchanged)

SELECT strftime('%Y', at) FROM T WHERE id = 1;
-- Actual: '1'

SELECT COUNT(*) FROM T WHERE length(at) = 23;
-- Actual: 0
-- Expected: 1

SELECT COUNT(*) FROM T WHERE date(at) = '2026-01-01';
-- Actual: 0

The equivalent literal-only function evaluation works:

SELECT strftime('%Y-%m-%d', '2026-01-01 ...');
-- Actual: '2026-01-01'

Impact

linq2db's SQLite dialect translates DateTime comparisons into expressions such as:

strftime('%Y-%m-%d %H:%M:%f', [x].[at]) =
strftime('%Y-%m-%d %H:%M:%f', @p)

Consequently, queries such as the following return no rows without reporting an error:

.Where(x => x.At == date)
.Where(x => x.At > date)

String operations such as ToUpper(), Length, and Substring() translate to upper, length, and substr and are affected by the same problem.

Apparent cause

SqlParser.DML.ScalarFunctions.cs evaluates functions in literal-only queries through ExecuteSelectLiteralQuery, but function calls over rows appear to be ignored.

Expected behavior

Scalar functions should evaluate their column arguments for each row, both in projections and predicates.

This conflicts with the full SQLite compatibility policy in AGENTS.md and is not documented in docs/sharpcoredb-known-issues.md.

The existing DateTime_ShouldRoundTrip test does not catch this because it filters by Name, not by the date column.

2. GetByIdAsync ignores its keys and returns the first row

Severity: High — incorrect entity retrieval and potential data exposure

Location: FunctionalLinq2DbContext.cs:31–59

Probe results:

GetByIdAsync([2])   → Id = 1
GetByIdAsync([999]) → Id = 1

Expected results:

  • Key 2 should return the entity with Id = 2.
  • A nonexistent key such as 999 should return None.

The implementation calls GetTable<T>().Take(1) without reading keyValues.

It also catches every exception and returns None, making database failures indistinguishable from “not found.”

Suggested fix

  • Obtain primary-key metadata using MappingSchema.GetEntityDescriptor(typeof(T)).
  • Order key columns by PrimaryKeyOrder.
  • Validate that the supplied key count matches the mapped primary key.
  • Build an Expression<Func<T, bool>> matching all key columns.
  • Do not silently convert database errors into None.

linq2db caches entity descriptors, so the reflection-overhead concern in the existing comment should not require ignoring key metadata.

3. AddSharpCoreDBLinq2Db(Action<DataOptions>) discards configuration

Location: Extensions.cs:62

Probe result:

LinqToDBException: Invalid configuration. Configuration string is not provided.

DataOptions is immutable: each UseX(...) call returns a new instance. Calling configureOptions(options) through an Action<DataOptions> discards those returned instances, leaving the registered options unconfigured.

Suggested fix

Accept a function and retain its result:

Func<DataOptions, DataOptions>

4. The DataConnection(DataOptions) constructor replaces the user's mapping schema

Location: SharpCoreDBDataConnection.cs:44

The constructor calls options.UseMappingSchema(...), which linq2db documents as replacing previous registrations.

Probe result:

Configured fluent mapping: Unattributed → custom_table
Generated SQL targets:    [Unattributed]

Impact

Custom table and column mappings supplied through the user's mapping schema are silently lost.

Suggested fix

Use UseAdditionalMappingSchema in both the constructor and Bind, preserving the user's schema while adding the SharpCoreDB converters. Verify mapping precedence with regression tests.

5. DI registration shares one connection across scopes

Location: Extensions.cs:31–48

Confirmed observation: Two separate DI scopes received the same DbConnection instance.

The registered options capture an already-created SharpCoreDBConnection. linq2db does not dispose a connection that it does not own.

Impact

ADO.NET connections are not generally safe for concurrent use. Sharing one connection across requests also risks sharing transaction state: one request's transaction could include another request's writes.

Verification boundary: The shared connection instance was reproduced. Concurrent corruption and cross-request rollback were not reproduced; the overlapping-scope probe was sequential.

Suggested fix

Use a connection factory:

UseConnectionFactory(
    provider,
    _ => new SharpCoreDBConnection(connectionString))

Each DataConnection should receive and own its own connection.

SharpCoreDBConnection.Open already uses SharpCoreDBInstancePool with acquire/release reference counting, so separate connection objects can still use the underlying pool.

The same connection-sharing hazard applies when callers reuse the DataOptions returned by CreateOptions.

6. Mapping-schema converters are inconsistent or bypassed

Location: SharpCoreDBMappingSchema.cs

Observed stored values included:

at = '2026-01-01 12:00:00.000'
g  = 'b775aff1-d7f9-…'

The DateTime value was read back with Kind = Unspecified.

GUID formatting

  • The parameter converter writes "D" format (lines 49–50).
  • The GUID-to-string converter uses a different format.
  • The README promises compact ("N") formatting.

Different representations can prevent text-based GUID comparisons from matching stored values.

Date/time conversion

  • The configured "O" converters appear to be bypassed by linq2db's own formatting.
  • DateTimeKind.Utc is not preserved on round-trip.
  • Sub-millisecond ticks are lost.
  • The current test allows a 1 ms tolerance, masking precision loss.
  • DateTime.Parse(str) depends on the current culture and does not specify DateTimeStyles.RoundtripKind.

Other mapping concerns

  • The bool/int converters duplicate SQLite-provider behavior and register a global int → bool conversion.
  • ConfigureCustomMapping mutates the process-wide Instance singleton.
  • Global mutations can leak between connections, while linq2db's mapping caches may prevent later changes from taking effect as expected.

Suggested direction

Define and test one consistent storage format for each supported type. Preserve user-provided mapping schemas rather than requiring mutation of a global singleton.

Design and robustness suggestions

7. Make TransactionAsync rollback cancellation-safe

The error path calls:

RollbackAsync(cancellationToken)

If that token is already cancelled, rollback can fail and obscure the original exception.

Consider using CancellationToken.None for rollback and preserving the original failure. Transaction disposal also provides rollback behavior.

The callback currently has the form:

Func<Task<TResult>>

Consider exposing the participating context and token explicitly:

Func<FunctionalLinq2DbContext, CancellationToken, Task<TResult>>

8. Make the error model consistent

Current behavior differs by method:

  • GetByIdAsync swallows exceptions.
  • FindOne, Query, and GetAll throw.
  • Mutation methods return Fin.
  • Cancellation before a call throws, while cancellation during a call can become Fin.Fail.

Choose and document a consistent policy. For example:

  • Reads return Fin<Option<T>> where appropriate.
  • Cancellation always propagates.
  • Non-cancellation failures follow the documented result model.

Where exceptions are converted to results, exclude cancellation:

catch (Exception ex) when (ex is not OperationCanceledException)
{
    // Convert the failure to the documented result type.
}

9. Make InsertBatchAsync configurable and preserve row-count range

  • MaxBatchSize = 1000 is hard-coded.
  • With UseParameters = true, the parameter count grows with both batch size and mapped column count.
  • Casting RowsCopied from long to int can overflow for large imports.

Consider accepting optional BulkCopyOptions and returning long.

10. Register FunctionalLinq2DbContext in DI

The wrapper currently requires manual registration. Provide a supported registration with a documented lifetime and connection-ownership model to reduce accidental connection sharing.

11. Investigate whether the SQLite native dependency can be avoided

Microsoft.Data.Sqlite brings in the SQLitePCLRaw native bundle (e_sqlite3), even though SharpCoreDB executes the SQL.

A dialect-only provider could potentially remove that dependency and reduce confusion around the provider arrangement discussed in #497.

Not yet verified: This requires checking linq2db's provider constructors and supported configuration paths.

12. Update README and package claims

The README currently:

  • Refers to v1.9.5.
  • Shows installation with --version 2.0.0.0.
  • Claims “Zero-dependency.”
  • Claims “Native AOT.”
  • Describes GUID storage as a “compact string.”

These statements should be reconciled with the current implementation and dependencies.

Because linq2db compiles expressions at runtime, the Native AOT claim should be validated with a PublishAot smoke test rather than assumed.

Changes to the .csproj package description may require separate consideration under the project's release-metadata rule.

13. Minor cleanup and allocation improvements

  • SharpCoreDBDataProvider.cs contains SharpCoreDBProviderExtensions; align the filename and type name.
  • Remove unused using directives.
  • Replace Take(1).ToListAsync() in FindOneAsync with FirstOrDefaultAsync() where semantics permit.
  • Review the list-to-Seq materialization in QueryAsync to avoid unnecessary intermediate allocations.
  • Remove obsolete SQLite -wal/-shm file cleanup from the test fixture.

Test coverage gaps

The current suite reports 26/26 passing, but does not cover:

  • GetByIdAsync returning the requested entity.
  • GetByIdAsync returning None for a missing key.
  • Composite-key ordering and key-count validation.
  • Both DI registration overloads.
  • Separate connection instances across DI scopes.
  • Connection ownership and disposal.
  • UseSharpCoreDB.
  • Preservation of a user-supplied mapping schema.
  • DateTime filters using ==, <, and >.
  • Scalar functions over columns in projections and WHERE clauses.
  • String-function translations such as upper, length, and substr.
  • GUID filtering and consistent storage format.
  • Date/time kind and precision guarantees.
  • DeleteAsync(entity).
  • Fin.Fail paths.
  • Consistent cancellation behavior.

Suggested priority

  1. Fix scalar-function evaluation over columns.
  2. Fix GetByIdAsync key handling.
  3. Fix immutable DataOptions configuration.
  4. Preserve user mapping schemas.
  5. Correct DI connection creation and ownership.
  6. Resolve converter inconsistencies and add regression coverage.
  7. Address the remaining API, documentation, and cleanup items.

Activity

  1. added
    bug
    enhancement
    on Nov 18, 2026
  2. added a commit that references this issue on Nov 28, 2026
  3. MPCoreDeveloper commented on Nov 28, 2026

    @MPCoreDeveloper
    Owner

    Thanks @CastleSoft — this report was exceptional. Every one of the 13 points came with a probe, the expected result and the exception text, which is what made it possible to fix the whole set in one pass.

    Status: all 13 points are addressed on master. The fixes landed in PR #516 (fix/linq2db-adapter-and-scalar-functions) and the engine stack #518–#524.

    # Point Status / where
    1 Scalar functions over columns Fixed — SqlScalarExpression + SqlDateTimeFunctions evaluate per row; ScalarFunctionOverColumnTests
    2 GetByIdAsync ignored keys Fixed — real PK predicate from PrimaryKeyOrder, key-count/type validation, errors propagate; GetByIdAsyncTests (9 cases, all red before)
    3 AddSharpCoreDBLinq2Db(Action<DataOptions>) discarded config Fixed — overload is now Func<DataOptions, DataOptions>; DependencyInjectionTests
    4 DataConnection(DataOptions) replaced the mapping schema Fixed — UseAdditionalMappingSchema, the caller's schema keeps priority; MappingSchemaTests
    5 DI shared one connection Fixed — options carry a connection factory, each scope owns its connection (shares the instance pool); DependencyInjectionTests
    6 Converter / culture / Guid format / DateTimeKind Fixed — one SqlLiteralFormatter, invariant culture, RoundtripKind, D Guid form; SqlLiteralCultureTests (72 cases), MappingSchemaTests
    7 TransactionAsync rollback cancellation-safe Fixed — TransactionAsync((ctx, token) => …); cancellation always surfaces as OperationCanceledException
    8 Error model consistency Fixed — documented contract: Option/Seq throw, Fin captures Fail, cancellation always throws
    9 InsertBatchAsync configurable / row-count range Fixed — InsertBatchAsync(entities, BulkCopyOptions); ProviderSpecific mapped to MultipleRows
    10 Register FunctionalLinq2DbContext in DI Fixed — AddSharpCoreDBLinq2Db registers it with the same lifetime (TryAdd, caller's registration kept)
    11 Avoid the SQLite native dependency Fixed — depends on Microsoft.Data.Sqlite.Core, no e_sqlite3 bundle
    12 README / package claims Fixed — version line, install, “zero-dependency”/Native-AOT claims removed, contract documented
    13 Minor cleanup Done — SharpCoreDBProviderExtensions rename, dead SqlParser.EvaluateScalarFunction removed, obsolete -wal/-shm cleanup dropped

    Verification — Release build of master (net11.0 / .NET 11), commit e74ebe3f:

    • SharpCoreDB.Tests — 2449 / 0 failed (6 skipped)
    • SharpCoreDB.Functional.Linq2DB.Tests — 96 / 0 (was 26 at report time)
    • SharpCoreDB.EntityFrameworkCore.Tests — 116 / 0
    • SharpCoreDB.VectorSearch.Tests — 255 / 0

    Your exact probes are now pinned directly by ScalarFunctionOverColumnTests and GetByIdAsyncTests (e.g. SELECT upper(at) FROM T, GetByIdAsync([2]) → Id = 2, GetByIdAsync([999]) → None), and both pass.

    The fixes are on master and will be in the next published package. Per the project's issue-closure policy this stays open until that release is published — the moment it ships I'll close it naming the version. You are credited in CONTRIBUTORS.md for this report and for the #518–#524 engine stack. Thank you!

  4. MPCoreDeveloper commented on Nov 28, 2026

    @MPCoreDeveloper
    Owner

    Closed as resolved — all 13 points are addressed on master.

    Recap of the resolution:

    # Point Where
    1 Scalar functions over columns SqlScalarExpression + SqlDateTimeFunctions evaluate per row; ScalarFunctionOverColumnTests
    2 GetByIdAsync ignored keys Real PK predicate from PrimaryKeyOrder, key-count/type validation, errors propagate; GetByIdAsyncTests (9 cases, red before)
    3 AddSharpCoreDBLinq2Db(Action<DataOptions>) discarded config Now Func<DataOptions, DataOptions>; DependencyInjectionTests
    4 DataConnection(DataOptions) replaced the mapping schema UseAdditionalMappingSchema, the caller's schema keeps priority; MappingSchemaTests
    5 DI shared one connection Connection factory per scope; DependencyInjectionTests
    6 Converter / culture / Guid / DateTimeKind One SqlLiteralFormatter, invariant + RoundtripKind, D Guid form; SqlLiteralCultureTests (72 cases), MappingSchemaTests
    7 TransactionAsync rollback cancellation-safe TransactionAsync((ctx, token) => …); cancellation always OperationCanceledException
    8 Error model consistency Documented contract: Option/Seq throw, Fin captures Fail, cancellation throws
    9 InsertBatchAsync configurable InsertBatchAsync(entities, BulkCopyOptions); ProviderSpecific → MultipleRows
    10 Register FunctionalLinq2DbContext in DI AddSharpCoreDBLinq2Db registers it (TryAdd)
    11 Avoid the SQLite native dependency Depends on Microsoft.Data.Sqlite.Core, no e_sqlite3 bundle
    12 README / package claims Version line and install fixed, “zero-dependency”/Native-AOT claims removed, contract documented
    13 Minor cleanup SharpCoreDBProviderExtensions rename, dead code removed, obsolete -wal/-shm cleanup dropped

    Evidence — full run on master before the next release:

    • SharpCoreDB.Functional.Linq2DB.Tests — 96 / 0 (was 26 at report time).
    • Core 2980 / 0 (6 skipped), EF Core 116 / 0, VectorSearch 255 / 0.
    • Full matrix across all 17 test projects: 4886 / 0 failed / 6 skipped.

    The fixes landed in PR #516 (fix/linq2db-adapter-and-scalar-functions) and the engine stack #518–#524, and are on master now; they will be in the next published package (the current published 2.1.4 predates them).

    You are credited in CONTRIBUTORS.md for this report and for the #518–#524 engine stack. Thank you — this was an exceptionally actionable report.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugenhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions