Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 5 additions & 4 deletions src/frontend/sidebar.topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -994,12 +994,13 @@ export const sidebarTopics: StarlightSidebarTopicsUserConfig = [
]
},
{ label: "Oracle", slug: "integrations/databases/oracle" },
{
label: "PostgreSQL",
{ label: "PostgreSQL",
collapsed: true,
items: [
{ label: "Integration overview", slug: "integrations/databases/postgres" },
{ label: "Community extensions", slug: "integrations/databases/postgresql-extensions" }
{ label: "Get started", slug: "integrations/databases/postgres/postgres-get-started" },
{ label: "Hosting integration (AppHost)", slug: "integrations/databases/postgres/postgres-host" },
{ label: "Client integration (Your app)", slug: "integrations/databases/postgres/postgres-client" },
{ label: "Community extensions", slug: "integrations/databases/postgres/postgresql-extensions" }
]
},
{ label: "Qdrant", slug: "integrations/databases/qdrant" },
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
---
title: PostgreSQL Client integration reference
description: Learn how to use the Aspire PostgreSQL Client integration to query PostgreSQL databases from your Aspire projects.
---

import { Image } from 'astro:assets';
import InstallPackage from '@components/InstallPackage.astro';
import InstallDotNetPackage from '@components/InstallDotNetPackage.astro';
import { Aside, Code, Steps, Tabs, TabItem } from '@astrojs/starlight/components';
import postgresIcon from '@assets/icons/postgresql-icon.png';

<Image
src={postgresIcon}
alt="PostgreSQL logo"
width={100}
height={100}
class:list={'float-inline-left icon'}
data-zoom-off
/>

To get started with the Aspire PostgreSQL integrations, follow the [Get started with PostgreSQL integrations](../postgres-get-started/) guide.

In this article includes full details about the Aspire PostgreSQL Client integration, which allows you to connect to and interact with PostgreSQL databases from your Aspire consuming projects.

## Installation

To get started with the Aspire PostgreSQL client integration, install the [📦 Aspire.Npgsql](https://www.nuget.org/packages/Aspire.Npgsql) NuGet package in the client-consuming project, that is, the project for the application that uses the PostgreSQL client. The PostgreSQL client integration registers an [NpgsqlDataSource](https://www.npgsql.org/doc/api/Npgsql.NpgsqlDataSource.html) instance that you can use to interact with PostgreSQL.

<InstallDotNetPackage packageName="Aspire.Npgsql" />

## Add Npgsql client

In the `Program.cs` file of your client-consuming project, call the `AddNpgsqlDataSource` extension method on any `IHostApplicationBuilder` to register an `NpgsqlDataSource` for use via the dependency injection container. The method takes a connection name parameter.

```csharp title="C# — Program.cs"
builder.AddNpgsqlDataSource(connectionName: "postgresdb");
```

<Aside type="tip">
The `connectionName` parameter must match the name used when adding the PostgreSQL server resource in the AppHost project. For more information, see [Add PostgreSQL server resource](#add-postgresql-server-resource).
</Aside>

After adding `NpgsqlDataSource` to the builder, you can get the `NpgsqlDataSource` instance using dependency injection. For example, to retrieve your data source object from an example service define it as a constructor parameter and ensure the `ExampleService` class is registered with the dependency injection container:

```csharp title="C# — ExampleService.cs"
public class ExampleService(NpgsqlDataSource dataSource)
{
// Use dataSource...
}
```

## Add keyed Npgsql client

There might be situations where you want to register multiple `NpgsqlDataSource` instances with different connection names. To register keyed Npgsql clients, call the `AddKeyedNpgsqlDataSource` method:

```csharp title="C# — Program.cs"
builder.AddKeyedNpgsqlDataSource(name: "chat");
builder.AddKeyedNpgsqlDataSource(name: "queue");
```

Then you can retrieve the `NpgsqlDataSource` instances using dependency injection. For example, to retrieve the connection from an example service:

```csharp title="C# — ExampleService.cs"
public class ExampleService(
[FromKeyedServices("chat")] NpgsqlDataSource chatDataSource,
[FromKeyedServices("queue")] NpgsqlDataSource queueDataSource)
{
// Use data sources...
}
```

## Properties of the PostgreSQL resources

When you use the `WithReference` method to pass a PostgreSQL server or database resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

Aspire exposes each property as an environment variable named `[RESOURCE]_[PROPERTY]`. For instance, the `Uri` property of a resource called `db1` becomes `DB1_URI`.

### PostgreSQL server resource

The PostgreSQL server resource exposes the following connection properties:

| Property Name | Description |
|---------------|-------------|
| `Host` | The hostname or IP address of the PostgreSQL server |
| `Port` | The port number the PostgreSQL server is listening on |
| `Username` | The username for authentication |
| `Password` | The password for authentication |
| `Uri` | The connection URI in postgresql:// format, with the format `postgresql://{Username}:{Password}@{Host}:{Port}` |
| `JdbcConnectionString` | JDBC-format connection string, with the format `jdbc:postgresql://{Host}:{Port}`. User and password credentials are provided as separate `Username` and `Password` properties. |

### PostgreSQL database resource

The PostgreSQL database resource inherits all properties from its parent `PostgresServerResource` and adds:

| Property Name | Description |
|---------------|-------------|
| `Uri` | The connection URI with the database name, with the format `postgresql://{Username}:{Password}@{Host}:{Port}/{DatabaseName}` |
| `JdbcConnectionString` | JDBC connection string with database name, with the format `jdbc:postgresql://{Host}:{Port}/{DatabaseName}`. User and password credentials are provided as separate `Username` and `Password` properties. |
| `DatabaseName` | The name of the database |

## Configuration

The Aspire PostgreSQL integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.

### Use a connection string

When using a connection string from the `ConnectionStrings` configuration section, you can provide the name of the connection string when calling the `AddNpgsqlDataSource` method:

```csharp title="C# — Program.cs"
builder.AddNpgsqlDataSource("postgresdb");
```

Then the connection string will be retrieved from the `ConnectionStrings` configuration section:

```json title="JSON — appsettings.json"
{
"ConnectionStrings": {
"postgresdb": "Host=myserver;Database=postgresdb"
}
}
```

For more information, see the [ConnectionString](https://www.npgsql.org/doc/connection-string-parameters.html).

### Use configuration providers

The Aspire PostgreSQL integration supports `Microsoft.Extensions.Configuration`. It loads the `NpgsqlSettings` from `appsettings.json` or other configuration files by using the `Aspire:Npgsql` key. Example `appsettings.json` that configures some of the options:

The following example shows an `appsettings.json` file that configures some of the available options:

```json title="JSON — appsettings.json"
{
"Aspire": {
"Npgsql": {
"ConnectionString": "Host=myserver;Database=postgresdb",
"DisableHealthChecks": false,
"DisableTracing": true,
"DisableMetrics": false
}
}
}
```

For the complete PostgreSQL client integration JSON schema, see [Aspire.Npgsql/ConfigurationSchema.json](https://github.com/dotnet/aspire/blob/v9.1.0/src/Components/Aspire.Npgsql/ConfigurationSchema.json).

### Use inline delegates

You can also pass the `Action<NpgsqlSettings> configureSettings` delegate to set up some or all the options inline, for example to disable health checks:

```csharp title="C# — Program.cs"
builder.AddNpgsqlDataSource(
"postgresdb",
static settings => settings.DisableHealthChecks = true);
```

## Client integration health checks

By default, Aspire _client integrations_ have health checks enabled for all services. Similarly, many Aspire _hosting integrations_ also enable health check endpoints. For more information, see:

- Adds the [`NpgSqlHealthCheck`](https://github.com/Xabaril/AspNetCore.Diagnostics.HealthChecks/blob/master/src/HealthChecks.NpgSql/NpgSqlHealthCheck.cs), which verifies that commands can be successfully executed against the underlying Postgres database.
- Integrates with the `/health` HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

## Observability and telemetry

Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as *the pillars of observability*. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the [Configuration](#configuration) section.

### Logging

The Aspire PostgreSQL integration uses the following log categories:

- `Npgsql.Connection`
- `Npgsql.Command`
- `Npgsql.Transaction`
- `Npgsql.Copy`
- `Npgsql.Replication`
- `Npgsql.Exception`

### Tracing

The Aspire PostgreSQL integration will emit the following tracing activities using OpenTelemetry:

- `Npgsql`

### Metrics

The Aspire PostgreSQL integration will emit the following metrics using OpenTelemetry:

- Npgsql:
- `ec_Npgsql_bytes_written_per_second`
- `ec_Npgsql_bytes_read_per_second`
- `ec_Npgsql_commands_per_second`
- `ec_Npgsql_total_commands`
- `ec_Npgsql_current_commands`
- `ec_Npgsql_failed_commands`
- `ec_Npgsql_prepared_commands_ratio`
- `ec_Npgsql_connection_pools`
- `ec_Npgsql_multiplexing_average_commands_per_batch`
- `ec_Npgsql_multiplexing_average_write_time_per_batch`
Loading
Loading