Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP transactions, savepoints and connection pooling #16320

Closed
wants to merge 34 commits into from

Conversation

cirospaciari
Copy link
Member

@cirospaciari cirospaciari commented Jan 11, 2025

What does this PR do?

  • Documentation or TypeScript types (it's okay to leave the rest blank in this case)
  • Code changes

Add support for transactions:

BEGIN / COMMIT await sql.begin([options = ''], fn) -> fn()

import { SQL } from "bun:sql";

const sql = new SQL({
  host: "localhost",
  port: 5432,
  user: "ciro",
  password: "bunbunbun",
  database: "bun",
});

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]
})

SAVEPOINT await sql.savepoint([name], fn) -> fn()

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

  const [account] = (await sql.savepoint(sql =>
    sql`
      insert into accounts (
        user_id
      ) values (
        ${ user.user_id }
      )
    `
  ).catch(err => {
    // Account could not be created. ROLLBACK SAVEPOINT is called because we caught the rejection.
  })) || []

  return [user, account]
})
.then(([user, account]) => {
  // great success - COMMIT succeeded
})
.catch(() => {
  // not so good - ROLLBACK was called
})

How did you verify your code works?

@robobun
Copy link

robobun commented Jan 11, 2025

Updated 12:42 PM PT - Jan 13th, 2025

@cirospaciari, your commit 25eeff3 has passed in #9515! 🎉


🧪   try this PR locally:

bunx bun-pr 16320

@cirospaciari cirospaciari changed the title WIP transactions WIP transactions and savepoints Jan 11, 2025
@cirospaciari cirospaciari changed the title WIP transactions and savepoints WIP transactions, savepoints and connection pooling Jan 11, 2025
cirospaciari and others added 25 commits January 10, 2025 16:58
Co-authored-by: Jarred Sumner <[email protected]>
Co-authored-by: Dylan Conway <[email protected]>
Co-authored-by: Michael H <[email protected]>
@cirospaciari cirospaciari deleted the ciro/postgres-transactions branch January 13, 2025 20:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.