Bulk insert from array of objects in sqlite using prisma

48 Views Asked by At

Inserting a list of pokemons:Pokemon[] into sqlite using prisma. This is the type Pokemon which i pass to main() function.

type Pokemon = {
  abilities: Ability[];
  id: string;
  name: string;
  height: number;
  weight: number;
  types: Type[];
  stats: Stat[];
};

type Ability = {
  name: string;
  is_hidden: boolean;
};

also this is main():

import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();

export default async function main(pokemons: Pokemon[]) {

  const pokemonsData = pokemons.map((pokemon) => {
    return {
      id: Number(pokemon.id),
      name: pokemon.name,
      height: pokemon.height,
      weight: pokemon.weight,
    };
  });

  const insertPokemonsData = [];
  for (const data of pokemonsData) {
    insertPokemonsData.push(prisma.pokemon.create({ data }));
  }
  await prisma.$transaction(insertPokemonsData);

  pokemons.map(async (pokemon) => {
    const abilitiesData = pokemon.abilities.map((ability) => {
      return {
        name: ability.name,
        is_hidden: ability.is_hidden,
        pokemonId: pokemon.id,
      };
    });

    const insertsAbilitiesData = [];
    for (const data of abilitiesData) {
      insertsAbilitiesData.push(prisma.ability.create({ data }));
    }
    await prisma.$transaction(insertsAbilitiesData);
  });
}

first I insert all pokemons and then for each pokemon, their abilities is inserted, but not all abilities are inserted and each time the code is executed, different number of rows is inserted inside Abilities table.

prisma schema :

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

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

model Pokemon {
  id Int @id
  name String
  height Int
  weight Int
  abilities Ability[]
  
}

model Ability {
  id Int @id @default(autoincrement())
  name String
  is_hidden Boolean
  pokemon Pokemon @relation(fields: [pokemonId], references: [id])
  pokemonId Int
}


prisma gives me this error **internal error: entered unreachable code

This is a non-recoverable error which probably happens when the Prisma Query Engine has a panic.**

I have an array of pokemons and each pokemon has an array of abilities so I created two table one for pokemons and the other one for abilities and the relationshiop is one to many. I was expecting that all the abilities would be inserted but it did not.

0

There are 0 best solutions below