-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJsdbcAutoConfiguration.js
More file actions
355 lines (322 loc) · 11.6 KB
/
JsdbcAutoConfiguration.js
File metadata and controls
355 lines (322 loc) · 11.6 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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/**
* JsdbcAutoConfiguration — CDI auto-configuration for JSDBC.
*
* Config prefix defaults to 'boot.datasource' (aligned with Spring's
* spring.datasource.*). Custom prefix supported for secondary datasources.
*
* Config keys (substitute your prefix):
* {prefix}.url — JSDBC connection URL (required)
* {prefix}.username — database username (optional)
* {prefix}.password — database password (optional)
* {prefix}.initialize — run schema.sql + data.sql on start (default: true)
* {prefix}.schema — path to schema SQL file (default: 'config/schema.sql')
* {prefix}.data — path to data SQL file (default: 'config/data.sql')
* {prefix}.pool.enabled — enable connection pooling (default: false)
* {prefix}.pool.min — min pool size (default: 0)
* {prefix}.pool.max — max pool size (default: 10)
* {prefix}.pool.acquireTimeoutMillis — acquire timeout ms (default: 30000)
* {prefix}.pool.idleTimeoutMillis — idle timeout ms (default: 30000)
*/
import { readFileSync, existsSync } from 'fs';
import { conditionalOnProperty } from '@alt-javascript/cdi';
import { DataSource, PooledDataSource, SingleConnectionDataSource } from '@alt-javascript/jsdbc-core';
import { JsdbcTemplate, NamedParameterJsdbcTemplate } from '@alt-javascript/jsdbc-template';
export const DEFAULT_PREFIX = 'boot.datasource';
/**
* CDI-managed DataSource. Reads connection properties from config at the
* given prefix. Implements setApplicationContext for lifecycle access.
*/
export class ConfiguredDataSource {
constructor() {
this._delegate = null;
this._applicationContext = null;
this._prefix = DEFAULT_PREFIX; // overridden by DataSourceBuilder
this._connectionPromise = null; // mutex: prevents concurrent getConnection() from creating two connections
}
setApplicationContext(ctx) {
this._applicationContext = ctx;
}
init() {
const config = this._applicationContext.config;
const p = this._prefix;
const url = config.get(`${p}.url`);
const props = { url };
if (config.has(`${p}.username`)) props.username = config.get(`${p}.username`);
if (config.has(`${p}.password`)) props.password = config.get(`${p}.password`);
const poolEnabled = config.has(`${p}.pool.enabled`) && config.get(`${p}.pool.enabled`);
if (poolEnabled) {
const pool = {};
if (config.has(`${p}.pool.min`)) pool.min = config.get(`${p}.pool.min`);
if (config.has(`${p}.pool.max`)) pool.max = config.get(`${p}.pool.max`);
if (config.has(`${p}.pool.acquireTimeoutMillis`)) {
pool.acquireTimeoutMillis = config.get(`${p}.pool.acquireTimeoutMillis`);
}
if (config.has(`${p}.pool.idleTimeoutMillis`)) {
pool.idleTimeoutMillis = config.get(`${p}.pool.idleTimeoutMillis`);
}
props.pool = pool;
this._delegate = new PooledDataSource(props);
} else if (this._isInMemoryUrl(url)) {
this._delegate = new SingleConnectionDataSource(props);
} else {
this._delegate = new DataSource(props);
}
}
/**
* Get a connection from the underlying datasource.
*
* For SingleConnectionDataSource (in-memory), concurrent callers share one
* connection. A promise-mutex ensures only one connection is ever created
* even when multiple async callers race to getConnection() simultaneously.
*
* @returns {Promise<Connection>}
*/
async getConnection() {
// Fast path: delegate is not a SingleConnectionDataSource (pool or regular DS)
if (!(this._delegate instanceof SingleConnectionDataSource)) {
return this._delegate.getConnection();
}
// Mutex path: share one initialization promise across concurrent callers
if (!this._connectionPromise) {
this._connectionPromise = this._delegate.getConnection();
}
return this._connectionPromise;
}
/** @returns {string} */
getUrl() {
return this._delegate.getUrl?.() || this._delegate._url;
}
async destroy() {
if (this._delegate && typeof this._delegate.destroy === 'function') {
await this._delegate.destroy();
}
}
_isInMemoryUrl(url) {
return url.includes(':memory') || url.includes('::memory:');
}
}
/**
* SchemaInitializer — runs schema.sql then data.sql on application start.
*
* Controlled by {prefix}.initialize (default: true when files exist).
* File paths: {prefix}.schema (default: 'config/schema.sql')
* {prefix}.data (default: 'config/data.sql')
*
* Disable by setting {prefix}.initialize = false in config.
* Safe to use in tests — schema is applied each time the context starts
* (in-memory DBs start fresh anyway).
*/
export class SchemaInitializer {
constructor() {
this.dataSource = null; // autowired
this._applicationContext = null;
this._prefix = DEFAULT_PREFIX;
this._initPromise = null; // awaitable by tests and dependent beans
}
setApplicationContext(ctx) {
this._applicationContext = ctx;
}
/**
* Wait for schema initialisation to complete.
* CDI does not await async init() — callers that need the schema applied
* before querying should call await schemaInitializer.ready() after start.
* @returns {Promise<void>}
*/
async ready() {
if (this._initPromise) await this._initPromise;
}
init() {
// Store promise so ready() can await it; return it so CDI can observe errors
this._initPromise = this._doInit();
return this._initPromise;
}
async _doInit() {
const config = this._applicationContext.config;
const p = this._prefix;
// initialize defaults to true; set to false to suppress
if (config.has(`${p}.initialize`) && !config.get(`${p}.initialize`)) {
return;
}
const schemaPath = config.has(`${p}.schema`)
? config.get(`${p}.schema`)
: 'config/schema.sql';
const dataPath = config.has(`${p}.data`)
? config.get(`${p}.data`)
: 'config/data.sql';
const conn = await this.dataSource.getConnection();
try {
await this._runFile(conn, schemaPath);
await this._runFile(conn, dataPath);
} finally {
if (conn && typeof conn.close === 'function') {
// don't close — SingleConnectionDataSource manages its own lifecycle
}
}
}
async _runFile(conn, filePath) {
if (!existsSync(filePath)) return;
const sql = readFileSync(filePath, 'utf8');
// Split on ; then strip leading -- line comments from each chunk before
// deciding whether the chunk is empty. A chunk like:
// -- my comment\nCREATE TABLE ...
// should NOT be discarded — only chunks that are purely comments.
const statements = sql
.split(';')
.map((s) => {
// Remove full-line comments (lines starting with --)
const stripped = s
.split('\n')
.filter((line) => !line.trim().startsWith('--'))
.join('\n')
.trim();
return stripped;
})
.filter((s) => s.length > 0);
for (const stmt of statements) {
const st = await conn.createStatement();
await st.execute(stmt);
}
}
}
/**
* DataSourceBuilder — fluent builder for named/secondary datasources.
*
* Spring's DataSourceBuilder pattern: one primary datasource is auto-configured;
* additional datasources are explicitly declared with their own config prefix
* and CDI bean name. This allows multiple adjacent (non-primary) datasources
* within the same application context.
*
* Usage (secondary datasource):
*
* // config:
* // boot.datasource.reporting.url: jsdbc:pg:...
* // boot.datasource.reporting.pool.enabled: true
*
* import { DataSourceBuilder } from '@alt-javascript/boot-jsdbc';
* const reportingComponents = DataSourceBuilder
* .create()
* .prefix('boot.datasource.reporting')
* .beanNames({ dataSource: 'reportingDataSource', jsdbcTemplate: 'reportingJsdbcTemplate' })
* .build();
*
* await jsdbcTemplateStarter({
* config,
* contexts: [new Context([...reportingComponents, new Singleton(ReportRepository)])],
* });
*
* // ReportRepository.reportingJsdbcTemplate is now auto-wired.
*/
export class DataSourceBuilder {
constructor() {
this._prefix = DEFAULT_PREFIX;
this._beanNames = {};
this._includeSchemaInitializer = true;
}
static create() {
return new DataSourceBuilder();
}
/**
* Config prefix for this datasource's properties.
* @param {string} prefix — e.g. 'boot.datasource.reporting'
*/
prefix(prefix) {
this._prefix = prefix;
return this;
}
/**
* Override CDI bean names. Keys: dataSource, jsdbcTemplate,
* namedParameterJsdbcTemplate, schemaInitializer.
* @param {object} names — partial override map
*/
beanNames(names) {
this._beanNames = { ...this._beanNames, ...names };
return this;
}
/**
* Disable SchemaInitializer registration for this datasource.
*/
withoutSchemaInitializer() {
this._includeSchemaInitializer = false;
return this;
}
/**
* Build CDI component definition array for this datasource.
* @returns {Array} CDI component definitions
*/
build() {
const prefix = this._prefix;
const names = this._beanNames;
const dsName = names.dataSource ?? 'dataSource';
const jtName = names.jsdbcTemplate ?? 'jsdbcTemplate';
const njtName = names.namedParameterJsdbcTemplate ?? 'namedParameterJsdbcTemplate';
const siName = names.schemaInitializer ?? 'schemaInitializer';
// Build a DataSource class with the correct prefix baked in
class BoundDataSource extends ConfiguredDataSource {
constructor() {
super();
this._prefix = prefix;
}
}
Object.defineProperty(BoundDataSource, 'name', { value: dsName });
const components = [
{
name: dsName,
Reference: BoundDataSource,
scope: 'singleton',
condition: (config, components) => {
if (components[dsName]) return false;
return config.has(`${prefix}.url`);
},
},
{
name: jtName,
Reference: JsdbcTemplate,
scope: 'singleton',
constructorArgs: [dsName],
dependsOn: dsName,
condition: conditionalOnProperty(`${prefix}.url`),
},
{
name: njtName,
Reference: NamedParameterJsdbcTemplate,
scope: 'singleton',
constructorArgs: [dsName],
dependsOn: dsName,
condition: conditionalOnProperty(`${prefix}.url`),
},
];
if (this._includeSchemaInitializer) {
class BoundSchemaInitializer extends SchemaInitializer {
constructor() {
super();
this._prefix = prefix;
}
}
Object.defineProperty(BoundSchemaInitializer, 'name', { value: siName });
// Wire dataSource to the named bean for this builder's datasource
const siRef = {
name: siName,
Reference: BoundSchemaInitializer,
scope: 'singleton',
properties: [{ name: 'dataSource', reference: dsName }],
dependsOn: dsName,
condition: conditionalOnProperty(`${prefix}.url`),
};
components.push(siRef);
}
return components;
}
}
/**
* Returns CDI component definitions for the primary datasource.
*
* Equivalent to DataSourceBuilder.create().prefix(prefix).build().
*
* @param {object} [options]
* @param {string} [options.prefix='boot.datasource'] — config key prefix
* @returns {Array} CDI component definitions
*/
export function jsdbcAutoConfiguration(options = {}) {
const prefix = options.prefix ?? DEFAULT_PREFIX;
return DataSourceBuilder.create().prefix(prefix).build();
}