Database
Learn how to work with databases in VitNode plugins using Drizzle ORM and PostgreSQL.
VitNode plugins seamlessly integrate with databases using Drizzle ORM and PostgreSQL. This guide shows you how to define schemas, perform database operations, and manage migrations.
Defining Schema
Create your database schema in the database directory of your plugin. Each table should be defined in its own file for better organization.
import { pgTable, serial, timestamp } from "drizzle-orm/pg-core";
export const blog_categories = pgTable("blog_categories", {
id: serial().primaryKey(),
createdAt: timestamp().notNull().defaultNow(),
updatedAt: timestamp()
.notNull()
.$onUpdate(() => new Date())
});Accessing Database
Access the database in your plugin handlers using c.get('database') from the Hono context. This provides a Drizzle ORM instance for all your database operations.
export const postsRoute = buildRoute({
pluginId: CONFIG_PLUGIN.pluginId,
route: {},
handler: async (c) => {
const data = await c
.get("database")
.select({
id: blog_posts.id,
title: blog_posts.title
})
.from(blog_posts);
return c.json(data);
}
});Database Operations
VitNode provides convenient commands for managing your database schema and migrations.
Creating Migrations
Generate migration files when you modify your database schema:
bun db:migratepnpm db:migratenpm run db:migrateAutomatic Updates in Development
VitNode automatically runs migrations and schema updates when you start your application in development mode, keeping your database in sync with your code.