-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.ts
222 lines (187 loc) · 6.72 KB
/
client.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
217
218
219
220
import {
Connection,
ConnectionOptions
} from './connection.ts'
import {
// Cursor,
CursorOptions,
ArrayCursor,
// ObjectCursor
} from './cursor.ts'
import {
DeferredStack
} from './deferred.ts'
export interface ClientOptions {
host?: string,
port?: string | number, // 5432
database?: string,
user?: string,
password?: string,
options?: Record<string, string>,
applicationName?: string
}
export class ClientOptionsReader {
constructor(public options: string | ClientOptions = {}) {}
read(): ConnectionOptions {
let options = this.options
if (typeof options === 'string') {
options = this.readDSN(options)
}
// check deno env access
let pqEnv: ClientOptions = {}
let denoEnvAccess = true
try {
pqEnv = this.readEnv()
} catch (error) {
if (error instanceof Deno.errors.PermissionDenied) {
denoEnvAccess = false
} else {
throw error
}
}
// port integer or string
let port: string
if (options.port) {
port = String(options.port)
} else if (pqEnv.port) {
port = String(options.port)
} else {
port = '5432'
}
return {
host: options.host ?? pqEnv.host ?? '127.0.0.1',
port: parseInt(port),
database: options.database ?? pqEnv.database ?? '',
user: options.user ?? pqEnv.user ?? '',
password: options.password ?? pqEnv.password,
options: options.options ?? pqEnv.options,
applicationName: options.applicationName ?? pqEnv.applicationName ?? 'psql'
}
}
/**
* dsn: postgresql://[user[:password]@][host][:port][,...][/database][?param1=value1&...]
* https://www.postgresql.org/docs/13/libpq-connect.html#LIBPQ-CONNSTRING
*/
readDSN(dsn: string): ClientOptions {
// URL object won't parse the URL if it doesn't recognize the protocol
// this line replaces the protocol with http and then leaves it up to URL
const [protocol, strippedUrl] = dsn.match(/(?:(?!:\/\/).)+/g) ?? ["", ""]
const url = new URL(`http:${strippedUrl}`)
const options = Object.fromEntries(url.searchParams.entries())
if (protocol !== 'postgres' && protocol !== 'postgresql') {
/**
* URIError means invalid arguments for encodeURI and decodeURI.
* here, dsn string invalid with the protocol
*/
throw new URIError(`dsn string with invalid driver: ${protocol}`)
}
return {
// driver: protocol,
host: url.hostname,
port: url.port,
database: url.pathname.slice(1), // remove leading slash from path
user: url.username,
password: url.password,
options: options,
applicationName: options.applicationName
}
}
/**
* following environment variables can be used to as connection parameter values
* https://www.postgresql.org/docs/13/libpq-envars.html
*/
readEnv(): ClientOptions {
const params = Deno.env.get("PGOPTIONS") // 'a=1 b=2 c=3'
const options = params ? params.split(' ').reduce(
(prev: Record<string, string>, curr: string) => {
const [key, value] = curr.split('=')
prev[key] = value
return prev
}, {} // initialValue
) : {}
return {
// driver: 'postgresql',
host: Deno.env.get("PGHOST"),
port: Deno.env.get("PGPORT"),
database: Deno.env.get("PGDATABASE"),
user: Deno.env.get("PGUSER"),
password: Deno.env.get("PGPASSWORD"),
options: options,
applicationName: Deno.env.get("PGAPPNAME")
}
}
}
export class Client {
connection: Connection
constructor(options: ClientOptions | string) {
const clientOptions = new ClientOptionsReader(options)
this.connection = new Connection(clientOptions.read())
}
async connect(): Promise<void> {
await this.connection.connect()
}
/**
* https://stackoverflow.com/questions/12802317/passing-class-as-parameter-causes-is-not-newable-error
*/
cursor(
// cursorFactory: new (connection: Connection | DeferredStack<Connection>, options: CursorOptions) => ArrayCursor | ObjectCursor = ArrayCursor,
// deno-lint-ignore no-explicit-any
cursorFactory: any = ArrayCursor,
options: CursorOptions = {}
) {
// pass connection instance to cursor factory
const cursor = new cursorFactory(this.connection as Connection, options)
return cursor
}
close(): void {
this.connection.close()
}
}
export class Pool {
connections!: Array<Connection>
connectionOptions!: ConnectionOptions
maxConnections!: number
availableConnections!: DeferredStack<Connection>
constructor(options: ClientOptions | string, maxConnections: number = 3) {
const clientOptions = new ClientOptionsReader(options)
this.connectionOptions = clientOptions.read()
this.maxConnections = maxConnections
}
async connect(): Promise<void> {
// connections
const connections = new Array(this.maxConnections).map(async () =>
await this._connect()
)
this.connections = await Promise.all(connections)
// initial available connections
this.availableConnections = new DeferredStack(
/* max */this.maxConnections,
/* iterable */this.connections,
/* initial */this._connect.bind(this)
)
}
private async _connect(): Promise<Connection> {
const connection = new Connection(this.connectionOptions)
await connection.connect()
return connection
}
/**
* https://stackoverflow.com/questions/12802317/passing-class-as-parameter-causes-is-not-newable-error
*/
cursor(
// cursorFactory: new (connection: Connection | DeferredStack<Connection>, options: CursorOptions) => ArrayCursor | ObjectCursor = ArrayCursor,
// deno-lint-ignore no-explicit-any
cursorFactory: any = ArrayCursor,
options: CursorOptions = {}
) {
// pass deferred stack connections instance to cursor factory
const cursor = new cursorFactory(this.availableConnections as DeferredStack<Connection>, options)
return cursor
}
async close(): Promise<void> {
while (this.availableConnections.available) {
const connection = await this.availableConnections.pop()
await connection.close()
}
}
}