BaNuni
BaNuni
DTDrizzle Team
Created by BaNuni on 9/8/2024 in #help
Typing `varchar` with a type reference instead of `enum` value
using varchar and enum in the docs:
import { varchar, pgTable } from "drizzle-orm/pg-core";
export const table = pgTable('table', {
varchar1: varchar('varchar1'),
varchar2: varchar('varchar2', { length: 256 }),
});
// will be inferred as text: "value1" | "value2" | null
varchar: varchar('varchar', { enum: ["value1", "value2"] }),
import { varchar, pgTable } from "drizzle-orm/pg-core";
export const table = pgTable('table', {
varchar1: varchar('varchar1'),
varchar2: varchar('varchar2', { length: 256 }),
});
// will be inferred as text: "value1" | "value2" | null
varchar: varchar('varchar', { enum: ["value1", "value2"] }),
CREATE TABLE IF NOT EXISTS "table" (
"varchar1" varchar,
"varchar2" varchar(256),
);
CREATE TABLE IF NOT EXISTS "table" (
"varchar1" varchar,
"varchar2" varchar(256),
);
makes using an external value as enum a bit complex. and requires me to import an actual runtime value, even though it's not being used.
import { pokemonNames } from '@myorg/pokemon-lib'

// typeof pokemonNames - ('bulbasaur' | 'venosaur' | ... |'mew')[]
...
pokemon: varchar('pokempon', {enum: pokemonNames}),
...
import { pokemonNames } from '@myorg/pokemon-lib'

// typeof pokemonNames - ('bulbasaur' | 'venosaur' | ... |'mew')[]
...
pokemon: varchar('pokempon', {enum: pokemonNames}),
...
this value would not be used in runtime, but only in dev / build type when types matter. I think it's better to type these fields with a type statement:
import type { PokemonName } from '@myorg/pokemon-lib'

...
pokemon: varchar<PokemonName[]>('pokempon'),
...
import type { PokemonName } from '@myorg/pokemon-lib'

...
pokemon: varchar<PokemonName[]>('pokempon'),
...
is there an elegant way to do it? I could as a workaround use

pokemon: varchar('pokempon', enum: ... as PokemonName[] ),

pokemon: varchar('pokempon', enum: ... as PokemonName[] ),
but this feels very hacky, any thoughts? suggestions?
1 replies
DTDrizzle Team
Created by BaNuni on 8/19/2024 in #help
Using generics with Table type
hey there, I'm trying to create a generic function, something like this:
function insertWithLogger<DataType>(data: DataType[], table: SomeTableType<Data>) {
logger.info("Inserting data, wow!")
db.insert(table).values(data)
logger.info("inserted data, amazing!")
}
function insertWithLogger<DataType>(data: DataType[], table: SomeTableType<Data>) {
logger.info("Inserting data, wow!")
db.insert(table).values(data)
logger.info("inserted data, amazing!")
}
Somebody know how to type SomeTableType<DataType> properly?
2 replies
DTDrizzle Team
Created by BaNuni on 12/27/2023 in #help
drizzle-kit dry run / different in/out
Hello! I want to test the matching of my migrations to the schema code declarations: My questions (I'm pretty sure "no" is the answer to all, so it's just stuff that I think will be good to support): 1. is there a programmatic way to run "generate migration"? didn't find any docs about a js api from drizzle-kit (only types) 2. is there a way to run a "dry run" / a way to have different "in" and "out" dirs? (this is why I need to copy) 3. is there a programmatic way to parse a config file, change it and pass it to drizzle-kit? I currently. have two different configs with just "out" different (I import the original and override though...) My current, primitive, test: (with some try catches)
describe('test migrations match schema', () => {
afterAll(async () => {
await rm(testDir, { recursive: true })
})
test('migrations match schema', async () => {
await cp(originDir, testDir, { recursive: true })
const beforeGenerations = await readdir(testDir)
execSync("yarn run drizzle-kit generate:pg --config ./src/drizzle.test-config.ts", { stdio: "inherit" })
const afterGenerations = await readdir(testDir)
expect(beforeGenerations).toEqual(afterGenerations);
})
})
describe('test migrations match schema', () => {
afterAll(async () => {
await rm(testDir, { recursive: true })
})
test('migrations match schema', async () => {
await cp(originDir, testDir, { recursive: true })
const beforeGenerations = await readdir(testDir)
execSync("yarn run drizzle-kit generate:pg --config ./src/drizzle.test-config.ts", { stdio: "inherit" })
const afterGenerations = await readdir(testDir)
expect(beforeGenerations).toEqual(afterGenerations);
})
})
1 replies
DTDrizzle Team
Created by BaNuni on 12/27/2023 in #help
"Duplicate Index" - but no dupliacte index...
Hey there, I've HAD a duplicate index in one of my schemas:
{ tenantId, f0, f1, f2 }) => ({
myUniqueIdx: uniqueIndex('uniqueIdx').on(tenantId, f1, f2),
myIdx: index('imyIdx').on(tenantId, f0, f1, f2),
myOtherIdx: index('myIdx').on(tenantId, f0, f2, f1),
}
{ tenantId, f0, f1, f2 }) => ({
myUniqueIdx: uniqueIndex('uniqueIdx').on(tenantId, f1, f2),
myIdx: index('imyIdx').on(tenantId, f0, f1, f2),
myOtherIdx: index('myIdx').on(tenantId, f0, f2, f1),
}
which resulted in the first one overridden in the generated migration. this code is already deployed I added 2 columns, (e.g f3 and f4) and when I'm trying to generate migrations (pg) I'm getting
We've found duplicated index name across public schema. Please rename your index in either the myTable table or the table with the duplicated index name
We've found duplicated index name across public schema. Please rename your index in either the myTable table or the table with the duplicated index name
Even though currently I've no duplication nowhere... I want to fix it now, so I changed to the very very sure that's not duplicate:
{ tenantId, f0, f1, f2 }) => ({
myUniqueIdx: uniqueIndex('aaa').on(tenantId, f1, f2),
myIdx: index('bbb').on(tenantId, f0, f1, f2),
myOtherIdx: index('ccc').on(tenantId, f0, f2, f1),
}
{ tenantId, f0, f1, f2 }) => ({
myUniqueIdx: uniqueIndex('aaa').on(tenantId, f1, f2),
myIdx: index('bbb').on(tenantId, f0, f1, f2),
myOtherIdx: index('ccc').on(tenantId, f0, f2, f1),
}
but I get the same error... If I remove all of them completely, The generation succeeds. Whay am I missing?
10 replies
DTDrizzle Team
Created by BaNuni on 12/14/2023 in #help
Conditional Select in M2M findMany Type Inference
hey there, I'm adding a method that allows the user to either get a list of objects, and sometimes get related objects al well (members). it works fine function-wise - but for some reason, the addition of the ternary doesn't give me any type hints. I'd assume it'll add them conditionally... Is this a bug? am I missing anything? here is my code's paraphrase:
return db.query.projects.findMany({
columns: {
id: true
},
with: {
membersMapping: {
columns: {
memberId: true,
},
//** this makes the type inference crazy!
with: withMembers ? { member: { columns: { name: true, age: true } } } : {}
}
}
})
return db.query.projects.findMany({
columns: {
id: true
},
with: {
membersMapping: {
columns: {
memberId: true,
},
//** this makes the type inference crazy!
with: withMembers ? { member: { columns: { name: true, age: true } } } : {}
}
}
})
2 replies
DTDrizzle Team
Created by BaNuni on 11/12/2023 in #help
Upsert Multiple using EXCLUDED
hey there - I want to upsert multiple values and overwrite certain fields in case of conflicts. using plain SQL it'd be something like this:
insert into
"surveil" ("id", "last_seen", "name")
values
('1','2023-09-19 10:50:38.285+00', 'BanuniZ'),
('2','2023-09-19 10:50:38.285+00', 'Misha')
on conflict (id) do update set "last_seen" = EXCLUDED."last_seen"
insert into
"surveil" ("id", "last_seen", "name")
values
('1','2023-09-19 10:50:38.285+00', 'BanuniZ'),
('2','2023-09-19 10:50:38.285+00', 'Misha')
on conflict (id) do update set "last_seen" = EXCLUDED."last_seen"
how could I achieve this with drizzle? I couldn't find anything in the docs...
4 replies
DTDrizzle Team
Created by BaNuni on 10/31/2023 in #help
Using Query Syntax to filter by FK's field
hey there, I have a schema of users and their pets name and type. a user can only own one pet, and a pet could have several owners. how would I use query syntax to get all the users that own a dog (type === 'dog')?
export const users = pgTable('users', {
id: serial('id').primaryKey(),
petId: text('petId'),
name: text('name'),
});
export const pets = pgTable('pets', {
id: serial('id').primaryKey(),
name: text('name'),
type: text('type'),
});

export const usersRelations = relations(users, ({ one }) => ({
pet: one(pets, { fields: [user.petId], references: [pet.id] }),

}));
export const users = pgTable('users', {
id: serial('id').primaryKey(),
petId: text('petId'),
name: text('name'),
});
export const pets = pgTable('pets', {
id: serial('id').primaryKey(),
name: text('name'),
type: text('type'),
});

export const usersRelations = relations(users, ({ one }) => ({
pet: one(pets, { fields: [user.petId], references: [pet.id] }),

}));
11 replies
DTDrizzle Team
Created by BaNuni on 9/14/2023 in #help
packing migration files with the library
hey there, I'm trying to use migrate inside from a library consumer (i.e I have a @mycompany/db-lib that has doMigration and from my internal dev-app, I want to do something like:
import { doMigrate } from '@mycompany/db-lib'

export const onMigrateClick = () => {
doMigrate()
}
import { doMigrate } from '@mycompany/db-lib'

export const onMigrateClick = () => {
doMigrate()
}
how could I refer to the migration sql files and _meta files inside @mycompany/db-lib ? I guess I should also include them in the lib somehow... maybe use an import-like mechanism to include the folder in the built directory?
1 replies
DTDrizzle Team
Created by BaNuni on 9/13/2023 in #help
Migration custom logger
Hey there, I'm want to run migration as part of my CI/CD, and would have liked the output of the migrate function to be passed to my custom logger function. is it something that is supported/planned? if not - i'd suggest adding two logging options infoLogger and errorLogger both of type (msg: string) => void thx
3 replies
DTDrizzle Team
Created by BaNuni on 9/5/2023 in #help
Utilizing Many-to-Many relationships
Yo, I'm trying to make sense of a the drizzle way to handling many-to-many relations, but can't seem to understand how to get the related object with one statement (like in a classing double-join query) could somebody give me an example of a query utilizing this relationship? for example - when setting up the example here: https://orm.drizzle.team/docs/rqb#many-to-many
4 replies