shutro 0.0.0-stage → 0.2.0

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 (165) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +99 -2
  3. package/dist/audit/index.d.ts +59 -0
  4. package/dist/audit/index.js +96 -0
  5. package/dist/cli/bin.d.ts +2 -0
  6. package/dist/cli/bin.js +11 -0
  7. package/dist/cli/cli.d.ts +10 -0
  8. package/dist/cli/cli.js +164 -0
  9. package/dist/cli/config.d.ts +18 -0
  10. package/dist/cli/config.js +49 -0
  11. package/dist/cli/errors.d.ts +16 -0
  12. package/dist/cli/errors.js +23 -0
  13. package/dist/cli/generate/generate.d.ts +33 -0
  14. package/dist/cli/generate/generate.js +84 -0
  15. package/dist/cli/generate/render.d.ts +23 -0
  16. package/dist/cli/generate/render.js +249 -0
  17. package/dist/cli/index.d.ts +12 -0
  18. package/dist/cli/index.js +12 -0
  19. package/dist/cli/init.d.ts +2 -0
  20. package/dist/cli/init.js +65 -0
  21. package/dist/cli/inspect.d.ts +10 -0
  22. package/dist/cli/inspect.js +82 -0
  23. package/dist/cli/packages.d.ts +6 -0
  24. package/dist/cli/packages.js +6 -0
  25. package/dist/cli/project.d.ts +18 -0
  26. package/dist/cli/project.js +39 -0
  27. package/dist/cli/resolve.d.ts +2 -0
  28. package/dist/cli/resolve.js +28 -0
  29. package/dist/core/compute/graph.d.ts +52 -0
  30. package/dist/core/compute/graph.js +162 -0
  31. package/dist/core/data/data.d.ts +59 -0
  32. package/dist/core/data/data.js +119 -0
  33. package/dist/core/data/load.d.ts +37 -0
  34. package/dist/core/data/load.js +236 -0
  35. package/dist/core/env/env.d.ts +468 -0
  36. package/dist/core/env/env.js +916 -0
  37. package/dist/core/env/identity.d.ts +43 -0
  38. package/dist/core/env/identity.js +65 -0
  39. package/dist/core/env/inspector.d.ts +55 -0
  40. package/dist/core/env/inspector.js +85 -0
  41. package/dist/core/env/time.d.ts +12 -0
  42. package/dist/core/env/time.js +38 -0
  43. package/dist/core/errors.d.ts +256 -0
  44. package/dist/core/errors.js +360 -0
  45. package/dist/core/events/events.d.ts +44 -0
  46. package/dist/core/events/events.js +58 -0
  47. package/dist/core/events/workers.d.ts +56 -0
  48. package/dist/core/events/workers.js +155 -0
  49. package/dist/core/index.d.ts +51 -0
  50. package/dist/core/index.js +42 -0
  51. package/dist/core/model/company.d.ts +6 -0
  52. package/dist/core/model/company.js +31 -0
  53. package/dist/core/model/faces.d.ts +42 -0
  54. package/dist/core/model/faces.js +1 -0
  55. package/dist/core/model/field.d.ts +479 -0
  56. package/dist/core/model/field.js +461 -0
  57. package/dist/core/model/generated.d.ts +77 -0
  58. package/dist/core/model/generated.js +1 -0
  59. package/dist/core/model/id.d.ts +33 -0
  60. package/dist/core/model/id.js +4 -0
  61. package/dist/core/model/model.d.ts +387 -0
  62. package/dist/core/model/model.js +566 -0
  63. package/dist/core/model/partition.d.ts +31 -0
  64. package/dist/core/model/partition.js +71 -0
  65. package/dist/core/model/related.d.ts +17 -0
  66. package/dist/core/model/related.js +60 -0
  67. package/dist/core/model/typed.d.ts +107 -0
  68. package/dist/core/model/typed.js +46 -0
  69. package/dist/core/money/currency.d.ts +39 -0
  70. package/dist/core/money/currency.js +37 -0
  71. package/dist/core/money/decimal.d.ts +26 -0
  72. package/dist/core/money/decimal.js +51 -0
  73. package/dist/core/money/fx.d.ts +68 -0
  74. package/dist/core/money/fx.js +124 -0
  75. package/dist/core/money/money.d.ts +84 -0
  76. package/dist/core/money/money.js +173 -0
  77. package/dist/core/money/quantity.d.ts +67 -0
  78. package/dist/core/money/quantity.js +108 -0
  79. package/dist/core/money/rounding.d.ts +11 -0
  80. package/dist/core/money/rounding.js +12 -0
  81. package/dist/core/recordset/aggregate.d.ts +22 -0
  82. package/dist/core/recordset/aggregate.js +258 -0
  83. package/dist/core/recordset/audit.d.ts +33 -0
  84. package/dist/core/recordset/audit.js +262 -0
  85. package/dist/core/recordset/compute.d.ts +36 -0
  86. package/dist/core/recordset/compute.js +414 -0
  87. package/dist/core/recordset/constraints.d.ts +9 -0
  88. package/dist/core/recordset/constraints.js +61 -0
  89. package/dist/core/recordset/domain.d.ts +31 -0
  90. package/dist/core/recordset/domain.js +300 -0
  91. package/dist/core/recordset/onchange.d.ts +43 -0
  92. package/dist/core/recordset/onchange.js +240 -0
  93. package/dist/core/recordset/recordset.d.ts +110 -0
  94. package/dist/core/recordset/recordset.js +789 -0
  95. package/dist/core/recordset/relations.d.ts +15 -0
  96. package/dist/core/recordset/relations.js +13 -0
  97. package/dist/core/recordset/rls.d.ts +15 -0
  98. package/dist/core/recordset/rls.js +108 -0
  99. package/dist/core/recordset/security.d.ts +56 -0
  100. package/dist/core/recordset/security.js +269 -0
  101. package/dist/core/recordset/sequences.d.ts +31 -0
  102. package/dist/core/recordset/sequences.js +154 -0
  103. package/dist/core/recordset/source.d.ts +9 -0
  104. package/dist/core/recordset/source.js +19 -0
  105. package/dist/core/recordset/sqlErrors.d.ts +6 -0
  106. package/dist/core/recordset/sqlErrors.js +39 -0
  107. package/dist/core/recordset/transitions.d.ts +10 -0
  108. package/dist/core/recordset/transitions.js +80 -0
  109. package/dist/core/recordset/types.d.ts +415 -0
  110. package/dist/core/recordset/types.js +8 -0
  111. package/dist/core/recordset/values.d.ts +33 -0
  112. package/dist/core/recordset/values.js +177 -0
  113. package/dist/core/recordset/writes.d.ts +42 -0
  114. package/dist/core/recordset/writes.js +786 -0
  115. package/dist/core/registry/ddl.d.ts +31 -0
  116. package/dist/core/registry/ddl.js +174 -0
  117. package/dist/core/registry/extension.d.ts +94 -0
  118. package/dist/core/registry/extension.js +90 -0
  119. package/dist/core/registry/module.d.ts +89 -0
  120. package/dist/core/registry/module.js +98 -0
  121. package/dist/core/registry/registry.d.ts +130 -0
  122. package/dist/core/registry/registry.js +591 -0
  123. package/dist/core/security/runtime.d.ts +102 -0
  124. package/dist/core/security/runtime.js +232 -0
  125. package/dist/driver-pg/driver.d.ts +88 -0
  126. package/dist/driver-pg/driver.js +177 -0
  127. package/dist/driver-pg/errors.d.ts +72 -0
  128. package/dist/driver-pg/errors.js +182 -0
  129. package/dist/driver-pg/index.d.ts +7 -0
  130. package/dist/driver-pg/index.js +7 -0
  131. package/dist/i18n/index.d.ts +25 -0
  132. package/dist/i18n/index.js +51 -0
  133. package/dist/migrate/apply.d.ts +78 -0
  134. package/dist/migrate/apply.js +167 -0
  135. package/dist/migrate/catalog.d.ts +10 -0
  136. package/dist/migrate/catalog.js +122 -0
  137. package/dist/migrate/diff.d.ts +98 -0
  138. package/dist/migrate/diff.js +160 -0
  139. package/dist/migrate/errors.d.ts +21 -0
  140. package/dist/migrate/errors.js +31 -0
  141. package/dist/migrate/index.d.ts +18 -0
  142. package/dist/migrate/index.js +18 -0
  143. package/dist/migrate/render.d.ts +5 -0
  144. package/dist/migrate/render.js +101 -0
  145. package/dist/migrate/schema.d.ts +61 -0
  146. package/dist/migrate/schema.js +233 -0
  147. package/dist/security/index.d.ts +147 -0
  148. package/dist/security/index.js +278 -0
  149. package/dist/sequence/index.d.ts +63 -0
  150. package/dist/sequence/index.js +106 -0
  151. package/dist/sql/ast.d.ts +49 -0
  152. package/dist/sql/ast.js +47 -0
  153. package/dist/sql/builder/builder.d.ts +215 -0
  154. package/dist/sql/builder/builder.js +308 -0
  155. package/dist/sql/builder/expression.d.ts +80 -0
  156. package/dist/sql/builder/expression.js +126 -0
  157. package/dist/sql/compile.d.ts +18 -0
  158. package/dist/sql/compile.js +41 -0
  159. package/dist/sql/errors.d.ts +13 -0
  160. package/dist/sql/errors.js +16 -0
  161. package/dist/sql/index.d.ts +19 -0
  162. package/dist/sql/index.js +19 -0
  163. package/dist/sql/tag.d.ts +47 -0
  164. package/dist/sql/tag.js +123 -0
  165. package/package.json +82 -4
@@ -0,0 +1,182 @@
1
+ import postgres from 'postgres';
2
+ /**
3
+ * Base class of every error raised by `@shutro/driver-pg`. Same convention as `ShutroError` in `@shutro/core`: the
4
+ * message says what went wrong and ends with {@link DriverError.hint}, which says how to fix it.
5
+ */
6
+ export class DriverError extends Error {
7
+ code;
8
+ hint;
9
+ /** True when re-running the whole transaction may succeed (serialization failure, deadlock). */
10
+ retryable;
11
+ sqlState;
12
+ constraint;
13
+ table;
14
+ column;
15
+ detail;
16
+ constructor(code, problem, hint, details = {}, retryable = false) {
17
+ super(`${problem} ${hint}`, details.cause === undefined ? undefined : { cause: details.cause });
18
+ this.name = new.target.name;
19
+ this.code = code;
20
+ this.hint = hint;
21
+ this.retryable = retryable;
22
+ this.sqlState = details.sqlState;
23
+ this.constraint = details.constraint;
24
+ this.table = details.table;
25
+ this.column = details.column;
26
+ this.detail = details.detail;
27
+ }
28
+ }
29
+ /** A unique, foreign-key, not-null, check or exclusion constraint was violated (SQLSTATE class 23). */
30
+ export class ConstraintViolationError extends DriverError {
31
+ kind;
32
+ constructor(kind, problem, hint, details) {
33
+ super('CONSTRAINT_VIOLATION', problem, hint, details);
34
+ this.kind = kind;
35
+ }
36
+ }
37
+ /** 40001: the transaction conflicted with a concurrent one. Retry the whole transaction. */
38
+ export class SerializationFailureError extends DriverError {
39
+ constructor(details) {
40
+ super('SERIALIZATION_FAILURE', 'The transaction conflicted with a concurrent transaction (serialization failure).', 'Retry the whole transaction; shutro.run() does this automatically (RFC 0003 §7.5).', details, true);
41
+ }
42
+ }
43
+ /** 40P01: deadlock detected. Retry the whole transaction. */
44
+ export class DeadlockError extends DriverError {
45
+ constructor(details) {
46
+ super('DEADLOCK', 'The transaction was chosen as a deadlock victim.', 'Retry the whole transaction; to avoid it, lock records in a consistent order (e.g. by id).', details, true);
47
+ }
48
+ }
49
+ /** 57014: the statement exceeded `statement_timeout`. */
50
+ export class StatementTimeoutError extends DriverError {
51
+ constructor(details) {
52
+ super('STATEMENT_TIMEOUT', 'The statement was cancelled because it exceeded statement_timeout.', 'Add an index, process the data in smaller batches, or raise statementTimeoutMs for this transaction.', details);
53
+ }
54
+ }
55
+ /** 55P03: waiting for a lock exceeded `lock_timeout`. */
56
+ export class LockTimeoutError extends DriverError {
57
+ constructor(details) {
58
+ super('LOCK_TIMEOUT', 'Waiting for a lock exceeded lock_timeout.', 'Another transaction holds the lock: retry later, use FOR UPDATE SKIP LOCKED for queues, or raise lockTimeoutMs.', details);
59
+ }
60
+ }
61
+ /** 25006: a write in a read-only transaction. */
62
+ export class ReadOnlyTransactionError extends DriverError {
63
+ constructor(details) {
64
+ super('READ_ONLY_TRANSACTION', 'A write was attempted in a read-only transaction.', 'Run writes in a read-write transaction (readOnly: false), or move the write out of the report/replica code path.', details);
65
+ }
66
+ }
67
+ /** The server could not be reached, the connection broke, or authentication failed. */
68
+ export class ConnectionError extends DriverError {
69
+ constructor(problem, hint, details) {
70
+ super('CONNECTION_FAILED', problem, hint, details);
71
+ }
72
+ }
73
+ /** Any other PostgreSQL error. */
74
+ export class QueryError extends DriverError {
75
+ constructor(problem, hint, details) {
76
+ super('QUERY_FAILED', problem, hint, details);
77
+ }
78
+ }
79
+ const CONSTRAINT_KINDS = {
80
+ '23505': 'unique',
81
+ '23503': 'foreign_key',
82
+ '23502': 'not_null',
83
+ '23514': 'check',
84
+ '23P01': 'exclusion',
85
+ };
86
+ const CONNECTION_CODES = new Set([
87
+ 'ECONNREFUSED',
88
+ 'ECONNRESET',
89
+ 'ENOTFOUND',
90
+ 'ETIMEDOUT',
91
+ 'EPIPE',
92
+ 'CONNECTION_CLOSED',
93
+ 'CONNECTION_ENDED',
94
+ 'CONNECTION_DESTROYED',
95
+ 'CONNECT_TIMEOUT',
96
+ ]);
97
+ function constraintMessage(kind, d, serverMessage = '') {
98
+ const on = d.table === undefined ? '' : ` on "${d.table}"`;
99
+ const detail = d.detail === undefined ? '' : `${d.detail} `;
100
+ switch (kind) {
101
+ case 'unique':
102
+ return [
103
+ `A record with the same value already exists (unique constraint "${d.constraint ?? '?'}"${on}).`,
104
+ `${detail}Use a different value, or update the existing record instead of creating a new one.`,
105
+ ];
106
+ case 'foreign_key':
107
+ return [
108
+ `The record references a missing record, or is still referenced (foreign key "${d.constraint ?? '?'}"${on}).`,
109
+ `${detail}Check that the referenced record exists, or reassign or delete the records that reference it first.`,
110
+ ];
111
+ case 'not_null':
112
+ return [
113
+ `A required value is missing (column "${d.column ?? '?'}"${on}).`,
114
+ 'Provide a value, or give the field a default.',
115
+ ];
116
+ case 'check':
117
+ if (d.constraint === undefined && /no partition/i.test(serverMessage))
118
+ return [
119
+ `No partition accepts the row${on}.`,
120
+ `${detail}Create the partition for this value first (partitionStatements / rangePartitions), or add a DEFAULT partition.`,
121
+ ];
122
+ return [
123
+ `A value breaks the check constraint "${d.constraint ?? '?'}"${on}.`,
124
+ `${detail}Correct the value so it satisfies the constraint.`,
125
+ ];
126
+ case 'exclusion':
127
+ return [
128
+ `The record overlaps an existing one (exclusion constraint "${d.constraint ?? '?'}"${on}).`,
129
+ `${detail}Change the overlapping range or value.`,
130
+ ];
131
+ }
132
+ }
133
+ /**
134
+ * Maps a postgres.js error to a typed {@link DriverError}. Anything else (including errors thrown by business
135
+ * code and already-mapped errors) is returned unchanged.
136
+ */
137
+ export function mapPostgresError(error) {
138
+ if (error instanceof DriverError)
139
+ return error;
140
+ if (error instanceof postgres.PostgresError) {
141
+ const details = {
142
+ sqlState: error.code,
143
+ constraint: error.constraint_name,
144
+ table: error.table_name,
145
+ column: error.column_name,
146
+ detail: error.detail,
147
+ cause: error,
148
+ };
149
+ const kind = CONSTRAINT_KINDS[error.code];
150
+ if (kind !== undefined) {
151
+ const [problem, hint] = constraintMessage(kind, details, error.message);
152
+ return new ConstraintViolationError(kind, problem, hint, details);
153
+ }
154
+ switch (error.code) {
155
+ case '40001':
156
+ return new SerializationFailureError(details);
157
+ case '40P01':
158
+ return new DeadlockError(details);
159
+ case '57014':
160
+ return new StatementTimeoutError(details);
161
+ case '55P03':
162
+ return new LockTimeoutError(details);
163
+ case '25006':
164
+ return new ReadOnlyTransactionError(details);
165
+ }
166
+ if (/^(08|28|57P0)/.test(error.code)) {
167
+ return new ConnectionError(`PostgreSQL closed or refused the connection (${error.code}: ${error.message}).`, 'Check credentials and that the server is running; the transaction outcome is unknown, so verify before retrying.', details);
168
+ }
169
+ return new QueryError(`PostgreSQL error ${error.code}: ${error.message}.`, error.hint ?? 'See sqlState and detail; this usually means the SQL or the schema is wrong.', details);
170
+ }
171
+ if (error instanceof Error) {
172
+ const code = error.code;
173
+ if (typeof code === 'string' && CONNECTION_CODES.has(code)) {
174
+ return new ConnectionError(`Could not talk to PostgreSQL (${code}: ${error.message}).`, 'Check that the server is running and reachable at the configured URL (host, port, firewall, PgBouncer).', { cause: error });
175
+ }
176
+ }
177
+ return error;
178
+ }
179
+ /** True when `error` is a {@link DriverError} worth retrying as a whole transaction. */
180
+ export function isRetryable(error) {
181
+ return error instanceof DriverError && error.retryable;
182
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/driver-pg`: the PostgreSQL connection layer (RFC 0007). It wraps postgres.js behind a small interface
4
+ * (`Driver`, `DriverConnection`). No other Shutro package imports postgres.js.
5
+ */
6
+ export { createDriver, type Driver, type DriverConnection, type DriverOptions, type DriverQuery, type Isolation, type Row, type TxOptions, } from './driver.js';
7
+ export { ConnectionError, type ConstraintKind, ConstraintViolationError, DeadlockError, DriverError, type DriverErrorCode, type DriverErrorDetails, isRetryable, LockTimeoutError, mapPostgresError, QueryError, ReadOnlyTransactionError, SerializationFailureError, StatementTimeoutError, } from './errors.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/driver-pg`: the PostgreSQL connection layer (RFC 0007). It wraps postgres.js behind a small interface
4
+ * (`Driver`, `DriverConnection`). No other Shutro package imports postgres.js.
5
+ */
6
+ export { createDriver, } from './driver.js';
7
+ export { ConnectionError, ConstraintViolationError, DeadlockError, DriverError, isRetryable, LockTimeoutError, mapPostgresError, QueryError, ReadOnlyTransactionError, SerializationFailureError, StatementTimeoutError, } from './errors.js';
@@ -0,0 +1,25 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/i18n`: the pure rules of translatable fields (RFC 0011). A translatable value is a map from language
4
+ * code to text, stored as JSONB; reading resolves the environment language with a fallback to the source language,
5
+ * writing merges into the map. Core applies these on `translate: true` fields; applications can use them on their
6
+ * own JSON.
7
+ */
8
+ /** Language → text, as stored in a `translate: true` column (`{ "en_US": "Laptop", "bn_BD": "ল্যাপটপ" }`). */
9
+ export type Translations = Readonly<Record<string, string>>;
10
+ /** `en_US`, `bn_BD`, `fr`, `pt_BR`. */
11
+ export declare const LANG_CODE: RegExp;
12
+ /** True for a well-formed language code. */
13
+ export declare function isLangCode(value: unknown): value is string;
14
+ /** True for a plain object whose keys are language codes and whose values are strings. */
15
+ export declare function isTranslations(value: unknown): value is Translations;
16
+ /**
17
+ * The text to show for `lang`: the language itself, then the source language, then the first translation by sorted
18
+ * language code (so a record translated only in `fr_FR` still shows something), else `null`.
19
+ */
20
+ export declare function resolveTranslation(value: Translations | null | undefined, lang: string, source: string): string | null;
21
+ /**
22
+ * The map after writing `value` in `lang`: a string sets that language (and the source language when the record has
23
+ * no source text yet, so readers of other languages see the new text); a map sets every language it names.
24
+ */
25
+ export declare function mergeTranslation(existing: Translations | null | undefined, value: string | Translations, lang: string, source: string): Translations;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * `@shutro/i18n`: the pure rules of translatable fields (RFC 0011). A translatable value is a map from language
4
+ * code to text, stored as JSONB; reading resolves the environment language with a fallback to the source language,
5
+ * writing merges into the map. Core applies these on `translate: true` fields; applications can use them on their
6
+ * own JSON.
7
+ */
8
+ /** `en_US`, `bn_BD`, `fr`, `pt_BR`. */
9
+ export const LANG_CODE = /^[a-z]{2,3}(_[A-Z]{2})?$/;
10
+ /** True for a well-formed language code. */
11
+ export function isLangCode(value) {
12
+ return typeof value === 'string' && LANG_CODE.test(value);
13
+ }
14
+ /** True for a plain object whose keys are language codes and whose values are strings. */
15
+ export function isTranslations(value) {
16
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
17
+ return false;
18
+ return Object.entries(value).every(([k, v]) => isLangCode(k) && typeof v === 'string');
19
+ }
20
+ /**
21
+ * The text to show for `lang`: the language itself, then the source language, then the first translation by sorted
22
+ * language code (so a record translated only in `fr_FR` still shows something), else `null`.
23
+ */
24
+ export function resolveTranslation(value, lang, source) {
25
+ if (value === null || value === undefined)
26
+ return null;
27
+ const own = value[lang];
28
+ if (own !== undefined)
29
+ return own;
30
+ const fallback = value[source];
31
+ if (fallback !== undefined)
32
+ return fallback;
33
+ const first = Object.keys(value).sort()[0];
34
+ return first === undefined ? null : (value[first] ?? null);
35
+ }
36
+ /**
37
+ * The map after writing `value` in `lang`: a string sets that language (and the source language when the record has
38
+ * no source text yet, so readers of other languages see the new text); a map sets every language it names.
39
+ */
40
+ export function mergeTranslation(existing, value, lang, source) {
41
+ const base = { ...(existing ?? {}) };
42
+ if (typeof value === 'string') {
43
+ if (base[source] === undefined)
44
+ base[source] = value;
45
+ base[lang] = value;
46
+ return Object.freeze(base);
47
+ }
48
+ for (const [k, v] of Object.entries(value))
49
+ base[k] = v;
50
+ return Object.freeze(base);
51
+ }
@@ -0,0 +1,78 @@
1
+ import { type Registry } from '../core/index.js';
2
+ import type { Driver } from '../driver-pg/index.js';
3
+ import { type Operation } from './diff.js';
4
+ /** A planned migration: operations, the destructive subset, and the rendered statements. */
5
+ export interface MigrationPlan {
6
+ readonly operations: readonly Operation[];
7
+ readonly destructive: readonly Operation[];
8
+ /** Statements with their destructiveness, in execution order. */
9
+ readonly statements: readonly {
10
+ readonly sql: string;
11
+ readonly destructive: boolean;
12
+ }[];
13
+ }
14
+ /** Compares the registry with the live database and plans the changes. */
15
+ export declare function planMigration(options: {
16
+ readonly driver: Driver;
17
+ readonly registry: Registry;
18
+ readonly schema?: string;
19
+ }): Promise<MigrationPlan>;
20
+ /** A migration file on disk. */
21
+ export interface MigrationFile {
22
+ readonly version: string;
23
+ readonly name: string;
24
+ readonly path: string;
25
+ }
26
+ /** Writes the plan as the next versioned file (`0001_name.sql`). */
27
+ export declare function writeMigrationFile(options: {
28
+ readonly dir: string;
29
+ readonly name: string;
30
+ readonly plan: MigrationPlan;
31
+ }): Promise<MigrationFile>;
32
+ /** Parses a migration file into statements (comments dropped; `-- destructive` marks the next statement). */
33
+ export declare function parseMigrationFile(content: string): {
34
+ readonly sql: string;
35
+ readonly destructive: boolean;
36
+ }[];
37
+ /** Applied and pending migrations. */
38
+ export interface MigrationStatus {
39
+ readonly applied: readonly {
40
+ readonly version: string;
41
+ readonly name: string;
42
+ readonly appliedAt: Date;
43
+ }[];
44
+ readonly pending: readonly MigrationFile[];
45
+ }
46
+ /** Reads the ledger and the directory. @throws {MigrationChecksumError} when an applied file was edited. */
47
+ export declare function migrationStatus(options: {
48
+ readonly driver: Driver;
49
+ readonly dir: string;
50
+ }): Promise<MigrationStatus>;
51
+ /** Result of {@link applyMigrations}. */
52
+ export interface MigrationResult {
53
+ readonly applied: readonly MigrationFile[];
54
+ /** Modules whose recorded version changed (fresh installs have `from: null`). */
55
+ readonly modules: readonly {
56
+ readonly module: string;
57
+ readonly from: string | null;
58
+ readonly to: string;
59
+ }[];
60
+ /** Data-migration hooks that ran, in order. */
61
+ readonly hooks: readonly {
62
+ readonly module: string;
63
+ readonly version: string;
64
+ }[];
65
+ }
66
+ /**
67
+ * Applies pending migration files in order (each in its own transaction, recorded in `shutro_migration`), then runs
68
+ * the data-migration hooks of upgraded modules and records module versions in `shutro_module`.
69
+ *
70
+ * @throws {DestructiveMigrationError} for a file with destructive statements unless `allowDestructive` is set.
71
+ * @throws {MigrationChecksumError} when an applied file was edited.
72
+ */
73
+ export declare function applyMigrations(options: {
74
+ readonly driver: Driver;
75
+ readonly dir: string;
76
+ readonly registry: Registry;
77
+ readonly allowDestructive?: boolean;
78
+ }): Promise<MigrationResult>;
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Planning, versioned migration files, the ledger, and module data-migration hooks.
3
+ */
4
+ import { createHash } from 'node:crypto';
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { compareVersions } from '../core/index.js';
8
+ import { compile, sql } from '../sql/index.js';
9
+ import { readLiveSchema } from './catalog.js';
10
+ import { diffSchema } from './diff.js';
11
+ import { DestructiveMigrationError, MigrationChecksumError, MigrationFileError } from './errors.js';
12
+ import { renderOperation } from './render.js';
13
+ import { desiredSchema } from './schema.js';
14
+ /** Compares the registry with the live database and plans the changes. */
15
+ export async function planMigration(options) {
16
+ const live = await readLiveSchema(options.driver, options.schema ?? 'public');
17
+ const operations = diffSchema(desiredSchema(options.registry), live);
18
+ return {
19
+ operations,
20
+ destructive: operations.filter((o) => o.destructive),
21
+ statements: operations.map((o) => ({ sql: renderOperation(o), destructive: o.destructive })),
22
+ };
23
+ }
24
+ const FILE = /^(\d{4})_([a-z0-9_]+)\.sql$/;
25
+ const DESTRUCTIVE_MARK = '-- destructive';
26
+ function listFiles(dir) {
27
+ if (!existsSync(dir))
28
+ return [];
29
+ return readdirSync(dir)
30
+ .filter((f) => FILE.test(f))
31
+ .sort()
32
+ .map((f) => {
33
+ const m = FILE.exec(f);
34
+ return { version: m[1], name: m[2], path: join(dir, f) };
35
+ });
36
+ }
37
+ /** Writes the plan as the next versioned file (`0001_name.sql`). */
38
+ export async function writeMigrationFile(options) {
39
+ const { dir, name, plan } = options;
40
+ if (!/^[a-z0-9_]+$/.test(name))
41
+ throw new MigrationFileError(`${JSON.stringify(name)} is not a migration name.`, 'Use lower-case letters, digits and underscores, e.g. "add_sale_margin".');
42
+ mkdirSync(dir, { recursive: true });
43
+ const existing = listFiles(dir);
44
+ const version = String(Number(existing.at(-1)?.version ?? '0') + 1).padStart(4, '0');
45
+ const lines = [
46
+ `-- shutro migration ${version}: ${name} (generated ${new Date().toISOString()})`,
47
+ `-- ${plan.statements.length} statement(s), ${plan.destructive.length} destructive`,
48
+ '',
49
+ ];
50
+ for (const s of plan.statements) {
51
+ if (s.destructive)
52
+ lines.push(DESTRUCTIVE_MARK);
53
+ lines.push(`${s.sql};`, '');
54
+ }
55
+ const path = join(dir, `${version}_${name}.sql`);
56
+ writeFileSync(path, `${lines.join('\n')}\n`);
57
+ return { version, name, path };
58
+ }
59
+ /** Parses a migration file into statements (comments dropped; `-- destructive` marks the next statement). */
60
+ export function parseMigrationFile(content) {
61
+ const statements = [];
62
+ let buffer = [];
63
+ let destructive = false;
64
+ for (const raw of content.split('\n')) {
65
+ const line = raw.trimEnd();
66
+ if (line.trim() === DESTRUCTIVE_MARK) {
67
+ destructive = true;
68
+ continue;
69
+ }
70
+ if (line.trim().startsWith('--') || line.trim() === '')
71
+ continue;
72
+ buffer.push(line);
73
+ if (line.endsWith(';')) {
74
+ statements.push({ sql: buffer.join('\n').slice(0, -1), destructive });
75
+ buffer = [];
76
+ destructive = false;
77
+ }
78
+ }
79
+ if (buffer.length > 0)
80
+ statements.push({ sql: buffer.join('\n'), destructive });
81
+ return statements;
82
+ }
83
+ function checksum(content) {
84
+ return createHash('sha256').update(content).digest('hex');
85
+ }
86
+ async function ensureLedger(conn) {
87
+ await conn.query({
88
+ text: 'CREATE TABLE IF NOT EXISTS "shutro_migration" ("version" text PRIMARY KEY, "name" text NOT NULL, "checksum" text NOT NULL, "applied_at" timestamp with time zone NOT NULL DEFAULT now())',
89
+ params: [],
90
+ });
91
+ await conn.query({
92
+ text: 'CREATE TABLE IF NOT EXISTS "shutro_module" ("name" text PRIMARY KEY, "version" text NOT NULL, "installed_at" timestamp with time zone NOT NULL DEFAULT now(), "updated_at" timestamp with time zone NOT NULL DEFAULT now())',
93
+ params: [],
94
+ });
95
+ }
96
+ /** Reads the ledger and the directory. @throws {MigrationChecksumError} when an applied file was edited. */
97
+ export async function migrationStatus(options) {
98
+ const files = listFiles(options.dir);
99
+ return options.driver.transaction({ isolation: 'read committed' }, async (conn) => {
100
+ await ensureLedger(conn);
101
+ const rows = await conn.query(compile(sql `SELECT version, name, checksum, applied_at FROM ${sql.id('shutro_migration')} ORDER BY version`));
102
+ const byVersion = new Map(rows.map((r) => [r.version, r]));
103
+ for (const file of files) {
104
+ const row = byVersion.get(file.version);
105
+ if (row !== undefined && row.checksum !== checksum(readFileSync(file.path, 'utf8')))
106
+ throw new MigrationChecksumError(file.path);
107
+ }
108
+ return {
109
+ applied: rows.map((r) => ({ version: r.version, name: r.name, appliedAt: r.applied_at })),
110
+ pending: files.filter((f) => !byVersion.has(f.version)),
111
+ };
112
+ });
113
+ }
114
+ /**
115
+ * Applies pending migration files in order (each in its own transaction, recorded in `shutro_migration`), then runs
116
+ * the data-migration hooks of upgraded modules and records module versions in `shutro_module`.
117
+ *
118
+ * @throws {DestructiveMigrationError} for a file with destructive statements unless `allowDestructive` is set.
119
+ * @throws {MigrationChecksumError} when an applied file was edited.
120
+ */
121
+ export async function applyMigrations(options) {
122
+ const { driver, registry } = options;
123
+ const status = await migrationStatus({ driver, dir: options.dir });
124
+ const applied = [];
125
+ for (const file of status.pending) {
126
+ const content = readFileSync(file.path, 'utf8');
127
+ const statements = parseMigrationFile(content);
128
+ const destructive = statements.filter((s) => s.destructive).map((s) => s.sql);
129
+ if (destructive.length > 0 && options.allowDestructive !== true)
130
+ throw new DestructiveMigrationError(file.path, destructive);
131
+ await driver.transaction({ isolation: 'read committed' }, async (conn) => {
132
+ for (const s of statements)
133
+ await conn.query({ text: s.sql, params: [] });
134
+ await conn.query(compile(sql `INSERT INTO ${sql.id('shutro_migration')} (version, name, checksum) VALUES (${file.version}, ${file.name}, ${checksum(content)})`));
135
+ });
136
+ applied.push(file);
137
+ }
138
+ const modules = [];
139
+ const hooks = [];
140
+ for (const module of registry.modules) {
141
+ await driver.transaction({ isolation: 'read committed' }, async (conn) => {
142
+ await ensureLedger(conn);
143
+ const [row] = await conn.query(compile(sql `SELECT version FROM ${sql.id('shutro_module')} WHERE name = ${module.name}`));
144
+ if (row === undefined) {
145
+ await conn.query(compile(sql `INSERT INTO ${sql.id('shutro_module')} (name, version) VALUES (${module.name}, ${module.version})`));
146
+ modules.push({ module: module.name, from: null, to: module.version });
147
+ return;
148
+ }
149
+ if (compareVersions(row.version, module.version) >= 0)
150
+ return;
151
+ const ctx = {
152
+ registry,
153
+ sql: (strings, ...values) => conn.query(compile(sql(strings, ...values))),
154
+ };
155
+ for (const hook of module.migrations) {
156
+ if (compareVersions(hook.version, row.version) <= 0 ||
157
+ compareVersions(hook.version, module.version) > 0)
158
+ continue;
159
+ await hook.up(ctx);
160
+ hooks.push({ module: module.name, version: hook.version });
161
+ }
162
+ await conn.query(compile(sql `UPDATE ${sql.id('shutro_module')} SET version = ${module.version}, updated_at = now() WHERE name = ${module.name}`));
163
+ modules.push({ module: module.name, from: row.version, to: module.version });
164
+ });
165
+ }
166
+ return { applied, modules, hooks };
167
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Reads the live schema of a PostgreSQL schema (namespace) from `pg_catalog` into the same shape as the desired
3
+ * schema. The migration ledger tables (`shutro_*`) are left out.
4
+ */
5
+ import type { Driver } from '../driver-pg/index.js';
6
+ import type { LiveSchema } from './schema.js';
7
+ /** `'x'::character varying` → `'x'`, `(0)::numeric` → `0`, `now()` unchanged. */
8
+ export declare function normalizeDefault(expression: string | null): string | null;
9
+ /** Reads tables, columns, constraints and indexes of `schema` (default `public`). */
10
+ export declare function readLiveSchema(driver: Driver, schema?: string): Promise<LiveSchema>;
@@ -0,0 +1,122 @@
1
+ import { compile, sql } from '../sql/index.js';
2
+ const ON_DELETE = {
3
+ a: 'NO ACTION',
4
+ r: 'RESTRICT',
5
+ c: 'CASCADE',
6
+ n: 'SET NULL',
7
+ };
8
+ /** `'x'::character varying` → `'x'`, `(0)::numeric` → `0`, `now()` unchanged. */
9
+ export function normalizeDefault(expression) {
10
+ if (expression === null)
11
+ return null;
12
+ let e = expression.trim();
13
+ e = e.replace(/::[a-z_ ]+(\([^)]*\))?(\[\])?$/i, '');
14
+ while (e.startsWith('(') && e.endsWith(')'))
15
+ e = e.slice(1, -1);
16
+ return e;
17
+ }
18
+ /** Reads tables, columns, constraints and indexes of `schema` (default `public`). */
19
+ export async function readLiveSchema(driver, schema = 'public') {
20
+ const tables = {};
21
+ const tableRows = await driver.query(compile(sql `SELECT c.relname AS name FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p') AND NOT c.relispartition ORDER BY c.relname`));
22
+ for (const { name } of tableRows) {
23
+ if (name.startsWith('shutro_'))
24
+ continue;
25
+ tables[name] = {
26
+ columns: {},
27
+ primaryKey: [],
28
+ foreignKeys: {},
29
+ uniques: {},
30
+ checks: {},
31
+ indexes: {},
32
+ };
33
+ }
34
+ const columnRows = await driver.query(compile(sql `SELECT c.relname AS "table", a.attname AS name, format_type(a.atttypid, a.atttypmod) AS type, a.attnotnull AS notnull, a.attidentity AS identity,
35
+ pg_get_expr(d.adbin, d.adrelid) AS def
36
+ FROM pg_attribute a
37
+ JOIN pg_class c ON c.oid = a.attrelid
38
+ JOIN pg_namespace n ON n.oid = c.relnamespace
39
+ LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
40
+ WHERE n.nspname = ${schema} AND c.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
41
+ ORDER BY c.relname, a.attnum`));
42
+ for (const row of columnRows) {
43
+ const table = tables[row.table];
44
+ if (table === undefined)
45
+ continue;
46
+ table.columns[row.name] = {
47
+ name: row.name,
48
+ type: row.type,
49
+ nullable: !row.notnull,
50
+ default: normalizeDefault(row.def),
51
+ identity: row.identity === 'a' || row.identity === 'd',
52
+ backfill: null,
53
+ };
54
+ }
55
+ const constraintRows = await driver.query(compile(sql `SELECT c.relname AS "table", con.conname AS name, con.contype AS type, pg_get_constraintdef(con.oid) AS def, con.confdeltype AS ondelete,
56
+ (SELECT array_agg(a.attname ORDER BY k.ordinality) FROM unnest(con.conkey) WITH ORDINALITY AS k(attnum, ordinality)
57
+ JOIN pg_attribute a ON a.attrelid = con.conrelid AND a.attnum = k.attnum) AS columns,
58
+ fc.relname AS ftable
59
+ FROM pg_constraint con
60
+ JOIN pg_class c ON c.oid = con.conrelid
61
+ JOIN pg_namespace n ON n.oid = c.relnamespace
62
+ LEFT JOIN pg_class fc ON fc.oid = con.confrelid
63
+ WHERE n.nspname = ${schema}
64
+ ORDER BY c.relname, con.conname`));
65
+ for (const row of constraintRows) {
66
+ const table = tables[row.table];
67
+ if (table === undefined)
68
+ continue;
69
+ const columns = row.columns ?? [];
70
+ switch (row.type) {
71
+ case 'p':
72
+ table.primaryKey = columns;
73
+ break;
74
+ case 'f':
75
+ table.foreignKeys[row.name] = {
76
+ column: columns[0] ?? '',
77
+ references: row.ftable ?? '',
78
+ onDelete: ON_DELETE[row.ondelete ?? 'a'] ?? 'NO ACTION',
79
+ };
80
+ break;
81
+ case 'u':
82
+ table.uniques[row.name] = columns;
83
+ break;
84
+ case 'c':
85
+ table.checks[row.name] = row.def.replace(/^CHECK \((.*)\)$/s, '$1');
86
+ break;
87
+ default:
88
+ break;
89
+ }
90
+ }
91
+ const indexRows = await driver.query(compile(sql `SELECT t.relname AS "table", i.relname AS name, ix.indisunique AS "unique", am.amname AS method,
92
+ (SELECT array_agg(a.attname ORDER BY k.ordinality) FROM unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ordinality)
93
+ JOIN pg_attribute a ON a.attrelid = ix.indrelid AND a.attnum = k.attnum) AS columns,
94
+ pg_get_indexdef(ix.indexrelid) AS def, ix.indpred IS NOT NULL AS partial
95
+ FROM pg_index ix
96
+ JOIN pg_class i ON i.oid = ix.indexrelid
97
+ JOIN pg_class t ON t.oid = ix.indrelid
98
+ JOIN pg_namespace n ON n.oid = t.relnamespace
99
+ JOIN pg_am am ON am.oid = i.relam
100
+ WHERE n.nspname = ${schema} AND NOT ix.indisprimary
101
+ AND NOT EXISTS (SELECT 1 FROM pg_constraint con WHERE con.conindid = ix.indexrelid)
102
+ ORDER BY t.relname, i.relname`));
103
+ for (const row of indexRows) {
104
+ const table = tables[row.table];
105
+ if (table === undefined)
106
+ continue;
107
+ const opclass = /gin_trgm_ops/.test(row.def) ? 'gin_trgm_ops' : undefined;
108
+ const where = row.partial ? (/ WHERE \((.*)\)$/s.exec(row.def)?.[1] ?? '') : undefined;
109
+ table.indexes[row.name] = {
110
+ columns: row.columns ?? [],
111
+ unique: row.unique,
112
+ method: row.method,
113
+ ...(opclass === undefined ? {} : { opclass }),
114
+ ...(where === undefined ? {} : { where }),
115
+ };
116
+ }
117
+ const extensionRows = await driver.query(compile(sql `SELECT extname AS name FROM pg_extension ORDER BY extname`));
118
+ const result = {};
119
+ for (const [name, t] of Object.entries(tables))
120
+ result[name] = { name, ...t };
121
+ return { tables: result, extensions: extensionRows.map((r) => r.name) };
122
+ }