ReferenceError: Cannot access 'addon' before initialization

This is one of the files in ./schema/
import {
integer,
primaryKey,
sqliteTable,
text,
} from "drizzle-orm/sqlite-core";
import { Entity } from "../abstract/Entity.ts";
import { organisation, rental } from "@/db/index.ts";
import { relations } from "drizzle-orm";

export const addon = sqliteTable("addon", {
...Entity,
name: text("name").notNull(),
description: text("description").notNull(),
price: integer("price").notNull(),
organisationId: text("organisationId").notNull(),
});

export const addonRelations = relations(addon, ({ one, many }) => ({
organisation: one(organisation, {
fields: [addon.organisationId],
references: [organisation.id],
}),
addontsToRentals: many(addonsToRentals),
}));

export const addonsToRentals = sqliteTable(
"addons_to_rentals",
{
addonId: text("addonId")
.notNull()
.references(() => addon.id),
rentalId: text("rentalId")
.notNull()
.references(() => rental.id),
},
t => ({
pk: primaryKey(t.addonId, t.rentalId),
}),
);

export const addonsToRentalsRelations = relations(
addonsToRentals,
({ one }) => ({
addon: one(addon, {
fields: [addonsToRentals.addonId],
references: [addon.id],
}),
rental: one(rental, {
fields: [addonsToRentals.rentalId],
references: [rental.id],
}),
}),
);
import {
integer,
primaryKey,
sqliteTable,
text,
} from "drizzle-orm/sqlite-core";
import { Entity } from "../abstract/Entity.ts";
import { organisation, rental } from "@/db/index.ts";
import { relations } from "drizzle-orm";

export const addon = sqliteTable("addon", {
...Entity,
name: text("name").notNull(),
description: text("description").notNull(),
price: integer("price").notNull(),
organisationId: text("organisationId").notNull(),
});

export const addonRelations = relations(addon, ({ one, many }) => ({
organisation: one(organisation, {
fields: [addon.organisationId],
references: [organisation.id],
}),
addontsToRentals: many(addonsToRentals),
}));

export const addonsToRentals = sqliteTable(
"addons_to_rentals",
{
addonId: text("addonId")
.notNull()
.references(() => addon.id),
rentalId: text("rentalId")
.notNull()
.references(() => rental.id),
},
t => ({
pk: primaryKey(t.addonId, t.rentalId),
}),
);

export const addonsToRentalsRelations = relations(
addonsToRentals,
({ one }) => ({
addon: one(addon, {
fields: [addonsToRentals.addonId],
references: [addon.id],
}),
rental: one(rental, {
fields: [addonsToRentals.rentalId],
references: [rental.id],
}),
}),
);
When I run npx drizzle-kit generate:sqlite I get the error:
ReferenceError: Cannot access 'addon' before initialization
at Object.addon (/Users/notluksus/Work/velocita/db/schema/addon.ts:1:1)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/schema/addon.ts:14:45)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/schema/index.ts:10:45)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/index.ts:16:45)
at Function.entries (<anonymous>)
at Object.extractTablesRelationalConfig (/Users/notluksus/Work/velocita/node_modules/drizzle-orm/alias-72a4082c.cjs:3445:39)
at drizzle (/Users/notluksus/Work/velocita/node_modules/src/better-sqlite3/driver.ts:32:24)
at Object.<anonymous> (/Users/notluksus/Work/velocita/db/index.ts:6:12)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._compile (/Users/notluksus/Work/velocita/node_modules/drizzle-kit/index.cjs:8604:30)
ReferenceError: Cannot access 'addon' before initialization
at Object.addon (/Users/notluksus/Work/velocita/db/schema/addon.ts:1:1)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/schema/addon.ts:14:45)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/schema/index.ts:10:45)
at Object.get [as addon] (/Users/notluksus/Work/velocita/db/index.ts:16:45)
at Function.entries (<anonymous>)
at Object.extractTablesRelationalConfig (/Users/notluksus/Work/velocita/node_modules/drizzle-orm/alias-72a4082c.cjs:3445:39)
at drizzle (/Users/notluksus/Work/velocita/node_modules/src/better-sqlite3/driver.ts:32:24)
at Object.<anonymous> (/Users/notluksus/Work/velocita/db/index.ts:6:12)
at Module._compile (node:internal/modules/cjs/loader:1226:14)
at Module._compile (/Users/notluksus/Work/velocita/node_modules/drizzle-kit/index.cjs:8604:30)
And I don't understand why since the schema doesn't have any self references
22 Replies
benjick
benjick15mo ago
Any good way of debugging this yet?
Angelelz
Angelelz15mo ago
The error mentions a file .../schema/addon.ts What's in that file?
maupiszon
maupiszon14mo ago
it's simple problem probably is here
import { organisation, rental } from "@/db/index.ts";
import { organisation, rental } from "@/db/index.ts";
because you use a alias try change it into relative path ___ sorry for my English but i try learn it
hotshoe
hotshoe14mo ago
Same issue here. Can somebody from drizzle team please comment? Appears to be a circular reference problem that breaks queries and drizzle-kit push, etc. I'm working around the issue by putting all my schema into the same file, but this is less than ideal, naturally. I'd create a repro but I've already lost my entire evening to this (but will do so if needed. just lmk). thx!
hotshoe
hotshoe14mo ago
GitHub
[BUG]: Relations circular reference breaks query and drizzle-kit pu...
What version of drizzle-orm are you using? 0.28.6 What version of drizzle-kit are you using? 0.19.13 Describe the Bug Query relations involving multiple tables (i.e., .schema files) where circular ...
hotshoe
hotshoe14mo ago
Again, for anybody running into this issue, adding all my schema and relations into single file resolved the issue for me.
benjick
benjick14mo ago
This issue is due to circular circular dependencies. For me I had an enum which was imported into one file and then another, so I just extracted it to its own file which cleared it up
Angelelz
Angelelz14mo ago
A repro repo will come a long way. It's very likely an issue on your imports and an actual circular dependency
hotshoe
hotshoe14mo ago
I'll work on a repro. I previously (before filing ticket) double and triple checked for an circ deps on my end and the only ones I could find were the ones that the drizzle schema and relatiions declarations require me to introduce.
hotshoe
hotshoe14mo ago
Here is a repo repro'ing the issue -- https://github.com/rolanday/drizzle-circ-dep It's a solid-start project, but not important. Just run the package.json db:push script and you'll see output below. I didn't bother working up a query because I've observed that whenever the push command fails so will the runtime query.
Reading config file '/Users/roland/GitHub/public/issues/drizzle-circ-dep/drizzle.config.ts'
ReferenceError: Cannot access 'account' before initialization
at Object.account (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/account.schema.ts:1:1)
at Object.get [as account] (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/account.schema.ts:14:45)
at Object.<anonymous> (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/user.schema.ts:17:43)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._compile (/Users/roland/GitHub/public/issues/drizzle-circ-dep/node_modules/drizzle-kit/index.cjs:8623:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Object.newLoader [as .ts] (/Users/roland/GitHub/public/issues/drizzle-circ-dep/node_modules/drizzle-kit/index.cjs:8627:13)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Module.require (node:internal/modules/cjs/loader:1143:19)
Reading config file '/Users/roland/GitHub/public/issues/drizzle-circ-dep/drizzle.config.ts'
ReferenceError: Cannot access 'account' before initialization
at Object.account (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/account.schema.ts:1:1)
at Object.get [as account] (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/account.schema.ts:14:45)
at Object.<anonymous> (/Users/roland/GitHub/public/issues/drizzle-circ-dep/src/schema/user.schema.ts:17:43)
at Module._compile (node:internal/modules/cjs/loader:1256:14)
at Module._compile (/Users/roland/GitHub/public/issues/drizzle-circ-dep/node_modules/drizzle-kit/index.cjs:8623:30)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Object.newLoader [as .ts] (/Users/roland/GitHub/public/issues/drizzle-circ-dep/node_modules/drizzle-kit/index.cjs:8627:13)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Module.require (node:internal/modules/cjs/loader:1143:19)
GitHub
GitHub - rolanday/drizzle-circ-dep
Contribute to rolanday/drizzle-circ-dep development by creating an account on GitHub.
Angelelz
Angelelz14mo ago
Sounds good, I'll check it out if I have some time today
hotshoe
hotshoe14mo ago
Thank you @Angelelz . Btw, the repro does indeed have circ deps, but these are artifacts of expressing relations between schema in multiple files. Very possible I'm going about it the wrong way, but not seeing any other way short of expressing expressing all in a single file (my current workaround).
Angelelz
Angelelz14mo ago
Alright let me take a look You definitely have circular dependencies The solution it's pretty simple
hotshoe
hotshoe14mo ago
I'm all ears
Angelelz
Angelelz14mo ago
Just remove the relations from the user schema file, and create a new file just for the relations
import { relations } from "drizzle-orm";
import { user } from "./user.schema";
import { profile } from "./profile.schema";
import { email } from "./email.schema";
import { account } from "./account.schema";

export const userRelations = relations(user, ({ many, }) => ({
profile: many(profile),
email: many(email),
account: many(account),
}));

export const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id],
}),
}));

export const profileRelations = relations(profile, ({ one }) => ({
user: one(user, {
fields: [profile.userId],
references: [user.id],
}),
}));

export const emailRelations = relations(email, ({ one }) => ({
user: one(user, {
fields: [email.userId],
references: [user.id],
}),
}));
import { relations } from "drizzle-orm";
import { user } from "./user.schema";
import { profile } from "./profile.schema";
import { email } from "./email.schema";
import { account } from "./account.schema";

export const userRelations = relations(user, ({ many, }) => ({
profile: many(profile),
email: many(email),
account: many(account),
}));

export const accountRelations = relations(account, ({ one }) => ({
user: one(user, {
fields: [account.userId],
references: [user.id],
}),
}));

export const profileRelations = relations(profile, ({ one }) => ({
user: one(user, {
fields: [profile.userId],
references: [user.id],
}),
}));

export const emailRelations = relations(email, ({ one }) => ({
user: one(user, {
fields: [email.userId],
references: [user.id],
}),
}));
hotshoe
hotshoe14mo ago
I tried that, but then the relations don't seem to get picked up when I build query i'll try again, but is there any special convention I need to follow? Or idea is I should be able to express relations in sidecar files along side my schema (just like what you have ^^). Btw, ty for taking time to look into this. I'll go ahead and give another try breaking out the relations into separate file(s), but wasn't working for me last night.
Angelelz
Angelelz14mo ago
No description
Angelelz
Angelelz14mo ago
You create an index.ts file that looks like this:
export * from "./account.schema"
export * from "./email.schema"
export * from "./profile.schema"
export * from "./relations.schema"
export * from "./user.schema"
export * from "./account.schema"
export * from "./email.schema"
export * from "./profile.schema"
export * from "./relations.schema"
export * from "./user.schema"
This is what your db file should look like:
import { drizzle } from "drizzle-orm/node-postgres";
import { Client } from "pg";
import * as schema from './src/schema/index'

const client = new Client({
host: "127.0.0.1",
port: 5432,
user: "postgres",
password: "password",
database: "db_name",
});

await client.connect();
const db = drizzle({} as any, { schema});


const query = db.query.user.findMany({with: {
profile: true
}})
import { drizzle } from "drizzle-orm/node-postgres";
import { Client } from "pg";
import * as schema from './src/schema/index'

const client = new Client({
host: "127.0.0.1",
port: 5432,
user: "postgres",
password: "password",
database: "db_name",
});

await client.connect();
const db = drizzle({} as any, { schema});


const query = db.query.user.findMany({with: {
profile: true
}})
And it will infer properly
Angelelz
Angelelz14mo ago
I pushed all my changes to a fork: https://github.com/Angelelz/drizzle-circ-dep
GitHub
GitHub - Angelelz/drizzle-circ-dep: correction repo
correction repo. Contribute to Angelelz/drizzle-circ-dep development by creating an account on GitHub.
hotshoe
hotshoe14mo ago
I'll take a look now. ty for this! Hi @Angelelz , got to the bottom of the issue with your help. When I created my relations to support query (after creating my table schemas), I didn't go back and add relations.schema.ts to the list of barrel exports. (Like I mentioned, I originally had them factored out this way.) This in-turn lead me to incorrectly believe I needed to keep the relations in same file as user.schema, which admittedly made no sense to me, but it worked -- from perspective of being able to type out the query in VS -- in effect sending me down the wrong path. Apologies for eating up your time on this, and I much appreciate! Hopefully helps somebody down the road who runs into similar. Thanks again!! You rock.
djarran
djarran14mo ago
Wanted to confirm the above advice worked. Thank you @hotshoe for the further questions, really saved me a lot of time. And thanks to Angelelz for answering!
P.S.Nikhil
P.S.Nikhil11mo ago
It helped me to solve it
Want results from more Discord servers?
Add your server