diff --git a/src/frontend/config/sidebar/integrations.topics.ts b/src/frontend/config/sidebar/integrations.topics.ts
index b48da3169..231a8d50e 100644
--- a/src/frontend/config/sidebar/integrations.topics.ts
+++ b/src/frontend/config/sidebar/integrations.topics.ts
@@ -1200,7 +1200,11 @@ export const integrationTopics: StarlightSidebarTopicsUserConfig = {
slug: 'integrations/databases/postgres/postgres-host',
},
{
- label: 'Client integration (Your app)',
+ label: 'Connect to PostgreSQL',
+ slug: 'integrations/databases/postgres/postgres-connect',
+ },
+ {
+ label: 'Client integration (.NET)',
slug: 'integrations/databases/postgres/postgres-client',
},
{
diff --git a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-client.mdx b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-client.mdx
index a4099b059..001e4a022 100644
--- a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-client.mdx
+++ b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-client.mdx
@@ -26,7 +26,11 @@ import postgresIcon from '@assets/icons/postgresql-icon.png';
To get started with the Aspire PostgreSQL integrations, follow the [Get started with PostgreSQL integrations](../postgres-get-started/) guide.
-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.
+This article covers the Aspire PostgreSQL **Client integration** for .NET applications. It uses the [π¦ Aspire.Npgsql](https://www.nuget.org/packages/Aspire.Npgsql) NuGet package to connect to and interact with PostgreSQL databases from your .NET consuming projects.
+
+
## Installation
@@ -80,32 +84,7 @@ public class ExampleService(
## 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 |
+For a full reference of PostgreSQL connection properties and environment variables, see [Connect to PostgreSQL](../postgres-connect/).
## Configuration
diff --git a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-connect.mdx b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-connect.mdx
new file mode 100644
index 000000000..31882e0f1
--- /dev/null
+++ b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-connect.mdx
@@ -0,0 +1,227 @@
+---
+title: Connect to PostgreSQL
+description: Learn how to connect to PostgreSQL from any language when using Aspire to host your PostgreSQL resources.
+---
+
+import { Image } from 'astro:assets';
+import { Aside, Tabs, TabItem } from '@astrojs/starlight/components';
+import postgresIcon from '@assets/icons/postgresql-icon.png';
+
+
+
+When you reference a PostgreSQL resource from the AppHost with `WithReference` (C#) or `withReference` (TypeScript), Aspire automatically injects connection information into the consuming application as environment variables. This page shows how to read those variables and connect to PostgreSQL from any language.
+
+
+
+## Connection properties
+
+Aspire exposes each property as an environment variable named `[RESOURCE]_[PROPERTY]`. For instance, the `Uri` property of a resource called `postgresdb` becomes `POSTGRESDB_URI`.
+
+### PostgreSQL server
+
+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. |
+
+**Example connection strings:**
+
+```
+Uri: postgresql://postgres:p%40ssw0rd1@localhost:5432
+JdbcConnectionString: jdbc:postgresql://localhost:5432
+```
+
+### PostgreSQL database
+
+The PostgreSQL database resource inherits all properties from its parent server resource 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 |
+
+**Example connection strings:**
+
+```
+Uri: postgresql://postgres:p%40ssw0rd1@localhost:5432/catalog
+JdbcConnectionString: jdbc:postgresql://localhost:5432/catalog
+```
+
+## Connect from your application
+
+The following examples show how to connect to PostgreSQL from different languages. Each example assumes you have a PostgreSQL database resource named `postgresdb` referenced from your AppHost.
+
+
+
+
+Install the PostgreSQL client library:
+
+```bash title="Terminal"
+npm install pg
+```
+
+Read the injected environment variables and connect:
+
+```javascript title="JavaScript β index.js"
+import pg from 'pg';
+
+// Read Aspire-injected connection properties
+const client = new pg.Client({
+ user: process.env.POSTGRESDB_USERNAME,
+ host: process.env.POSTGRESDB_HOST,
+ database: process.env.POSTGRESDB_DATABASENAME,
+ password: process.env.POSTGRESDB_PASSWORD,
+ port: process.env.POSTGRESDB_PORT,
+});
+
+await client.connect();
+```
+
+Or use the connection URI directly:
+
+```javascript title="JavaScript β Connect with URI"
+const client = new pg.Client({
+ connectionString: process.env.POSTGRESDB_URI,
+});
+
+await client.connect();
+```
+
+
+
+
+Install a PostgreSQL driver. This example uses `psycopg`:
+
+```bash title="Terminal"
+pip install psycopg[binary]
+```
+
+Read the injected environment variables and connect:
+
+```python title="Python β app.py"
+import os
+import psycopg
+
+# Read the Aspire-injected connection URI
+postgres_uri = os.getenv("POSTGRESDB_URI")
+
+async with await psycopg.AsyncConnection.connect(
+ postgres_uri, autocommit=True
+) as conn:
+ # Use conn to query the database...
+ pass
+```
+
+
+
+
+Use the `pgx` driver, the most actively maintained and feature-rich PostgreSQL driver for Go:
+
+```bash title="Terminal"
+go get github.com/jackc/pgx/v5
+```
+
+> **Note:** [`lib/pq`](https://github.com/lib/pq) is another popular Go PostgreSQL driver, but `pgx` is recommended for new projects because it offers better performance, native PostgreSQL protocol support, and active maintenance.
+
+Read the injected environment variables and connect:
+
+```go title="Go β main.go"
+package main
+
+import (
+ "context"
+ "os"
+ "github.com/jackc/pgx/v5"
+)
+
+func main() {
+ // Read the Aspire-injected connection URI
+ connStr := os.Getenv("POSTGRESDB_URI")
+
+ conn, err := pgx.Connect(context.Background(), connStr)
+ if err != nil {
+ panic(err)
+ }
+ defer conn.Close(context.Background())
+}
+```
+
+
+
+
+For .NET applications, the recommended approach is to use the [Client integration (.NET)](../postgres-client/), which provides automatic dependency injection, health checks, and telemetry.
+
+If you prefer to connect using environment variables directly:
+
+```csharp title="C# β Program.cs"
+var connectionString = Environment.GetEnvironmentVariable(
+ "POSTGRESDB_URI");
+
+await using var dataSource = NpgsqlDataSource.Create(connectionString!);
+await using var conn = await dataSource.OpenConnectionAsync();
+```
+
+
+
+
+## Passing custom environment variables from the AppHost
+
+If your application expects specific environment variable names, you can pass individual connection properties from the AppHost:
+
+
+
+```csharp title="C# β AppHost.cs"
+var builder = DistributedApplication.CreateBuilder(args);
+
+var postgres = builder.AddPostgres("postgres");
+var database = postgres.AddDatabase("myDatabase");
+
+var app = builder.AddExecutable("my-app", "node", "app.js", ".")
+ .WithReference(database)
+ .WithEnvironment(context =>
+ {
+ context.EnvironmentVariables["POSTGRES_HOST"] = postgres.Resource.PrimaryEndpoint.Property(EndpointProperty.Host);
+ context.EnvironmentVariables["POSTGRES_PORT"] = postgres.Resource.PrimaryEndpoint.Property(EndpointProperty.Port);
+ context.EnvironmentVariables["POSTGRES_USER"] = postgres.Resource.UserNameParameter;
+ context.EnvironmentVariables["POSTGRES_PASSWORD"] = postgres.Resource.PasswordParameter;
+ context.EnvironmentVariables["POSTGRES_DATABASE"] = database.Resource.DatabaseName;
+ });
+
+builder.Build().Run();
+```
+
+
+```typescript title="TypeScript β apphost.ts"
+import { createBuilder } from './.modules/aspire.js';
+
+const builder = await createBuilder();
+
+const postgres = await builder.addPostgres("postgres");
+const database = await postgres.addDatabase("myDatabase");
+
+await builder.addNodeApp("my-app", "./app", "index.js")
+ .withReference(database)
+ .withEnvironment("POSTGRES_USER", postgres.userName)
+ .withEnvironment("POSTGRES_PASSWORD", postgres.password)
+ .withEnvironment("POSTGRES_DATABASE", "myDatabase");
+
+await builder.build().run();
+```
+
+
diff --git a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-get-started.mdx b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-get-started.mdx
index c586c2d61..8e7729c84 100644
--- a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-get-started.mdx
+++ b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-get-started.mdx
@@ -4,13 +4,10 @@ description: Learn how to set up the Aspire PostgreSQL Hosting and Client integr
---
import { Image } from 'astro:assets';
-import { Kbd } from 'starlight-kbd/components';
-import InstallPackage from '@components/InstallPackage.astro';
import InstallDotNetPackage from '@components/InstallDotNetPackage.astro';
-import { Aside, CardGrid, LinkCard, Code, Steps, Tabs, TabItem } from '@astrojs/starlight/components';
+import { Aside, CardGrid, LinkCard, Tabs, TabItem } from '@astrojs/starlight/components';
import PivotSelector from '@components/PivotSelector.astro';
import Pivot from '@components/Pivot.astro';
-import ThemeImage from '@components/ThemeImage.astro';
import postgresIcon from '@assets/icons/postgresql-icon.png';
To follow this guide, you must have created an Aspire solution to work with. To learn how to do that, see [Build your first Aspire app](../../../../get-started/first-app/).
-## Set up hosting integration
+## Set up the PostgreSQL Hosting integration
-To begin, install the Aspire PostgreSQL Hosting integration in your Aspire AppHost project. This integration allows you to create and manage PostgreSQL database instances from your Aspire hosting projects:
-
-
-
-Next, in the AppHost project, create instances of PostgreSQL server and database resources, then pass the database to the consuming client projects:
+Choose your AppHost language, then add PostgreSQL to the AppHost. For the full C# and TypeScript hosting API surface, see [PostgreSQL Hosting integration](../postgres-host/).
-
+
-```csharp title="AppHost.cs"
-var builder = DistributedApplication.CreateBuilder(args);
+## TypeScript AppHost quickstart
-var postgres = builder.AddPostgres("postgres");
-var postgresdb = postgres.AddDatabase("postgresdb");
+Use this path when your Aspire solution is modeled in `apphost.ts`.
-var exampleProject = builder.AddProject("apiservice")
- .WaitFor(postgresdb)
- .WithReference(postgresdb);
-```
+### Add the PostgreSQL Hosting integration with the Aspire CLI
-
-
-
-
-```csharp title="apphost.cs"
-var builder = DistributedApplication.CreateBuilder(args);
+```bash title="Terminal"
+aspire add postgres
+```
-var postgres = builder.AddPostgres("postgres");
-var postgresdb = postgres.AddDatabase("postgresdb");
+This updates your `aspire.config.json` with the PostgreSQL hosting integration package:
-var exampleProject = builder.AddUvicornApp("api", "./api", "main:app")
- .WithExternalHttpEndpoints()
- .WaitFor(postgresdb)
- .WithReference(postgresdb);
+```json title="aspire.config.json" ins={3}
+{
+ "packages": {
+ "Aspire.Hosting.PostgreSQL": "*"
+ }
+}
```
-
+### Model PostgreSQL resources in `apphost.ts`
-
+```typescript title="apphost.ts"
+import { createBuilder } from './.modules/aspire.js';
-```csharp title="AppHost.cs"
-var builder = DistributedApplication.CreateBuilder(args);
+const builder = await createBuilder();
-var postgres = builder.AddPostgres("postgres");
-var postgresdb = postgres.AddDatabase("postgresdb");
+const postgres = await builder.addPostgres("postgres");
+const postgresdb = await postgres.addDatabase("postgresdb");
-var api = builder.AddNodeApp("api", "./api", scriptPath: "index.js")
- .WithExternalHttpEndpoints()
- .WaitFor(postgresdb)
- .WithReference(postgresdb);
+await builder.addNodeApp("api", "./api", "index.js")
+ .withExternalHttpEndpoints()
+ .waitFor(postgresdb)
+ .withReference(postgresdb);
```
-
-
-## Use the integration in client projects
+### Connect from your consuming app
-Now that the hosting integration is ready, the next step is to install and configure the client integration in any projects that need to use it.
+The examples below assume your `apphost.ts` file references `postgresdb` from the consuming app with `withReference(postgresdb)`.
-### Set up client projects
+
+
-
+Install the PostgreSQL client library in your JavaScript or TypeScript consuming project:
-In each of these consuming client projects, install the Aspire PostgreSQL client integration:
+```bash title="Terminal"
+npm install pg
+```
-
+Import `pg` in code files that interact with the database:
+
+```javascript title="JavaScript - Import pg"
+import pg from 'pg';
+```
-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.
+Use the `process.env` object to read the injected PostgreSQL properties:
-```csharp title="C# β Program.cs"
-builder.AddNpgsqlDataSource(connectionName: "postgresdb");
+```javascript title="JavaScript - Obtain configuration properties"
+const pguser = process.env.POSTGRESDB_USERNAME;
+const pgpassword = process.env.POSTGRESDB_PASSWORD;
+const pghost = process.env.POSTGRESDB_HOST;
+const pgport = process.env.POSTGRESDB_PORT;
+const pgdatabase = process.env.POSTGRESDB_DATABASENAME;
```
-
+Connect to PostgreSQL with `pg`:
-
+```javascript title="JavaScript - Connect to PostgreSQL"
+const client = new pg.Client({
+ user: pguser,
+ host: pghost,
+ database: pgdatabase,
+ password: pgpassword,
+ port: pgport,
+});
+
+await client.connect();
+```
-
+
+
-To interact with PostgreSQL databases in your Python consuming projects, you need to include a PostgreSQL adapter library. Two popular options are `psycopg` (synchronous) and `asyncpg` (asynchronous). You can install either of these libraries using pip. In this article, example code uses `psycopg`:
+Install a PostgreSQL driver in your Python consuming project. This example uses `psycopg`:
-```bash
+```bash title="Terminal"
pip install psycopg[binary]
```
-Ensure that you `import psycopg` in code files that interact with the database. You should also import the `os` module to access environment variables:
+Import `os` and `psycopg` in code files that interact with the database:
```python title="Python - Import psycopg"
-import psycopg
import os
+import psycopg
```
-
+Use `os.getenv()` to read the injected PostgreSQL properties:
-
+```python title="Python - Obtain configuration properties"
+postgres_uri = os.getenv("POSTGRESDB_URI")
+postgres_name = os.getenv("POSTGRESDB_DATABASENAME")
+```
-To interact with PostgreSQL databases in your JavaScript consuming projects, you need to include a PostgreSQL client library. A popular option is `pg`. You can install this library using npm:
+Connect to PostgreSQL with `psycopg`:
-```bash
-npm install pg
+```python title="Python - Connect to PostgreSQL"
+async with await psycopg.AsyncConnection.connect(postgres_uri, autocommit=True) as conn:
```
-Ensure that you `import pg` in code files that interact with the database:
+
+
-```javascript title="JavaScript - Import pg"
-import pg from 'pg';
+Install the Aspire PostgreSQL client integration in each C# consuming project:
+
+
+
+In `Program.cs`, call the `AddNpgsqlDataSource` extension method on an `IHostApplicationBuilder` to register an `NpgsqlDataSource` for use via dependency injection:
+
+```csharp title="C# - Program.cs"
+builder.AddNpgsqlDataSource(connectionName: "postgresdb");
```
-
+
-### Use injected PostgreSQL properties
+Get the `NpgsqlDataSource` instance by using dependency injection:
+
+```csharp title="C# - ExampleService.cs"
+public class ExampleService(NpgsqlDataSource dataSource)
+{
+ // Use dataSource to query the database...
+}
+```
-In the AppHost, when you used the `WithReference` method to pass a PostgreSQL server or database resource to a consuming client project, Aspire injects several configuration properties that you can 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 `postgresdb` becomes `POSTGRESDB_URI`.
+
-Use the `GetValue()` method to obtain these environment variables in consuming projects:
+## C# AppHost quickstart
-```csharp title="C# - Obtain configuration properties"
-string hostname = builder.Configuration.GetValue("POSTGRESDB_HOST");
-string databaseport = builder.Configuration.GetValue("POSTGRESDB_PORT");
-string jdbcconnectionstring = builder.Configuration.GetValue("POSTGRESDB_JDBCCONNECTIONSTRING");
-string databasename = builder.Configuration.GetValue("POSTGRESDB_DATABASE");
-```
+Use this path when your Aspire solution is modeled in `AppHost.cs`.
-
+### Add the PostgreSQL Hosting integration to the AppHost
-
+```bash title="Terminal"
+aspire add postgres
+```
-Use the `os.getenv()` method to obtain these environment variables in consuming projects:
+Or, add the package manually in either `AppHost.cs` or `AppHost.csproj`:
-```python title="Python - Obtain configuration properties"
-postgres_uri = os.getenv("POSTGRESDB_URI")
-postgres_name = os.getenv("POSTGRESDB_DATABASE", "db")
+```csharp title="C# - AppHost.cs"
+#:package Aspire.Hosting.PostgreSQL@*
```
-
+```xml title="XML - AppHost.csproj"
+
+```
-
+### Model PostgreSQL resources in `AppHost.cs`
-Use the `process.env` method to obtain these environment variables in consuming projects:
+```csharp title="AppHost.cs"
+var builder = DistributedApplication.CreateBuilder(args);
-```javascript title="JavaScript - Obtain configuration properties"
-const pguser = process.env.POSTGRESDB_USERNAME;
-const pgpassword = process.env.POSTGRESDB_PASSWORD;
-const pghost = process.env.POSTGRESDB_HOST;
-const pgport = process.env.POSTGRESDB_PORT;
-const pgdatabase = process.env.POSTGRESDB_DATABASE;
-```
+var postgres = builder.AddPostgres("postgres");
+var postgresdb = postgres.AddDatabase("postgresdb");
-
+var api = builder.AddProject("apiservice")
+ .WaitFor(postgresdb)
+ .WithReference(postgresdb);
+```
-### Use PostgreSQL resources in client code
+### Connect from your consuming app
-
+The examples below assume your `AppHost.cs` file references `postgresdb` from the consuming app with `WithReference(postgresdb)`.
+
+
+
-Now that you've added `NpgsqlDataSource` to the builder in the consuming project, you can use the PostgreSQL resource to get and store data. 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:
+Install the Aspire PostgreSQL client integration in each C# consuming project:
-```csharp title="C# β ExampleService.cs"
+
+
+In `Program.cs`, call the `AddNpgsqlDataSource` extension method on an `IHostApplicationBuilder` to register an `NpgsqlDataSource` for use via dependency injection:
+
+```csharp title="C# - Program.cs"
+builder.AddNpgsqlDataSource(connectionName: "postgresdb");
+```
+
+
+
+Get the `NpgsqlDataSource` instance by using dependency injection:
+
+```csharp title="C# - ExampleService.cs"
public class ExampleService(NpgsqlDataSource dataSource)
{
// Use dataSource to query the database...
}
```
-Having obtained the data source, you can work with the PostgreSQL database as you would in any other C# application.
+
+
-
+Install a PostgreSQL driver in your Python consuming project. This example uses `psycopg`:
-
+```bash title="Terminal"
+pip install psycopg[binary]
+```
-Use the information you have obtained about the PostgreSQL resource to connect to the database. Here is an example of how to connect using `psycopg`:
+Import `os` and `psycopg` in code files that interact with the database:
+
+```python title="Python - Import psycopg"
+import os
+import psycopg
+```
+
+Use `os.getenv()` to read the injected PostgreSQL properties:
+
+```python title="Python - Obtain configuration properties"
+postgres_uri = os.getenv("POSTGRESDB_URI")
+postgres_name = os.getenv("POSTGRESDB_DATABASENAME")
+```
+
+Connect to PostgreSQL with `psycopg`:
```python title="Python - Connect to PostgreSQL"
async with await psycopg.AsyncConnection.connect(postgres_uri, autocommit=True) as conn:
```
-Having obtained the connection, you can work with the PostgreSQL database as you would in any other Python application.
+
+
-
+Install the PostgreSQL client library in your JavaScript or TypeScript consuming project:
-
+```bash title="Terminal"
+npm install pg
+```
+
+Import `pg` in code files that interact with the database:
+
+```javascript title="JavaScript - Import pg"
+import pg from 'pg';
+```
+
+Use the `process.env` object to read the injected PostgreSQL properties:
-Use the information you have obtained about the PostgreSQL resource to connect to the database. Here is an example of how to connect using `pg`:
+```javascript title="JavaScript - Obtain configuration properties"
+const pguser = process.env.POSTGRESDB_USERNAME;
+const pgpassword = process.env.POSTGRESDB_PASSWORD;
+const pghost = process.env.POSTGRESDB_HOST;
+const pgport = process.env.POSTGRESDB_PORT;
+const pgdatabase = process.env.POSTGRESDB_DATABASENAME;
+```
+
+Connect to PostgreSQL with `pg`:
```javascript title="JavaScript - Connect to PostgreSQL"
const client = new pg.Client({
- user: pguser,
- host: pghost,
- database: pgdatabase,
- password: pgpassword,
- port: pgport,
+ user: pguser,
+ host: pghost,
+ database: pgdatabase,
+ password: pgpassword,
+ port: pgport,
});
-client.connect();
+await client.connect();
```
-Having obtained the connection, you can work with the PostgreSQL database as you would in any other JavaScript application.
+
+
## Next steps
-Now, that you have an Aspire app with PostgreSQL integrations up and running, you can use the following reference documents to learn how to configure and interact with the PostgreSQL resources:
+Now that you have an Aspire app with PostgreSQL integrations up and running, you can use the following reference documents to learn how to configure and interact with the PostgreSQL resources:
-
-
\ No newline at end of file
+
diff --git a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx
index c0a3a04ac..eb23de1c5 100644
--- a/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx
+++ b/src/frontend/src/content/docs/integrations/databases/postgres/postgres-host.mdx
@@ -1,12 +1,11 @@
---
title: PostgreSQL Hosting integration
-description: Learn how to use the Aspire PostgreSQL Hosting integration to orchestrate and confgure a PostgreSQL database in an Aspire solution.
+description: Learn how to use the Aspire PostgreSQL Hosting integration to orchestrate and configure a PostgreSQL database in an Aspire solution.
---
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 { Aside, Steps, Tabs, TabItem } from '@astrojs/starlight/components';
+import PivotSelector from '@components/PivotSelector.astro';
import postgresIcon from '@assets/icons/postgresql-icon.png';
+
+Use this selector to switch the C# and TypeScript examples throughout the page.
## Installation
@@ -33,12 +43,49 @@ The PostgreSQL hosting integration models various PostgreSQL resources as the fo
To access these types and APIs for expressing them as resources in your [`AppHost`](/get-started/app-host/) project, install the [π¦ Aspire.Hosting.PostgreSQL](https://www.nuget.org/packages/Aspire.Hosting.PostgreSQL) NuGet package:
-
+
+
+
+```bash title="Terminal"
+aspire add postgres
+```
+
+Or, choose a manual installation approach:
+
+```csharp title="C# β AppHost.cs"
+#:package Aspire.Hosting.PostgreSQL@*
+```
+
+```xml title="XML β AppHost.csproj"
+
+```
+
+
+
+
+```bash title="Terminal"
+aspire add postgres
+```
+
+This updates your `aspire.config.json` with the PostgreSQL hosting integration package:
+
+```json title="aspire.config.json" ins={3}
+{
+ "packages": {
+ "Aspire.Hosting.PostgreSQL": "13.2.0"
+ }
+}
+```
+
+
+
## Add PostgreSQL server resource
-In your AppHost project, call `AddPostgres` on the `builder` instance to add a PostgreSQL server resource then call `AddDatabase` on the `postgres` instance to add a database resource as shown in the following example:
+In your AppHost project, add a PostgreSQL server resource and then add a database resource as shown in the following examples:
+
+
```csharp title="C# β AppHost.cs"
var builder = DistributedApplication.CreateBuilder(args);
@@ -46,29 +93,46 @@ var postgres = builder.AddPostgres("postgres");
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject("apiservice")
- .WithReference(postgresdb);
+ .WithReference(postgresdb);
+
+// After adding all resources, run the app...
+```
+
+
+```typescript title="TypeScript β apphost.ts"
+import { createBuilder } from './.modules/aspire.js';
+
+const builder = await createBuilder();
+
+const postgres = await builder.addPostgres("postgres");
+const postgresdb = await postgres.addDatabase("postgresdb");
+
+await builder.addNodeApp("api", "./api", "index.js")
+ .withReference(postgresdb);
// After adding all resources, run the app...
```
+
+
-1. When Aspire adds a container image to the app host, as shown in the preceding example with the `docker.io/library/postgres` image, it creates a new PostgreSQL server instance on your local machine. A reference to your PostgreSQL server and database instance (the `postgresdb` variable) are used to add a dependency to the `ExampleProject`.
+1. When Aspire adds a container image to the app host, as shown in the preceding example with the `docker.io/library/postgres` image, it creates a new PostgreSQL server instance on your local machine. A reference to the `postgresdb` database resource is then used to add a dependency to the consuming project.
1. When adding a database resource to the app model, the database is created if it doesn't already exist. The creation of the database relies on the AppHost eventing APIs, specifically `ResourceReadyEvent`. In other words, when the `postgres` resource is _ready_, the event is raised and the database resource is created.
-1. The PostgreSQL server resource includes default credentials with a `username` of `"postgres"` and randomly generated `password` using the `CreateDefaultPasswordParameter` method.
+1. The PostgreSQL server resource includes default credentials with a `username` of `"postgres"` and a randomly generated `password` using the `CreateDefaultPasswordParameter` method.
-1. The `WithReference` method configures a connection in the `ExampleProject` named `"messaging"`.
+1. The AppHost reference call configures a connection in the consuming project named after the referenced database resource, such as `postgresdb` in the preceding example.
## Add PostgreSQL resource with database scripts
@@ -79,8 +143,10 @@ By default, when you add a `PostgresDatabaseResource`, it relies on the followin
CREATE DATABASE ""
```
-To alter the default script, chain a call to the `WithCreationScript` method on the database resource builder:
+To alter the default script, configure the database resource with a custom creation script:
+
+
```csharp title="C# β AppHost.cs"
var builder = DistributedApplication.CreateBuilder(args);
@@ -94,16 +160,42 @@ var creationScript = $$"""
""";
var db = postgres.AddDatabase(databaseName)
- .WithCreationScript(creationScript);
+ .WithCreationScript(creationScript);
builder.AddProject()
- .WithReference(db)
- .WaitFor(db);
+ .WithReference(db)
+ .WaitFor(db);
+
+// After adding all resources, run the app...
+```
+
+
+```typescript title="TypeScript β apphost.ts"
+import { createBuilder } from './.modules/aspire.js';
+
+const builder = await createBuilder();
+
+const postgres = await builder.addPostgres("postgres");
+
+const databaseName = "app_db";
+const creationScript = `
+-- Create the database
+CREATE DATABASE ${databaseName};
+`;
+
+const db = await postgres.addDatabase(databaseName);
+await db.withCreationScript(creationScript);
+
+await builder.addNodeApp("api", "./api", "index.js")
+ .withReference(db)
+ .waitFor(db);
// After adding all resources, run the app...
```
+
+
-The preceding example creates a database named `app_db`. The script is run when the database resource is created. The script is passed as a string to the `WithCreationScript` method, which is then run in the context of the PostgreSQL resource.
+The preceding example creates a database named `app_db`. The script is run when the database resource is created. The script is passed as a string to the database resource's creation-script API and then run in the context of the PostgreSQL resource.