Skip to content
Merged
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
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
},
"dependencies": {
"@hiogawa/tiny-sql": "^0.0.3",
"kysely": "^0.26.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
Expand Down
8 changes: 0 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/db/d1-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export function createD1Api(options: D1ApiConfig): D1Database {

// TODO: we might not need "/dump" and "/execute" ? (actually "/execute" is currently 404 Not Found...)
if (url !== "/query") {
throw new Error("D1API_ERROR", {
throw new Error("UNOFFICIAL_D1_API_ERROR", {
cause: `unsupported endpoint '${url}'`,
});
}
Expand All @@ -50,7 +50,7 @@ export function createD1Api(options: D1ApiConfig): D1Database {
const resJson = await res.json();
const parsed = Z_QUERY_RESPONSE.parse(resJson);
if (!parsed.success) {
throw new Error("D1API_ERROR", { cause: resJson });
throw new Error("UNOFFICIAL_D1_API_ERROR", { cause: resJson });
}

const dummyRes = {
Expand Down
86 changes: 0 additions & 86 deletions src/db/d1-kysely.ts

This file was deleted.

15 changes: 0 additions & 15 deletions src/db/index.ts

This file was deleted.

10 changes: 3 additions & 7 deletions src/db/repl.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,16 @@
import { sql } from "kysely";
import { db, initializeDb } from ".";
import { setWorkerEnvDev } from "../utils/worker-env-dev";
import { sql } from "./sql";

// usage:
// pnpm repl
// > await sql`SELECT 1 + 1`.execute(db)
// > await sql`PRAGMA table_list`.execute(db)
// > await db.selectFrom("counter").selectAll().execute()
// > await sql`SELECT 1 + 1`.all()
// > await sql`PRAGMA table_list`.all()

async function main() {
console.log("* setting up globals...");
await setWorkerEnvDev();
await initializeDb();
Object.assign(globalThis, {
sql,
db,
});
}

Expand Down
8 changes: 0 additions & 8 deletions src/db/schema.ts

This file was deleted.

35 changes: 35 additions & 0 deletions src/db/sql.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { tinyassert } from "@hiogawa/utils";
import { env } from "../utils/worker-env";

//
// quick and dirty raw query buider
//

type D1Primitive = number | string | null;

export function sql<T = Record<string, D1Primitive>>(
strings: TemplateStringsArray,
...values: D1Primitive[]
) {
const query = strings.raw.join("?");
const stmt = env.db.prepare(query).bind(...values);
const self = {
all: async (): Promise<T[]> => {
const result = await stmt.all();
tinyassert(result.success, result.error);
return (result.results ?? []) as T[];
},
first: async (): Promise<T | undefined> => {
const rows = await self.all();
return rows[0];
},
firstOrThrow: async (): Promise<T> => {
const row = await self.first();
if (typeof row === "undefined") {
throw new Error("sql.firstOrThrow", { cause: { query, values } });
}
return row;
},
};
return self;
}
57 changes: 7 additions & 50 deletions src/rpc/server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import type { RequestHandler } from "@hattip/compose";
import { type TinyRpcRoutes, createTinyRpcHandler } from "@hiogawa/tiny-rpc";
import { zodFn } from "@hiogawa/tiny-rpc/dist/zod";
import { tinyassert } from "@hiogawa/utils";
import { sql } from "kysely";
import { z } from "zod";
import { db } from "../db";
import { sql } from "../db/sql";
import { env } from "../utils/worker-env";

export type RpcRoutes = typeof rpcRoutes;
Expand Down Expand Up @@ -48,57 +46,16 @@ const counterD1 = {
id: 1,

async get() {
// it's simple enough to get away with raw query
// but use kysely just for the sake of testing src/db/d1-api.ts

// d1 raw query
sqlD1<{ value: number }>`SELECT value from counter where id = ${this.id}`;

// kysely raw query
sql`SELECT value from counter where id = ${this.id}`;

// kysely query builder
const row = await db
.selectFrom("counter")
.select("value")
.where("id", "=", this.id)
.executeTakeFirstOrThrow();
const row = await sql<{
value: number;
}>`SELECT value from counter where id = ${this.id}`.firstOrThrow();
return row.value;
},

async update(delta: number) {
// d1 raw query
sqlD1`UPDATE Counter SET value = value + ${delta} WHERE id = ${this.id} RETURNING value`;

// kysely raw query
sql`UPDATE Counter SET value = value + ${delta} WHERE id = ${this.id} RETURNING value`;

// kysely query builder
const row = await db
.updateTable("counter")
.set({ value: sql`value + ${delta}` })
.where("id", "=", this.id)
.returning("value")
.executeTakeFirstOrThrow();
const row = await sql<{
value: number;
}>`UPDATE counter SET value = value + ${delta} WHERE id = ${this.id} RETURNING value`.firstOrThrow();
return row.value;
},
};

//
// simple raw query without kysely
//

type D1Primitive = number | string | null;

function sqlD1<T = Record<string, D1Primitive>>(
strings: TemplateStringsArray,
...values: D1Primitive[]
): () => Promise<T[]> {
const query = strings.raw.join("?");
const stmt = env.db.prepare(query).bind(...values);
return async () => {
const result = await stmt.all();
tinyassert(result.success, result.error);
return (result.results ?? []) as T[];
};
}
2 changes: 0 additions & 2 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { type RequestHandler, compose } from "@hattip/compose";
import { once } from "@hiogawa/utils";
import { loggerMiddleware } from "@hiogawa/utils-experimental";
import { importIndexHtml } from "@hiogawa/vite-import-index-html/dist/runtime";
import { initializeDb } from "../db";
import { rpcHandler } from "../rpc/server";
import { initializeEnv } from "../utils/worker-env";
import { runSSR } from "./ssr";
Expand Down Expand Up @@ -32,7 +31,6 @@ function htmlHandler(): RequestHandler {
function bootstrapHander(): RequestHandler {
return once(async () => {
await initializeEnv();
await initializeDb();
});
}

Expand Down