0.0.2 • Published 1 year ago

pglite-pool v0.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

pglite-pool

Simplifies using pglite in Node/Bun for codegen and tests by using pglite-server to create a Postgres server at a random port.

Each instance created by getPostgres / withPostgres is fully ephemeral and isolated.

Usage

Both a teardown style and a callback style are supported.

Teardown style

import { getPostgres } from 'pglite-pool';

async function main() {
  const pg = await getPostgres()

  // pg.pool is an already connected Postgres pool
  const pool = pg.pool

  // Do pool things...
  await pool.query('select 1')

  const client = await pool.connect()
  await client.query('select 1')
  client.release()

  // Teardowns the pool, server, and in-memory Postgres instance
  await pg.teardown()
}

Callback Style

import { withPostgres } from 'pglite-pool';

async function main() {
  const anythingString = await withPostgres(async (pg) => {
    const pool = pg.pool
    await pool.query('select 1')
    return 'anything';
    // Teardown happens automatically after return
  })
}

With Connection String

In both the callback and teardown styles, the pg objection has a connectionString property.

This is useful for plugging into libraries such as kanel or graphile-migrate which construct their own Pool object internally.

For example, to run Kanel codegen without Docker or external setup, do:

// codegen.ts
import { processDatabase } from "kanel";
import { makeKyselyHook } from "kanel-kysely";
import { withPostgres } from 'pglite-pool'

const makeConfig = (connectionString: string) => {
  schemas: ["my_schema"],
  outputPath: "./src/database",
  preRenderHooks: [makeKyselyHook()],
  connection: {
    connectionString,
  },
};

await withPostgres(async (pg) => {
  await processDatabase(makeConfig(pg.connectionString));
})

run();

And then bun run codegen.ts just works™.

A full graphile-migrate + Kanel example might be:

import { processDatabase } from "kanel";
import { makeKyselyHook } from "kanel-kysely";
import { withPostgres } from 'pglite-pool'
import { watch } from "graphile-migrate";

const makeConfig = (connectionString: string) => {
  schemas: ["my_schema"],
  outputPath: "./src/database",
  preRenderHooks: [makeKyselyHook()],
  connection: {
    connectionString,
  },
};

await withPostgres(async (pg) => {
  await watch(
    {
      connectionString: pg.connectionString,
      migrationsFolder: "./migrations", // or other path to migrations folder
    },
    true
  );

  await processDatabase(makeConfig(pg.connectionString));
})

run();
0.0.2

1 year ago

0.0.1

1 year ago