kysely-org / kysely

A type-safe typescript SQL query builder
https://kysely.dev
MIT License
10.33k stars 262 forks source link

Kysely + bun = ReferenceError: Cannot access uninitialized variable #412

Closed zzzej closed 1 year ago

zzzej commented 1 year ago

Setting up a new project with Kysely and the PlanetScaleDialect. I get the following error after a simple query or even with I console.log(db)

The error:

 /// <reference types="./query-creator.d.ts" />
2 | import { SelectQueryBuilder } from './query-builder/select-query-builder.js';
   ^
ReferenceError: Cannot access uninitialized variable.

This is my db.ts file:

import { Kysely } from "kysely";
import { PlanetScaleDialect } from "kysely-planetscale";
import { DB } from "./types/Database";

const db = new Kysely<DB>({
  dialect: new PlanetScaleDialect({
    host: process.env.DB_URL,
    username: process.env.DB_USER,
    password: process.env.DB_PASS,
    fetch: fetch,
    useSharedConnection: false,
  }),
});

export default db;

this is where I want to execute the query:

import { Hono } from "hono";
import db from "./db";

const app = new Hono();

app.get("/", (c) => c.json({ message: "hello" }));

app.get("/test-data", async (c) => {
  console.log(db);
  // const testData = await db
  //   .selectFrom("testtable")
  //   .select(["id", "name"])
  //   .where("testtable.active", "=", 1)
  //   .execute();

  return c.json({ message: "test" });
});

export default app;

It works perfectly fine with just the planetscale driver (no kysely)

My system info: Laptop: M2 Pro Server: bun 0.5.8 Global node version: 16.19 Global npm: 9.6

igalklebanov commented 1 year ago

Hey πŸ‘‹

We've not tested Kysely on Bun.

Seems to be related to this issue.

zzzej commented 1 year ago

Thanks for pointing out the issue

Jarred-Sumner commented 1 year ago

This is an ESM <> CJS module load order bug in Bun (not a bug in Kysely)

Jarred-Sumner commented 1 year ago

Pushed a fix for this in the canary build of Bun

This canary build has quite a lot of changes (new bundler) so there could be other things that crop up, but if you want to try it:

bun upgrade --canary

Before:

image

After:

image
zzzej commented 1 year ago

Worked on bun version 0.6! πŸ™Œ

zzzej commented 1 year ago

To be clear version 0.6 has not been released as of today. To use this version you need to run

bun upgrade --canary

as @Jarred-Sumner mentioned above