Skip to content
Merged
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
60 changes: 59 additions & 1 deletion docs/database/includes/postgresql-app-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,71 @@ var exampleProject = builder.AddProject<Projects.ExampleProject>()
// After adding all resources, run the app...
```

When .NET 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 your PostgreSQL database instance (the `postgresdb` variable) are used to add a dependency to the `ExampleProject`. The PostgreSQL server resource includes default credentials with a `username` of `"postgres"` and randomly generated `password` using the <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter*> method.
When .NET 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`.

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 [app host eventing APIs](../../app-host/eventing.md), specifically <xref:Aspire.Hosting.ApplicationModel.ResourceReadyEvent>. In other words, when the `postgres` resource is _ready_, the event is raised and the database resource is created.

The PostgreSQL server resource includes default credentials with a `username` of `"postgres"` and randomly generated `password` using the <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter*> method.

The <xref:Aspire.Hosting.ResourceBuilderExtensions.WithReference%2A> method configures a connection in the `ExampleProject` named `"messaging"`. For more information, see [Container resource lifecycle](../../fundamentals/app-host-overview.md#container-resource-lifecycle).

> [!TIP]
> If you'd rather connect to an existing PostgreSQL server, call <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.AddConnectionString*> instead. For more information, see [Reference existing resources](../../fundamentals/app-host-overview.md#reference-existing-resources).

### Add PostgreSQL resource with database scripts

By default, when you add a <xref:Aspire.Hosting.ApplicationModel.PostgresDatabaseResource>, it relies on the following script to create the database:

```sql
CREATE DATABASE "<QUOTED_DATABASE_NAME>"
```

<!-- TODO: Use xref here when available

To alter the default script, chain a call to the <xref:Aspire.Hosting.PostgresBuilderExtensions.WithCreationScript*> method on the database resource builder:

-->

To alter the default script, chain a call to the `WithCreationScript` method on the database resource builder:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var postgres = builder.AddPostgres("postgres");

var databaseName = "app_db";
var creationScript = $$"""
-- Create the database
CREATE DATABASE {{databaseName}};

-- Connect to the database
\c {{databaseName}}

-- Create the todos table
CREATE TABLE todos (
id SERIAL PRIMARY KEY, -- Auto-incrementing unique ID
title VARCHAR(255) NOT NULL, -- Short description of the task
description TEXT, -- Optional detailed description
is_completed BOOLEAN DEFAULT FALSE, -- Completion status
due_date DATE, -- Optional due date
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- Creation timestamp
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP -- Last update timestamp
);

""";

var db = postgres.AddDatabase(databaseName)
.WithCreationScript(creationScript);

builder.AddProject<Projects.ExampleProject>()
.WithReference(db)
.WaitFor(db);

// After adding all resources, run the app...
```

The preceding example creates a database named `app_db` with a single `todos` table. The script is executed when the database resource is created. The script is passed as a string to the `WithCreationScript` method, which is then executed in the context of the SQL Server resource.

### Add PostgreSQL pgAdmin resource

When adding PostgreSQL resources to the `builder` with the `AddPostgres` method, you can chain calls to <xref:Aspire.Hosting.PostgresBuilderExtensions.WithPgAdmin*> to add the [**dpage/pgadmin4**](https://www.pgadmin.org/) container. This container is a cross-platform client for PostgreSQL databases, that serves a web-based admin dashboard. Consider the following example:
Expand Down
73 changes: 72 additions & 1 deletion docs/database/includes/sql-app-host.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,11 @@ builder.AddProject<Projects.ExampleProject>()
> [!NOTE]
> The SQL Server container is slow to start, so it's best to use a _persistent_ lifetime to avoid unnecessary restarts. For more information, see [Container resource lifetime](../../fundamentals/app-host-overview.md#container-resource-lifetime).

When .NET Aspire adds a container image to the app host, as shown in the preceding example with the `mcr.microsoft.com/mssql/server` image, it creates a new SQL Server instance on your local machine. A reference to your SQL Server resource builder (the `sql` variable) is used to add a database. The database is named `database` and then added to the `ExampleProject`. The SQL Server resource includes default credentials with a `username` of `sa` and a random `password` generated using the <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter*> method.
When .NET Aspire adds a container image to the app host, as shown in the preceding example with the `mcr.microsoft.com/mssql/server` image, it creates a new SQL Server instance on your local machine. A reference to your SQL Server resource builder (the `sql` variable) is used to add a database. The database is named `database` and then added to the `ExampleProject`.

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 [app host eventing APIs](../../app-host/eventing.md), specifically <xref:Aspire.Hosting.ApplicationModel.ResourceReadyEvent>. In other words, when the `sql` resource is _ready_, the event is raised and the database resource is created.

The SQL Server resource includes default credentials with a `username` of `sa` and a random `password` generated using the <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.CreateDefaultPasswordParameter*> method.

When the app host runs, the password is stored in the app host's secret store. It's added to the `Parameters` section, for example:

Expand All @@ -60,6 +64,73 @@ The <xref:Aspire.Hosting.ResourceBuilderExtensions.WithReference%2A> method conf
> [!TIP]
> If you'd rather connect to an existing SQL Server, call <xref:Aspire.Hosting.ParameterResourceBuilderExtensions.AddConnectionString*> instead. For more information, see [Reference existing resources](../../fundamentals/app-host-overview.md#reference-existing-resources).

### Add SQL Server resource with database scripts

By default, when you add a <xref:Aspire.Hosting.ApplicationModel.SqlServerDatabaseResource>, it relies on the following SQL script to create the database:

```sql
IF
(
NOT EXISTS
(
SELECT 1
FROM sys.databases
WHERE name = @DatabaseName
)
)
CREATE DATABASE [<QUOTED_DATABASE_NAME>];
```

<!-- TODO: Use xref here when available

To alter the default script, chain a call to the <xref:Aspire.Hosting.SqlServerBuilderExtensions.WithCreationScript*> method on the database resource builder:

-->

To alter the default script, chain a call to the `WithCreationScript` method on the database resource builder:

```csharp
var builder = DistributedApplication.CreateBuilder(args);

var sql = builder.AddSqlServer("sql")
.WithLifetime(ContainerLifetime.Persistent);

var databaseName = "app_db";
var creationScript = $$"""
IF DB_ID('{{databaseName}}') IS NULL
CREATE DATABASE [{{databaseName}}];
GO

-- Use the database
USE [{{databaseName}}];
GO

-- Create the todos table
CREATE TABLE todos (
id INT PRIMARY KEY AUTO_INCREMENT, -- Unique ID for each todo
title VARCHAR(255) NOT NULL, -- Short description of the task
description TEXT, -- Optional detailed description
is_completed BOOLEAN DEFAULT FALSE, -- Completion status
due_date DATE, -- Optional due date
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
GO

""";

var db = sql.AddDatabase(databaseName)
.WithCreationScript(creationScript);

builder.AddProject<Projects.ExampleProject>()
.WithReference(db)
.WaitFor(db);

// After adding all resources, run the app...
```

The preceding example creates a database named `app_db` with a single `todos` table. The SQL script is executed when the database resource is created. The script is passed as a string to the `WithCreationScript` method, which is then executed in the context of the SQL Server resource.

### Add SQL Server resource with data volume

To add a data volume to the SQL Server resource, call the <xref:Aspire.Hosting.SqlServerBuilderExtensions.WithDataVolume*> method on the SQL Server resource:
Expand Down