@owlmeans/postgres 0.1.18-rc.9 → 0.1.18

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/README.md +7 -6
  2. package/agent-meta/manifest.json +3 -3
  3. package/agent-meta/skills/postgres/SKILL.md +67 -16
  4. package/build/bootstrap.d.ts.map +1 -1
  5. package/build/bootstrap.js +12 -7
  6. package/build/bootstrap.js.map +1 -1
  7. package/build/index.d.ts +2 -0
  8. package/build/index.d.ts.map +1 -1
  9. package/build/index.js.map +1 -1
  10. package/build/service.d.ts +1 -5
  11. package/build/service.d.ts.map +1 -1
  12. package/build/service.js +23 -41
  13. package/build/service.js.map +1 -1
  14. package/build/types.local.d.ts +5 -0
  15. package/build/types.local.d.ts.map +1 -0
  16. package/build/types.local.js +2 -0
  17. package/build/types.local.js.map +1 -0
  18. package/build/utils/config/types.d.ts +30 -0
  19. package/build/utils/config/types.d.ts.map +1 -0
  20. package/build/utils/config/types.js +2 -0
  21. package/build/utils/config/types.js.map +1 -0
  22. package/build/utils/config.d.ts +4 -24
  23. package/build/utils/config.d.ts.map +1 -1
  24. package/build/utils/config.js +74 -87
  25. package/build/utils/config.js.map +1 -1
  26. package/build/utils/connection/types.d.ts +17 -0
  27. package/build/utils/connection/types.d.ts.map +1 -0
  28. package/build/utils/connection/types.js +2 -0
  29. package/build/utils/connection/types.js.map +1 -0
  30. package/build/utils/connection.d.ts +2 -13
  31. package/build/utils/connection.d.ts.map +1 -1
  32. package/build/utils/connection.js +33 -37
  33. package/build/utils/connection.js.map +1 -1
  34. package/package.json +14 -13
  35. package/src/bootstrap.ts +13 -11
  36. package/src/index.ts +2 -0
  37. package/src/service.ts +28 -58
  38. package/src/types.local.ts +5 -0
  39. package/src/utils/config/types.ts +28 -0
  40. package/src/utils/config.ts +80 -89
  41. package/src/utils/connection/types.ts +17 -0
  42. package/src/utils/connection.ts +36 -36
  43. package/tests/context.ts +3 -3
  44. package/tests/criteria.spec.ts +107 -0
  45. package/tests/crud.spec.ts +68 -18
  46. package/tests/custom-sql.spec.ts +3 -2
  47. package/tests/migration.spec.ts +34 -3
  48. package/tests/sync.spec.ts +91 -1
@@ -1,96 +1,83 @@
1
1
  import { PostgresConnectionError } from '@owlmeans/postgres-resource';
2
2
  import { DEF_POOL_SIZE, DEF_PORT } from '../consts.js';
3
- /**
4
- * Split a `postgres://` URL into pool fields.
5
- *
6
- * node-postgres accepts a `connectionString` directly, but the parsed values *override*
7
- * every sibling field — so `{ connectionString, database }` silently ignores the
8
- * database. Parsing here instead keeps overriding possible, which the admin path needs
9
- * to reach both the maintenance database and the target one over the same credentials.
10
- *
11
- * @throws {PostgresConnectionError}
12
- */
13
- export const parseUrl = (url) => {
14
- let parsed;
15
- try {
16
- parsed = new URL(url);
17
- }
18
- catch {
19
- throw new PostgresConnectionError('malformed-url');
20
- }
21
- if (!/^postgres(ql)?:$/.test(parsed.protocol)) {
22
- throw new PostgresConnectionError(`unexpected-protocol:${parsed.protocol.replace(':', '')}`);
23
- }
24
- const database = decodeURIComponent(parsed.pathname.replace(/^\//, ''));
25
- /** IPv6 literals arrive bracketed from `URL`; `pg` wants the bare address. */
26
- const host = decodeURIComponent(parsed.hostname).replace(/^\[|\]$/g, '');
27
- const mode = parsed.searchParams.get('sslmode');
28
- const config = {
29
- host,
30
- port: parsed.port !== '' ? parseInt(parsed.port, 10) : DEF_PORT
31
- };
32
- if (parsed.username !== '') {
33
- config.user = decodeURIComponent(parsed.username);
34
- }
35
- if (parsed.password !== '') {
36
- config.password = decodeURIComponent(parsed.password);
37
- }
38
- if (database !== '') {
39
- config.database = database;
40
- }
41
- if (mode != null && mode !== 'disable') {
42
- /**
43
- * `no-verify` is what a self signed in-cluster certificate needs, and is the only
44
- * mode that may skip verification — anything else keeps the chain checked.
45
- */
46
- config.ssl = mode === 'no-verify' ? { rejectUnauthorized: false } : true;
47
- }
48
- return config;
49
- };
50
- /**
51
- * Turn a {@link DbConfig} into a `pg` pool configuration.
52
- *
53
- * Values that start with `/` have already been read from disk by the `fileConfigReader`
54
- * middleware, so a file mounted secret and a literal one are indistinguishable here —
55
- * which is what lets a deployment move from env vars to mounted files without a code
56
- * change.
57
- */
58
- export const prepareConfig = (config, overrides) => {
59
- const meta = (config.meta ?? {});
60
- /**
61
- * `DbConfig.host` is an array for Mongo's replica sets. Postgres has no client side
62
- * equivalent — multi-host failover is the pooler's job — so only the first is used.
63
- */
64
- const host = Array.isArray(config.host) ? config.host[0] : config.host;
65
- const base = meta.url != null
66
- ? parseUrl(meta.url)
67
- : {
3
+ export const createPgConfigHelper = () => {
4
+ const parseUrl = (url) => {
5
+ let parsed;
6
+ try {
7
+ parsed = new URL(url);
8
+ }
9
+ catch {
10
+ throw new PostgresConnectionError('malformed-url');
11
+ }
12
+ if (!/^postgres(ql)?:$/.test(parsed.protocol)) {
13
+ throw new PostgresConnectionError(`unexpected-protocol:${parsed.protocol.replace(':', '')}`);
14
+ }
15
+ const database = decodeURIComponent(parsed.pathname.replace(/^\//, ''));
16
+ /** IPv6 literals arrive bracketed from `URL`; `pg` wants the bare address. */
17
+ const host = decodeURIComponent(parsed.hostname).replace(/^\[|\]$/g, '');
18
+ const mode = parsed.searchParams.get('sslmode');
19
+ const config = {
68
20
  host,
69
- port: config.port ?? DEF_PORT,
70
- ...(config.user != null ? { user: config.user } : {}),
71
- ...(config.secret != null ? { password: config.secret } : {}),
72
- /** Absent, libpq falls back to the connection user's name. */
73
- ...(meta.database != null ? { database: meta.database } : {})
21
+ port: parsed.port !== '' ? parseInt(parsed.port, 10) : DEF_PORT
74
22
  };
75
- const prepared = {
76
- ...base,
77
- max: meta.max ?? DEF_POOL_SIZE,
78
- ...(meta.ssl != null ? { ssl: meta.ssl } : {}),
79
- ...(meta.idleTimeoutMillis != null ? { idleTimeoutMillis: meta.idleTimeoutMillis } : {}),
80
- ...(meta.connectionTimeoutMillis != null
81
- ? { connectionTimeoutMillis: meta.connectionTimeoutMillis }
82
- : {}),
23
+ if (parsed.username !== '') {
24
+ config.user = decodeURIComponent(parsed.username);
25
+ }
26
+ if (parsed.password !== '') {
27
+ config.password = decodeURIComponent(parsed.password);
28
+ }
29
+ if (database !== '') {
30
+ config.database = database;
31
+ }
32
+ if (mode != null && mode !== 'disable') {
33
+ /**
34
+ * `no-verify` is what a self signed in-cluster certificate needs, and is the only
35
+ * mode that may skip verification — anything else keeps the chain checked.
36
+ */
37
+ config.ssl = mode === 'no-verify' ? { rejectUnauthorized: false } : true;
38
+ }
39
+ return config;
40
+ };
41
+ const prepareConfig = (config, overrides) => {
42
+ const meta = (config.meta ?? {});
83
43
  /**
84
- * A server side cap, so a query that outlives its caller stops holding a connection
85
- * and its locks — the failure mode that turns one slow statement into a stuck pool.
44
+ * `DbConfig.host` is an array for Mongo's replica sets. Postgres has no client side
45
+ * equivalent — multi-host failover is the pooler's job — so only the first is used.
86
46
  */
87
- ...(meta.statementTimeoutMillis != null
88
- ? { statement_timeout: meta.statementTimeoutMillis }
89
- : {}),
90
- ...overrides
47
+ const host = Array.isArray(config.host) ? config.host[0] : config.host;
48
+ const base = meta.url != null
49
+ ? parseUrl(meta.url)
50
+ : {
51
+ host,
52
+ port: config.port ?? DEF_PORT,
53
+ ...(config.user != null ? { user: config.user } : {}),
54
+ ...(config.secret != null ? { password: config.secret } : {}),
55
+ /** Absent, libpq falls back to the connection user's name. */
56
+ ...(meta.database != null ? { database: meta.database } : {})
57
+ };
58
+ const prepared = {
59
+ ...base,
60
+ max: meta.max ?? DEF_POOL_SIZE,
61
+ ...(meta.ssl != null ? { ssl: meta.ssl } : {}),
62
+ ...(meta.idleTimeoutMillis != null ? { idleTimeoutMillis: meta.idleTimeoutMillis } : {}),
63
+ ...(meta.connectionTimeoutMillis != null
64
+ ? { connectionTimeoutMillis: meta.connectionTimeoutMillis }
65
+ : {}),
66
+ /**
67
+ * A server side cap, so a query that outlives its caller stops holding a connection
68
+ * and its locks — the failure mode that turns one slow statement into a stuck pool.
69
+ */
70
+ ...(meta.statementTimeoutMillis != null
71
+ ? { statement_timeout: meta.statementTimeoutMillis }
72
+ : {}),
73
+ ...overrides
74
+ };
75
+ return prepared;
91
76
  };
92
- return prepared;
77
+ const poolDatabase = (pool) => pool.options?.database ?? pool.options?.user ?? '';
78
+ return { parseUrl, prepareConfig, poolDatabase };
93
79
  };
94
- /** Effective database of an open pool, as `pg` resolved it. */
95
- export const poolDatabase = (pool) => pool.options?.database ?? pool.options?.user ?? '';
80
+ export const pgConfigHelper = createPgConfigHelper();
81
+ /** @deprecated compat:factory-refactor — use `pgConfigHelper.parseUrl(…)` */
82
+ export const parseUrl = (url) => pgConfigHelper.parseUrl(url);
96
83
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/utils/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAA;AAKrE,OAAO,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAA;AAEtD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAc,EAAE;IAClD,IAAI,MAAW,CAAA;IACf,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IACvB,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAAC,eAAe,CAAC,CAAA;IACpD,CAAC;IACD,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC9C,MAAM,IAAI,uBAAuB,CAAC,uBAAuB,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,CAAC,CAAA;IAC9F,CAAC;IAED,MAAM,QAAQ,GAAG,kBAAkB,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAA;IACv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AC,uBAAuB,IAAI,IAAI;gBACtC,CAAC,CAAC,EAAE,uBAAuB,EAAE,IAAI,CAAC,uBAAuB,EAAE;gBAC3D,CAAC,CAAC,EAAE,CAAC;YACP;;;eAGG;YACH,GAAG,CAAC,IAAI,CAAC,sBAAsB,IAAI,IAAI;gBACrC,CAAC,CAAC,EAAE,iBAAiB,EAAE,IAAI,CAAC,sBAAsB,EAAE;gBACpD,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,SAAS;SACb,CAAA;QAED,OAAO,QAAQ,CAAA;IACjB,CAAC,CAAA;IAED,MAAM,YAAY,GAAG,CAAC,IAA8B,EAAU,EAAE,CAC9D,IAAI,CAAC,OAAO,EAAE,QAAQ,IAAI,IAAI,CAAC,OAAO,EAAE,IAAI,IAAI,EAAE,CAAA;IAEpD,OAAO,EAAE,QAAQ,EAAE,aAAa,EAAE,YAAY,EAAE,CAAA;AAClD,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,cAAc,GAAG,oBAAoB,EAAE,CAAA;AAEpD,6EAA6E;AAC7E,MAAM,CAAC,MAAM,QAAQ,GAAG,CAAC,GAAW,EAAc,EAAE,CAAC,cAAc,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAA"}
@@ -0,0 +1,17 @@
1
+ import type { PostgresMeta } from '@owlmeans/postgres-resource';
2
+ /** Readiness and namespace setup over one pool. */
3
+ export interface PgConnectionHelper {
4
+ /**
5
+ * Wait for the server to answer a query, not merely to accept a socket.
6
+ *
7
+ * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
8
+ * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
9
+ * deployment grew its own copy of this loop; this is the one.
10
+ *
11
+ * @throws {PostgresConnectionError}
12
+ */
13
+ probe: (meta: PostgresMeta, location: string) => Promise<void>;
14
+ /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
15
+ ensureSchema: (schema: string) => Promise<void>;
16
+ }
17
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../../src/utils/connection/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAA;AAE/D,mDAAmD;AACnD,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;OAQG;IACH,KAAK,EAAE,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;IAC9D,4DAA4D;IAC5D,YAAY,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,CAAA;CAChD"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/utils/connection/types.ts"],"names":[],"mappings":""}
@@ -1,15 +1,4 @@
1
- import type { PostgresMeta } from '@owlmeans/postgres-resource';
2
1
  import type { Pool } from 'pg';
3
- /**
4
- * Wait for the server to answer a query, not merely to accept a socket.
5
- *
6
- * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
7
- * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
8
- * deployment grew its own copy of this loop; this is the one.
9
- *
10
- * @throws {PostgresConnectionError}
11
- */
12
- export declare const probe: (pool: Pool, meta: PostgresMeta, location: string) => Promise<void>;
13
- /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
14
- export declare const ensureSchema: (pool: Pool, schema: string) => Promise<void>;
2
+ import type { PgConnectionHelper } from './connection/types.js';
3
+ export declare const makePgConnectionHelper: (pool: Pool) => PgConnectionHelper;
15
4
  //# sourceMappingURL=connection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAA;AAC/D,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAkB9B;;;;;;;;GAQG;AACH,eAAO,MAAM,KAAK,SAAgB,IAAI,QAAQ,YAAY,YAAY,MAAM,KAAG,OAAO,CAAC,IAAI,CAyB1F,CAAA;AAED,4DAA4D;AAC5D,eAAO,MAAM,YAAY,SAAgB,IAAI,UAAU,MAAM,KAAG,OAAO,CAAC,IAAI,CAM3E,CAAA"}
1
+ {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,IAAI,CAAA;AAG9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAA;AAkB/D,eAAO,MAAM,sBAAsB,SAAU,IAAI,KAAG,kBAuCnD,CAAA"}
@@ -1,5 +1,7 @@
1
- import { pgErrorToResourceError, PostgresConnectionError, quoteIdent } from '@owlmeans/postgres-resource';
1
+ import { pgErrorHelper, pgNameHelper, PostgresConnectionError } from '@owlmeans/postgres-resource';
2
+ import { logger } from '@owlmeans/log';
2
3
  import { DEF_RETRIES, DEF_RETRY_DELAY, TERMINAL_CONNECT_CODES } from '../consts.js';
4
+ const log = logger('postgres');
3
5
  /**
4
6
  * Retryable means "the server isn't up yet". A driver level failure carries no `code` at
5
7
  * all (`ECONNREFUSED`, DNS) and is exactly the case worth waiting on; a Postgres error
@@ -12,45 +14,39 @@ const isTransient = (error) => {
12
14
  }
13
15
  return !TERMINAL_CONNECT_CODES.includes(code);
14
16
  };
15
- /**
16
- * Wait for the server to answer a query, not merely to accept a socket.
17
- *
18
- * Postgres binds its port before it finishes recovery, so a sidecar or an operator managed
19
- * instance routinely accepts a connection and then refuses to run anything. Every OwlMeans
20
- * deployment grew its own copy of this loop; this is the one.
21
- *
22
- * @throws {PostgresConnectionError}
23
- */
24
- export const probe = async (pool, meta, location) => {
25
- const retries = Math.max(1, meta.retries ?? DEF_RETRIES);
26
- const delay = meta.retryDelayMillis ?? DEF_RETRY_DELAY;
27
- let last;
28
- for (let attempt = 1; attempt <= retries; ++attempt) {
17
+ export const makePgConnectionHelper = (pool) => {
18
+ const { pgErrorToResourceError } = pgErrorHelper;
19
+ const probe = async (meta, location) => {
20
+ const retries = Math.max(1, meta.retries ?? DEF_RETRIES);
21
+ const delay = meta.retryDelayMillis ?? DEF_RETRY_DELAY;
22
+ let last;
23
+ for (let attempt = 1; attempt <= retries; ++attempt) {
24
+ try {
25
+ await pool.query('SELECT 1');
26
+ return;
27
+ }
28
+ catch (error) {
29
+ last = error;
30
+ if (attempt === retries || !isTransient(error)) {
31
+ break;
32
+ }
33
+ log.debug('Postgres not ready, retrying', { location, attempt, retries, delay });
34
+ await new Promise(resolve => setTimeout(resolve, delay));
35
+ }
36
+ }
37
+ const translated = pgErrorToResourceError(last);
38
+ const failure = new PostgresConnectionError(`unreachable:${location}:${translated.message}`);
39
+ failure.cause = last;
40
+ throw failure;
41
+ };
42
+ const ensureSchema = async (schema) => {
29
43
  try {
30
- await pool.query('SELECT 1');
31
- return;
44
+ await pool.query(`CREATE SCHEMA IF NOT EXISTS ${pgNameHelper.quoteIdent(schema)}`);
32
45
  }
33
46
  catch (error) {
34
- last = error;
35
- if (attempt === retries || !isTransient(error)) {
36
- break;
37
- }
38
- console.log(`${location}: not ready (${attempt}/${retries}), retrying in ${delay}ms…`);
39
- await new Promise(resolve => setTimeout(resolve, delay));
47
+ throw pgErrorToResourceError(error);
40
48
  }
41
- }
42
- const translated = pgErrorToResourceError(last);
43
- const failure = new PostgresConnectionError(`unreachable:${location}:${translated.message}`);
44
- failure.cause = last;
45
- throw failure;
46
- };
47
- /** `CREATE SCHEMA IF NOT EXISTS` on a pooled connection. */
48
- export const ensureSchema = async (pool, schema) => {
49
- try {
50
- await pool.query(`CREATE SCHEMA IF NOT EXISTS ${quoteIdent(schema)}`);
51
- }
52
- catch (error) {
53
- throw pgErrorToResourceError(error);
54
- }
49
+ };
50
+ return { probe, ensureSchema };
55
51
  };
56
52
  //# sourceMappingURL=connection.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"connection.js","sourceRoot":"","sources":["../../src/utils/connection.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAA;AAIzG,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,cAAc,CAAA;AAEnF;;;;GAIG;AACH,MAAM,WAAW,GAAG,CAAC,KAAc,EAAW,EAAE;IAC9C,MAAM,IAAI,GAAI,KAAkC,EAAE,IAAI,CAAA;IACtD,IAAI,IAAI,IAAI,IAAI,EAAE,CAAC;QACjB,OAAO,IAAI,CAAA;IACb,CAAC;IAED,OAAO,CAAC,sBAAsB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAA;AAC/C,CAAC,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,KAAK,EAAE,IAAU,EAAE,IAAkB,EAAE,QAAgB,EAAiB,EAAE;IAC7F,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,OAAO,IAAI,WAAW,CAAC,CAAA;IACxD,MAAM,KAAK,GAAG,IAAI,CAAC,gBAAgB,IAAI,eAAe,CAAA;IACtD,IAAI,IAAa,CAAA;IAEjB,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,OAAO,EAAE,EAAE,OAAO,EAAE,CAAC;QACpD,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAA;YAE5B,OAAM;QACR,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,GAAG,KAAK,CAAA;YACZ,IAAI,OAAO,KAAK,OAAO,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,EAAE,CAAC;gBAC/C,MAAK;YACP,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,GAAG,QAAQ,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;QAC5F,OAAO,CAAC,KAAK,GAAG,IAAI,CAAA;QAEpB,MAAM,OAAO,CAAA;IACf,CAAC,CAAA;IAED,MAAM,YAAY,GAAG,KAAK,EAAE,MAAc,EAAiB,EAAE;QAC3D,IAAI,CAAC;YACH,MAAM,IAAI,CAAC,KAAK,CAAC,+BAA+B,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,EAAE,CAAC,CAAA;QACpF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,sBAAsB,CAAC,KAAK,CAAC,CAAA;QACrC,CAAC;IACH,CAAC,CAAA;IAED,OAAO,EAAE,KAAK,EAAE,YAAY,EAAE,CAAA;AAChC,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@owlmeans/postgres",
3
- "version": "0.1.18-rc.9",
3
+ "version": "0.1.18",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -22,20 +22,21 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@owlmeans/basic-keys": "^0.1.18-rc.8",
26
- "@owlmeans/context": "^0.1.18-rc.6",
27
- "@owlmeans/postgres-resource": "^0.1.18-rc.8",
28
- "@owlmeans/resource": "^0.1.18-rc.7",
29
- "@owlmeans/server-context": "^0.1.18-rc.7",
30
- "drizzle-orm": "~0.45.2",
31
- "pg": "^8.22.0"
25
+ "@owlmeans/basic-keys": "^0.1.18",
26
+ "@owlmeans/context": "^0.1.18",
27
+ "@owlmeans/postgres-resource": "^0.1.18",
28
+ "@owlmeans/resource": "^0.1.18",
29
+ "@owlmeans/server-context": "^0.1.18",
30
+ "@owlmeans/log": "^0.1.18",
31
+ "drizzle-orm": "~0.45.3",
32
+ "pg": "^8.23.1"
32
33
  },
33
34
  "devDependencies": {
34
- "@owlmeans/dep-config": "workspace:*",
35
- "@owlmeans/test-integration": "^0.1.18-rc.6",
36
- "@types/bun": "^1.3.14",
37
- "@types/node": "^26.1.0",
38
- "@types/pg": "^8.20.4",
35
+ "@owlmeans/dep-config": "^0.1.18",
36
+ "@owlmeans/test-integration": "^0.1.18",
37
+ "@types/bun": "^1.4.2",
38
+ "@types/node": "^26.6.4",
39
+ "@types/pg": "^8.23.1",
39
40
  "nodemon": "^3.1.14",
40
41
  "typescript": "^7.0.2"
41
42
  },
package/src/bootstrap.ts CHANGED
@@ -1,11 +1,12 @@
1
- import {
2
- assertSqlIdentifier, PostgresBootstrapError, quoteIdent, quoteLiteral
3
- } from '@owlmeans/postgres-resource'
1
+ import { pgNameHelper, PostgresBootstrapError } from '@owlmeans/postgres-resource'
2
+ import { logger } from '@owlmeans/log'
4
3
  import { Pool } from 'pg'
5
4
  import type { PoolClient } from 'pg'
6
5
 
7
6
  import type { BootstrapOptions, BootstrapReport, PostgresService } from './types.js'
8
- import { prepareConfig } from './utils/config.js'
7
+ import { pgConfigHelper } from './utils/config.js'
8
+
9
+ const log = logger('postgres')
9
10
 
10
11
  const exists = async (client: PoolClient, text: string, value: string): Promise<boolean> => {
11
12
  const result = await client.query(text, [value])
@@ -29,6 +30,7 @@ const exists = async (client: PoolClient, text: string, value: string): Promise<
29
30
  export const bootstrapDb = async (
30
31
  service: PostgresService, configAlias: string, opts: BootstrapOptions
31
32
  ): Promise<BootstrapReport> => {
33
+ const { assertSqlIdentifier, quoteIdent, quoteLiteral } = pgNameHelper
32
34
  const role = assertSqlIdentifier(opts.role, 'role')
33
35
  const database = assertSqlIdentifier(opts.database ?? opts.role, 'database')
34
36
  const schema = opts.schema != null ? assertSqlIdentifier(opts.schema, 'schema') : null
@@ -80,7 +82,7 @@ export const bootstrapDb = async (
80
82
  client.release()
81
83
  }
82
84
 
83
- const target = new Pool(prepareConfig(config, { database, max: 1 }))
85
+ const target = new Pool(pgConfigHelper.prepareConfig(config, { database, max: 1 }))
84
86
  try {
85
87
  if (schema != null) {
86
88
  /**
@@ -108,12 +110,12 @@ export const bootstrapDb = async (
108
110
  await target.end().catch(() => undefined)
109
111
  }
110
112
 
111
- console.log(
112
- `@owlmeans/postgres: bootstrap ${role}@${database} —`
113
- + ` role ${report.roleCreated ? 'created' : report.passwordRotated ? 'rotated' : 'present'},`
114
- + ` database ${report.databaseCreated ? 'created' : 'present'}`
115
- + (schema != null ? `, schema ${schema} ready` : '')
116
- )
113
+ log.info('Postgres bootstrap applied', {
114
+ role, database,
115
+ roleState: report.roleCreated ? 'created' : report.passwordRotated ? 'rotated' : 'present',
116
+ databaseState: report.databaseCreated ? 'created' : 'present',
117
+ ...(schema != null ? { schema } : {}),
118
+ }, { event: 'db.bootstrap' })
117
119
 
118
120
  return report
119
121
  }
package/src/index.ts CHANGED
@@ -4,4 +4,6 @@ export * from './bootstrap.js'
4
4
  export * from './middleware.js'
5
5
  export * from './service.js'
6
6
  export * from './utils/config.js'
7
+ export type * from './utils/config/types.js'
7
8
  export * from './utils/connection.js'
9
+ export type * from './utils/connection/types.js'
package/src/service.ts CHANGED
@@ -1,34 +1,32 @@
1
1
  import { makeKeyPairModel } from '@owlmeans/basic-keys'
2
- import { assertContext, Layer } from '@owlmeans/context'
3
- import type { BasicContext } from '@owlmeans/context'
4
- import {
5
- makeTx, pgErrorToResourceError, pgIdentifier, refOf, resolvePlaceholders
6
- } from '@owlmeans/postgres-resource'
7
- import type { PostgresDb, PostgresMeta } from '@owlmeans/postgres-resource'
2
+ import { assertContext } from '@owlmeans/context'
3
+ import { makeTx, pgErrorHelper, pgNameHelper, pgPlaceholdersOf, type PostgresDb, type PostgresMeta } from '@owlmeans/postgres-resource'
4
+ import { logThrottle, logger } from '@owlmeans/log'
8
5
  import { createDbService } from '@owlmeans/resource'
9
- import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
10
- import { drizzle } from 'drizzle-orm/node-postgres'
11
- import type { NodePgDatabase } from 'drizzle-orm/node-postgres'
12
- import { Pool } from 'pg'
13
- import type { QueryResultRow } from 'pg'
6
+ import { drizzle, type NodePgDatabase } from 'drizzle-orm/node-postgres'
7
+ import { Pool, type QueryResultRow } from 'pg'
14
8
 
15
9
  import { DEFAULT_ALIAS } from './consts.js'
16
10
  import { bootstrapDb } from './bootstrap.js'
17
11
  import { drainMiddleware } from './middleware.js'
18
12
  import type { PostgresService } from './types.js'
19
- import { poolDatabase, prepareConfig } from './utils/config.js'
20
- import { ensureSchema, probe } from './utils/connection.js'
13
+ import { pgConfigHelper } from './utils/config.js'
14
+ import { makePgConnectionHelper } from './utils/connection.js'
15
+ import type { Config, Context } from './types.local.js'
16
+
17
+ const log = logger('postgres')
21
18
 
22
- type Config = ServerConfig
23
- interface Context<C extends Config = Config> extends ServerContext<C> { }
24
19
 
25
20
  export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresService => {
26
21
  const location = `postgres:${alias}`
22
+ const { pgErrorToResourceError } = pgErrorHelper
23
+ const { pgIdentifier } = pgNameHelper
24
+ const { poolDatabase, prepareConfig } = pgConfigHelper
27
25
 
28
26
  /**
29
27
  * Handles are cached per config alias rather than rebuilt per call: `db()` runs on every
30
28
  * single resource operation, and both the Drizzle binding and the schema name are fixed
31
- * for the lifetime of a service instance — a layer switch produces a *new* instance.
29
+ * for the lifetime of the service — one instance per alias, for the whole process.
32
30
  */
33
31
  const handles: Map<string, PostgresDb> = new Map()
34
32
  const deferred: Map<string, Array<() => Promise<void>>> = new Map()
@@ -44,9 +42,9 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
44
42
  drizzle: drizzle(pool) as NodePgDatabase<Record<string, never>>,
45
43
  pool,
46
44
  /**
47
- * `name()` is the layer aware namespace — the Postgres SCHEMA here, where Mongo
48
- * reads the same value as a database name. It can outgrow 63 bytes once a layer
49
- * suffix is appended, which Postgres would truncate silently.
45
+ * `name()` is the configured namespace — the Postgres SCHEMA here, where Mongo
46
+ * reads the same value as a database name. `pgIdentifier` holds it inside the
47
+ * 63 byte limit Postgres would otherwise truncate silently.
50
48
  */
51
49
  schema: pgIdentifier(service.name(configAlias)),
52
50
  database: poolDatabase(pool)
@@ -65,23 +63,9 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
65
63
  return
66
64
  }
67
65
 
68
- if (service.layers == null) {
69
- service.layers = [Layer.Global]
70
- }
71
- /**
72
- * Sensitivity *adds* a layer the service is willing to serve. The Mongo copy of this
73
- * block tests `includes` where it means `!includes`, so it only ever appends a layer
74
- * that is already there — a latent no-op, corrected here.
75
- */
76
- if (config.serviceSensitive === true && !service.layers.includes(Layer.Service)) {
77
- service.layers.push(Layer.Service)
78
- }
79
- if (config.entitySensitive === true && !service.layers.includes(Layer.Entity)) {
80
- service.layers.push(Layer.Entity)
81
- }
82
-
83
66
  const meta = (config.meta ?? {}) as PostgresMeta
84
67
  const pool = new Pool(prepareConfig(config))
68
+ const connection = makePgConnectionHelper(pool)
85
69
 
86
70
  /**
87
71
  * Not optional: node-postgres emits `error` on *idle* clients when the server closes
@@ -89,11 +73,13 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
89
73
  * on an EventEmitter terminates the process.
90
74
  */
91
75
  pool.on('error', error => {
92
- console.error(`${location}: idle client error — ${(error as Error).message}`)
76
+ if (logThrottle(`${location}:idle-error`)) {
77
+ log.warn('Postgres idle client error', { location, error })
78
+ }
93
79
  })
94
80
 
95
81
  try {
96
- await probe(pool, meta, location)
82
+ await connection.probe(meta, location)
97
83
  } catch (error) {
98
84
  await pool.end().catch(() => undefined)
99
85
  throw error
@@ -113,7 +99,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
113
99
  * from the service alias would leave an empty `postgres` schema behind on every boot.
114
100
  */
115
101
  if (config.schema != null) {
116
- await ensureSchema(pool, pgIdentifier(service.name(configAlias)))
102
+ await connection.ensureSchema(pgIdentifier(service.name(configAlias)))
117
103
  }
118
104
  },
119
105
 
@@ -125,7 +111,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
125
111
  qualify: resourceAlias => {
126
112
  const context = assertContext<Config, Context>(service.ctx as Context, location)
127
113
 
128
- return refOf(context as unknown as BasicContext<any>, null, resourceAlias)
114
+ return pgPlaceholdersOf(context).refOf(null, resourceAlias)
129
115
  },
130
116
 
131
117
  query: async <Row extends QueryResultRow = QueryResultRow>(
@@ -135,7 +121,7 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
135
121
  const context = assertContext<Config, Context>(service.ctx as Context, location)
136
122
  try {
137
123
  const result = await db.pool.query<Row>(
138
- resolvePlaceholders(text, context as unknown as BasicContext<any>, null), params as never[]
124
+ pgPlaceholdersOf(context).resolvePlaceholders(text, null), params as never[]
139
125
  )
140
126
 
141
127
  return result.rows
@@ -147,13 +133,14 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
147
133
  transaction: async (fn, configAlias) => {
148
134
  const db = await service.db(configAlias)
149
135
  const context = assertContext<Config, Context>(service.ctx as Context, location)
136
+ const placeholders = pgPlaceholdersOf(context)
150
137
  const client = await db.pool.connect()
151
138
  try {
152
139
  await client.query('BEGIN')
153
140
  const result = await fn(makeTx(
154
141
  client,
155
- text => resolvePlaceholders(text, context as unknown as BasicContext<any>, null),
156
- resourceAlias => refOf(context as unknown as BasicContext<any>, null, resourceAlias)
142
+ text => placeholders.resolvePlaceholders(text, null),
143
+ resourceAlias => placeholders.refOf(null, resourceAlias)
157
144
  ))
158
145
  await client.query('COMMIT')
159
146
 
@@ -243,23 +230,6 @@ export const makePostgresDbService = (alias: string = DEFAULT_ALIAS): PostgresSe
243
230
  ]
244
231
  ))
245
232
  )
246
- },
247
-
248
- reinitializeContext: <T>(context: BasicContext<ServerConfig>) => {
249
- const _service = makePostgresDbService(alias)
250
-
251
- _service.ctx = context
252
- _service.layers = service.layers
253
-
254
- /**
255
- * Pools carry over instead of being reopened. A layer switch changes the Postgres
256
- * *schema*, not the server, and `max_connections` is a cluster wide budget — a pool
257
- * per tenant exhausts it long before the tenants run out. The handle cache is
258
- * deliberately *not* carried: its schema name is what the switch just changed.
259
- */
260
- Object.assign(_service.clients, service.clients)
261
-
262
- return _service as T
263
233
  }
264
234
  }, service => async () => {
265
235
  const context = assertContext<Config, Context>(service.ctx as Context, location)
@@ -0,0 +1,5 @@
1
+ import type { ServerConfig, ServerContext } from '@owlmeans/server-context'
2
+
3
+ export type Config = ServerConfig
4
+
5
+ export interface Context<C extends Config = Config> extends ServerContext<C> { }