Skip to content

Commit

Permalink
✨ ability to re-run query from history
Browse files Browse the repository at this point in the history
  • Loading branch information
nabeelvalley committed Dec 9, 2023
1 parent 2193656 commit 5ae6192
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/commands/history/list.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default class List extends AppCommand {
async run(): Promise<any> {
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',
Expand All @@ -40,7 +40,7 @@ export default class List extends AppCommand {
},

where: {
AND: [
OR: [
{
query: {
contains: search,
Expand Down
70 changes: 70 additions & 0 deletions src/commands/query/history.ts
Original file line number Diff line number Diff line change
@@ -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<any> {
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
}
}
}

0 comments on commit 5ae6192

Please sign in to comment.