Skip to content

Commit

Permalink
Document how to use postgres with a conn pool
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 committed Sep 23, 2024
1 parent 86e3615 commit 9b8f0ca
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
15 changes: 14 additions & 1 deletion docs/docs/Platforms/postgres.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,24 @@ targets:

Then, perhaps this example database is helpful as a starting point:

{{ load_snippet('(full)','lib/snippets/platforms/postgres.dart.excerpt.json') }}
{{ load_snippet('setup','lib/snippets/platforms/postgres.dart.excerpt.json') }}

After starting a database server, for example by running `docker run -p 5432:5432 -e POSTGRES_PASSWORD=postgres postgres`,
you can run the example to see drift talking to Postgres.

## Custom connections and connection pools

The unnamed `PgDatabase` constructor mirrors the options found on the `Endpoint` class in
`package:postgres`, as it uses that class to establish a connection to PostgreSQL.
In some cases, for instance because you already have an existing Postgres connection or because
you need something different from the existing `Endpoint`, you can use `PgDatabase.opened`
with your existing `Session` from `package:postgres`.

This technique is also useful for pooling connections to Postgres, as the `Pool` implementation
from `package:postgres` implements the `Session` interface:

{{ load_snippet('pool','lib/snippets/platforms/postgres.dart.excerpt.json') }}

## API extensions

The postgres library provides a few [custom types](../sql_api/types.md) enabling you to use
Expand Down
18 changes: 18 additions & 0 deletions docs/lib/snippets/platforms/postgres.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// #docregion setup
import 'package:drift/drift.dart';
import 'package:drift_postgres/drift_postgres.dart';
import 'package:postgres/postgres.dart';
Expand Down Expand Up @@ -43,3 +44,20 @@ void main() async {

await driftDatabase.close();
}
// #enddocregion setup

List<Endpoint> get yourListOfEndpoints => throw 'stub';

// #docregion pool
Future<void> openWithPool() async {
final pool = Pool.withEndpoints(yourListOfEndpoints);

final driftDatabase = MyDatabase(PgDatabase.opened(pool));
await driftDatabase.users.select().get();

// Note that PgDatabase.opened() doesn't close the underlying connection when
// the drift database is closed.
await driftDatabase.close();
await pool.close();
}
// #enddocregion pool

0 comments on commit 9b8f0ca

Please sign in to comment.