Hellnet.Database 1.1.2

dotnet add package Hellnet.Database --version 1.1.2
                    
NuGet\Install-Package Hellnet.Database -Version 1.1.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Hellnet.Database" Version="1.1.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Hellnet.Database" Version="1.1.2" />
                    
Directory.Packages.props
<PackageReference Include="Hellnet.Database" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Hellnet.Database --version 1.1.2
                    
#r "nuget: Hellnet.Database, 1.1.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Hellnet.Database@1.1.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Hellnet.Database&version=1.1.2
                    
Install as a Cake Addin
#tool nuget:?package=Hellnet.Database&version=1.1.2
                    
Install as a Cake Tool

Hellnet.Database

Biblioteca de infraestrutura de banco de dados PostgreSQL-first para .NET. Configuração via environment variables, modular, cloud-native.

Env vars → HellnetDatabaseOptions → NpgsqlDataSource → IDatabaseExecutor / IRepository<T>

NuGet


Instalação

dotnet add package Hellnet.Database

Configuração

Via environment variables (recomendado)

export HELLNET_DATABASE_HOST=localhost
export HELLNET_DATABASE_PORT=5432
export HELLNET_DATABASE_NAME=mydb
export HELLNET_DATABASE_USERNAME=postgres
export HELLNET_DATABASE_PASSWORD=password
builder.Services.AddHellnetDatabase();

Via options explícitas

builder.Services.AddHellnetDatabase(new HellnetDatabaseOptions
{
    Host = "pg.internal",
    Database = "orders",
    Username = "app",
    Password = "secret",
});

Uso

IDatabaseExecutor — SQL puro com Dapper

public class OrderService
{
    private readonly IDatabaseExecutor _db;

    public OrderService(IDatabaseExecutor db) => _db = db;

    // Query
    public async Task<IReadOnlyList<Order>> GetPendingAsync()
        => await _db.QueryAsync<Order>(
            "SELECT * FROM orders WHERE status = @Status",
            new { Status = "pending" });

    // Single row
    public async Task<Order?> GetByIdAsync(int id)
        => await _db.QueryFirstOrDefaultAsync<Order>(
            "SELECT * FROM orders WHERE id = @Id", new { Id = id });

    // Execute (insert/update/delete)
    public async Task<int> UpdateStatusAsync(int id, string status)
        => await _db.ExecuteAsync(
            "UPDATE orders SET status = @Status WHERE id = @Id",
            new { Id = id, Status = status });

    // Scalar
    public async Task<int> CountAsync()
        => await _db.ExecuteScalarAsync<int>(
            "SELECT COUNT(*) FROM orders");
}

Transações

await db.TransactionAsync(async tx =>
{
    await tx.ExecuteAsync("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    await tx.ExecuteAsync("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
});
// Commit automático. Se exception → rollback automático.

Repository Pattern

public class ProductService
{
    private readonly IRepository<Product> _products;

    public ProductService(IRepository<Product> products) => _products = products;

    public async Task<Product?> GetAsync(int id) => await _products.GetByIdAsync(id);

    public async Task<IReadOnlyList<Product>> SearchAsync(ProductSpec spec)
        => await _products.FindAsync(spec);
}

public sealed class ProductSpec(string term) : ISpecification<Product>
{
    public string Sql => "SELECT * FROM products WHERE name ILIKE @Term";
    public object? Parameters => new { Term = $"%{term}%" };
    public string? OrderBy => null;
}

Resultados tipados

DatabaseResult<User> result = await DatabaseResult<User>.Success(user, duration);
if (result.IsSuccess) { /* use result.Data */ }

PageResult<Order> page = new()
{
    Items = orders,
    TotalCount = 100,
    Page = 1,
    PageSize = 20,
};

Variáveis de Ambiente

Variável Obrigatório Padrão Descrição
HELLNET_DATABASE_HOST localhost Host do PostgreSQL
HELLNET_DATABASE_PORT 5432 Porta
HELLNET_DATABASE_NAME Nome do banco
HELLNET_DATABASE_USERNAME Usuário
HELLNET_DATABASE_PASSWORD Senha
HELLNET_DATABASE_POOL_MIN_SIZE 10 Pool mínimo
HELLNET_DATABASE_POOL_MAX_SIZE 100 Pool máximo
HELLNET_DATABASE_COMMAND_TIMEOUT_SECONDS 30 Command timeout
HELLNET_DATABASE_RETRY_ENABLED true Habilitar retry
HELLNET_DATABASE_RETRY_MAX_COUNT 3 Máximo de retry attempts
HELLNET_DATABASE_RETRY_BASE_DELAY_MS 100 Delay base do backoff

Resiliência (Polly)

Retry automático com exponential backoff. Erros permanentes não são retentados:

SQL State Erro Motivo
42601 syntax_error Bug no código
23505 unique_violation Dado duplicado
23503 foreign_key_violation Referência inválida
42501 insufficient_privilege Permissão negada
42P01 undefined_table Tabela não existe
42703 undefined_column Coluna não existe

Desabilitar por env:

export HELLNET_DATABASE_RETRY_ENABLED=false

Arquitetura

Hellnet.Database
├── Abstractions
│   ├── IDatabaseExecutor       ← QueryAsync, ExecuteAsync, Scalar
│   ├── IDatabaseTransaction    ← Begin/Commit/Rollback
│   ├── IDatabaseConnectionFactory ← Factory pattern
│   ├── IRepository<T>          ← CRUD genérico
│   ├── ISpecification<T>       ← Query filters
│   ├── DatabaseResult<T>       ← Typed result
│   └── PageResult<T>           ← Paginated result
├── Configuration
│   ├── HellnetDatabaseOptions  ← Options imutáveis (init)
│   └── DatabaseEnvBinder       ← Env-first reader
├── PostgreSql
│   ├── PostgresConnectionFactory  ← NpgsqlDataSource
│   ├── NpgsqlExecutor             ← Dapper
│   ├── NpgsqlTransaction          ← Transaction
│   └── PostgresRepository<T>      ← Repository implementation
└── Resilience
    └── DatabaseRetryPolicy     ← Polly + SQL state discrimination

Observabilidade

Hellnet.Database não possui instrumentação própria. Use os pacotes OpenTelemetry padrão:

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddNpgsql())
    .WithMetrics(m => m.AddNpgsqlInstrumentation());

Health checks e logging são delegados ao Hellnet.Observability.


Repositórios Relacionados

Repo Propósito
hellnet-dep-kafka Kafka pub/sub
hellnet-dep-observability OpenTelemetry + logging
hellnet-dep-cache Multi-layer cache
hellnet-dep-schema Schema registry management

Licença

Apache 2.0 © 2026 Hellnet

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.1.2 125 7/9/2026
1.0.9 109 7/9/2026