piscopancer
piscopancer
Explore posts from servers
PPrisma
Created by piscopancer on 11/17/2024 in #help-and-questions
Infer type from create query?
here's the function that creates a new Schedule. Attention to the shape, not data
async function createSchedule() {
return db.schedule.create({
data: {
name: '',
days: {
create: [
{
holiday: true,
independentWorkDay: true,
lessons: {
create: [
{
place: 'some place',
type: 'lecture' satisfies LessonType,
subject: {
connect: {
id: 12, // the important part that the type would have this subject's id. There's no such field in `Prisma.LessonCreateArgs` ofc, so I need to infer the type from this function
},
},
},
],
},
},
],
},
},
})
}
async function createSchedule() {
return db.schedule.create({
data: {
name: '',
days: {
create: [
{
holiday: true,
independentWorkDay: true,
lessons: {
create: [
{
place: 'some place',
type: 'lecture' satisfies LessonType,
subject: {
connect: {
id: 12, // the important part that the type would have this subject's id. There's no such field in `Prisma.LessonCreateArgs` ofc, so I need to infer the type from this function
},
},
},
],
},
},
],
},
},
})
}
I want to get the type of the Lesson of the shape in this function. so it has to look like this
/**
* place: string
* type: string
* subject: {
* id: number
* }
*/
/**
* place: string
* type: string
* subject: {
* id: number
* }
*/
so that I can use somewhere else
const [lessons, setLessons] = useState<LessonToCreate[]>([])
setLessons([
{
place: '402',
type: 'seminar',
subject: {
id: 1
}
}
])
const [lessons, setLessons] = useState<LessonToCreate[]>([])
setLessons([
{
place: '402',
type: 'seminar',
subject: {
id: 1
}
}
])
Is there a utility type in prisma to infer this shape?
7 replies
PPrisma
Created by piscopancer on 11/15/2024 in #help-and-questions
narrow down String type using prisma client's extension?
can I explain to prisma client and typescript that this particular field needs to be a string union?
model Lesson {
id Int @id @default(autoincrement())
type String? // null | "practical" | "seminar" | "lecture"
model Lesson {
id Int @id @default(autoincrement())
type String? // null | "practical" | "seminar" | "lecture"
4 replies
PPrisma
Created by piscopancer on 11/15/2024 in #help-and-questions
`Prisma.skip` seen as `undefined`?
No description
5 replies
PPrisma
Created by piscopancer on 11/12/2024 in #help-and-questions
[React Native] DB duplicated to the emulator. Intentional?
No description
4 replies
PPrisma
Created by piscopancer on 11/12/2024 in #help-and-questions
[React Native] Creating client with Supabase crashes
with db.ts like so (pretty basic)
import { PrismaClient } from '@prisma/client/react-native'
import '@prisma/react-native'

export const db = new PrismaClient({
log: ['error'],
})

export async function initializeDb() {
try {
db.$applyPendingMigrations()
console.log('migrations complete')
} catch (e) {
console.error(`failed to apply migrations: ${e}`)
throw new Error('Applying migrations failed, your app is now in an inconsistent state. We cannot guarantee safety, it is now your responsibility to reset the database or tell the user to re-install the app')
}
}
import { PrismaClient } from '@prisma/client/react-native'
import '@prisma/react-native'

export const db = new PrismaClient({
log: ['error'],
})

export async function initializeDb() {
try {
db.$applyPendingMigrations()
console.log('migrations complete')
} catch (e) {
console.error(`failed to apply migrations: ${e}`)
throw new Error('Applying migrations failed, your app is now in an inconsistent state. We cannot guarantee safety, it is now your responsibility to reset the database or tell the user to re-install the app')
}
}
the app crashes after calling this function
useEffect(() => {
async function init() {
await initializeDb() // <-
}
init()
}, [])
useEffect(() => {
async function init() {
await initializeDb() // <-
}
init()
}, [])
with the following schema
generator client {
provider = "prisma-client-js"
previewFeatures = ["reactNative", "driverAdapters"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

model User {
id Int @id @default(autoincrement())
username String
}
generator client {
provider = "prisma-client-js"
previewFeatures = ["reactNative", "driverAdapters"]
}

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

model User {
id Int @id @default(autoincrement())
username String
}
11 replies
PPrisma
Created by piscopancer on 11/12/2024 in #help-and-questions
Prisma extension in vscode too slow
vscode: 1.95.2 prisma ext: v5.22.0
10 replies
PPrisma
Created by piscopancer on 6/14/2024 in #help-and-questions
Get type of `create` with `connect`?
db.course.create({
data: {
title: 'New course',
tutor: {
connect: {
id: 1
}
}
}
})
db.course.create({
data: {
title: 'New course',
tutor: {
connect: {
id: 1
}
}
}
})
I would like to get the type for object I pass to create function. How can I do that? I assume I should use internal Prisma utility types, right? The trick here is that tutor is a required property so it must be either created or connected (in my case, connected)
2 replies
DTDrizzle Team
Created by piscopancer on 6/4/2024 in #help
need postgres explanation
do I have to start my own server for my postgres database with user and password and run in alongside my next app to be able to connect to it with
import * as courses from '@/db/schema/courses'
import * as studentsCourses from '@/db/schema/courses-students'
import * as users from '@/db/schema/users'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Client } from 'pg'

const client = new Client({
connectionString: `postgres://user:password@host:port/db`,
})

export const db = drizzle(client, {
schema: {
...users,
...courses,
...studentsCourses,
},
})
import * as courses from '@/db/schema/courses'
import * as studentsCourses from '@/db/schema/courses-students'
import * as users from '@/db/schema/users'
import { drizzle } from 'drizzle-orm/node-postgres'
import { Client } from 'pg'

const client = new Client({
connectionString: `postgres://user:password@host:port/db`,
})

export const db = drizzle(client, {
schema: {
...users,
...courses,
...studentsCourses,
},
})
?
3 replies
DTDrizzle Team
Created by piscopancer on 3/26/2024 in #help
how to replicate **joins** in **db.query**?
this is a db.select query with a join to filter out only answers that are accepted
const queryAcceptedAnswers = (userId: number)=>
db.select()
.from(answersTable)
.where(eq(answersTable.authorId, userId))
.innerJoin(questionsTable, eq(answersTable.id, questionsTable.acceptedAnswerId))
const queryAcceptedAnswers = (userId: number)=>
db.select()
.from(answersTable)
.where(eq(answersTable.authorId, userId))
.innerJoin(questionsTable, eq(answersTable.id, questionsTable.acceptedAnswerId))
let's say, there may be 2 accepted answers, thus this will be the response
"acceptedAnswers": [
{
"answers": {
"id": 8,
"content": "🤡🤡🤡",
"authorId": 109352196,
"questionId": 7,
"createdAt": "2024-03-23T13:14:22.690Z",
"useless": false
},
"questions": {
"id": 7,
"title": "какыфмыфвфывс",
"content": "фывфывыфвывс",
"authorId": 109352196,
"createdAt": "2024-03-22T11:59:37.434Z",
"category": "отношения",
"acceptedAnswerId": 8
}
},
{
"answers": {
"id": 6,
"content": "aaa",
"authorId": 109352196,
"questionId": 8,
"createdAt": "2024-03-23T11:46:38.130Z",
"useless": false
},
"questions": {
"id": 8,
"title": "bruh",
"content": "bruh222",
"authorId": 109352196,
"createdAt": "2024-03-22T11:59:37.992Z",
"category": "отношения",
"acceptedAnswerId": 6
}
}
]
"acceptedAnswers": [
{
"answers": {
"id": 8,
"content": "🤡🤡🤡",
"authorId": 109352196,
"questionId": 7,
"createdAt": "2024-03-23T13:14:22.690Z",
"useless": false
},
"questions": {
"id": 7,
"title": "какыфмыфвфывс",
"content": "фывфывыфвывс",
"authorId": 109352196,
"createdAt": "2024-03-22T11:59:37.434Z",
"category": "отношения",
"acceptedAnswerId": 8
}
},
{
"answers": {
"id": 6,
"content": "aaa",
"authorId": 109352196,
"questionId": 8,
"createdAt": "2024-03-23T11:46:38.130Z",
"useless": false
},
"questions": {
"id": 8,
"title": "bruh",
"content": "bruh222",
"authorId": 109352196,
"createdAt": "2024-03-22T11:59:37.992Z",
"category": "отношения",
"acceptedAnswerId": 6
}
}
]
How do I use joins in db.query api that will result in the same response or will filter out users accepted answers in a similar way? is it even possible with db.query? do i have to manage my relations in the schema?
2 replies
DTDrizzle Team
Created by piscopancer on 3/25/2024 in #help
count() for join tables in query API
Usage I have a user page where you can see how many of their answers were considered correct (a person who asked a question accepted them, like on github). 3 tables are used: * users * questions * answers each answer has a column authorId which refers user.id, each question has acceptedAnswerId which refers answer.id
export function queryUser({ userId }: { userId: number }) {
return db.query.usersTable.findFirst({
where: (t, { eq }) => eq(t.id, userId),
with: {
questions: {
with: {
answers: {
columns: {
id: true,
authorId: true,
},
},
usersLikes: {
columns: {
questionId: true,
userId: true,
},
},
usersViews: {
columns: {
questionId: true,
},
},
},
},
},
extras: (t) => ({
// a number of "answers" (table, see above) whose "authorId" === t.id
// should return an integer 0/1/2/3/4/5/...
acceptedAnswers: count(t.id).as('accepted_answers'),
}),
})
}
export function queryUser({ userId }: { userId: number }) {
return db.query.usersTable.findFirst({
where: (t, { eq }) => eq(t.id, userId),
with: {
questions: {
with: {
answers: {
columns: {
id: true,
authorId: true,
},
},
usersLikes: {
columns: {
questionId: true,
userId: true,
},
},
usersViews: {
columns: {
questionId: true,
},
},
},
},
},
extras: (t) => ({
// a number of "answers" (table, see above) whose "authorId" === t.id
// should return an integer 0/1/2/3/4/5/...
acceptedAnswers: count(t.id).as('accepted_answers'),
}),
})
}
Draw your attention to the extras, what should be written there? I am not quite following
21 replies
DTDrizzle Team
Created by piscopancer on 3/22/2024 in #help
"You're about to add not-null useless column without default value, which contains 1 items"
No description
6 replies
DTDrizzle Team
Created by piscopancer on 3/18/2024 in #help
many-to-many foreign key constraint 787 issue
No description
4 replies
DTDrizzle Team
Created by piscopancer on 3/16/2024 in #help
use `count` in db.query?
export function queryQuestions() {
return db.query.questionsTable.findMany({
limit: 5,
orderBy: ({ createdAt }, { desc }) => desc(createdAt),
with: {
author: true,
answers: {
extras: //
}
},
})
}
export function queryQuestions() {
return db.query.questionsTable.findMany({
limit: 5,
orderBy: ({ createdAt }, { desc }) => desc(createdAt),
with: {
author: true,
answers: {
extras: //
}
},
})
}
I am not fully understanding the API, require support
4 replies
DTDrizzle Team
Created by piscopancer on 3/16/2024 in #help
2 tables cannot reference each others columns?
I have the following tables declaration:
export const questionsTable = sqliteTable('questions', {
// bla bla
acceptedAnswerId: text('accepted_answer_id').references(() => answersTable.id, {onDelete: 'cascade'}), // ERROR HERE
})

export const answersTable = sqliteTable('answers', {
// bla bla
questionId: text('question_id')
.notNull()
.references(() => questionsTable.id, { onDelete: 'cascade' }), // THIS REFERENCE DOES NOT LET ME CREATE A REFERENCE TO answersTable.id IN questionsTable.acceptedAnswerId, LOOK ABOVE
})
export const questionsTable = sqliteTable('questions', {
// bla bla
acceptedAnswerId: text('accepted_answer_id').references(() => answersTable.id, {onDelete: 'cascade'}), // ERROR HERE
})

export const answersTable = sqliteTable('answers', {
// bla bla
questionId: text('question_id')
.notNull()
.references(() => questionsTable.id, { onDelete: 'cascade' }), // THIS REFERENCE DOES NOT LET ME CREATE A REFERENCE TO answersTable.id IN questionsTable.acceptedAnswerId, LOOK ABOVE
})
As you can see, for some reason I CANNOT reference one table's column from the other table, while this table's column is already referenced by the other table. Can you explain why so and what should I do?
12 replies
DTDrizzle Team
Created by piscopancer on 3/11/2024 in #help
I do not understand relations 😟 (many to many, users can follow and have followers)
export const usersTable = sqliteTable('users', {
id: text('id').primaryKey(),
username: text('username'),
})

export const usersRelations = relations(usersTable, ({ many }) => ({
questions: many(questionsTable),
followers: many(usersTable, { relationName: 'followers' }),
following: many(usersTable, { relationName: 'following' }),
}))

export const usersToUsersTable = sqliteTable('users_to_users', {
followedId: text('followed_id')
.notNull()
.references(() => usersTable.id),
followerId: text('follower_id')
.notNull()
.references(() => usersTable.id),
})

export const usersToUsersRelations = relations(usersToUsersTable, ({ one }) => ({
followed: one(usersTable, {
fields: [usersToUsersTable.followedId],
references: [usersTable.id],
relationName: 'followers',
}),
follower: one(usersTable, {
fields: [usersToUsersTable.followerId],
references: [usersTable.id],
relationName: 'following',
}),
}))
export const usersTable = sqliteTable('users', {
id: text('id').primaryKey(),
username: text('username'),
})

export const usersRelations = relations(usersTable, ({ many }) => ({
questions: many(questionsTable),
followers: many(usersTable, { relationName: 'followers' }),
following: many(usersTable, { relationName: 'following' }),
}))

export const usersToUsersTable = sqliteTable('users_to_users', {
followedId: text('followed_id')
.notNull()
.references(() => usersTable.id),
followerId: text('follower_id')
.notNull()
.references(() => usersTable.id),
})

export const usersToUsersRelations = relations(usersToUsersTable, ({ one }) => ({
followed: one(usersTable, {
fields: [usersToUsersTable.followedId],
references: [usersTable.id],
relationName: 'followers',
}),
follower: one(usersTable, {
fields: [usersToUsersTable.followerId],
references: [usersTable.id],
relationName: 'following',
}),
}))
this is the code I tried but I messed up the relations and the error says the following:
throw new Error(
^

Error: There is not enough information to infer relation "__public__.usersTable.followers"
at normalizeRelation (C:\dev\web\next\selowafelnoe\node_modules\drizzle-orm\relations.cjs:261:9)
at C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:73:67
at Array.map (<anonymous>)
at C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:72:42
at Array.map (<anonymous>)
at extractRelations (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:71:51)
at sqliteQueryEngine (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:293:16)
at queryEngineForSetup (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:716:12)
at Command.<anonymous> (C:\dev\web\next\selowafelnoe\node_modules\drizzle-kit\bin.cjs:63755:62)
throw new Error(
^

Error: There is not enough information to infer relation "__public__.usersTable.followers"
at normalizeRelation (C:\dev\web\next\selowafelnoe\node_modules\drizzle-orm\relations.cjs:261:9)
at C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:73:67
at Array.map (<anonymous>)
at C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:72:42
at Array.map (<anonymous>)
at extractRelations (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:71:51)
at sqliteQueryEngine (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:293:16)
at queryEngineForSetup (C:\dev\web\next\selowafelnoe\node_modules\@drizzle-team\studio\index.js:716:12)
at Command.<anonymous> (C:\dev\web\next\selowafelnoe\node_modules\drizzle-kit\bin.cjs:63755:62)
2 replies