question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Seeding is possibly not working when nesting tables

See original GitHub issue

Bug description

Spend about an hour trying to seed nested tables. I think it is probably either a) currently broken, or b) can only be done using an extremely counterintuitive pattern.

Here is my code, it is only a small modification of the default seed.ts from the Next.js template:

import { Prisma, PrismaClient, Task } from '@prisma/client'
import faker from 'faker'

const prisma = new PrismaClient()

const NUMBER_OF_USERS = 10
const MAX_POSTS = 10
const MAX_PROFILES = 2
const MAX_TASKS = 10
const MAX_SUBTASKS = 10

const users: Prisma.UserCreateInput[] = Array.from({
  length: NUMBER_OF_USERS,
}).map((_, i) => ({
  email: faker.internet.email(),
  name: faker.name.firstName(),
  posts: {
    createMany: {
      data: Array.from({
        length: faker.datatype.number({ min: 0, max: MAX_POSTS }),
      }).map(() => ({
        content: faker.lorem.paragraphs(),
        title: faker.lorem.words(),
      })),
    },
  },
  profiles: {
    createMany: {
      data: Array.from({
        length: faker.datatype.number({ min: 1, max: MAX_PROFILES }),
      }).map(() => {
        const profile: Prisma.ProfileCreateManyUserInput = {
          bio: faker.lorem.paragraph(),
        }
        return profile
    }),
    },
  },

  tasks: {
    createMany: {
      data: Array.from({
        length: faker.datatype.number({ min: 1, max: MAX_TASKS }),
      }).map(() => {

        const subTasks = {
          createMany: {
            data: Array.from({
              length: faker.datatype.number({ min: 0, max: MAX_SUBTASKS }),
            }).map(() => {
              const subTask: Prisma.SubTaskCreateInput = {
                content: faker.lorem.lines(1),
                isCompleted: false,
              }
              return subTask
            })
          }
        }

        return {
          details: faker.lorem.paragraph(2),
          subTasks
        }
      }),
    }
  }
}))

async function main() {
  await prisma.$transaction(
    users.map((user) =>
      prisma.user.create({
        data: user,
      }),
    ),
  )
}

main().finally(async () => {
  await prisma.$disconnect()
})

And here is the schema:

// how to commit changes to shcema (needed after each change):
// https://nstackoverflow.com/questions/67774292/how-to-fix-prisma-client-getting-undefined-for-custom-model/68682975#68682975 

generator client {
  provider = "prisma-client-js"
  previewFeatures = ["dataProxy"]
}

datasource db {
  provider = "postgres"
  url      = env("DATABASE_URL")
}

model Post {
  postId   Int     @id @default(autoincrement())
  content   String?
  title     String
  authorId Int?
  author    User?   @relation(fields: [authorId], references: [userId])
}

model Profile {
  bio        String?
  profileId Int     @id @default(autoincrement())
  userId    Int
  user       User    @relation(fields: [userId], references: [userId])
}

model User {
  email    String    @unique
  name     String?
  userId  Int       @id @default(autoincrement())
  posts    Post[]
  profiles Profile[]
  tasks Task[]
}

model Task {
  id Int @id @default(autoincrement())
  details String // string as html
  subTasks SubTask[]
  userId Int
  user User @relation(fields: [userId], references: [userId])
}

model SubTask {
  id Int @id @default(autoincrement())
  content String
  isCompleted Boolean
  task Task @relation(fields: [id], references: [id])
}

Issue Analytics

  • State:closed
  • Created a year ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
Devner-tour-guides-collectivecommented, May 31, 2022

wait a sec… This is embarrassing, but it’s looking like there’s something wrong with the schema and that this is not actually a bug. I’ll do some debugging and let you all know, but maybe hold off on trying to replicate this until I know for sure.

0reactions
garrensmithcommented, Jul 1, 2022

I’m going to close this. Please open it again if you have any other issues.

Read more comments on GitHub >

github_iconTop Results From Across the Web

EF 4.3.1 Migrations Seeding not working as expected
Now when I run the migrate command (part of MSBuild script) when the DB does not exist, tables are created and the seeding...
Read more >
Automatic seeding for secondary replicas - Microsoft Learn
Learn about how automatic seeding can initialize secondary replicas as part of an Always On availability group with SQL 2016 and greater.
Read more >
Database seeding in Node.js - Level Up Coding
In this article I'd like to talk about database seeding using Node.js and MySQL: what it is and how to implement it.
Read more >
Migration and seeding instructions using Knex.js! - gists · GitHub
Migrations are a way to make database changes or updates, like creating or dropping tables, as well as updating a table with new...
Read more >
Oklahoma Garden Planning Guide
Vegetable Time to Plant Feet of Row Per Person Days to Harvest Cool Season Time to Plant Feet of Row Per Person Days to...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found