transactions.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. const assert = require('assert')
  2. const Cursor = require('../')
  3. const pg = require('pg')
  4. describe('transactions', () => {
  5. it('can execute multiple statements in a transaction', async () => {
  6. const client = new pg.Client()
  7. await client.connect()
  8. await client.query('begin')
  9. await client.query('CREATE TEMP TABLE foobar(id SERIAL PRIMARY KEY)')
  10. const cursor = client.query(new Cursor('SELECT * FROM foobar'))
  11. const rows = await new Promise((resolve, reject) => {
  12. cursor.read(10, (err, rows) => (err ? reject(err) : resolve(rows)))
  13. })
  14. assert.strictEqual(rows.length, 0)
  15. await client.query('ALTER TABLE foobar ADD COLUMN name TEXT')
  16. await client.end()
  17. })
  18. it('can execute multiple statements in a transaction if ending cursor early', async () => {
  19. const client = new pg.Client()
  20. await client.connect()
  21. await client.query('begin')
  22. await client.query('CREATE TEMP TABLE foobar(id SERIAL PRIMARY KEY)')
  23. const cursor = client.query(new Cursor('SELECT * FROM foobar'))
  24. await new Promise((resolve) => cursor.close(resolve))
  25. await client.query('ALTER TABLE foobar ADD COLUMN name TEXT')
  26. await client.end()
  27. })
  28. it('can execute multiple statements in a transaction if no data', async () => {
  29. const client = new pg.Client()
  30. await client.connect()
  31. await client.query('begin')
  32. // create a cursor that has no data response
  33. const createText = 'CREATE TEMP TABLE foobar(id SERIAL PRIMARY KEY)'
  34. const cursor = client.query(new Cursor(createText))
  35. const err = await new Promise((resolve) => cursor.read(100, resolve))
  36. assert.ifError(err)
  37. await client.query('ALTER TABLE foobar ADD COLUMN name TEXT')
  38. await client.end()
  39. })
  40. })