Raw SQL
Use `@vitehub/db` directly for raw SQL queries.
Raw SQL lives in @vitehub/db.
Configure top-level db and optional devDatabase, then use getDatabase() in server code.
Basic setup
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@vitehub/db/nuxt'],
db: {
connector: 'libsql',
options: {
url: 'file:.data/db/app.sqlite',
},
},
})
Runtime usage
server/api/posts.get.ts
import { getDatabase } from '@vitehub/db'
export default defineEventHandler(async () => {
const database = await getDatabase()
await database.exec(`
CREATE TABLE IF NOT EXISTS posts (
id integer primary key autoincrement,
title text not null
)
`)
await database.sql`INSERT INTO posts (title) VALUES (${'hello db'})`
const { rows } = await database.sql`SELECT * FROM posts ORDER BY id DESC`
return rows
})
Named connections
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@vitehub/db/nuxt'],
db: {
default: {
connector: 'libsql',
options: {
url: 'file:.data/db/app.sqlite',
},
},
analytics: {
connector: 'postgresql',
options: {
url: process.env.DATABASE_URL,
},
},
},
})
server/api/analytics.get.ts
import { getDatabase } from '@vitehub/db'
export default defineEventHandler(async () => {
const analyticsDb = await getDatabase('analytics')
const { rows } = await analyticsDb.sql`SELECT 1 AS ok`
return rows
})
Cloudflare D1
Use the ViteHub D1 connector path for raw SQL on Workers:
nuxt.config.ts
export default defineNuxtConfig({
modules: ['@vitehub/db/nuxt'],
db: {
connector: 'cloudflare-d1',
options: {
bindingName: 'DB',
},
},
})
Use
getDatabase() from @vitehub/db for raw SQL even when you also use db for Drizzle.