Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cli/commands/db.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import drop from './db/drop.mjs'
import dropAll from './db/drop-all.mjs'
import squash from './db/squash.mjs'
import sql from './db/sql.mjs'
import truncate from './db/truncate.mjs'

const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf-8'))

Expand All @@ -23,6 +24,7 @@ export default defineCommand({
drop,
'drop-all': dropAll,
squash,
sql
sql,
truncate
}
})
58 changes: 58 additions & 0 deletions cli/commands/db/truncate.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { defineCommand } from 'citty'
import { consola } from 'consola'
import { execa } from 'execa'
import { readFile } from 'node:fs/promises'
import { join } from 'pathe'
import { createDrizzleClient } from '@nuxthub/core/db'
import { sql } from 'drizzle-orm'
import { loadDotenv, dotenvArg } from '../../utils/dotenv.mjs'

export default defineCommand({
meta: {
name: 'truncate',
description: 'Truncate a table in the database.'
},
args: {
table: {
type: 'positional',
description: 'The name of the table to drop.',
required: true
},
cwd: {
type: 'option',
description: 'The directory to run the command in.',
required: false
},
dotenv: dotenvArg,
verbose: {
alias: 'v',
type: 'boolean',
description: 'Show verbose output.',
required: false
}
},
async run({ args }) {
if (args.verbose) {
// Set log level to debug
consola.level = 4
}
const cwd = args.cwd || process.cwd()
await loadDotenv({ cwd, dotenv: args.dotenv })
consola.info('Preparing database configuration...')
await execa({
stdio: 'pipe',
preferLocal: true,
cwd
})`nuxt prepare`
const hubConfig = JSON.parse(await readFile(join(cwd, '.nuxt/hub/db/config.json'), 'utf-8'))
consola.info(`Database: \`${hubConfig.db.dialect}\` with \`${hubConfig.db.driver}\` driver`)
const url = hubConfig.db.connection?.uri || hubConfig.db.connection?.url
if (url) consola.debug(`Database connection: \`${url}\``)
const hubDir = join(cwd, hubConfig.dir)
const db = await createDrizzleClient(hubConfig.db, hubDir)
const execute = hubConfig.db.dialect === 'sqlite' ? 'run' : 'execute'
await db[execute](sql.raw(`TRUNCATE TABLE \`${args.table}\`;`))
consola.success(`Table \`${args.table}\` truncated successfully.`)
await db.$client?.end?.()
}
})