porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.32k stars 265 forks source link

Transactions example in the README.md doesn't work as expected #649

Closed MarisaCodes closed 1 year ago

MarisaCodes commented 1 year ago

Transactions section in README

const [user, account] = await sql.begin(async sql => {
  const [user] = await sql`
    insert into users (
      name
    ) values (
      'Murray'
    )
  `

  const [account] = await sql`
    insert into accounts (
      user_id
    ) values (
      ${ user.user_id }
    )
  `

  return [user, account]
})

The above example is a bit confusing for someone who is new to postgres.js but I also believe that it does not work as intended. From tests I have done, the return value of an INSERT query using the sql`insert into table ...` function is an empty array (output straight from my terminal): Result(0) [].

(Here I attach a screenshot of my output)

image

I think the best way to remedy this is to use RETURNING in the INSERT query in function.

const [user, account] = await sql.begin(async sql => {
  const [user] = await sql`
    insert into users (
      name
    ) values (
      'Murray'
    )
returning *
 `

  const [account] = await sql`
    insert into accounts (
      user_id
    ) values (
      ${ user.user_id }
    )
returning *
 `

  return [user, account]
})

More info on RETURNING

This is a minor modification but debugging this has taken a couple of hours for me as I am slightly new to SQL syntax and to postgreSQL in general. I was trying to use the empty return from sql.begin but it turned out that the callback in sql.begin was the one returning the empty array even though the insert was successful.

I would love if this could be added to help new people who are probably going to check the readme for documentation. If it is needed may I submit a pull request too?

porsager commented 1 year ago

Very nice description, and you are absolutely right! It's very confusing that it's coded as if there would be a resulting user from the insert when the returning clause is missing ! Sorry that got you sidetracked, a PR is very much welcome.