tacomanator
tacomanator
DTDrizzle Team
Created by tacomanator on 12/25/2023 in #help
drizzle-kit snapshot files malformed error
I’m getting snapshot “xxxx_snapshot.json data is malformed" errors trying to generate a schema change. The error appears for each of the existing snapshot files. There were no schema updates since June, so all of the snapshot files are what was generated by the version available at that time or earlier (checked-in as generated). The latest version appears not to be able to work with these files, as the error message appears for every snapshot. I tried downgrading to 0.19.13 but then I get an error that the version is outdated an to upgrade. Any recommended approach to get the snapshot files up-to-date?
2 replies
DTDrizzle Team
Created by tacomanator on 9/27/2023 in #help
drizzle-kit tsconfig.json paths alias
Not a drizzle issue per-se, but running into an issue trying to make drizzle-kit work again by changing target to esnext. The database schema file references some other files using an alias defined in the tsconfig.json. Any advice on getting drizzle-kit to recognize this setting?
"compilerOptions": {
"target": "esnext",
"paths": {
"@/*": ["./*"]
}
}
"compilerOptions": {
"target": "esnext",
"paths": {
"@/*": ["./*"]
}
}
schema.ts:
import { values } from "@/path/to/file";
export const table = sqliteTable("table", { value: text("value", { enum: values })})
import { values } from "@/path/to/file";
export const table = sqliteTable("table", { value: text("value", { enum: values })})
$ drizzle-kit generate:sqlite
drizzle-kit: v0.19.13
drizzle-orm: v0.28.6

No config path provided, using default 'drizzle.config.ts'
Error: Cannot find module '@/path/to/file';
Require stack:
- /db/schema.ts
$ drizzle-kit generate:sqlite
drizzle-kit: v0.19.13
drizzle-orm: v0.28.6

No config path provided, using default 'drizzle.config.ts'
Error: Cannot find module '@/path/to/file';
Require stack:
- /db/schema.ts
3 replies
DTDrizzle Team
Created by tacomanator on 5/26/2023 in #help
Relations, three level nested where?
Given a User, Role, RoleToUser many-to-many relation:
export const userRelations = relations(User, ({ many }) => ({
roleToUser: many(RoleToUser),
}));

export const roleRelations = relations(Role, ({ many }) => ({
roleToUser: many(RoleToUser),
}));

export const roleToUserRelations = relations(RoleToUser, ({ one }) => ({
role: one(Role, { fields: [RoleToUser.roleId], references: [Role.id] }),
user: one(User, { fields: [RoleToUser.userId], references: [User.id] }),
}));
export const userRelations = relations(User, ({ many }) => ({
roleToUser: many(RoleToUser),
}));

export const roleRelations = relations(Role, ({ many }) => ({
roleToUser: many(RoleToUser),
}));

export const roleToUserRelations = relations(RoleToUser, ({ one }) => ({
role: one(Role, { fields: [RoleToUser.roleId], references: [Role.id] }),
user: one(User, { fields: [RoleToUser.userId], references: [User.id] }),
}));
Are we able to filter with where on the third level to, for example, find all users belonging to a role of the given name?
db.query.User.findMany({
with: {
roleToUser: {
with: {
role: {
where: eq(Role.name, "現場監督"),
},
},
},
},
}),
db.query.User.findMany({
with: {
roleToUser: {
with: {
role: {
where: eq(Role.name, "現場監督"),
},
},
},
},
}),
Currently it doesn't seem to work, although of course in this example I can start with Role instead to achieve the same thing....
9 replies
DTDrizzle Team
Created by tacomanator on 4/19/2023 in #help
Alias in from() change? (SQLite)
Did something change wrt using aliases in from()? Until recently I've been using aliases to affect the resulting object, but it seems to have stopped working as it did before. Previously:
const user = alias(User, "user");
const parent = alias(User, "parent");
const result = db
.select()
.from(user)
.leftJoin(parent, eq(user.parentId, parent.id))
.get();
console.log(result.user) // { user: {...}, parent: {...} }
const user = alias(User, "user");
const parent = alias(User, "parent");
const result = db
.select()
.from(user)
.leftJoin(parent, eq(user.parentId, parent.id))
.get();
console.log(result.user) // { user: {...}, parent: {...} }
In the current version, however, the query return type still has user in lowercase, but in the actual data it's uppercase, as if the alias is ignored (still working for innerJoin though).
5 replies
DTDrizzle Team
Created by tacomanator on 4/18/2023 in #help
CTE query of hierarchical data
I'd like to drizzle-ize this query:
WITH RECURSIVE
Child(n) AS (
VALUES('...id')
UNION
SELECT id FROM User, Child
WHERE User.parentId=Child.n
)
SELECT * FROM Application
WHERE Application.ownerUserId IN Child;
WITH RECURSIVE
Child(n) AS (
VALUES('...id')
UNION
SELECT id FROM User, Child
WHERE User.parentId=Child.n
)
SELECT * FROM Application
WHERE Application.ownerUserId IN Child;
But having trouble finding relevant docs. Is it possible without raw sql using $with?
4 replies
DTDrizzle Team
Created by tacomanator on 4/18/2023 in #help
createInsertSchema wrong type (drizzle-zod 0.3.1, sqlite))
11 replies
DTDrizzle Team
Created by tacomanator on 4/12/2023 in #help
sqliteTable wrapper which modifies fields, with proper types
More of a TypeScript question, but I'm trying to create a wrapper for sqliteTable to add a set of standard fields (and keys) to the fields provided:
import { sqliteTable, SQLiteTableFn } from "drizzle-orm/sqlite-core"

const extraFields = { ... }

const wrapper: SQLiteTableFn = (name, fields, keys) => {
return sqliteTable(
name,
{ ...extraFields, ...fields },
(Table) => ({ ...keys })
);
};
import { sqliteTable, SQLiteTableFn } from "drizzle-orm/sqlite-core"

const extraFields = { ... }

const wrapper: SQLiteTableFn = (name, fields, keys) => {
return sqliteTable(
name,
{ ...extraFields, ...fields },
(Table) => ({ ...keys })
);
};
This results in a type error on wrapper as the generics applied to SQLiteTableFn and the return value of wrapper return value sqliteTable on modified fields) no longer correspond. How can I create a type for wrapper which returns object properly typed?
3 replies
DTDrizzle Team
Created by tacomanator on 4/1/2023 in #help
Error migrating after updating to orm 0.23.3
After updating to the package released an hour ago, I am getting an error on migrating: error - RangeError: The supplied SQL string contains more than one statement at Database.prepare (.../node_modules/better-sqlite3/lib/methods/wrappers.js:5:21) at BetterSQLiteSession.prepareQuery (.../node_modules/drizzle-orm/better-sqlite3/session.js:19:34) at BetterSQLiteSession.prepareOneTimeQuery (.../node_modules/drizzle-orm/sqlite-core/session.js:14:21) at BetterSQLiteSession.run (.../node_modules/drizzle-orm/sqlite-core/session.js:17:21) at SQLiteSyncDialect.migrate (.../node_modules/drizzle-orm/sqlite-core/dialect.js:255:33) at migrate (.../node_modules/drizzle-orm/better-sqlite3/migrator.js:7:16) Migration code:
import { drizzle } from "drizzle-orm/better-sqlite3";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const db = drizzle(sqlite, { logger: true });
migrate(db, { migrationsFolder: "./db/migrations" });
import { drizzle } from "drizzle-orm/better-sqlite3";
import { migrate } from "drizzle-orm/better-sqlite3/migrator";
import Database from "better-sqlite3";

const sqlite = new Database("sqlite.db");
const db = drizzle(sqlite, { logger: true });
migrate(db, { migrationsFolder: "./db/migrations" });
4 replies
DTDrizzle Team
Created by tacomanator on 3/30/2023 in #help
Code generated value
I'm using SQLite. How can I create a custom type with an auto-generated value which is generated in code and not the database? I managed to get it to work, but I have to pass a blank value for the field whenever creating records otherwise I get a type error, and I'm having trouble finding the right combination of options.
import {customType, sqliteTable } from "drizzle-orm/sqlite-core";
import { createId } from "@paralleldrive/cuid2";

const cuid2 = customType<{ data: string; notNull: true }>({
dataType() { return "text"; },
toDriver(): string { return createId(); },
});

const users = sqliteTable("users",
{ id: cuid2("id").primaryKey() }
);

db.insert(users).values({id: ""}).run();
import {customType, sqliteTable } from "drizzle-orm/sqlite-core";
import { createId } from "@paralleldrive/cuid2";

const cuid2 = customType<{ data: string; notNull: true }>({
dataType() { return "text"; },
toDriver(): string { return createId(); },
});

const users = sqliteTable("users",
{ id: cuid2("id").primaryKey() }
);

db.insert(users).values({id: ""}).run();
If {id: ""} is left out of values, TypeScript complains: "property id is missing. On the other hand, setting a default or using default: true as configuration resolves the TypeScript error, but inserting records fails with a runtime error: UNIQUE constraint failed: users.id. Is there a better way that allows omitting the field on insert, does not result in a type error, and safely and reliably generates an value?
3 replies
DTDrizzle Team
Created by tacomanator on 3/27/2023 in #help
Cannot read properties of undefined (reading '0')
What is the expected behavior when using get() when there would be no matching results for a given select query? Does it return null or would this be an error? At present it's giving an error. I'm new to discord, but I guess I expected it to return a null. For example, the following query works and returns an empty array:
db.select().from(users).where(eq(users.email, email)).all();
db.select().from(users).where(eq(users.email, email)).all();
whereas changing all() to get() results in error trying to access first element of an empty array (drizzle-orm/utils.js:40:37):
db.select().from(users).where(eq(users.email, email)).get();
db.select().from(users).where(eq(users.email, email)).get();
6 replies