porsager / porsager/postgres

arbitrary UNSAFE_TRANSACTION errors when using sql.begin

Open
#823 3 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
JavaScript
Stars
8.7k
Forks
374
Avg merge
11d 16h
Merged PRs (30d)
1

Description

The following query arbitrary causes an UNSAVE_TRANSACTION error.

await this.sql.begin(async (tsql) => {
  await tsql`DELETE
            FROM mapping_table
            WHERE a_id = ${aId}`;
  if (items.length === 0) {
    return;
  }
  await tsql`INSERT INTO mapping_table ${
    // eslint-disable-next-line @ts-safeql/check-sql
    tsql(items, 'a_id', 'b_id')
  }`;
});

the error most likely happens when this code is executed very frequently and items is usually an array betwenn 0 and a few thousand items.

error:

Error: UNSAFE_TRANSACTION: Only use sql.begin, sql.reserved or max: 1
    at CommandComplete (/Users/juhwon/Projects/xx/xx/node_modules/postgres/cjs/src/connection.js:580:29)
    at handle (/Users/juhwon/Projects/xx/xx/node_modules/postgres/cjs/src/connection.js:476:6)
    at Socket.data (/Users/juhwon/Projects/xx/xx/node_modules/postgres/cjs/src/connection.js:315:9)
    at Socket.emit (node:events:514:28)
    at addChunk (node:internal/streams/readable:376:12)
    at readableAddChunk (node:internal/streams/readable:349:9)
    at Socket.Readable.push (node:internal/streams/readable:286:10)
    at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
    at TCP.callbackTrampoline (node:internal/async_hooks:130:17)

to my understanding using sql.begin for something like this should be fine. have we found a bug here or is there something wrong with our code?

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the sql.begin entry point and reproduce the supplied DELETE and conditional INSERT under frequent concurrent calls. Inspect the transaction handling around the UNSAFE_TRANSACTION guard and compare it with the connection.js stack trace. Done means establishing whether this is a client bug or caller misuse, with the behavior covered by a reliable regression test if it is a bug.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, nodejs, postgresql
Domain
backend, databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.