@owlmeans/postgres-resource 0.1.15

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 (106) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -0
  3. package/agent-meta/instructions/postgres-resource.instructions.md +60 -0
  4. package/agent-meta/manifest.json +23 -0
  5. package/agent-meta/skills/postgres-resource/SKILL.md +186 -0
  6. package/build/consts.d.ts +81 -0
  7. package/build/consts.d.ts.map +1 -0
  8. package/build/consts.js +86 -0
  9. package/build/consts.js.map +1 -0
  10. package/build/declarations.d.ts +12 -0
  11. package/build/declarations.d.ts.map +1 -0
  12. package/build/declarations.js +28 -0
  13. package/build/declarations.js.map +1 -0
  14. package/build/errors.d.ts +70 -0
  15. package/build/errors.d.ts.map +1 -0
  16. package/build/errors.js +201 -0
  17. package/build/errors.js.map +1 -0
  18. package/build/helper.d.ts +4 -0
  19. package/build/helper.d.ts.map +1 -0
  20. package/build/helper.js +5 -0
  21. package/build/helper.js.map +1 -0
  22. package/build/index.d.ts +8 -0
  23. package/build/index.d.ts.map +1 -0
  24. package/build/index.js +7 -0
  25. package/build/index.js.map +1 -0
  26. package/build/resource.d.ts +4 -0
  27. package/build/resource.d.ts.map +1 -0
  28. package/build/resource.js +395 -0
  29. package/build/resource.js.map +1 -0
  30. package/build/types.d.ts +273 -0
  31. package/build/types.d.ts.map +1 -0
  32. package/build/types.js +2 -0
  33. package/build/types.js.map +1 -0
  34. package/build/utils/criteria.d.ts +24 -0
  35. package/build/utils/criteria.d.ts.map +1 -0
  36. package/build/utils/criteria.js +209 -0
  37. package/build/utils/criteria.js.map +1 -0
  38. package/build/utils/diff.d.ts +24 -0
  39. package/build/utils/diff.d.ts.map +1 -0
  40. package/build/utils/diff.js +330 -0
  41. package/build/utils/diff.js.map +1 -0
  42. package/build/utils/index.d.ts +12 -0
  43. package/build/utils/index.d.ts.map +1 -0
  44. package/build/utils/index.js +12 -0
  45. package/build/utils/index.js.map +1 -0
  46. package/build/utils/introspect.d.ts +7 -0
  47. package/build/utils/introspect.d.ts.map +1 -0
  48. package/build/utils/introspect.js +70 -0
  49. package/build/utils/introspect.js.map +1 -0
  50. package/build/utils/life-cycle.d.ts +39 -0
  51. package/build/utils/life-cycle.d.ts.map +1 -0
  52. package/build/utils/life-cycle.js +119 -0
  53. package/build/utils/life-cycle.js.map +1 -0
  54. package/build/utils/marshal.d.ts +36 -0
  55. package/build/utils/marshal.d.ts.map +1 -0
  56. package/build/utils/marshal.js +152 -0
  57. package/build/utils/marshal.js.map +1 -0
  58. package/build/utils/migrations.d.ts +16 -0
  59. package/build/utils/migrations.d.ts.map +1 -0
  60. package/build/utils/migrations.js +108 -0
  61. package/build/utils/migrations.js.map +1 -0
  62. package/build/utils/name.d.ts +39 -0
  63. package/build/utils/name.d.ts.map +1 -0
  64. package/build/utils/name.js +63 -0
  65. package/build/utils/name.js.map +1 -0
  66. package/build/utils/schema.d.ts +28 -0
  67. package/build/utils/schema.d.ts.map +1 -0
  68. package/build/utils/schema.js +356 -0
  69. package/build/utils/schema.js.map +1 -0
  70. package/build/utils/sql.d.ts +22 -0
  71. package/build/utils/sql.d.ts.map +1 -0
  72. package/build/utils/sql.js +0 -0
  73. package/build/utils/sql.js.map +1 -0
  74. package/build/utils/sync.d.ts +21 -0
  75. package/build/utils/sync.d.ts.map +1 -0
  76. package/build/utils/sync.js +93 -0
  77. package/build/utils/sync.js.map +1 -0
  78. package/build/utils/table.d.ts +8 -0
  79. package/build/utils/table.d.ts.map +1 -0
  80. package/build/utils/table.js +68 -0
  81. package/build/utils/table.js.map +1 -0
  82. package/package.json +50 -0
  83. package/src/consts.ts +95 -0
  84. package/src/declarations.ts +41 -0
  85. package/src/errors.ts +242 -0
  86. package/src/helper.ts +7 -0
  87. package/src/index.ts +7 -0
  88. package/src/resource.ts +524 -0
  89. package/src/types.ts +310 -0
  90. package/src/utils/criteria.ts +246 -0
  91. package/src/utils/diff.ts +363 -0
  92. package/src/utils/index.ts +11 -0
  93. package/src/utils/introspect.ts +87 -0
  94. package/src/utils/life-cycle.ts +155 -0
  95. package/src/utils/marshal.ts +175 -0
  96. package/src/utils/migrations.ts +135 -0
  97. package/src/utils/name.ts +79 -0
  98. package/src/utils/schema.ts +426 -0
  99. package/src/utils/sql.ts +0 -0
  100. package/src/utils/sync.ts +106 -0
  101. package/src/utils/table.ts +76 -0
  102. package/tests/errors.spec.ts +121 -0
  103. package/tests/name.spec.ts +75 -0
  104. package/tests/schema.spec.ts +258 -0
  105. package/tests/sql.spec.ts +104 -0
  106. package/tsconfig.json +16 -0
@@ -0,0 +1,175 @@
1
+ import type { ResourceRecord } from '@owlmeans/resource'
2
+ import { types as pgTypes } from 'pg'
3
+
4
+ import { ID_FIELD, PgTypeOid } from '../consts.js'
5
+ import type { ColumnSpec, TableSpec } from '../types.js'
6
+
7
+ /**
8
+ * Parse a temporal value the way the driver would have.
9
+ *
10
+ * Drizzle's node-postgres session installs its own `getTypeParser` that hands date and
11
+ * timestamp columns back as raw text, because its own statically declared column types do
12
+ * the conversion. Ours are compiled at runtime and can't, so the driver's parser is called
13
+ * directly — the same function, just later. Raw SQL never comes through here, since that
14
+ * path keeps the driver's default parsers.
15
+ */
16
+ const toDate = (value: string, column: ColumnSpec): unknown => {
17
+ const oid = column.sqlType.startsWith('timestamp with time zone')
18
+ ? PgTypeOid.TimestampTz
19
+ : column.sqlType.startsWith('timestamp')
20
+ ? PgTypeOid.Timestamp
21
+ : PgTypeOid.Date
22
+
23
+ return (pgTypes.getTypeParser(oid as never) as (raw: string) => unknown)(value)
24
+ }
25
+
26
+ const fromDriver = (value: unknown, column: ColumnSpec): unknown => {
27
+ if (value == null) {
28
+ return value
29
+ }
30
+ /** Ciphertext is opaque — coercing it would corrupt it. */
31
+ if (column.secure) {
32
+ return value
33
+ }
34
+
35
+ switch (column.jsonType) {
36
+ case 'number':
37
+ /** Postgres returns `numeric` as a string to protect precision the JS number can't hold. */
38
+ return typeof value === 'string' ? parseFloat(value) : value
39
+ case 'integer':
40
+ return typeof value === 'string' ? parseInt(value, 10) : value
41
+ case 'bigint': {
42
+ if (typeof value !== 'string' && typeof value !== 'bigint') {
43
+ return value
44
+ }
45
+ const parsed = Number(value)
46
+ if (!Number.isSafeInteger(parsed)) {
47
+ console.warn(
48
+ `@owlmeans/postgres-resource: "${column.column}" holds ${value}, which exceeds the safe`
49
+ + ' integer range — the value read back is imprecise.'
50
+ )
51
+ }
52
+
53
+ return parsed
54
+ }
55
+ case 'binary':
56
+ return Buffer.isBuffer(value) ? value.toString('base64') : value
57
+ case 'date':
58
+ return typeof value === 'string' ? toDate(value, column) : value
59
+ default:
60
+ return value
61
+ }
62
+ }
63
+
64
+ const toDriver = (value: unknown, column: ColumnSpec): unknown => {
65
+ if (value == null) {
66
+ return value
67
+ }
68
+ if (column.secure) {
69
+ return value
70
+ }
71
+ if (column.jsonb) {
72
+ /**
73
+ * node-postgres stringifies plain objects on its own but turns arrays into Postgres
74
+ * array literals, which a jsonb column rejects. Stringifying here covers both.
75
+ */
76
+ return typeof value === 'string' ? value : JSON.stringify(value)
77
+ }
78
+ if (column.jsonType === 'date' && !(value instanceof Date)) {
79
+ return new Date(value as string | number)
80
+ }
81
+ if (column.jsonType === 'binary' && typeof value === 'string') {
82
+ return Buffer.from(value, 'base64')
83
+ }
84
+
85
+ return value
86
+ }
87
+
88
+ /**
89
+ * Turn a driver row into a record: physical column names back to schema property names,
90
+ * plus the coercions node-postgres leaves to the caller.
91
+ *
92
+ * Columns the spec doesn't know about — computed expressions, joined columns from custom
93
+ * SQL — are kept verbatim. A join result is more useful than a lossy projection.
94
+ */
95
+ export const rowToRecord = <T extends ResourceRecord>(row: Record<string, unknown>, spec: TableSpec): T => {
96
+ const record: Record<string, unknown> = {}
97
+ for (const [key, value] of Object.entries(row)) {
98
+ const column = spec.byColumn[key]
99
+ if (column == null) {
100
+ record[key] = value
101
+ continue
102
+ }
103
+ record[column.property] = fromDriver(value, column)
104
+ }
105
+ if (record[ID_FIELD] != null) {
106
+ record[ID_FIELD] = `${record[ID_FIELD]}`
107
+ }
108
+
109
+ return record as T
110
+ }
111
+
112
+ /**
113
+ * Same coercion as {@link rowToRecord}, for rows Drizzle produced.
114
+ *
115
+ * Drizzle keys its results by the table object's JS property names — which are the schema
116
+ * property names — where raw SQL returns physical column names. Two functions rather than
117
+ * one lookup that tries both, because a schema that renames `a` to column `b` while another
118
+ * property is itself named `b` would make the combined lookup pick the wrong spec.
119
+ */
120
+ export const resultToRecord = <T extends ResourceRecord>(
121
+ row: Record<string, unknown>, spec: TableSpec
122
+ ): T => {
123
+ const record: Record<string, unknown> = {}
124
+ for (const [key, value] of Object.entries(row)) {
125
+ const column = spec.byProperty[key]
126
+ record[key] = column == null ? value : fromDriver(value, column)
127
+ }
128
+ if (record[ID_FIELD] != null) {
129
+ record[ID_FIELD] = `${record[ID_FIELD]}`
130
+ }
131
+
132
+ return record as T
133
+ }
134
+
135
+ /**
136
+ * Turn a record into the values Drizzle inserts, keyed by property name (Drizzle owns the
137
+ * property to column mapping).
138
+ *
139
+ * `undefined` properties are dropped so a partial write touches only what was supplied;
140
+ * an explicit `null` is kept, because nulling a column is a real intent.
141
+ */
142
+ export const recordToValues = (record: Record<string, unknown>, spec: TableSpec): Record<string, unknown> => {
143
+ const values: Record<string, unknown> = {}
144
+ for (const [key, value] of Object.entries(record)) {
145
+ const column = spec.byProperty[key]
146
+ if (column == null || value === undefined) {
147
+ continue
148
+ }
149
+ values[column.property] = toDriver(value, column)
150
+ }
151
+
152
+ return values
153
+ }
154
+
155
+ /**
156
+ * Every managed column, with anything the record omits explicitly nulled.
157
+ *
158
+ * This is what makes `update()` a replace rather than a merge — the semantics mongo's
159
+ * `replaceOne` gives, kept identical so a resource behaves the same on either backend.
160
+ * The primary key and unmanaged columns are never nulled.
161
+ */
162
+ export const recordToFullValues = (
163
+ record: Record<string, unknown>, spec: TableSpec
164
+ ): Record<string, unknown> => {
165
+ const values: Record<string, unknown> = {}
166
+ for (const column of spec.columns) {
167
+ if (spec.primaryKey.includes(column.column) || spec.unmanaged.includes(column.column)) {
168
+ continue
169
+ }
170
+ const value = record[column.property]
171
+ values[column.property] = value === undefined ? null : toDriver(value, column)
172
+ }
173
+
174
+ return values
175
+ }
@@ -0,0 +1,135 @@
1
+ import type { Migration, MigrationStore } from '@owlmeans/resource'
2
+ import type { PoolClient, QueryResultRow } from 'pg'
3
+
4
+ import { pgErrorToResourceError } from '../errors.js'
5
+ import type { PostgresTx, TableSpec } from '../types.js'
6
+ import { qualify, quoteIdent } from './name.js'
7
+
8
+ /**
9
+ * A transaction façade over a checked out client. `{{alias}}` resolution is injected so
10
+ * migrations can address other resources by alias without importing the context.
11
+ */
12
+ export const makeTx = (
13
+ client: PoolClient, resolve: (text: string) => string, ref: (alias?: string) => string
14
+ ): PostgresTx => ({
15
+ client,
16
+
17
+ query: async <Row extends QueryResultRow = QueryResultRow>(text: string, params?: unknown[]) => {
18
+ try {
19
+ const result = await client.query<Row>(resolve(text), params as never[])
20
+ return result.rows
21
+ } catch (error) {
22
+ throw pgErrorToResourceError(error)
23
+ }
24
+ },
25
+
26
+ queryOne: async <Row extends QueryResultRow = QueryResultRow>(text: string, params?: unknown[]) => {
27
+ try {
28
+ const result = await client.query<Row>(resolve(text), params as never[])
29
+ return result.rows[0] ?? null
30
+ } catch (error) {
31
+ throw pgErrorToResourceError(error)
32
+ }
33
+ },
34
+
35
+ execute: async (text: string, params?: unknown[]) => {
36
+ try {
37
+ const result = await client.query(resolve(text), params as never[])
38
+ return result.rowCount ?? 0
39
+ } catch (error) {
40
+ throw pgErrorToResourceError(error)
41
+ }
42
+ },
43
+
44
+ ref
45
+ })
46
+
47
+ /**
48
+ * Migration ledger, one table per Postgres schema.
49
+ *
50
+ * It lives inside the resource's own schema, so an Entity layer schema carries its own
51
+ * ledger — correct, because it also carries its own tables.
52
+ */
53
+ export const makeMigrationStore = (
54
+ client: PoolClient,
55
+ spec: TableSpec,
56
+ table: string,
57
+ resolve: (text: string) => string,
58
+ ref: (alias?: string) => string
59
+ ): MigrationStore<PostgresTx> => {
60
+ const ledger = qualify(spec.schema, table)
61
+
62
+ return {
63
+ ensure: async () => {
64
+ try {
65
+ await client.query(
66
+ `CREATE TABLE IF NOT EXISTS ${ledger} (`
67
+ + ` ${quoteIdent('alias')} text NOT NULL,`
68
+ + ` ${quoteIdent('name')} text NOT NULL,`
69
+ + ` ${quoteIdent('stage')} text NOT NULL DEFAULT 'pre',`
70
+ + ` ${quoteIdent('checksum')} text,`
71
+ + ` ${quoteIdent('baseline')} boolean NOT NULL DEFAULT false,`
72
+ + ` ${quoteIdent('applied_at')} timestamptz NOT NULL DEFAULT now(),`
73
+ + ` ${quoteIdent('duration_ms')} integer,`
74
+ + ` CONSTRAINT ${quoteIdent(`${table}_pkey`)} PRIMARY KEY (${quoteIdent('alias')}, ${quoteIdent('name')})`
75
+ + ')'
76
+ )
77
+ } catch (error) {
78
+ throw pgErrorToResourceError(error)
79
+ }
80
+ },
81
+
82
+ applied: async alias => {
83
+ const result = await client.query<{ name: string, checksum: string | null }>(
84
+ `SELECT ${quoteIdent('name')}, ${quoteIdent('checksum')} FROM ${ledger} WHERE ${quoteIdent('alias')} = $1`,
85
+ [alias]
86
+ )
87
+
88
+ return result.rows.reduce<Record<string, string | null>>((applied, row) => {
89
+ applied[row.name] = row.checksum
90
+ return applied
91
+ }, {})
92
+ },
93
+
94
+ baseline: async (alias, migrations) => {
95
+ const values = migrations
96
+ .map((_, position) => `($1, $${position * 3 + 2}, $${position * 3 + 3}, $${position * 3 + 4}, true)`)
97
+ .join(', ')
98
+ const params: unknown[] = [alias]
99
+ for (const migration of migrations) {
100
+ params.push(migration.name, migration.stage, migration.checksum)
101
+ }
102
+ try {
103
+ await client.query(
104
+ `INSERT INTO ${ledger} (${quoteIdent('alias')}, ${quoteIdent('name')}, ${quoteIdent('stage')},`
105
+ + ` ${quoteIdent('checksum')}, ${quoteIdent('baseline')}) VALUES ${values}`
106
+ + ` ON CONFLICT (${quoteIdent('alias')}, ${quoteIdent('name')}) DO NOTHING`,
107
+ params as never[]
108
+ )
109
+ } catch (error) {
110
+ throw pgErrorToResourceError(error)
111
+ }
112
+ },
113
+
114
+ run: async (alias: string, migration: Migration<PostgresTx>) => {
115
+ const started = Date.now()
116
+ await client.query('BEGIN')
117
+ try {
118
+ await migration.apply(makeTx(client, resolve, ref))
119
+ /**
120
+ * The ledger row commits with the migration itself, so a migration is never left
121
+ * half applied and recorded — the pair is atomic or neither happened.
122
+ */
123
+ await client.query(
124
+ `INSERT INTO ${ledger} (${quoteIdent('alias')}, ${quoteIdent('name')}, ${quoteIdent('stage')},`
125
+ + ` ${quoteIdent('checksum')}, ${quoteIdent('duration_ms')}) VALUES ($1, $2, $3, $4, $5)`,
126
+ [alias, migration.name, migration.stage, migration.checksum, Date.now() - started] as never[]
127
+ )
128
+ await client.query('COMMIT')
129
+ } catch (error) {
130
+ await client.query('ROLLBACK').catch(() => undefined)
131
+ throw pgErrorToResourceError(error)
132
+ }
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,79 @@
1
+ import { sha256 } from '@noble/hashes/sha2'
2
+ import { hex } from '@scure/base'
3
+ import type { DbConfig, ResourceRecord } from '@owlmeans/resource'
4
+
5
+ import { PG_MAX_IDENTIFIER } from '../consts.js'
6
+ import type { PostgresResource } from '../types.js'
7
+
8
+ const SAFE_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_$]*$/
9
+
10
+ /**
11
+ * Coerce an arbitrary name into a legal Postgres identifier of at most 63 bytes.
12
+ *
13
+ * The shared `dbName()` helper's own overflow fallback emits 96 characters, which the
14
+ * server would silently truncate — losing the hash suffix that made the name unique in
15
+ * the first place. Truncating here keeps the disambiguator inside the limit.
16
+ */
17
+ export const pgIdentifier = (name: string): string => {
18
+ const sanitized = name.replace(/[^A-Za-z0-9_$]/g, '_')
19
+ const prefixed = /^[A-Za-z_]/.test(sanitized) ? sanitized : `_${sanitized}`
20
+ if (Buffer.byteLength(prefixed, 'utf8') <= PG_MAX_IDENTIFIER) {
21
+ return prefixed
22
+ }
23
+ const digest = hex.encode(sha256(new TextEncoder().encode(name))).substring(0, 32)
24
+
25
+ return `${prefixed.substring(0, 30)}_${digest}`
26
+ }
27
+
28
+ /**
29
+ * Assert a value is safe to interpolate as an identifier. Postgres can't bind identifiers
30
+ * as parameters, so every one of them reaches the server as text — which makes this the
31
+ * only thing standing between a config value and injection.
32
+ *
33
+ * @throws {SyntaxError}
34
+ */
35
+ export const assertSqlIdentifier = (value: string, what: string = 'identifier'): string => {
36
+ if (!SAFE_IDENTIFIER.test(value) || Buffer.byteLength(value, 'utf8') > PG_MAX_IDENTIFIER) {
37
+ throw new SyntaxError(`postgres:unsafe-${what}:${value}`)
38
+ }
39
+
40
+ return value
41
+ }
42
+
43
+ /** Quote an identifier for emission, doubling any interior quote. */
44
+ export const quoteIdent = (value: string): string => `"${value.replace(/"/g, '""')}"`
45
+
46
+ /**
47
+ * Quote a string literal. Only ever used for values Postgres refuses to bind — notably
48
+ * the password in `CREATE ROLE`.
49
+ *
50
+ * @throws {SyntaxError} on a NUL byte, which no escaping makes safe.
51
+ */
52
+ export const quoteLiteral = (value: string): string => {
53
+ if (value.includes('\0')) {
54
+ throw new SyntaxError('postgres:unsafe-literal:nul-byte')
55
+ }
56
+
57
+ return `'${value.replace(/'/g, "''")}'`
58
+ }
59
+
60
+ export const qualify = (schema: string, table: string): string =>
61
+ `${quoteIdent(schema)}.${quoteIdent(table)}`
62
+
63
+ /**
64
+ * Physical table name of a resource: the explicit `name`, else the resource alias,
65
+ * prefixed per `DbConfig.resourcePrefix` and sanitized.
66
+ */
67
+ export const pgTableName = (config: DbConfig, resource: PostgresResource<ResourceRecord>): string =>
68
+ pgIdentifier(`${config.resourcePrefix ?? ''}${resource.name ?? resource.alias}`)
69
+
70
+ /**
71
+ * Derive a pair of int32s for `pg_advisory_lock` from a qualified table name, so every
72
+ * replica booting against the same table serializes on the same key.
73
+ */
74
+ export const advisoryKey = (qualified: string): [number, number] => {
75
+ const digest = sha256(new TextEncoder().encode(`owlmeans:${qualified}`))
76
+ const view = new DataView(digest.buffer, digest.byteOffset, digest.byteLength)
77
+
78
+ return [view.getInt32(0, false), view.getInt32(4, false)]
79
+ }