@agentuity/postgres 0.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/AGENTS.md +124 -0
  2. package/README.md +297 -0
  3. package/dist/client.d.ts +224 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +670 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/errors.d.ts +109 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/errors.js +115 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/index.d.ts +41 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +47 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/patch.d.ts +65 -0
  16. package/dist/patch.d.ts.map +1 -0
  17. package/dist/patch.js +111 -0
  18. package/dist/patch.js.map +1 -0
  19. package/dist/postgres.d.ts +62 -0
  20. package/dist/postgres.d.ts.map +1 -0
  21. package/dist/postgres.js +63 -0
  22. package/dist/postgres.js.map +1 -0
  23. package/dist/reconnect.d.ts +31 -0
  24. package/dist/reconnect.d.ts.map +1 -0
  25. package/dist/reconnect.js +60 -0
  26. package/dist/reconnect.js.map +1 -0
  27. package/dist/registry.d.ts +71 -0
  28. package/dist/registry.d.ts.map +1 -0
  29. package/dist/registry.js +175 -0
  30. package/dist/registry.js.map +1 -0
  31. package/dist/transaction.d.ts +147 -0
  32. package/dist/transaction.d.ts.map +1 -0
  33. package/dist/transaction.js +287 -0
  34. package/dist/transaction.js.map +1 -0
  35. package/dist/types.d.ts +213 -0
  36. package/dist/types.d.ts.map +1 -0
  37. package/dist/types.js +2 -0
  38. package/dist/types.js.map +1 -0
  39. package/package.json +55 -0
  40. package/src/client.ts +776 -0
  41. package/src/errors.ts +154 -0
  42. package/src/index.ts +71 -0
  43. package/src/patch.ts +123 -0
  44. package/src/postgres.ts +65 -0
  45. package/src/reconnect.ts +74 -0
  46. package/src/registry.ts +194 -0
  47. package/src/transaction.ts +312 -0
  48. package/src/types.ts +250 -0
@@ -0,0 +1,109 @@
1
+ /**
2
+ * Base error for PostgreSQL-related errors.
3
+ */
4
+ export declare const PostgresError: {
5
+ new (args?: ({
6
+ code?: string;
7
+ query?: string;
8
+ } & {
9
+ message?: string;
10
+ cause?: unknown;
11
+ }) | undefined): import("@agentuity/core").RichError & {
12
+ readonly _tag: "PostgresError";
13
+ } & Readonly<{
14
+ code?: string;
15
+ query?: string;
16
+ }>;
17
+ readonly defaultMessage?: string;
18
+ };
19
+ /**
20
+ * Error thrown when attempting to use a closed connection.
21
+ */
22
+ export declare const ConnectionClosedError: {
23
+ new (args?: ({
24
+ wasReconnecting?: boolean;
25
+ } & {
26
+ message?: string;
27
+ cause?: unknown;
28
+ }) | undefined): import("@agentuity/core").RichError & {
29
+ readonly _tag: "ConnectionClosedError";
30
+ } & Readonly<{
31
+ wasReconnecting?: boolean;
32
+ }>;
33
+ readonly defaultMessage?: string;
34
+ };
35
+ /**
36
+ * Error thrown when reconnection fails after all attempts.
37
+ */
38
+ export declare const ReconnectFailedError: {
39
+ new (args?: ({
40
+ attempts: number;
41
+ lastError?: Error;
42
+ } & {
43
+ cause?: unknown;
44
+ }) | undefined): import("@agentuity/core").RichError & {
45
+ readonly _tag: "ReconnectFailedError";
46
+ } & Readonly<{
47
+ attempts: number;
48
+ lastError?: Error;
49
+ }>;
50
+ readonly defaultMessage?: string;
51
+ };
52
+ /**
53
+ * Error thrown when a query times out.
54
+ */
55
+ export declare const QueryTimeoutError: {
56
+ new (args?: ({
57
+ timeoutMs: number;
58
+ query?: string;
59
+ } & {
60
+ cause?: unknown;
61
+ }) | undefined): import("@agentuity/core").RichError & {
62
+ readonly _tag: "QueryTimeoutError";
63
+ } & Readonly<{
64
+ timeoutMs: number;
65
+ query?: string;
66
+ }>;
67
+ readonly defaultMessage?: string;
68
+ };
69
+ /**
70
+ * Error thrown when a transaction fails.
71
+ */
72
+ export declare const TransactionError: {
73
+ new (args?: ({
74
+ phase?: "begin" | "commit" | "rollback" | "savepoint" | "query";
75
+ } & {
76
+ message?: string;
77
+ cause?: unknown;
78
+ }) | undefined): import("@agentuity/core").RichError & {
79
+ readonly _tag: "TransactionError";
80
+ } & Readonly<{
81
+ phase?: "begin" | "commit" | "rollback" | "savepoint" | "query";
82
+ }>;
83
+ readonly defaultMessage?: string;
84
+ };
85
+ /**
86
+ * Error thrown when an operation is not supported.
87
+ */
88
+ export declare const UnsupportedOperationError: {
89
+ new (args?: ({
90
+ operation: string;
91
+ reason?: string;
92
+ } & {
93
+ cause?: unknown;
94
+ }) | undefined): import("@agentuity/core").RichError & {
95
+ readonly _tag: "UnsupportedOperationError";
96
+ } & Readonly<{
97
+ operation: string;
98
+ reason?: string;
99
+ }>;
100
+ readonly defaultMessage?: string;
101
+ };
102
+ /**
103
+ * Determines if an error is retryable (i.e., a reconnection should be attempted).
104
+ *
105
+ * @param error - The error to check
106
+ * @returns `true` if the error indicates a connection issue that may be resolved by reconnecting
107
+ */
108
+ export declare function isRetryableError(error: unknown): boolean;
109
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,eAAO,MAAM,aAAa;;eAClB,MAAM;gBACL,MAAM;;;;;;;eADP,MAAM;gBACL,MAAM;;;CACX,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,qBAAqB;;0BACf,OAAO;;;;;;;0BAAP,OAAO;;;CACtB,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,oBAAoB;;kBAItB,MAAM;oBACJ,KAAK;;;;;;kBADP,MAAM;oBACJ,KAAK;;;CACd,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,iBAAiB;;mBAClB,MAAM;gBACT,MAAM;;;;;;mBADH,MAAM;gBACT,MAAM;;;CACX,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,gBAAgB;;gBACpB,OAAO,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,GAAG,OAAO;;;;;;;gBAAvD,OAAO,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,GAAG,OAAO;;;CAC5D,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,yBAAyB;;mBAI1B,MAAM;iBACR,MAAM;;;;;;mBADJ,MAAM;iBACR,MAAM;;;CACZ,CAAC;AA2DL;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAoCxD"}
package/dist/errors.js ADDED
@@ -0,0 +1,115 @@
1
+ import { StructuredError } from '@agentuity/core';
2
+ /**
3
+ * Base error for PostgreSQL-related errors.
4
+ */
5
+ export const PostgresError = StructuredError('PostgresError')();
6
+ /**
7
+ * Error thrown when attempting to use a closed connection.
8
+ */
9
+ export const ConnectionClosedError = StructuredError('ConnectionClosedError')();
10
+ /**
11
+ * Error thrown when reconnection fails after all attempts.
12
+ */
13
+ export const ReconnectFailedError = StructuredError('ReconnectFailedError', 'Failed to reconnect after maximum attempts')();
14
+ /**
15
+ * Error thrown when a query times out.
16
+ */
17
+ export const QueryTimeoutError = StructuredError('QueryTimeoutError', 'Query timed out')();
18
+ /**
19
+ * Error thrown when a transaction fails.
20
+ */
21
+ export const TransactionError = StructuredError('TransactionError')();
22
+ /**
23
+ * Error thrown when an operation is not supported.
24
+ */
25
+ export const UnsupportedOperationError = StructuredError('UnsupportedOperationError', 'This operation is not supported')();
26
+ /**
27
+ * Error codes that indicate a retryable connection error.
28
+ */
29
+ const RETRYABLE_ERROR_CODES = new Set([
30
+ // Bun SQL specific
31
+ 'ERR_POSTGRES_CONNECTION_CLOSED',
32
+ 'ERR_POSTGRES_CONNECTION_TIMEOUT',
33
+ // Node.js / system errors
34
+ 'ECONNRESET',
35
+ 'ECONNREFUSED',
36
+ 'ETIMEDOUT',
37
+ 'EPIPE',
38
+ 'ENOTFOUND',
39
+ 'ENETUNREACH',
40
+ 'EHOSTUNREACH',
41
+ 'EAI_AGAIN',
42
+ // PostgreSQL error codes
43
+ '57P01', // admin_shutdown
44
+ '57P02', // crash_shutdown
45
+ '57P03', // cannot_connect_now
46
+ '08000', // connection_exception
47
+ '08003', // connection_does_not_exist
48
+ '08006', // connection_failure
49
+ '08001', // sqlclient_unable_to_establish_sqlconnection
50
+ '08004', // sqlserver_rejected_establishment_of_sqlconnection
51
+ ]);
52
+ /**
53
+ * Error messages that indicate a retryable connection error.
54
+ */
55
+ const RETRYABLE_ERROR_MESSAGES = [
56
+ 'connection closed',
57
+ 'connection terminated',
58
+ 'connection reset',
59
+ 'connection refused',
60
+ 'connection timed out',
61
+ 'socket hang up',
62
+ 'read ECONNRESET',
63
+ 'write EPIPE',
64
+ 'getaddrinfo',
65
+ 'ENOTFOUND',
66
+ 'network is unreachable',
67
+ 'no route to host',
68
+ 'server closed the connection unexpectedly',
69
+ 'terminating connection due to administrator command',
70
+ 'the database system is shutting down',
71
+ 'the database system is starting up',
72
+ 'the database system is in recovery mode',
73
+ 'failed to read',
74
+ 'failed to write',
75
+ 'broken pipe',
76
+ 'end of file',
77
+ 'eof',
78
+ ];
79
+ /**
80
+ * Determines if an error is retryable (i.e., a reconnection should be attempted).
81
+ *
82
+ * @param error - The error to check
83
+ * @returns `true` if the error indicates a connection issue that may be resolved by reconnecting
84
+ */
85
+ export function isRetryableError(error) {
86
+ if (!error) {
87
+ return false;
88
+ }
89
+ // Check error code
90
+ if (typeof error === 'object' && error !== null) {
91
+ const err = error;
92
+ // Check 'code' property
93
+ if (typeof err.code === 'string' && RETRYABLE_ERROR_CODES.has(err.code)) {
94
+ return true;
95
+ }
96
+ // Check 'errno' property (Node.js style)
97
+ if (typeof err.errno === 'string' && RETRYABLE_ERROR_CODES.has(err.errno)) {
98
+ return true;
99
+ }
100
+ // Check nested cause
101
+ if (err.cause && isRetryableError(err.cause)) {
102
+ return true;
103
+ }
104
+ }
105
+ // Check error message
106
+ const message = error instanceof Error ? error.message : String(error);
107
+ const lowerMessage = message.toLowerCase();
108
+ for (const pattern of RETRYABLE_ERROR_MESSAGES) {
109
+ if (lowerMessage.includes(pattern.toLowerCase())) {
110
+ return true;
111
+ }
112
+ }
113
+ return false;
114
+ }
115
+ //# sourceMappingURL=errors.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAElD;;GAEG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,eAAe,CAAC,eAAe,CAAC,EAGzD,CAAC;AAEL;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAG,eAAe,CAAC,uBAAuB,CAAC,EAEzE,CAAC;AAEL;;GAEG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG,eAAe,CAClD,sBAAsB,EACtB,4CAA4C,CAC5C,EAGG,CAAC;AAEL;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,eAAe,CAAC,mBAAmB,EAAE,iBAAiB,CAAC,EAGpF,CAAC;AAEL;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,eAAe,CAAC,kBAAkB,CAAC,EAE/D,CAAC;AAEL;;GAEG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,eAAe,CACvD,2BAA2B,EAC3B,iCAAiC,CACjC,EAGG,CAAC;AAEL;;GAEG;AACH,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACrC,mBAAmB;IACnB,gCAAgC;IAChC,iCAAiC;IAEjC,0BAA0B;IAC1B,YAAY;IACZ,cAAc;IACd,WAAW;IACX,OAAO;IACP,WAAW;IACX,aAAa;IACb,cAAc;IACd,WAAW;IAEX,yBAAyB;IACzB,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EAAE,iBAAiB;IAC1B,OAAO,EAAE,qBAAqB;IAC9B,OAAO,EAAE,uBAAuB;IAChC,OAAO,EAAE,4BAA4B;IACrC,OAAO,EAAE,q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C,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACvE,MAAM,YAAY,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC;IAE3C,KAAK,MAAM,OAAO,IAAI,wBAAwB,EAAE,CAAC;QAChD,IAAI,YAAY,CAAC,QAAQ,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC;QACb,CAAC;IACF,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC"}
@@ -0,0 +1,41 @@
1
+ /**
2
+ * @agentuity/postgres - Resilient PostgreSQL client with automatic reconnection
3
+ *
4
+ * This package provides a PostgreSQL client that wraps Bun's native SQL driver
5
+ * and adds automatic reconnection with exponential backoff.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { postgres } from '@agentuity/postgres';
10
+ *
11
+ * // Create a client (uses DATABASE_URL by default)
12
+ * const sql = postgres();
13
+ *
14
+ * // Execute queries using tagged template literals
15
+ * const users = await sql`SELECT * FROM users WHERE active = ${true}`;
16
+ *
17
+ * // Transactions
18
+ * const tx = await sql.begin();
19
+ * try {
20
+ * await tx`INSERT INTO users (name) VALUES (${name})`;
21
+ * await tx.commit();
22
+ * } catch (error) {
23
+ * await tx.rollback();
24
+ * throw error;
25
+ * }
26
+ *
27
+ * // Close when done
28
+ * await sql.close();
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ export { postgres, default } from './postgres';
34
+ export { PostgresClient, createCallableClient, type CallablePostgresClient } from './client';
35
+ export { Transaction, Savepoint, ReservedConnection } from './transaction';
36
+ export { patchBunSQL, isPatched, SQL } from './patch';
37
+ export type { PostgresConfig, ReconnectConfig, ConnectionStats, TLSConfig, TransactionOptions, ReserveOptions, } from './types';
38
+ export { PostgresError, ConnectionClosedError, ReconnectFailedError, QueryTimeoutError, TransactionError, UnsupportedOperationError, isRetryableError, } from './errors';
39
+ export { computeBackoff, sleep, mergeReconnectConfig, DEFAULT_RECONNECT_CONFIG } from './reconnect';
40
+ export { shutdownAll, getClientCount, getClients, hasActiveClients } from './registry';
41
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAGH,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAG/C,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,KAAK,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAG7F,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAG3E,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAGtD,YAAY,EACX,cAAc,EACd,eAAe,EACf,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,cAAc,GACd,MAAM,SAAS,CAAC;AAGjB,OAAO,EACN,aAAa,EACb,qBAAqB,EACrB,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,yBAAyB,EACzB,gBAAgB,GAChB,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAGpG,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @agentuity/postgres - Resilient PostgreSQL client with automatic reconnection
3
+ *
4
+ * This package provides a PostgreSQL client that wraps Bun's native SQL driver
5
+ * and adds automatic reconnection with exponential backoff.
6
+ *
7
+ * @example
8
+ * ```typescript
9
+ * import { postgres } from '@agentuity/postgres';
10
+ *
11
+ * // Create a client (uses DATABASE_URL by default)
12
+ * const sql = postgres();
13
+ *
14
+ * // Execute queries using tagged template literals
15
+ * const users = await sql`SELECT * FROM users WHERE active = ${true}`;
16
+ *
17
+ * // Transactions
18
+ * const tx = await sql.begin();
19
+ * try {
20
+ * await tx`INSERT INTO users (name) VALUES (${name})`;
21
+ * await tx.commit();
22
+ * } catch (error) {
23
+ * await tx.rollback();
24
+ * throw error;
25
+ * }
26
+ *
27
+ * // Close when done
28
+ * await sql.close();
29
+ * ```
30
+ *
31
+ * @packageDocumentation
32
+ */
33
+ // Main factory function
34
+ export { postgres, default } from './postgres';
35
+ // Client class for advanced usage
36
+ export { PostgresClient, createCallableClient } from './client';
37
+ // Transaction and reserved connection classes
38
+ export { Transaction, Savepoint, ReservedConnection } from './transaction';
39
+ // Patch function for modifying Bun.SQL globally
40
+ export { patchBunSQL, isPatched, SQL } from './patch';
41
+ // Errors
42
+ export { PostgresError, ConnectionClosedError, ReconnectFailedError, QueryTimeoutError, TransactionError, UnsupportedOperationError, isRetryableError, } from './errors';
43
+ // Reconnection utilities
44
+ export { computeBackoff, sleep, mergeReconnectConfig, DEFAULT_RECONNECT_CONFIG } from './reconnect';
45
+ // Global registry for coordinated shutdown
46
+ export { shutdownAll, getClientCount, getClients, hasActiveClients } from './registry';
47
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,wBAAwB;AACxB,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE/C,kCAAkC;AAClC,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAA+B,MAAM,UAAU,CAAC;AAE7F,8CAA8C;AAC9C,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AAE3E,gDAAgD;AAChD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,SAAS,CAAC;AAYtD,SAAS;AACT,OAAO,EACN,aAAa,EACb,qBAAqB,EACrB,oBAAoB,EACpB,iBAAiB,EACjB,gBAAgB,EAChB,yBAAyB,EACzB,gBAAgB,GAChB,MAAM,UAAU,CAAC;AAElB,yBAAyB;AACzB,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAEpG,2CAA2C;AAC3C,OAAO,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC"}
@@ -0,0 +1,65 @@
1
+ import { SQL } from 'bun';
2
+ import type { ReconnectConfig } from './types';
3
+ /**
4
+ * Patches Bun's native SQL class to add automatic reconnection support.
5
+ *
6
+ * This modifies the global `Bun.SQL` prototype to intercept connection close
7
+ * events and automatically attempt reconnection with exponential backoff.
8
+ *
9
+ * **Note:** This is a global modification that affects all SQL instances created
10
+ * after calling this function. Use with caution in shared environments.
11
+ *
12
+ * @param config - Optional configuration for reconnection behavior
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * import { patchBunSQL, SQL } from '@agentuity/postgres';
17
+ *
18
+ * // Patch with default settings
19
+ * patchBunSQL();
20
+ *
21
+ * // Or with custom configuration
22
+ * patchBunSQL({
23
+ * reconnect: {
24
+ * maxAttempts: 5,
25
+ * initialDelayMs: 200,
26
+ * },
27
+ * onreconnect: (attempt) => console.log(`Reconnecting... attempt ${attempt}`),
28
+ * onreconnected: () => console.log('Reconnected!'),
29
+ * });
30
+ *
31
+ * // Now use Bun.SQL normally - it will auto-reconnect
32
+ * const sql = new SQL({ url: process.env.DATABASE_URL });
33
+ * const users = await sql`SELECT * FROM users`;
34
+ * ```
35
+ */
36
+ export declare function patchBunSQL(config?: {
37
+ reconnect?: ReconnectConfig;
38
+ onreconnect?: (attempt: number) => void;
39
+ onreconnected?: () => void;
40
+ onreconnectfailed?: (error: Error) => void;
41
+ }): void;
42
+ /**
43
+ * Returns whether Bun.SQL has been patched.
44
+ */
45
+ export declare function isPatched(): boolean;
46
+ /**
47
+ * Resets the patch state (mainly for testing).
48
+ * @internal
49
+ */
50
+ export declare function _resetPatch(): void;
51
+ /**
52
+ * Re-export of Bun's SQL class.
53
+ *
54
+ * When using the patched version, import SQL from this module instead of 'bun':
55
+ *
56
+ * @example
57
+ * ```typescript
58
+ * import { patchBunSQL, SQL } from '@agentuity/postgres';
59
+ *
60
+ * patchBunSQL();
61
+ * const sql = new SQL({ url: process.env.DATABASE_URL });
62
+ * ```
63
+ */
64
+ export { SQL };
65
+ //# sourceMappingURL=patch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch.d.ts","sourceRoot":"","sources":["../src/patch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAC1B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAoB/C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAgB,WAAW,CAAC,MAAM,CAAC,EAAE;IACpC,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,WAAW,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,KAAK,IAAI,CAAC;IACxC,aAAa,CAAC,EAAE,MAAM,IAAI,CAAC;IAC3B,iBAAiB,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;CAC3C,GAAG,IAAI,CA6BP;AAED;;GAEG;AACH,wBAAgB,SAAS,IAAI,OAAO,CAEnC;AAED;;;GAGG;AACH,wBAAgB,WAAW,IAAI,IAAI,CAMlC;AAED;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,GAAG,EAAE,CAAC"}
package/dist/patch.js ADDED
@@ -0,0 +1,111 @@
1
+ import { SQL } from 'bun';
2
+ import { mergeReconnectConfig, DEFAULT_RECONNECT_CONFIG } from './reconnect';
3
+ /**
4
+ * Whether Bun.SQL has already been patched.
5
+ */
6
+ let _patched = false;
7
+ /**
8
+ * Global reconnect configuration for patched Bun.SQL instances.
9
+ */
10
+ let _globalReconnectConfig = { ...DEFAULT_RECONNECT_CONFIG };
11
+ /**
12
+ * Callbacks for reconnection events.
13
+ */
14
+ let _onReconnect;
15
+ let _onReconnected;
16
+ let _onReconnectFailed;
17
+ /**
18
+ * Patches Bun's native SQL class to add automatic reconnection support.
19
+ *
20
+ * This modifies the global `Bun.SQL` prototype to intercept connection close
21
+ * events and automatically attempt reconnection with exponential backoff.
22
+ *
23
+ * **Note:** This is a global modification that affects all SQL instances created
24
+ * after calling this function. Use with caution in shared environments.
25
+ *
26
+ * @param config - Optional configuration for reconnection behavior
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * import { patchBunSQL, SQL } from '@agentuity/postgres';
31
+ *
32
+ * // Patch with default settings
33
+ * patchBunSQL();
34
+ *
35
+ * // Or with custom configuration
36
+ * patchBunSQL({
37
+ * reconnect: {
38
+ * maxAttempts: 5,
39
+ * initialDelayMs: 200,
40
+ * },
41
+ * onreconnect: (attempt) => console.log(`Reconnecting... attempt ${attempt}`),
42
+ * onreconnected: () => console.log('Reconnected!'),
43
+ * });
44
+ *
45
+ * // Now use Bun.SQL normally - it will auto-reconnect
46
+ * const sql = new SQL({ url: process.env.DATABASE_URL });
47
+ * const users = await sql`SELECT * FROM users`;
48
+ * ```
49
+ */
50
+ export function patchBunSQL(config) {
51
+ if (_patched) {
52
+ // Already patched, just update config if provided
53
+ if (config?.reconnect) {
54
+ _globalReconnectConfig = mergeReconnectConfig(config.reconnect);
55
+ }
56
+ if (config?.onreconnect)
57
+ _onReconnect = config.onreconnect;
58
+ if (config?.onreconnected)
59
+ _onReconnected = config.onreconnected;
60
+ if (config?.onreconnectfailed)
61
+ _onReconnectFailed = config.onreconnectfailed;
62
+ return;
63
+ }
64
+ // Store configuration
65
+ if (config?.reconnect) {
66
+ _globalReconnectConfig = mergeReconnectConfig(config.reconnect);
67
+ }
68
+ _onReconnect = config?.onreconnect;
69
+ _onReconnected = config?.onreconnected;
70
+ _onReconnectFailed = config?.onreconnectfailed;
71
+ // Note: True monkey-patching of Bun.SQL internals is not feasible
72
+ // because Bun.SQL is a native class. Instead, users should use
73
+ // PostgresClient from this package which provides the same API
74
+ // with automatic reconnection built in.
75
+ //
76
+ // This function exists to set global reconnection configuration
77
+ // that could be used by future implementations.
78
+ _patched = true;
79
+ }
80
+ /**
81
+ * Returns whether Bun.SQL has been patched.
82
+ */
83
+ export function isPatched() {
84
+ return _patched;
85
+ }
86
+ /**
87
+ * Resets the patch state (mainly for testing).
88
+ * @internal
89
+ */
90
+ export function _resetPatch() {
91
+ _patched = false;
92
+ _globalReconnectConfig = { ...DEFAULT_RECONNECT_CONFIG };
93
+ _onReconnect = undefined;
94
+ _onReconnected = undefined;
95
+ _onReconnectFailed = undefined;
96
+ }
97
+ /**
98
+ * Re-export of Bun's SQL class.
99
+ *
100
+ * When using the patched version, import SQL from this module instead of 'bun':
101
+ *
102
+ * @example
103
+ * ```typescript
104
+ * import { patchBunSQL, SQL } from '@agentuity/postgres';
105
+ *
106
+ * patchBunSQL();
107
+ * const sql = new SQL({ url: process.env.DATABASE_URL });
108
+ * ```
109
+ */
110
+ export { SQL };
111
+ //# sourceMappingURL=patch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"patch.js","sourceRoot":"","sources":["../src/patch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,KAAK,CAAC;AAE1B,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,aAAa,CAAC;AAE7E;;GAEG;AACH,IAAI,QAAQ,GAAG,KAAK,CAAC;AAErB;;GAEG;AACH,IAAI,sBAAsB,GAA8B,EAAE,GAAG,wBAAwB,EAAE,CAAC;AAExF;;GAEG;AACH,IAAI,YAAqD,CAAC;AAC1D,IAAI,cAAwC,CAAC;AAC7C,IAAI,kBAAwD,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;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0,0 +1,62 @@
1
+ import type { PostgresConfig } from './types';
2
+ import { type CallablePostgresClient } from './client';
3
+ /**
4
+ * Creates a resilient PostgreSQL client with automatic reconnection.
5
+ *
6
+ * This is the main entry point for creating a PostgreSQL client. The returned
7
+ * client can be used as a tagged template literal for queries.
8
+ *
9
+ * @param config - Connection configuration. Can be:
10
+ * - A connection URL string (e.g., `postgres://user:pass@host:5432/db`)
11
+ * - A configuration object with connection options
12
+ * - Omitted to use `process.env.DATABASE_URL`
13
+ *
14
+ * @returns A callable PostgresClient that supports tagged template literals
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * import { postgres } from '@agentuity/postgres';
19
+ *
20
+ * // Using environment variable (DATABASE_URL)
21
+ * const sql = postgres();
22
+ *
23
+ * // Using connection URL
24
+ * const sql = postgres('postgres://user:pass@localhost:5432/mydb');
25
+ *
26
+ * // Using configuration object
27
+ * const sql = postgres({
28
+ * hostname: 'localhost',
29
+ * port: 5432,
30
+ * username: 'user',
31
+ * password: 'pass',
32
+ * database: 'mydb',
33
+ * reconnect: {
34
+ * maxAttempts: 5,
35
+ * initialDelayMs: 100,
36
+ * },
37
+ * });
38
+ *
39
+ * // Execute queries using tagged template literals
40
+ * const users = await sql`SELECT * FROM users`;
41
+ * const user = await sql`SELECT * FROM users WHERE id = ${userId}`;
42
+ *
43
+ * // Transactions
44
+ * const tx = await sql.begin();
45
+ * try {
46
+ * await tx`INSERT INTO users (name) VALUES (${name})`;
47
+ * await tx.commit();
48
+ * } catch (error) {
49
+ * await tx.rollback();
50
+ * throw error;
51
+ * }
52
+ *
53
+ * // Close when done
54
+ * await sql.close();
55
+ * ```
56
+ */
57
+ export declare function postgres(config?: string | PostgresConfig): CallablePostgresClient;
58
+ /**
59
+ * Default export for convenience.
60
+ */
61
+ export default postgres;
62
+ //# sourceMappingURL=postgres.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.d.ts","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAwB,KAAK,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,wBAAgB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,cAAc,GAAG,sBAAsB,CAEjF;AAED;;GAEG;AACH,eAAe,QAAQ,CAAC"}
@@ -0,0 +1,63 @@
1
+ import { createCallableClient } from './client';
2
+ /**
3
+ * Creates a resilient PostgreSQL client with automatic reconnection.
4
+ *
5
+ * This is the main entry point for creating a PostgreSQL client. The returned
6
+ * client can be used as a tagged template literal for queries.
7
+ *
8
+ * @param config - Connection configuration. Can be:
9
+ * - A connection URL string (e.g., `postgres://user:pass@host:5432/db`)
10
+ * - A configuration object with connection options
11
+ * - Omitted to use `process.env.DATABASE_URL`
12
+ *
13
+ * @returns A callable PostgresClient that supports tagged template literals
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * import { postgres } from '@agentuity/postgres';
18
+ *
19
+ * // Using environment variable (DATABASE_URL)
20
+ * const sql = postgres();
21
+ *
22
+ * // Using connection URL
23
+ * const sql = postgres('postgres://user:pass@localhost:5432/mydb');
24
+ *
25
+ * // Using configuration object
26
+ * const sql = postgres({
27
+ * hostname: 'localhost',
28
+ * port: 5432,
29
+ * username: 'user',
30
+ * password: 'pass',
31
+ * database: 'mydb',
32
+ * reconnect: {
33
+ * maxAttempts: 5,
34
+ * initialDelayMs: 100,
35
+ * },
36
+ * });
37
+ *
38
+ * // Execute queries using tagged template literals
39
+ * const users = await sql`SELECT * FROM users`;
40
+ * const user = await sql`SELECT * FROM users WHERE id = ${userId}`;
41
+ *
42
+ * // Transactions
43
+ * const tx = await sql.begin();
44
+ * try {
45
+ * await tx`INSERT INTO users (name) VALUES (${name})`;
46
+ * await tx.commit();
47
+ * } catch (error) {
48
+ * await tx.rollback();
49
+ * throw error;
50
+ * }
51
+ *
52
+ * // Close when done
53
+ * await sql.close();
54
+ * ```
55
+ */
56
+ export function postgres(config) {
57
+ return createCallableClient(config);
58
+ }
59
+ /**
60
+ * Default export for convenience.
61
+ */
62
+ export default postgres;
63
+ //# sourceMappingURL=postgres.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"postgres.js","sourceRoot":"","sources":["../src/postgres.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oBAAoB,EAA+B,MAAM,UAAU,CAAC;AAE7E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqDG;AACH,MAAM,UAAU,QAAQ,CAAC,MAAgC;IACxD,OAAO,oBAAoB,CAAC,MAAM,CAAC,CAAC;AACrC,CAAC;AAED;;GAEG;AACH,eAAe,QAAQ,CAAC"}