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
16 changes: 7 additions & 9 deletions examples/drizzle/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Hono Integration for RivetKit
# Drizzle Integration for RivetKit

Example project demonstrating Hono web framework integration with [RivetKit](https://rivetkit.org).
Example project demonstrating Drizzle ORM integration with [RivetKit](https://rivetkit.org).

[Learn More →](https://github.com/rivet-gg/rivetkit)

Expand All @@ -16,18 +16,16 @@ Example project demonstrating Hono web framework integration with [RivetKit](htt

```sh
git clone https://github.com/rivet-gg/rivetkit
cd rivetkit/examples/hono
npm install
cd rivetkit/examples/drizzle
pnpm install
```

### Development

```sh
npm run dev
pnpm run dev
```

Open your browser to http://localhost:3000 to see the Hono server with RivetKit integration.
Open your browser to https://studio.rivet.gg/ to see your RivetKit server.

## License

Apache 2.0
Apache 2.0
6 changes: 6 additions & 0 deletions examples/drizzle/drizzle/0000_flippant_bloodstrike.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE `messages_table` (
`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
`sender` text NOT NULL,
`text` text NOT NULL,
`timestamp` integer NOT NULL
);
8 changes: 0 additions & 8 deletions examples/drizzle/drizzle/0000_wonderful_iron_patriot.sql

This file was deleted.

30 changes: 12 additions & 18 deletions examples/drizzle/drizzle/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{
"version": "6",
"dialect": "sqlite",
"id": "22f3d49c-97d5-46ca-b0f1-99950c3efec7",
"id": "cb13fd0c-ec74-4b9d-b939-8ad091b0dca1",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"users_table": {
"name": "users_table",
"messages_table": {
"name": "messages_table",
"columns": {
"id": {
"name": "id",
Expand All @@ -14,35 +14,29 @@
"notNull": true,
"autoincrement": true
},
"name": {
"name": "name",
"sender": {
"name": "sender",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"age": {
"name": "age",
"type": "integer",
"text": {
"name": "text",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"timestamp": {
"name": "timestamp",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"users_table_email_unique": {
"name": "users_table_email_unique",
"columns": ["email"],
"isUnique": true
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
Expand Down
11 changes: 2 additions & 9 deletions examples/drizzle/drizzle/meta/_journal.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,8 @@
{
"idx": 0,
"version": "6",
"when": 1750711614205,
"tag": "0000_wonderful_iron_patriot",
"breakpoints": true
},
{
"idx": 1,
"version": "6",
"when": 1750716663518,
"tag": "0001_rich_susan_delgado",
"when": 1755196233006,
"tag": "0000_flippant_bloodstrike",
"breakpoints": true
}
]
Expand Down
2 changes: 1 addition & 1 deletion examples/drizzle/drizzle/migrations.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import m0000 from "./0000_wonderful_iron_patriot.sql";
import m0000 from "./0000_flippant_bloodstrike.sql";
import journal from "./meta/_journal.json";

export default {
Expand Down
7 changes: 4 additions & 3 deletions examples/drizzle/package.json
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
{
"name": "example-sqlite",
"name": "example-drizzle",
"version": "0.9.9",
"private": true,
"type": "module",
"scripts": {
"dev": "tsx --watch src/server.ts",
"dev": "tsx --loader @rivetkit/sql-loader --watch src/server.ts",
"check-types": "tsc --noEmit"
},
"devDependencies": {
"@types/node": "^22.13.9",
"rivetkit": "workspace:*",
"@rivetkit/sql-loader": "workspace:*",
"tsx": "^3.12.7",
"typescript": "^5.5.2"
},
"dependencies": {
"@rivetkit/db": "workspace:*",
"@rivetkit/actor": "workspace:*",
"drizzle-kit": "^0.31.2",
"drizzle-orm": "^0.44.2"
},
Expand Down
15 changes: 7 additions & 8 deletions examples/drizzle/src/db/schema.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
// import { int, sqliteTable, text } from "@rivetkit/db/drizzle";
import { int, sqliteTable, text } from "@rivetkit/db/drizzle";

// export const usersTable = sqliteTable("users_table", {
// id: int().primaryKey({ autoIncrement: true }),
// name: text().notNull(),
// age: int().notNull(),
// email: text().notNull().unique(),
// email2: text().notNull().unique(),
// });
export const messagesTable = sqliteTable("messages_table", {
id: int().primaryKey({ autoIncrement: true }),
sender: text().notNull(),
text: text().notNull(),
timestamp: int().notNull(),
});
53 changes: 30 additions & 23 deletions examples/drizzle/src/registry.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,32 @@
// import { actor, setup } from "rivetkit";
// import { db } from "@rivetkit/db/drizzle";
// import * as schema from "./db/schema";
// import migrations from "../drizzle/migrations";
import { actor, setup } from "@rivetkit/actor";
import { db } from "@rivetkit/db/drizzle";
import { desc } from "drizzle-orm";
import migrations from "../drizzle/migrations";
import * as schema from "./db/schema";

// export const counter = actor({
// db: db({ schema, migrations }),
// state: {
// count: 0,
// },
// onAuth: () => {
// // Configure auth here
// },
// actions: {
// increment: (c, x: number) => {
// // createState or state fix fix fix
// c.db.c.state.count += x;
// return c.state.count;
// },
// },
// });
export const chat = actor({
db: db({ schema, migrations }),
onAuth: () => {},
actions: {
// Callable functions from clients: https://rivet.gg/docs/actors/actions
sendMessage: async (c, sender: string, text: string) => {
const message = { sender, text, timestamp: Date.now() };
// State changes are automatically persisted
await c.db.insert(schema.messagesTable).values(message);
// Send events to all connected clients: https://rivet.gg/docs/actors/events
c.broadcast("newMessage", message);
return message;
},

// export const registry = setup({
// use: { counter },
// });
getHistory: (c) =>
c.db
.select()
.from(schema.messagesTable)
.orderBy(desc(schema.messagesTable.timestamp))
.limit(100),
},
});

export const registry = setup({
use: { chat },
});
8 changes: 2 additions & 6 deletions examples/drizzle/src/server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
// import { registry } from "./registry";
// import { createMemoryDriver } from "@rivetkit/memory";
// import { serve } from "@rivetkit/nodejs";
import { registry } from "./registry";

// serve(registry, {
// driver: createMemoryDriver(),
// });
registry.runServer();
21 changes: 12 additions & 9 deletions packages/core/src/inspector/actor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,20 +181,22 @@ export function createActorInspectorRouter() {
const db = await c.var.inspector.accessors.getDb();

// Get list of tables
const rows = await db.execute(`PRAGMA table_list`);
const rows = await db.prepare(`PRAGMA table_list`).all();
const tables = TablesSchema.parse(rows).filter(
(table) => table.schema !== "temp" && !table.name.startsWith("sqlite_"),
);
// Get columns for each table
const tablesInfo = await Promise.all(
tables.map((table) => db.execute(`PRAGMA table_info(${table.name})`)),
tables.map((table) =>
db.prepare(`PRAGMA table_info(${table.name})`).all(),
),
);
const columns = tablesInfo.map((def) => ColumnsSchema.parse(def));

// Get foreign keys for each table
const foreignKeysList = await Promise.all(
tables.map((table) =>
db.execute(`PRAGMA foreign_key_list(${table.name})`),
db.prepare(`PRAGMA foreign_key_list(${table.name})`).all(),
),
);
const foreignKeys = foreignKeysList.map((def) =>
Expand All @@ -204,7 +206,7 @@ export function createActorInspectorRouter() {
// Get record counts for each table
const countInfo = await Promise.all(
tables.map((table) =>
db.execute(`SELECT COUNT(*) as count FROM ${table.name}`),
db.prepare(`SELECT COUNT(*) as count FROM ${table.name}`).all(),
),
);
const counts = countInfo.map((def) => {
Expand Down Expand Up @@ -239,13 +241,14 @@ export function createActorInspectorRouter() {
const db = await c.var.inspector.accessors.getDb();

try {
const result = (await db.execute(
c.req.valid("json").query,
...(c.req.valid("json").params || []),
)) as unknown;
const result = (await db
.prepare(
c.req.valid("json").query,
...(c.req.valid("json").params || []),
)
.all()) as unknown;
return c.json({ result }, 200);
} catch (error) {
c;
return c.json({ error: (error as Error).message }, 500);
}
},
Expand Down
14 changes: 8 additions & 6 deletions packages/db/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,16 @@ export type DatabaseProvider<DB extends RawAccess> = {
onMigrate: (client: DB) => void | Promise<void>;
};

type ExecuteFunction = (
query: string,
...args: unknown[]
) => Promise<unknown[]>;
type PrepareFunction = (query: string, ...args: unknown[]) => Statement;

type Statement = {
all(...args: unknown[]): Promise<unknown[]>;
run(...args: unknown[]): Promise<unknown>;
};

export type RawAccess = {
/**
* Executes a raw SQL query.
* Prepares a raw SQL query.
*/
execute: ExecuteFunction;
prepare: PrepareFunction;
};
30 changes: 26 additions & 4 deletions packages/db/src/drizzle/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,20 @@ export function db<
const client = durableDrizzle<TSchema, SQLiteShim>(conn, config);
return Object.assign(client, {
// client.$client.exec is the underlying SQLite client
execute: async (query, ...args) =>
client.$client.exec(query, ...args),
prepare: (query, ...args) => {
return {
all: async (...innerArgs) =>
client.$client.exec(
query,
...(innerArgs.length > 0 ? innerArgs : args),
) as Promise<unknown[]>,
run: async (...innerArgs) =>
client.$client.exec(
query,
...(innerArgs.length > 0 ? innerArgs : args),
) as Promise<unknown>,
};
},
} satisfies RawAccess);
}

Expand All @@ -72,8 +84,18 @@ export function db<
});

return Object.assign(client, {
execute: async (query, ...args) =>
client.$client.prepare(query).all(...args),
prepare: (query, ...args) => {
return {
all: async (...innerArgs) =>
client.$client
.prepare(query)
.all(...(innerArgs.length > 0 ? innerArgs : args)),
run: async (...innerArgs) =>
client.$client
.prepare(query)
.run(...(innerArgs.length > 0 ? innerArgs : args)),
};
},
} satisfies RawAccess);
},
onMigrate: async (client) => {
Expand Down
Loading
Loading