Nexttag.Data.Sql.Postgres 1.0.0

dotnet add package Nexttag.Data.Sql.Postgres --version 1.0.0
                    
NuGet\Install-Package Nexttag.Data.Sql.Postgres -Version 1.0.0
                    
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="Nexttag.Data.Sql.Postgres" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Nexttag.Data.Sql.Postgres" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Nexttag.Data.Sql.Postgres" />
                    
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 Nexttag.Data.Sql.Postgres --version 1.0.0
                    
#r "nuget: Nexttag.Data.Sql.Postgres, 1.0.0"
                    
#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 Nexttag.Data.Sql.Postgres@1.0.0
                    
#: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=Nexttag.Data.Sql.Postgres&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Nexttag.Data.Sql.Postgres&version=1.0.0
                    
Install as a Cake Tool

Nexttag.Data.Sql.Postgres

Provider PostgreSQL para Nexttag.Data.Sql: introspecta schema via information_schema e executa consultas em transação somente-leitura com statement_timeout.

Instalar

dotnet add package Nexttag.Data.Sql.Postgres
dotnet add package Nexttag.Data.Sql

Requer .NET 10.

Registrar (Program.cs)

var connStr = builder.Configuration.GetConnectionString("Datasource")
    ?? throw new InvalidOperationException("ConnectionStrings:Datasource ausente.");

builder.Services.AddSingleton<ISqlSchemaReader>(_ => new PgSqlSchemaReader(connStr));
builder.Services.AddSingleton<ISqlExecutor>(_ => new PgSqlExecutor(connStr));

Para múltiplos datasources (multi-tenant), instancie PgSqlSchemaReader/PgSqlExecutor por requisição passando a connection string do tenant.

Configurar

// appsettings.json
{
  "ConnectionStrings": {
    "Datasource": "Host=192.168.0.172;Port=5432;Database=meu_banco;Username=readonly_user;Password=<senha>"
  }
}

Pré-requisito de infra: PostgreSQL compartilhado em 192.168.0.172:5432 (dev: dev_postgres:5432).

Recomendação: use um usuário com permissão apenas de SELECT. A lib aplica SET TRANSACTION READ ONLY e statement_timeout, mas o usuário read-only é a camada mais importante.

-- Criar usuário read-only no banco do cliente
CREATE USER readonly_user WITH PASSWORD '<senha>';
GRANT CONNECT ON DATABASE meu_banco TO readonly_user;
GRANT USAGE ON SCHEMA public TO readonly_user;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly_user;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly_user;

Usar

PgSqlSchemaReader — introspectar schema

var allow = new[] {
    new TableRef("public", "pedidos"),
    new TableRef("public", "clientes")
};

var schemaReader = new PgSqlSchemaReader(connStr);
IReadOnlyList<TableInfo> schema = await schemaReader.ReadAsync(allow, ct);
// schema[0].Schema, schema[0].Name, schema[0].Columns (List<ColumnInfo>)

PgSqlExecutor — executar consulta read-only

var executor = new PgSqlExecutor(connStr);

// Testar conectividade
await executor.TestConnectionAsync(ct); // lança se falhar

// Executar SELECT validado
var resultado = await executor.ExecuteAsync(
    sql: "SELECT id, total FROM public.pedidos LIMIT 100",
    maxRows: 1000,
    timeoutSeconds: 15,
    ct: ct);

foreach (var row in resultado.Rows)
    Console.WriteLine(string.Join(", ", row));

Receitas

Uso completo com NlToSql e SqlGuard

var allow = new[] { new TableRef("public", "pedidos"), new TableRef("public", "clientes") };
var schema   = await new PgSqlSchemaReader(connStr).ReadAsync(allow, ct);
var proposta = await new NlToSql(chatClient).GenerateAsync("top 5 clientes por valor", schema);
var veredito = SqlGuard.Validate(proposta.Sql, allow);
if (!veredito.Allowed) return Results.Problem(veredito.Reason, statusCode: 422);
var dados    = await new PgSqlExecutor(connStr).ExecuteAsync(veredito.Sql, maxRows: 500);

Instanciar por tenant (sem DI singleton)

// Em um serviço scoped que carrega a conn string do datasource do tenant
var executor = new PgSqlExecutor(_protector.Unprotect(datasource.ConnectionStringEnc));
var resultado = await executor.ExecuteAsync(sql, maxRows: 1000, timeoutSeconds: 15, ct);

Testar conexão no health check

app.MapGet("/health/db", async (ISqlExecutor executor) => {
    await executor.TestConnectionAsync();
    return Results.Ok("ok");
});

Notas

  • Transação READ ONLY + SET LOCAL statement_timeout são aplicados em toda execução — o banco rejeita qualquer DML mesmo que passe pelo guard.
  • ReadAsync consulta information_schema.columns — o usuário precisa de USAGE no schema para enxergar as tabelas.
  • maxRows no ExecuteAsync trunca o cursor no lado .NET (não injeta LIMIT — use SqlGuard.Validate antes para garantir LIMIT no SQL).
  • Em produção (single-tenant), a connection string vem do IConfiguration. Em multi-tenant, instancie por request com a conn string do cliente.
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.0.0 136 6/17/2026