Exploring Efficient Database Connection Management in Postgres with Drizzle

ive got a simple migrator script for postgres using drizzle but it got me thinking, is there a better way to initialize and eventually disconnect from a database connection? is there an equivilent for a 'finally' clause or is Effect.match the best way to disconnect for both success and failure conditions?

import "dotenv/config";
import { drizzle } from "drizzle-orm/postgres-js";
import { migrate } from "drizzle-orm/postgres-js/migrator";
import { Config, Console, Effect } from "effect";
import { UnknownException } from "effect/Cause";
import { resolve } from "path";
import postgres from "postgres";
import * as schema from "../schema";

const migrator = Effect.gen(function* ($) {
  const url = yield* $(Config.string("DATABASE_URL"));
  const client = postgres(url, { max: 1 });

  yield* $(
    Effect.tryPromise({
      try: () =>
        migrate(drizzle(client, { schema }), {
          migrationsFolder: resolve(__dirname, "../migrations"),
        }),
      catch: (err) => new UnknownException(err, "An error occured during migration."),
    }),
    Effect.tapErrorCause(Console.error),
    Effect.match({
      onFailure: () => client.end({ timeout: 5000 }),
      onSuccess: () => client.end({ timeout: 5000 }),
    }),
    Effect.tap(() => Console.log("Migration successful. Disconnecting...")),
  );
});

Effect.runPromise(migrator);
Was this page helpful?