addamsson
addamsson
Explore posts from servers
DTDrizzle Team
Created by addamsson on 6/10/2024 in #help
Drizzle complains when I'm trying to insert into a table.
I have a schema that looks like this:
export const Organization = pGtable(
"Organization",
{
id: text("id").primaryKey().notNull(),
name: text("name").notNull(),
createdAt: timestamp("createdAt", { precision: 3, mode: "string" })
.defaultNow()
.notNull(),
updatedAt: timestamp("updatedAt", {
precision: 3,
mode: "string",
}).notNull(),
},
(table) => {
return {
name_key: uniqueIndex("Organization_name_key").using(
"btree",
table.name,
),
};
},
);
export const Organization = pGtable(
"Organization",
{
id: text("id").primaryKey().notNull(),
name: text("name").notNull(),
createdAt: timestamp("createdAt", { precision: 3, mode: "string" })
.defaultNow()
.notNull(),
updatedAt: timestamp("updatedAt", {
precision: 3,
mode: "string",
}).notNull(),
},
(table) => {
return {
name_key: uniqueIndex("Organization_name_key").using(
"btree",
table.name,
),
};
},
);
and when I'm trying to run a query against it:
import * as schema from "../src/drizzle/schema";
import { Client } from "pg";

export const client = new Client({
connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(client, { schema });

await db.insert(Organization).values({
id: "68184833-8d03-41d6-95a2-4f23c4f097d6",
name: "org",
createdAt: new Date(),
updatedAt: new Date(),
});
import * as schema from "../src/drizzle/schema";
import { Client } from "pg";

export const client = new Client({
connectionString: process.env.DATABASE_URL,
});

export const db = drizzle(client, { schema });

await db.insert(Organization).values({
id: "68184833-8d03-41d6-95a2-4f23c4f097d6",
name: "org",
createdAt: new Date(),
updatedAt: new Date(),
});
typescript complains that my data is wrong:
Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; ...
Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; ...
if I add as any at the end it works, but I'd rather not opt-out of type-safety. What am I doing wrong?
5 replies
DTDrizzle Team
Created by addamsson on 6/10/2024 in #help
Is it possible to use the Query API to select many-to-many relations?
In prisma I can do this to select the entities from the "other side" of a many-to-many join:
export const select = {
id: true,
email: true,
name: true,
teams: {
select: {
teamId: true,
// 👇 here
team: {
select: {
orgId: true,
name: true,
},
},
},
},
};
export const select = {
id: true,
email: true,
name: true,
teams: {
select: {
teamId: true,
// 👇 here
team: {
select: {
orgId: true,
name: true,
},
},
},
},
};
I tried the same with Drizzle:
json{
columns: {
id: true,
email: true,
name: true,
},
with: {
teamConnections: {
columns: {
teamId: true,
// 💥 oops
},
},
}
}
json{
columns: {
id: true,
email: true,
name: true,
},
with: {
teamConnections: {
columns: {
teamId: true,
// 💥 oops
},
},
}
}
and it seems that Drizzle doesn't know about these? Is there a way to perform deep nesting or do I have to resort to using the Select API?
3 replies
DTDrizzle Team
Created by addamsson on 6/10/2024 in #help
How can I configure `drizzle-kit introspect` to generate a schema with a schema?
I'm using this guide to migrate from Prisma to Drizzle and when I'm calling drizzle-kit introspect it generates a schema.ts file without using a pg schema. It should be obvious to drizzle-kit that I'm using schemas since I have ?schema=myschema at the end of the database connection string. How can I fix this?
1 replies
DTDrizzle Team
Created by addamsson on 6/4/2024 in #help
How can I "tell" Drizzle if a migration is considered "done" or not when migrating from Prisma?
I'm migrating my project from Prisma to Drizzle following the migration guide and I've bumped into a problem. Drizzle correctly generates a migration file that says:
-- Current sql file was generated after introspecting the database
-- If you want to run this migration please uncomment this code before executing migrations
-- Current sql file was generated after introspecting the database
-- If you want to run this migration please uncomment this code before executing migrations
my problem is that this will fail when I start my application:
await client.connect();
// This command run all migrations from the migrations folder and apply changes to the database
await migrate(db, {
migrationsFolder: resolve(__dirname, "../src/drizzle"),
});
await client.connect();
// This command run all migrations from the migrations folder and apply changes to the database
await migrate(db, {
migrationsFolder: resolve(__dirname, "../src/drizzle"),
});
with:
error: unterminated /* comment at or near "/*
DO $$ BEGIN
CREATE TYPE "public"."AccountProvider" AS ENUM('LOCAL', 'DISCORD');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
"
error: unterminated /* comment at or near "/*
DO $$ BEGIN
CREATE TYPE "public"."AccountProvider" AS ENUM('LOCAL', 'DISCORD');
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
"
so right after the unterminated /* that comes with the script. If I uncomment this script then it fails with:
error: column "providerid" does not exist
error: column "providerid" does not exist
I think this migration shouldn't run at all, since it was generated from my existing schema (so no migration is necessary). Is there a way to mark a migration as "done"? I checked and Drizzle created a drizzle schema in my database and it has an empty __drizzle_migrations table.
35 replies
DTDrizzle Team
Created by addamsson on 6/4/2024 in #help
Is it necessary to define both sides of a relation?
I'm looking at the docs and it is not clear whether I need to define both sides (eg: both one and many) of a relation when working with a Drizzle schema. I've just migrated my Prisma schema and I'm in the process of adding relations. If I have this for example:
export const OrgToTeam = relations(Organization, ({ many }) => ({
teams: many(Team),
}));
export const OrgToTeam = relations(Organization, ({ many }) => ({
teams: many(Team),
}));
do I also have to add:
export const TeamToOrg = relations(Team, ({ one }) => ({
org: one(Organization),
}));
export const TeamToOrg = relations(Team, ({ one }) => ({
org: one(Organization),
}));
if I want to join my Organizations when I query a Team?
1 replies
DTDrizzle Team
Created by addamsson on 6/4/2024 in #help
How can I properly configure Drizzle?
I'm following the Prisma migration guide and I have a few problems: My database is in my own schema, but I can't find the option to specify the schema. Drizzle defaults to public which is an antipattern (and also empty in my case). Apart from this even though I configure Drizzle to put the schema file in a specific folder:
export default defineConfig({
dialect: "postgresql",
out: "./src/drizzle",
schema: "./src/repository/schema.ts",
dbCredentials: {
url: process.env.DATABASE_URL ?? fail("DATABASE_URL is not defined"),
},
verbose: true,
strict: true,
});
export default defineConfig({
dialect: "postgresql",
out: "./src/drizzle",
schema: "./src/repository/schema.ts",
dbCredentials: {
url: process.env.DATABASE_URL ?? fail("DATABASE_URL is not defined"),
},
verbose: true,
strict: true,
});
it puts the resulting schema.ts in ./src/drizzle/schema.ts Is this something I can configure?
19 replies
DTDrizzle Team
Created by addamsson on 6/3/2024 in #help
Is there a way to do a "down" migration with Drizzle?
I'm looking at the docs of Drizzle migrations and I can't seem to find how to write migrations that can be rolled back.
18 replies
DTDrizzle Team
Created by addamsson on 5/25/2024 in #help
How can I generate / migrate a schema if I'm using an in-memory Postgresql?
I'm trying to use an embedded PostgreSQL (for demonstration purposes) and I've bumped into an issue with migrations: I cannot generate the migration scripts from the CLI because there is no running database, but there is also no programmatic accesss to the generator. How can I solve this problem?
1 replies
DIAdiscord.js - Imagine an app
Created by addamsson on 5/7/2024 in #djs-questions
My bot doesn't get the full list of channels on a server
Hi there! I'm working on a bot that posts messages in a channel and I've just noticed that this functionality no longer works. I did some digging and it seems that not all channels are listed when using client.channels.cache. I checked all permissions, and viewed the server by using the bot's role and everything looks fine, my bot is supposed to see the relevant channels, but when I do this:
const channel = client.channels.cache.get(myChannelId);
const channel = client.channels.cache.get(myChannelId);
only a subset of all visible channels is returned. I double checked and the channel id I'm using (myChannelId) is good, but it is not in the list. Am I supposed to invalidate the cache somehow? What am I missing?
65 replies
DIAdiscord.js - Imagine an app
Created by addamsson on 10/10/2023 in #djs-questions
How to send a message to a channel?
No description
12 replies
DIAdiscord.js - Imagine an app
Created by addamsson on 9/18/2023 in #djs-questions
onInteractionCreate doesn't get called when I select a previously deselected parameter
I have a command that has 2 autocomplete parameters:
const data = new SlashCommandBuilder()
.setName(name)
.setDescription("Sets the current channel as a daily sync channel")
.addStringOption((option) =>
option
.setName(Options.org)
.setDescription("Filter for organization")
.setRequired(true)
.setAutocomplete(true)
)
.addStringOption((option) =>
option
.setName(Options.team)
.setDescription("Filter for team")
.setRequired(false)
.setAutocomplete(true)
);
const data = new SlashCommandBuilder()
.setName(name)
.setDescription("Sets the current channel as a daily sync channel")
.addStringOption((option) =>
option
.setName(Options.org)
.setDescription("Filter for organization")
.setRequired(true)
.setAutocomplete(true)
)
.addStringOption((option) =>
option
.setName(Options.team)
.setDescription("Filter for team")
.setRequired(false)
.setAutocomplete(true)
);
By default it pops up the org as an option which works fine, but if I press backspace and delete this suggestion I can select other parameters. In my case I selected team, and proceeded to select a team. After that when I select org from the parameters I get displayed the previous suggestions. My problem is that I have some code that filters organizations if a team is selected:
if (focusedOption.name === OrgAndTeamOptions.org) {
// 📘 if we have a team, then only the team's org is selectable
if (teamId) {
const teamOrgId = user.teams.find(
(team) => team.teamId === teamId
)?.team.orgId;
choices = user.organizations
.filter((org) => org.orgId === teamOrgId)
.map((org) => ({
name: org.organization.name,
value: org.orgId,
}));
} else {
choices = user.organizations.map((org) => ({
name: org.organization.name,
value: org.orgId,
}));
}
}
if (focusedOption.name === OrgAndTeamOptions.org) {
// 📘 if we have a team, then only the team's org is selectable
if (teamId) {
const teamOrgId = user.teams.find(
(team) => team.teamId === teamId
)?.team.orgId;
choices = user.organizations
.filter((org) => org.orgId === teamOrgId)
.map((org) => ({
name: org.organization.name,
value: org.orgId,
}));
} else {
choices = user.organizations.map((org) => ({
name: org.organization.name,
value: org.orgId,
}));
}
}
This works if the user starts to type something, but the whole InteractionCreate callback doesn't get called when I simply select org, the old list is displayed instead. How can I force the reloading of the organizations that the user can pick? I'd like to use autocomplete as it is possible that there are many organizations / teams to choose from.
8 replies
DIAdiscord.js - Imagine an app
Created by addamsson on 9/12/2023 in #djs-questions
How to make sure that a channels.create call followed by a channels.fetch call is consistent?
Right now I have some code that creates a category and then adds some channels to it. What I've noticed is that there is some sort of race condition. Whenever I create a new category with
await guild.channels.create({
type: ChannelType.GuildCategory,
name: groupToCreate,
});
await guild.channels.create({
type: ChannelType.GuildCategory,
name: groupToCreate,
});
then there is a seemingly random chance that a subsequent
await guild.channels.fetch();
await guild.channels.fetch();
call will not contain the newly created category. How can i make sure that fetch is in a happens-before relationship with create? Note that I also tried:
await guild.channels.fetch(undefined, {
force: true,
});
await guild.channels.fetch(undefined, {
force: true,
});
to no avail. 😦
5 replies
DIAdiscord.js - Imagine an app
Created by addamsson on 9/8/2023 in #djs-questions
How to create a new channel for a guild?
I have a bot that will create a text channel to write into when invited. My question is how can I do this with discord.js? More specifically. I have this code that I have written by just exploring the API:
const guild = await client.guilds.cache.get("<some-id>");
guild?.channels.create({
name: "test",
type: ChannelType.GuildText,
topic: "test",
});
const guild = await client.guilds.cache.get("<some-id>");
guild?.channels.create({
name: "test",
type: ChannelType.GuildText,
topic: "test",
});
I'm guessing that this will work, but I'm not sure I understand what cache is about. I've seen this throughout the API, but I'm not sure how it works. Do I have to load the cache, or does it happen lazily whenever I try to interact with something?
78 replies