Skip to content

Instantly share code, notes, and snippets.

@thecodeboss
Created July 22, 2022 22:01
Show Gist options
  • Select an option

  • Save thecodeboss/7713313afe7917d6bdf8bcdd96d4df1e to your computer and use it in GitHub Desktop.

Select an option

Save thecodeboss/7713313afe7917d6bdf8bcdd96d4df1e to your computer and use it in GitHub Desktop.

Revisions

  1. thecodeboss created this gist Jul 22, 2022.
    40 changes: 40 additions & 0 deletions prisma-slonik-usage.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,40 @@
    import { PrismaClient } from '@prisma/client';
    import type { User } from '@prisma/client';
    import { createPool, sql } from 'slonik';

    export const buildBaseConnectionURL = (config) => {
    return (
    'postgresql://' +
    config.DB_USER +
    ':' +
    config.DB_PASS +
    '@' +
    config.DB_HOST +
    ':' +
    config.DB_PORT +
    '/' +
    config.DB_NAME
    );
    };

    export const buildPrismaDatabaseURL = (config) => {
    return buildBaseConnectionURL(config) + '?schema=' + config.DB_SCHEMA;
    };

    export const buildSlonikConnectionURL = (config) => {
    return buildBaseConnectionURL(config) + '?options=-csearch_path=%3d' + config.DB_SCHEMA;
    }

    // Prisma Client
    const prisma = new PrismaClient({
    datasources: { db: { url: buildPrismaDatabaseURL(config) } },
    });

    // Slonik Client
    const db = createPool(buildSlonikConnectionURL(config));

    // Example Prisma query:
    const users = await prisma.user.findMany();

    // Example Slonik query:
    const users = await db.any<User>(sql`SELECT * FROM "User"`);