Skip to content

Instantly share code, notes, and snippets.

@capaj
Last active January 9, 2026 13:28
Show Gist options
  • Select an option

  • Save capaj/3146508038acb1ff309de6b58e1050ca to your computer and use it in GitHub Desktop.

Select an option

Save capaj/3146508038acb1ff309de6b58e1050ca to your computer and use it in GitHub Desktop.
import { encode } from '@toon-format/toon'
import { sql } from 'drizzle-orm'
import { db } from './src/db/db' // replace
import { env } from './src/env' // replace
/**
* Run a SQL query against the current database from .env
*/
async function runQuery() {
// Get the SQL query from the command line arguments
const query = process.argv.slice(2).join(' ')
const isUpdateDelete =
query.toUpperCase().includes('UPDATE') ||
query.toUpperCase().includes('DELETE')
if (
env.DATABASE_URL.includes('production-url') && // replace with what you have
isUpdateDelete
) {
throw new Error(
'You are trying to run a query against the production database.'
)
}
if (!query) {
console.error('Please provide a SQL query as an argument.')
console.error('Usage: bun run-sql.ts "SELECT * FROM campaigns LIMIT 5"')
process.exit(1)
}
try {
const start = performance.now()
const result = await db.execute(sql.raw(query))
const end = performance.now()
if (result && (Array.isArray(result) || typeof result === 'object')) {
console.log(encode(result))
if (Array.isArray(result)) {
console.log(
`\nReturned ${result.length} rows in ${(end - start).toFixed(2)}ms`
)
} else {
console.log(`\nQuery executed in ${(end - start).toFixed(2)}ms`)
}
} else {
console.log('Result:', result)
console.log(`Query executed in ${(end - start).toFixed(2)}ms`)
}
} catch (error) {
console.error('Error executing query:', error)
process.exit(1)
}
process.exit(0)
}
runQuery()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment