Next.js Discord

Discord Forum

Postgres Multiple Inserts

Unanswered
Selkirk Rex posted this in #help-forum
Open in Discord
Selkirk RexOP
I am trying to run a query that performs multiple inserts, around 700 rows at once as single row inserts isn't performant enough due to timeouts.

Below is an example of my code, but it keeps erroring "ERROR: syntax error at or near "$1""

I was looking through the documentation on how to do this within Nextjs -- But I can't seem to find anything.

static async createMany(data: Omit<Item, "id">[]): Promise<Item[]> {
    const insert = data.map(item => {
      return {...item, id: cuid()} as Item
    });

    const values = insert.map((item) => {
      return `(${item.id}, ${item.refrenced_id}, ${item.timestamp}, ${item.some_value}, ${item.some_other_value})`
    });

    await sql`INSERT INTO table(id, refrenced_id, timestamp, some_value, some_other_value)
            VALUES(${values.join(',')})`;

    return insert;
  }

1 Reply

Selkirk RexOP
I was able to resolve the issue by removing the need for the sql template literal -- instantiating the Postgres Client directly and calling client.query(). Probably not the recommended way about this, I am open to alternatives?