From 5ae619288ecd00b354f194d88844367e475da8c4 Mon Sep 17 00:00:00 2001 From: Nabeel Valley <36758308+nabeelvalley@users.noreply.github.com> Date: Sat, 9 Dec 2023 13:15:38 +0100 Subject: [PATCH] :sparkles: ability to re-run query from history --- src/commands/history/list.ts | 4 +- src/commands/query/history.ts | 70 +++++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 2 deletions(-) create mode 100644 src/commands/query/history.ts diff --git a/src/commands/history/list.ts b/src/commands/history/list.ts index bc14fc0..0d5e45e 100644 --- a/src/commands/history/list.ts +++ b/src/commands/history/list.ts @@ -29,7 +29,7 @@ export default class List extends AppCommand { async run(): Promise { const {flags, args} = await this.parse(List) const {search = ''} = args - const {alias = '', count, aliasExact, format} = flags + const {alias, count, aliasExact, format} = flags const result = await this.load( 'Searching', @@ -40,7 +40,7 @@ export default class List extends AppCommand { }, where: { - AND: [ + OR: [ { query: { contains: search, diff --git a/src/commands/query/history.ts b/src/commands/query/history.ts new file mode 100644 index 0000000..3f87761 --- /dev/null +++ b/src/commands/query/history.ts @@ -0,0 +1,70 @@ +import {Args, Flags, ux} from '@oclif/core' +import {PrismaClient} from '@prisma/client' +import {format, printFormatted} from '../../output.js' +import {AppCommand} from '../../AppCommand.js' + +export default class SQL extends AppCommand { + static args = { + id: Args.integer({description: 'ID of history command to execute', required: true}), + } + + static description = 'Re-run a previous database query' + + static examples = [] + + static flags = { + format, + withAlias: Flags.string({description: 'Override the initial alias used to run the command', required: false}), + } + + async run(): Promise { + const {args, flags} = await this.parse(SQL) + const {id} = args + const {format, withAlias} = flags + + const history = await this.db.history.findFirst({ + where: { + id, + }, + }) + + if (!history) { + ux.error(`History with id '${id}' not found`) + } + + const alias = withAlias || history.connectionAlias + const connection = await this.getConnection(alias) + + this.assertConnectionExists(alias, connection) + + const client = new PrismaClient({ + datasourceUrl: connection.connectionString, + }) + + const saveHistory = (success: boolean) => + this.db.history.upsert({ + where: { + id, + connectionAlias: alias, + }, + update: { + lastUsed: new Date(), + }, + create: { + success, + lastUsed: new Date(), + query: history.query, + connectionAlias: alias, + }, + }) + + try { + const result = await this.load('Executing query', client.$queryRawUnsafe(history.query)) + printFormatted(format, result) + await saveHistory(true) + } catch (err) { + await saveHistory(false) + throw err + } + } +}