Created
September 11, 2025 06:57
-
-
Save cgrothaus/e41aa8a28f0c2309bc72d56634988be8 to your computer and use it in GitHub Desktop.
Interactive database console for Prisma ORM (Typescript)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env tsx | |
| // Backend Console - Interactive Prisma REPL | |
| // Similar to Rails console for experimenting with database queries | |
| import { PrismaClient } from '@prisma/client'; | |
| import repl from 'repl'; | |
| import util from 'util'; | |
| // Initialize Prisma Client with event-based logging to see SQL queries and bound parameters | |
| const prisma = new PrismaClient({ | |
| log: [ | |
| { emit: 'event', level: 'query' }, | |
| { emit: 'stdout', level: 'error' }, | |
| { emit: 'stdout', level: 'info' }, | |
| { emit: 'stdout', level: 'warn' }, | |
| ], | |
| }); | |
| // Subscribe to query events to log SQL and bound parameters | |
| prisma.$on('query', (e) => { | |
| console.log('---'); | |
| console.log(e.query); | |
| console.log(e.params); | |
| console.log(String(e.duration) + 'ms'); | |
| console.log('---'); | |
| }); | |
| function usage() { | |
| console.log('π Backend Console'); | |
| console.log('π Prisma Client loaded as "prisma"'); | |
| console.log('π‘ Examples:'); | |
| console.log(' await prisma.user.findMany()'); | |
| console.log(' await prisma.tenant.count()'); | |
| console.log(' await prisma.$queryRaw`SELECT COUNT(*) FROM "user"`'); | |
| console.log( | |
| ' await prisma.organization.findFirst({ include: { tenants: true } })', | |
| ); | |
| console.log(''); | |
| } | |
| usage(); | |
| // Start REPL with Prisma client in context | |
| const replServer = repl.start({ | |
| prompt: 'prisma-console> ', | |
| useColors: true, | |
| }); | |
| // Add prisma to the REPL context | |
| replServer.context.prisma = prisma; | |
| // Add helpful utilities to the REPL context | |
| replServer.context.inspect = util.inspect; | |
| replServer.context.log = console.log; | |
| replServer.context.help = usage; | |
| // Add types to the REPL context for better autocompletion | |
| replServer.context.PrismaClient = PrismaClient; | |
| // Cleanup function for disconnecting Prisma | |
| function cleanupAndExit() { | |
| console.log('\nπ Disconnecting from database...'); | |
| prisma | |
| .$disconnect() | |
| .catch((err: unknown) => { | |
| console.error('Error disconnecting from database:', err); | |
| }) | |
| .finally(() => process.exit(0)); | |
| } | |
| // Handle cleanup on exit | |
| replServer.on('exit', cleanupAndExit); | |
| process.on('SIGINT', cleanupAndExit); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment