I just can’t stop having fun using bun
I have an old postgresql database backup. I need to quickly inspect the tables/models in the database and then extract data from it.
After having the backup sql ready output-backup.sql
. I created a docker-compose.yml
file to quickly spin up a postgres instance.
version: '3.1'
services:
postgres:
image: postgres:latest
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: example_dev
ports:
- "54321:5432"
volumes:
- postgres_data:/var/lib/postgresql/data
volumes:
postgres_data:
Now let’s re-dump the data back into the local database.
psql -U postgres -h localhost -p 54321 -d example_dev -f output-backup.sql
Okay the fun parts begin.
Set up a new package using bun
:
mkdir data-explorer
cd data-explorer && bun init -y
Now let’s add prisma:
bun add prisma
bunx prisma init --datasource-provider postgresql
Remember to change the DATABASE_URL to our local one in .env
:
DATABASE_URL="postgresql://postgres:postgres@localhost:54321/example_dev?schema=public"
Inspect the database now:
bunx prisma db pull
Generate prisma client:
bunx prisma generate
Hooray!
Now we can play with the database:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
const allUsers = await prisma.users.findMany();
console.log(allUsers.length);
See it now:
bun run index.ts
The beauty of Prisma is that the generated schema.prisma
is like a X-Ray to the database. Not only we can see the tables and relations, but also we can manupulate it in a type safe way (with autocompletion of course).
Such a joyful experience.
I still can’t believe how easy it is to run a TypeScript project using bun
with massive npm modules without losing my mind.
https://bun.sh/guides/ecosystem/prisma https://www.prisma.io/docs/getting-started/setup-prisma/add-to-existing-project/relational-databases/introspection-typescript-postgresql