-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransaction.ts
More file actions
147 lines (133 loc) · 3.78 KB
/
transaction.ts
File metadata and controls
147 lines (133 loc) · 3.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import type postgres from "postgres";
import {
SqlConnectionError,
type SqlQueryOptions,
type SqlQueryResult,
SqlQueryResultErrorImpl,
SqlQueryResultFailureImpl,
SqlQueryResultSuccessImpl,
type SqlTransaction,
} from "@probitas/client-sql";
import { mapPostgresError } from "./errors.ts";
/**
* PostgreSQL transaction implementation.
*
* Wraps a postgres.js reserved connection to provide transaction semantics.
*/
export class PostgresTransaction implements SqlTransaction {
readonly #sql: postgres.ReservedSql;
#committed = false;
#rolledBack = false;
/**
* Creates a new PostgresTransaction.
*
* @param sql - Reserved SQL connection from postgres.js
*/
constructor(sql: postgres.ReservedSql) {
this.#sql = sql;
}
/**
* Checks if the transaction is still active.
*/
#assertActive(): void {
if (this.#committed) {
throw new Error("Transaction has already been committed");
}
if (this.#rolledBack) {
throw new Error("Transaction has already been rolled back");
}
}
/**
* Execute a query within the transaction.
*
* @param sql - SQL query string
* @param params - Optional query parameters
* @param options - Optional query options
*/
// deno-lint-ignore no-explicit-any
async query<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<SqlQueryResult<T>> {
// Determine whether to throw on error (default false for transactions)
const shouldThrow = options?.throwOnError ?? false;
this.#assertActive();
const startTime = performance.now();
try {
const result = await this.#sql.unsafe<T[]>(sql, params as never[]);
const duration = performance.now() - startTime;
return new SqlQueryResultSuccessImpl<T>({
rows: result as unknown as readonly T[],
rowCount: result.count ?? result.length,
duration,
});
} catch (error) {
const duration = performance.now() - startTime;
const sqlError = mapPostgresError(
error as { message: string; code?: string },
);
// Throw error if required
if (shouldThrow) {
throw sqlError;
}
// Return Failure for connection errors, Error for query errors
if (sqlError instanceof SqlConnectionError) {
return new SqlQueryResultFailureImpl<T>(sqlError, duration);
}
return new SqlQueryResultErrorImpl<T>(sqlError, duration);
}
}
/**
* Execute a query and return the first row or undefined.
*
* @param sql - SQL query string
* @param params - Optional query parameters
* @param options - Optional query options
*/
// deno-lint-ignore no-explicit-any
async queryOne<T = Record<string, any>>(
sql: string,
params?: unknown[],
options?: SqlQueryOptions,
): Promise<T | undefined> {
// queryOne always throws on error for convenience
const result = await this.query<T>(sql, params, {
...options,
throwOnError: true,
});
// result.ok is guaranteed to be true here due to throwOnError: true
if (!result.ok) {
throw result.error;
}
return result.rows[0];
}
/**
* Commit the transaction.
*/
async commit(): Promise<void> {
this.#assertActive();
try {
await this.#sql.unsafe("COMMIT");
this.#committed = true;
} catch (error) {
throw mapPostgresError(error as { message: string; code?: string });
} finally {
this.#sql.release();
}
}
/**
* Rollback the transaction.
*/
async rollback(): Promise<void> {
this.#assertActive();
try {
await this.#sql.unsafe("ROLLBACK");
this.#rolledBack = true;
} catch (error) {
throw mapPostgresError(error as { message: string; code?: string });
} finally {
this.#sql.release();
}
}
}