From 9b8f0cab4691f893201b65c2633fc925a78ff366 Mon Sep 17 00:00:00 2001 From: Simon Binder Date: Mon, 23 Sep 2024 20:57:27 +0200 Subject: [PATCH] Document how to use postgres with a conn pool https://github.com/simolus3/drift/issues/3236 --- docs/docs/Platforms/postgres.md | 15 ++++++++++++++- docs/lib/snippets/platforms/postgres.dart | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/docs/docs/Platforms/postgres.md b/docs/docs/Platforms/postgres.md index 26ae58483..3f02ec8db 100644 --- a/docs/docs/Platforms/postgres.md +++ b/docs/docs/Platforms/postgres.md @@ -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 diff --git a/docs/lib/snippets/platforms/postgres.dart b/docs/lib/snippets/platforms/postgres.dart index 24365e4e3..794475c08 100644 --- a/docs/lib/snippets/platforms/postgres.dart +++ b/docs/lib/snippets/platforms/postgres.dart @@ -1,3 +1,4 @@ +// #docregion setup import 'package:drift/drift.dart'; import 'package:drift_postgres/drift_postgres.dart'; import 'package:postgres/postgres.dart'; @@ -43,3 +44,20 @@ void main() async { await driftDatabase.close(); } +// #enddocregion setup + +List get yourListOfEndpoints => throw 'stub'; + +// #docregion pool +Future 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