prismaのcreateManyでは200レコードまでしか登録できない

prismaのcreateManyを使って約1000件のデータを保存したかったのですが、データベースには200件までしか登録されませんでした。

目次

問題

prismaのcreateManyに1000件のデータを突っ込んで保存。

const data = await fetch(url);
const items: itemType[] = await data.json(); // 約1000件のデータ

await prisma.auction.createMany({
  data: items.map((item) => ({
    name: item.name,
    price: item.price,
  })),
  skipDuplicates: true,
});

1000件のデータを突っ込んでいるけど、この方法では200件までしか保存されません。

prisma側での制限はないようですが、使っているデータベースのパラメータ制限によるものです。

解決方法

データを100件ごとの配列を作って、トランザクションを使って保存。

const arrayChunk = <T>([...array], size: number = 1): T[][] => {
  return array.reduce(
    (acc, value, index) =>
      index % size ? acc : [...acc, array.slice(index, index + size)],
    []
  );
};

const data = await fetch(url);
const items: itemType[] = await data.json();
const chunkedItems: itemType[][] = arrayChunk(items, 100);

for (let i = 0; j < chunkedItems.length; i++) {
  await tx.auction.createMany({
    data: chunkedItems[i].map((item) => ({
      name: item.name,
      price: item.price,
    })),
  });
}

おわりに

この方法を組み合わせても良さそう

const newPosts = [
  { id: 1, title: 'Join the Prisma Slack on https://slack.prisma.io' },
  { id: 2, title: 'Follow Prisma on Twitter' },
];

// create
const createManyPosts = newPosts.map((post) =>
  photon.posts.create({
    data: post,
  }),
);

Promise.all(createManyPosts);

// upsert
const upsertManyPosts = newPosts.map((post) =>
  photon.posts.upsert({
    where: { id: post.id },
    create: post,
    update: post,
  }),
);

Promise.all(upsertManyPosts);

参考

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

コメント

コメントする


The reCAPTCHA verification period has expired. Please reload the page.

目次