Branch Status
main Dotnet 10

SharpPersistence

SharpPersistence is a collection of robust, extensible, and thoroughly tested .NET libraries for working with database systems.

Installation

To install the packages, run the following commands:

dotnet add package SharpPersistence.Abstractions
dotnet add package SharpPersistence
dotnet add package SharpPersistence.EfCore

Or visit:

Features

SqlParser

Basic Usage

1. Create SQL files with tagged blocks:

-- #start# GetAllUsers
SELECT u.Id, u.Name, u.Email, u.CreatedAt
FROM Users u
WHERE u.Id = :userId
ORDER BY u.Name
-- #end# GetAllUsers

-- #start# GetActiveUsers
SELECT u.Id, u.Name, u.Email
FROM Users u
WHERE u.IsActive = 1 AND u.IsDeleted = 0
ORDER BY u.LastLoginDate DESC
-- #end# GetActiveUsers

2. Configure your project to copy SQL files:


<Project>
    <PropertyGroup>
        <DefaultItemExcludes>
            $(DefaultItemExcludes);out/**;publish/**;bin/**;obj/**
        </DefaultItemExcludes>
    </PropertyGroup>

    <ItemGroup>
        <Content Include="**\*.sql"
                 Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)"
                 CopyToOutputDirectory="PreserveNewest"
                 TargetPath="sharp_persistence_sql_files\$(AssemblyName)\%(RecursiveDir)\%(Filename)%(Extension)"/>
    </ItemGroup>
</Project>


<PropertyGroup>
    <DefaultItemExcludes>
        $(DefaultItemExcludes);out/**;publish/**;bin/**;obj/**
    </DefaultItemExcludes>
</PropertyGroup>

<ItemGroup>
<Content Include="**\*.sql"
         Exclude="$(DefaultItemExcludes);$(DefaultExcludesInProjectFolder)"
         CopyToOutputDirectory="PreserveNewest"
         TargetPath="sharp_persistence_sql_files\$(AssemblyName)\%(RecursiveDir)\%(Filename)%(Extension)"/>
</ItemGroup>

3. Parse and use in your application:

// Parse SQL files at startup
IParsedSqlStorage parsedSqlStorage = new SqlParser().ParseFromStorage();

// Access parsed SQL by tag name (case-insensitive) through C# indexer
string getAllUsersQuery = parsedSqlStorage["GetAllUsers"];
// Use the query...

// Safe access with TryGet
if (parsedSqlStorage.TryGetParsedSql("GetAllUsers", out string? query))
{
    // Use the query...
}

4. Dependency Injection (ASP.NET Core):

// In Program.cs
IParsedSqlStorage parsedSqlStatements = new SqlParser().ParseFromStorage();
builder.Services.AddSingleton<IParsedSqlStorage>(parsedSqlStatements);

// In your service classes
public class UserService
{
    private readonly IDbConnectionFactory _dbConnectionFactory;
    private readonly IParsedSqlStorage _parsedSqlStorage;

    public UserService(IDbConnectionFactory dbConnectionFactory, IParsedSqlStorage parsedSqlStorage)
    {
        _dbConnectionFactory = dbConnectionFactory;
        _parsedSqlStorage = parsedSqlStorage;
    }

    public async Task<IEnumerable<User>> GetAllUsersAsync(int userId, CancellationToken ct)
    {
        var sql = _parsedSqlStorage["GetAllUsers"];

        await using var connection = await _dbConnectionFactory.CreateConnectionAsync(ct);

        var parameters = new { userId };

        return await connection.QueryAsync<User>(new CommandDefinition(sql, parameters,
            cancellationToken: ct));
    }
}

Notes: SqlParser validates your SQL files at startup and throws detailed error messages for:

SqlCheckConstraintBuilder

Setup

var cc = new SqlCheckConstraintBuilder
{
    Dialect = SqlDialect.PostgreSql,                   // PostgreSql | MySql | SqlServer | Oracle | Sqlite
    IdentifierCase = SqlIdentifierCase.LowerSnakeCase, // PascalCase | LowerSnakeCase | UpperSnakeCase
    DelimitIdentifiers = true,                         // required
    NestedSeparator = "_"                              // optional, default "_"
};

Column Selection & Operations

Examples with EF Core IEntityTypeConfiguration

var cc = new SqlCheckConstraintBuilder
{
    Dialect = SqlDialect.PostgreSql,
    IdentifierCase = SqlIdentifierCase.LowerSnakeCase,
    DelimitIdentifiers = false
};

var order = cc.For<Order>();

builder.ToTable(t =>
{
    t.HasCheckConstraint("ck_order_country",
        order.NestedColumn(x => x.ShippingAddress.Country).Length().In(2, 3));

    t.HasCheckConstraint("ck_order_net_total",
        order.Column(x => x.Subtotal).Math().Minus(order.Column(x => x.Discount).Coalesce(0m).Math()).GreaterThan(0));

    t.HasCheckConstraint("ck_order_status",
        order.Column(x => x.Status).EnumAsString().In(OrderStatus.Draft, OrderStatus.Confirmed));

    t.HasCheckConstraint("ck_order_priority",
        order.Column(x => x.IsPriority).BoolAsNumeric().EqualTo(1));

    t.HasCheckConstraint(
        "ck_order_shipped_at",
        cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Shipped))
          .Then(order.Column(x => x.ShippedAt).IsNotNull())
    );

    // Multi-branch conditional rule via cc.If(...).Then(...) (all dialects including Oracle)
    t.HasCheckConstraint(
        "ck_order_status_timestamps",
        cc.And(
            cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Shipped))
              .Then(order.Column(x => x.ShippedAt).IsNotNull()),
            cc.If(order.Column(x => x.Status).EqualTo(OrderStatus.Cancelled))
              .Then(order.Column(x => x.CancelledAt).IsNotNull())
        )
    );

    // Multi-branch CASE (for PostgreSQL/MySQL; for Oracle prefer cc.If(...).Then(...))
    t.HasCheckConstraint(
        "ck_order_discount_tier",
        cc.Case()
            .When(order.Column(x => x.Total).GreaterThan(100m))
            .Then(order.Column(x => x.Discount).LessThanOrEqual(50m))
            .EndWithElse(order.Column(x => x.Discount).LessThanOrEqual(10m))
    );

    t.HasCheckConstraint("ck_order_tenant",
        cc.RawColumn<Guid>("tenant_id").NotEqualTo(Guid.Empty));
});

RepositoryCore with IRepositoryCore

// Register / inject IRepositoryCore<User> (or your derived interface)
var allData = await repo.Query()
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .OffsetPaginate(page: 1, limit: 20)
    .Select(u => new { u.Id, u.Name })
    .GetAllAsync(ct);

var singleData = await repo.Query()
    .Where(u => u.Id == id)
    .EnableTracking()
    .GetFirstOrDefaultAsync(ct);

bool hasPending = await repo.Query()
    .Where(u => u.IsActive)
    .ExistsAsync(u => u.IsPending, ct);

int deleted = await repo.RemoveManyDirectAsync(u => !u.IsActive, ct);

int purged = await repo.RemoveManyDirectIgnoringFiltersAsync(
    u => u.IsDeleted,
    [AppDbContext.SoftDeleteFilter],
    ct);

// Aggregates (single column or computed expression)
decimal total = await orderRepo.Query()
    .Where(x => x.IsPaid)
    .SumAsync(x => x.Total, ct);

decimal netTotal = await orderRepo.Query()
    .Where(x => x.IsPaid)
    .SumAsync(x => x.Subtotal - x.Discount, ct);

DateTime? latestOrderAt = await orderRepo.Query()
    .Where(x => x.CustomerId == customerId)
    .MaxOrNullAsync(x => x.CreatedAt, ct);

RepositoryBase with IRepositoryBase (Obsolete)

// Legacy overload style (obsolete)
var user = await repo.GetOneAsync(u => u.IsActive);

// Recommended fluent query style (via IRepositoryCore)
var page = await repo.Query()
    .Where(u => u.IsActive)
    .OrderBy(u => u.Name)
    .OffsetPaginate(page: 1, limit: 20)
    .GetAllAsync(ct);

UnitOfWork with IUnitOfWork

Testing

Contributing

Contributions are welcome! Please open issues or submit pull requests for bug fixes, improvements, or new features.