diff --git a/README.md b/README.md index 08dd512..550fe9a 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ PostgreSQL client for Deno * [x] client * [x] pool * [ ] ssl -* [ ] transactions +* [x] transactions ## Useage diff --git a/connection.ts b/connection.ts index eec61b8..a8336ea 100644 --- a/connection.ts +++ b/connection.ts @@ -128,6 +128,7 @@ export default class Connection { } async query(sql: string): Promise { + this.activeQuery = new Query(); const encodedSql = this.encoder.encode(sql); const sqlLen = encodedSql.byteLength; const size = 1 + 4 + sqlLen + 1; // Byte1('Q') + Int32 + String + 1(null terminator) diff --git a/query.ts b/query.ts index bd3536b..eecfc13 100644 --- a/query.ts +++ b/query.ts @@ -23,7 +23,6 @@ export default class Query { const parser = parsers.get(dataTypeID); const val = msg.fields[i]; row[name] = parser ? parser(val) : val; - row[name] = val; } this.rows.push(row); diff --git a/test/transaction.test.ts b/test/transaction.test.ts new file mode 100644 index 0000000..9a0618f --- /dev/null +++ b/test/transaction.test.ts @@ -0,0 +1,65 @@ +import { Pool } from "../mod.ts"; +import { + assert, + assertEquals, + assertThrowsAsync, +} from "https://deno.land/std/testing/asserts.ts"; + +const decoder = new TextDecoder(); +const { test } = Deno; + +const pool = new Pool({ + password: "esri@123", +}); + +test("transaction should ok", async () => { + // prepare data + const { rowCount, rows } = await pool.query( + `INSERT INTO users(id, name) VALUES(1, 'zfx') RETURNING id`, + ); + assert(rowCount === 1); + assert(rows.length === 1); + assert(rows[0].id === 1); + + const client = await pool.connect(); + + try { + // rollback + await client.query("BEGIN"); + const del = await client.query("DELETE FROM users WHERE id=1"); + assert(del.command === "DELETE"); + assert(del.rowCount === 1); + const { rows } = await client.query("SELECT * FROM users"); + assert(rows.length === 0); + await client.query("ROLLBACK"); + const res = await client.query("SELECT * FROM users"); + assert(res.rows.length === 1); + assert(res.rows[0].id === 1); + assert(res.rows[0].name === "zfx"); + + // commit + try { + await client.query("BEGIN"); + const { rows } = await client.query( + `INSERT INTO users(id, name) VALUES(2, 'zfx2') RETURNING id`, + ); + assert(rows.length === 1); + assert(rows[0].id === 2); + await client.query("COMMIT"); + const res = await client.query("SELECT * FROM users"); + assert(res.rows.length === 2); + } catch (e) { + await client.query("ROLLBACK"); + throw e; + } + } catch (error) { + console.debug(error); + assert(false); + } finally { + // clean + client.release(); + const res = await pool.query("DELETE FROM users WHERE id in(1, 2)"); + assert(res.rowCount === 2); + await pool.end(); + } +});