-
Notifications
You must be signed in to change notification settings - Fork 97
/
pool.ts
216 lines (199 loc) · 6.31 KB
/
pool.ts
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { PoolClient } from "./client.ts";
import {
type ClientConfiguration,
type ClientOptions,
type ConnectionString,
createParams,
} from "./connection/connection_params.ts";
import { DeferredAccessStack } from "./utils/deferred.ts";
/**
* Connection pools are a powerful resource to execute parallel queries and
* save up time in connection initialization. It is highly recommended that all
* applications that require concurrent access use a pool to communicate
* with their PostgreSQL database
*
* ```ts
* import { Pool } from "https://deno.land/x/postgres/mod.ts";
* const pool = new Pool({
* database: "database",
* hostname: "hostname",
* password: "password",
* port: 5432,
* user: "user",
* }, 10); // Creates a pool with 10 available connections
*
* const client = await pool.connect();
* await client.queryArray`SELECT 1`;
* client.release();
* ```
*
* You can also opt to not initialize all your connections at once by passing the `lazy`
* option when instantiating your pool, this is useful to reduce startup time. In
* addition to this, the pool won't start the connection unless there isn't any already
* available connections in the pool
*
* ```ts
* import { Pool } from "https://deno.land/x/postgres/mod.ts";
* // Creates a pool with 10 max available connections
* // Connection with the database won't be established until the user requires it
* const pool = new Pool({}, 10, true);
*
* // Connection is created here, will be available from now on
* const client_1 = await pool.connect();
* await client_1.queryArray`SELECT 1`;
* client_1.release();
*
* // Same connection as before, will be reused instead of starting a new one
* const client_2 = await pool.connect();
* await client_2.queryArray`SELECT 1`;
*
* // New connection, since previous one is still in use
* // There will be two open connections available from now on
* const client_3 = await pool.connect();
* client_2.release();
* client_3.release();
* ```
*/
export class Pool {
#available_connections?: DeferredAccessStack<PoolClient>;
#connection_params: ClientConfiguration;
#ended = false;
#lazy: boolean;
// TODO
// Initialization should probably have a timeout
#ready: Promise<void>;
#size: number;
/**
* The number of open connections available for use
*
* Lazily initialized pools won't have any open connections by default
*/
get available(): number {
if (!this.#available_connections) {
return 0;
}
return this.#available_connections.available;
}
/**
* The number of total connections open in the pool
*
* Both available and in use connections will be counted
*/
get size(): number {
if (!this.#available_connections) {
return 0;
}
return this.#available_connections.size;
}
/**
* A class that manages connection pooling for PostgreSQL clients
*/
constructor(
connection_params: ClientOptions | ConnectionString | undefined,
size: number,
lazy: boolean = false,
) {
this.#connection_params = createParams(connection_params);
this.#lazy = lazy;
this.#size = size;
// This must ALWAYS be called the last
this.#ready = this.#initialize();
}
// TODO
// Rename to getClient or similar
// The connect method should initialize the connections instead of doing it
// in the constructor
/**
* This will return a new client from the available connections in
* the pool
*
* In the case of lazy initialized pools, a new connection will be established
* with the database if no other connections are available
*
* ```ts
* import { Pool } from "https://deno.land/x/postgres/mod.ts";
* const pool = new Pool({}, 10);
* const client = await pool.connect();
* await client.queryArray`UPDATE MY_TABLE SET X = 1`;
* client.release();
* ```
*/
async connect(): Promise<PoolClient> {
// Reinitialize pool if it has been terminated
if (this.#ended) {
this.#ready = this.#initialize();
}
await this.#ready;
return this.#available_connections!.pop();
}
/**
* This will close all open connections and set a terminated status in the pool
*
* ```ts
* import { Pool } from "https://deno.land/x/postgres/mod.ts";
* const pool = new Pool({}, 10);
*
* await pool.end();
* console.assert(pool.available === 0, "There are connections available after ending the pool");
* await pool.end(); // An exception will be thrown, pool doesn't have any connections to close
* ```
*
* However, a terminated pool can be reused by using the "connect" method, which
* will reinitialize the connections according to the original configuration of the pool
*
* ```ts
* import { Pool } from "https://deno.land/x/postgres/mod.ts";
* const pool = new Pool({}, 10);
* await pool.end();
* const client = await pool.connect();
* await client.queryArray`SELECT 1`; // Works!
* client.release();
* ```
*/
async end(): Promise<void> {
if (this.#ended) {
throw new Error("Pool connections have already been terminated");
}
await this.#ready;
while (this.available > 0) {
const client = await this.#available_connections!.pop();
await client.end();
}
this.#available_connections = undefined;
this.#ended = true;
}
/**
* Initialization will create all pool clients instances by default
*
* If the pool is lazily initialized, the clients will connect when they
* are requested by the user, otherwise they will all connect on initialization
*/
async #initialize() {
const initialized = this.#lazy ? 0 : this.#size;
const clients = Array.from({ length: this.#size }, async (_e, index) => {
const client: PoolClient = new PoolClient(
this.#connection_params,
() => this.#available_connections!.push(client),
);
if (index < initialized) {
await client.connect();
}
return client;
});
this.#available_connections = new DeferredAccessStack(
await Promise.all(clients),
(client) => client.connect(),
(client) => client.connected,
);
this.#ended = false;
}
/**
* This will return the number of initialized clients in the pool
*/
async initialized(): Promise<number> {
if (!this.#available_connections) {
return 0;
}
return await this.#available_connections.initialized();
}
}