@c9up/atlas 0.1.3 → 0.1.4
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.
- package/db.darwin-arm64.node +0 -0
- package/db.darwin-x64.node +0 -0
- package/db.linux-arm64-gnu.node +0 -0
- package/db.linux-x64-gnu.node +0 -0
- package/db.win32-x64-msvc.node +0 -0
- package/dist/AtlasProvider.d.ts +106 -0
- package/dist/AtlasProvider.d.ts.map +1 -0
- package/dist/AtlasProvider.js +190 -0
- package/dist/AtlasProvider.js.map +1 -0
- package/dist/BaseEntity.d.ts +255 -0
- package/dist/BaseEntity.d.ts.map +1 -0
- package/dist/BaseEntity.js +420 -0
- package/dist/BaseEntity.js.map +1 -0
- package/dist/BaseRepository.d.ts +175 -0
- package/dist/BaseRepository.d.ts.map +1 -0
- package/dist/BaseRepository.js +1394 -0
- package/dist/BaseRepository.js.map +1 -0
- package/dist/ModelQuery.d.ts +338 -0
- package/dist/ModelQuery.d.ts.map +1 -0
- package/dist/ModelQuery.js +1598 -0
- package/dist/ModelQuery.js.map +1 -0
- package/dist/Transaction.d.ts +15 -0
- package/dist/Transaction.d.ts.map +1 -0
- package/dist/Transaction.js +67 -0
- package/dist/Transaction.js.map +1 -0
- package/dist/adapters/NapiDbAdapter.d.ts +34 -0
- package/dist/adapters/NapiDbAdapter.d.ts.map +1 -0
- package/dist/adapters/NapiDbAdapter.js +96 -0
- package/dist/adapters/NapiDbAdapter.js.map +1 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +4 -0
- package/dist/config.js.map +1 -0
- package/dist/configure.d.ts +10 -0
- package/dist/configure.d.ts.map +1 -0
- package/dist/configure.js +25 -0
- package/dist/configure.js.map +1 -0
- package/dist/decorators/entity.d.ts +235 -0
- package/dist/decorators/entity.d.ts.map +1 -0
- package/dist/decorators/entity.js +264 -0
- package/dist/decorators/entity.js.map +1 -0
- package/dist/decorators/hooks.d.ts +70 -0
- package/dist/decorators/hooks.d.ts.map +1 -0
- package/dist/decorators/hooks.js +107 -0
- package/dist/decorators/hooks.js.map +1 -0
- package/dist/decorators/scope.d.ts +35 -0
- package/dist/decorators/scope.d.ts.map +1 -0
- package/dist/decorators/scope.js +29 -0
- package/dist/decorators/scope.js.map +1 -0
- package/dist/errors.d.ts +54 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +82 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +39 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +28 -0
- package/dist/index.js.map +1 -0
- package/dist/naming/NamingStrategy.d.ts +52 -0
- package/dist/naming/NamingStrategy.d.ts.map +1 -0
- package/dist/naming/NamingStrategy.js +65 -0
- package/dist/naming/NamingStrategy.js.map +1 -0
- package/dist/query/QueryBuilder.d.ts +95 -0
- package/dist/query/QueryBuilder.d.ts.map +1 -0
- package/dist/query/QueryBuilder.js +310 -0
- package/dist/query/QueryBuilder.js.map +1 -0
- package/dist/query/native.d.ts +18 -0
- package/dist/query/native.d.ts.map +1 -0
- package/dist/query/native.js +49 -0
- package/dist/query/native.js.map +1 -0
- package/dist/schema/Migration.d.ts +55 -0
- package/dist/schema/Migration.d.ts.map +1 -0
- package/dist/schema/Migration.js +68 -0
- package/dist/schema/Migration.js.map +1 -0
- package/dist/schema/MigrationRunner.d.ts +115 -0
- package/dist/schema/MigrationRunner.d.ts.map +1 -0
- package/dist/schema/MigrationRunner.js +402 -0
- package/dist/schema/MigrationRunner.js.map +1 -0
- package/dist/schema/Schema.d.ts +22 -0
- package/dist/schema/Schema.d.ts.map +1 -0
- package/dist/schema/Schema.js +51 -0
- package/dist/schema/Schema.js.map +1 -0
- package/dist/schema/SchemaBuilder.d.ts +14 -0
- package/dist/schema/SchemaBuilder.d.ts.map +1 -0
- package/dist/schema/SchemaBuilder.js +13 -0
- package/dist/schema/SchemaBuilder.js.map +1 -0
- package/dist/schema/Seeder.d.ts +54 -0
- package/dist/schema/Seeder.d.ts.map +1 -0
- package/dist/schema/Seeder.js +89 -0
- package/dist/schema/Seeder.js.map +1 -0
- package/dist/schema/TableBuilder.d.ts +86 -0
- package/dist/schema/TableBuilder.d.ts.map +1 -0
- package/dist/schema/TableBuilder.js +211 -0
- package/dist/schema/TableBuilder.js.map +1 -0
- package/dist/schema/types.d.ts +28 -0
- package/dist/schema/types.d.ts.map +1 -0
- package/dist/schema/types.js +19 -0
- package/dist/schema/types.js.map +1 -0
- package/dist/services/db.d.ts +22 -0
- package/dist/services/db.d.ts.map +1 -0
- package/dist/services/db.js +37 -0
- package/dist/services/db.js.map +1 -0
- package/dist/testing/DatabaseCleanup.d.ts +19 -0
- package/dist/testing/DatabaseCleanup.d.ts.map +1 -0
- package/dist/testing/DatabaseCleanup.js +40 -0
- package/dist/testing/DatabaseCleanup.js.map +1 -0
- package/dist/testing/Factory.d.ts +59 -0
- package/dist/testing/Factory.d.ts.map +1 -0
- package/dist/testing/Factory.js +105 -0
- package/dist/testing/Factory.js.map +1 -0
- package/dist/testing/TestDatabase.d.ts +25 -0
- package/dist/testing/TestDatabase.d.ts.map +1 -0
- package/dist/testing/TestDatabase.js +52 -0
- package/dist/testing/TestDatabase.js.map +1 -0
- package/dist/testing/index.d.ts +4 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +4 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/utils/casing.d.ts +5 -0
- package/dist/utils/casing.d.ts.map +1 -0
- package/dist/utils/casing.js +9 -0
- package/dist/utils/casing.js.map +1 -0
- package/dist/utils/dialectFromUrl.d.ts +10 -0
- package/dist/utils/dialectFromUrl.d.ts.map +1 -0
- package/dist/utils/dialectFromUrl.js +8 -0
- package/dist/utils/dialectFromUrl.js.map +1 -0
- package/dist/utils/identifier.d.ts +19 -0
- package/dist/utils/identifier.d.ts.map +1 -0
- package/dist/utils/identifier.js +27 -0
- package/dist/utils/identifier.js.map +1 -0
- package/dist/utils/safePath.d.ts +22 -0
- package/dist/utils/safePath.d.ts.map +1 -0
- package/dist/utils/safePath.js +46 -0
- package/dist/utils/safePath.js.map +1 -0
- package/dist/utils/transactionBrand.d.ts +5 -0
- package/dist/utils/transactionBrand.d.ts.map +1 -0
- package/dist/utils/transactionBrand.js +5 -0
- package/dist/utils/transactionBrand.js.map +1 -0
- package/index.darwin-arm64.node +0 -0
- package/index.darwin-x64.node +0 -0
- package/index.linux-arm64-gnu.node +0 -0
- package/index.linux-x64-gnu.node +0 -0
- package/index.win32-x64-msvc.node +0 -0
- package/package.json +1 -1
package/db.darwin-arm64.node
CHANGED
|
Binary file
|
package/db.darwin-x64.node
CHANGED
|
Binary file
|
package/db.linux-arm64-gnu.node
CHANGED
|
Binary file
|
package/db.linux-x64-gnu.node
CHANGED
|
Binary file
|
package/db.win32-x64-msvc.node
CHANGED
|
Binary file
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AtlasProvider — Ream provider for the Atlas ORM.
|
|
3
|
+
*
|
|
4
|
+
* Connects to one or more databases via the Rust ream-db driver
|
|
5
|
+
* (SQLite/PostgreSQL/MySQL). Runs migrations on boot for the default
|
|
6
|
+
* connection.
|
|
7
|
+
*
|
|
8
|
+
* Multi-connection support (story 32.9):
|
|
9
|
+
*
|
|
10
|
+
* // config/database.ts
|
|
11
|
+
* export default {
|
|
12
|
+
* default: 'primary',
|
|
13
|
+
* connections: {
|
|
14
|
+
* primary: { url: 'postgres://.../primary' },
|
|
15
|
+
* tenant1: { url: 'postgres://.../tenant1' },
|
|
16
|
+
* },
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* // Code
|
|
20
|
+
* const primary = app.container.resolve('db') // default
|
|
21
|
+
* const tenant1 = app.container.resolve('db:tenant1') // named
|
|
22
|
+
*/
|
|
23
|
+
/**
|
|
24
|
+
* Structural slice of the host framework's app context — only the surface
|
|
25
|
+
* AtlasProvider actually uses. Declared locally so atlas does NOT import
|
|
26
|
+
* `@c9up/ream`; any framework whose context exposes a `config.get(key)`
|
|
27
|
+
* reader and a `container.singleton(token, factory)` binder satisfies this
|
|
28
|
+
* contract via TypeScript structural compatibility.
|
|
29
|
+
*
|
|
30
|
+
* The `token` type mirrors ream's `ServiceToken` union (`string | symbol |
|
|
31
|
+
* ctor`) so AtlasProvider can grow into class-as-token / Symbol-keyed
|
|
32
|
+
* bindings without re-coupling to `@c9up/ream`. AtlasProvider itself only
|
|
33
|
+
* uses `string` tokens today.
|
|
34
|
+
*/
|
|
35
|
+
export interface AtlasAppContext {
|
|
36
|
+
container: {
|
|
37
|
+
singleton(token: string | symbol | (new (...args: never[]) => unknown), factory: () => unknown): void;
|
|
38
|
+
};
|
|
39
|
+
config: {
|
|
40
|
+
get<T = unknown>(key: string): T | undefined;
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Canonical sqlite production pragma recipe.
|
|
45
|
+
*
|
|
46
|
+
* journal_mode = WAL // writes go to a side-log, readers don't block
|
|
47
|
+
* synchronous = NORMAL // one fsync per commit (on the WAL); recovery
|
|
48
|
+
* // still rebuilds a consistent DB after crash
|
|
49
|
+
*
|
|
50
|
+
* Drops INSERT latency by ~5–10x vs sqlite's default
|
|
51
|
+
* (`journal_mode=delete` + `synchronous=FULL`) without sacrificing
|
|
52
|
+
* durability. Spread the constant into `pragmas` so app-specific overrides
|
|
53
|
+
* stay literal:
|
|
54
|
+
*
|
|
55
|
+
* pragmas: { ...SQLITE_PROD_PRAGMAS, foreign_keys: "ON" }
|
|
56
|
+
*/
|
|
57
|
+
export declare const SQLITE_PROD_PRAGMAS: Readonly<{
|
|
58
|
+
readonly journal_mode: "WAL";
|
|
59
|
+
readonly synchronous: "NORMAL";
|
|
60
|
+
}>;
|
|
61
|
+
/** One connection's settings. */
|
|
62
|
+
export interface ConnectionConfig {
|
|
63
|
+
/** Connection URL: "sqlite:data/app.db", "postgres://...", "mysql://..." */
|
|
64
|
+
url: string;
|
|
65
|
+
/** Minimum pool connections (default: 1) */
|
|
66
|
+
poolMin?: number;
|
|
67
|
+
/** Maximum pool connections (default: 10) */
|
|
68
|
+
poolMax?: number;
|
|
69
|
+
/**
|
|
70
|
+
* Connection-level pragmas (sqlite only). Each entry becomes a
|
|
71
|
+
* `PRAGMA <key> = <value>;` issued before the first query.
|
|
72
|
+
*
|
|
73
|
+
* Most apps want `{ journal_mode: "WAL", synchronous: "NORMAL" }` —
|
|
74
|
+
* disk-backed, durable, and ~5–10x faster than the default
|
|
75
|
+
* `journal_mode=delete` + `synchronous=FULL` (two fsyncs per
|
|
76
|
+
* commit). Ignored for postgres / mysql URLs.
|
|
77
|
+
*/
|
|
78
|
+
pragmas?: Record<string, string | number>;
|
|
79
|
+
}
|
|
80
|
+
/** Full database config — single-connection (legacy) OR multi-connection. */
|
|
81
|
+
export interface AtlasDatabaseConfig extends ConnectionConfig {
|
|
82
|
+
/** Name of the default connection when `connections` is set. Defaults to `"primary"`. */
|
|
83
|
+
default?: string;
|
|
84
|
+
/** Named connections. When present, top-level `url` is treated as `connections[default].url`. */
|
|
85
|
+
connections?: Record<string, ConnectionConfig>;
|
|
86
|
+
migrations?: {
|
|
87
|
+
path?: string;
|
|
88
|
+
/**
|
|
89
|
+
* Custom name for the migrations tracking table. Defaults to `"_migrations"`.
|
|
90
|
+
* Must match `/^[A-Za-z_][A-Za-z0-9_]*$/` — the `MigrationRunner` constructor
|
|
91
|
+
* throws `AtlasError("MIGRATION_INVALID_TABLE_NAME")` otherwise.
|
|
92
|
+
*/
|
|
93
|
+
table?: string;
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
export default class AtlasProvider {
|
|
97
|
+
#private;
|
|
98
|
+
protected app: AtlasAppContext;
|
|
99
|
+
constructor(app: AtlasAppContext);
|
|
100
|
+
register(): void;
|
|
101
|
+
boot(): Promise<void>;
|
|
102
|
+
shutdown(): Promise<void>;
|
|
103
|
+
start(): Promise<void>;
|
|
104
|
+
ready(): Promise<void>;
|
|
105
|
+
}
|
|
106
|
+
//# sourceM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OAAO,OAAO,aAAa;;IAKrB,SAAS,CAAC,GAAG,EAAE,eAAe;gBAApB,GAAG,EAAE,eAAe;IAE1C,QAAQ;IAEF,IAAI;IAyFJ,QAAQ;IA6BR,KAAK;IACL,KAAK;CAwDX"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AtlasProvider — Ream provider for the Atlas ORM.
|
|
3
|
+
*
|
|
4
|
+
* Connects to one or more databases via the Rust ream-db driver
|
|
5
|
+
* (SQLite/PostgreSQL/MySQL). Runs migrations on boot for the default
|
|
6
|
+
* connection.
|
|
7
|
+
*
|
|
8
|
+
* Multi-connection support (story 32.9):
|
|
9
|
+
*
|
|
10
|
+
* // config/database.ts
|
|
11
|
+
* export default {
|
|
12
|
+
* default: 'primary',
|
|
13
|
+
* connections: {
|
|
14
|
+
* primary: { url: 'postgres://.../primary' },
|
|
15
|
+
* tenant1: { url: 'postgres://.../tenant1' },
|
|
16
|
+
* },
|
|
17
|
+
* }
|
|
18
|
+
*
|
|
19
|
+
* // Code
|
|
20
|
+
* const primary = app.container.resolve('db') // default
|
|
21
|
+
* const tenant1 = app.container.resolve('db:tenant1') // named
|
|
22
|
+
*/
|
|
23
|
+
import { createNapiConnection, } from "./adapters/NapiDbAdapter.js";
|
|
24
|
+
import { setAtlasDialect } from "./query/native.js";
|
|
25
|
+
import { MigrationRunner, } from "./schema/MigrationRunner.js";
|
|
26
|
+
import { dialectFromUrl } from "./utils/dialectFromUrl.js";
|
|
27
|
+
/**
|
|
28
|
+
* Canonical sqlite production pragma recipe.
|
|
29
|
+
*
|
|
30
|
+
* journal_mode = WAL // writes go to a side-log, readers don't block
|
|
31
|
+
* synchronous = NORMAL // one fsync per commit (on the WAL); recovery
|
|
32
|
+
* // still rebuilds a consistent DB after crash
|
|
33
|
+
*
|
|
34
|
+
* Drops INSERT latency by ~5–10x vs sqlite's default
|
|
35
|
+
* (`journal_mode=delete` + `synchronous=FULL`) without sacrificing
|
|
36
|
+
* durability. Spread the constant into `pragmas` so app-specific overrides
|
|
37
|
+
* stay literal:
|
|
38
|
+
*
|
|
39
|
+
* pragmas: { ...SQLITE_PROD_PRAGMAS, foreign_keys: "ON" }
|
|
40
|
+
*/
|
|
41
|
+
export const SQLITE_PROD_PRAGMAS = Object.freeze({
|
|
42
|
+
journal_mode: "WAL",
|
|
43
|
+
synchronous: "NORMAL",
|
|
44
|
+
});
|
|
45
|
+
export default class AtlasProvider {
|
|
46
|
+
app;
|
|
47
|
+
/** Map of connection name → open connection. Populated at boot. */
|
|
48
|
+
#connections = new Map();
|
|
49
|
+
#defaultName = "primary";
|
|
50
|
+
constructor(app) {
|
|
51
|
+
this.app = app;
|
|
52
|
+
}
|
|
53
|
+
register() { }
|
|
54
|
+
async boot() {
|
|
55
|
+
const config = this.app.config.get("database");
|
|
56
|
+
if (!config)
|
|
57
|
+
return;
|
|
58
|
+
// Normalize: if `connections` is not set, build a single-entry map from top-level config.
|
|
59
|
+
const { connections, defaultName } = this.#resolveConnections(config);
|
|
60
|
+
this.#defaultName = defaultName;
|
|
61
|
+
// Open every connection in parallel — multi-database apps with slow-to-
|
|
62
|
+
// handshake drivers (Postgres over TLS, RDS proxies) previously paid the
|
|
63
|
+
// sum of the round-trip times on boot; now it's the max.
|
|
64
|
+
//
|
|
65
|
+
// `Promise.allSettled` lets us distinguish successes from failures without
|
|
66
|
+
// losing the already-opened connections. If any connection rejected, we
|
|
67
|
+
// close every successful one before rethrowing so a partial boot never
|
|
68
|
+
// leaks pools/sockets.
|
|
69
|
+
const entries = Object.entries(connections);
|
|
70
|
+
const results = await Promise.allSettled(entries.map(([, settings]) => createNapiConnection(settings.url, settings.poolMin ?? 1, settings.poolMax ?? 10, settings.pragmas)));
|
|
71
|
+
const failures = [];
|
|
72
|
+
const successes = [];
|
|
73
|
+
results.forEach((r, i) => {
|
|
74
|
+
const [name] = entries[i];
|
|
75
|
+
if (r.status === "fulfilled")
|
|
76
|
+
successes.push({ name, conn: r.value });
|
|
77
|
+
else
|
|
78
|
+
failures.push({ name, error: r.reason });
|
|
79
|
+
});
|
|
80
|
+
if (failures.length > 0) {
|
|
81
|
+
// Tear down the successes so we don't leak any pool that the runtime
|
|
82
|
+
// has already opened. Closures run in parallel with allSettled so a
|
|
83
|
+
// stuck close doesn't block the rollback path.
|
|
84
|
+
await Promise.allSettled(successes.map((s) => s.conn.close()));
|
|
85
|
+
const first = failures[0];
|
|
86
|
+
const others = failures
|
|
87
|
+
.slice(1)
|
|
88
|
+
.map((f) => `${f.name}: ${String(f.error)}`)
|
|
89
|
+
.join("; ");
|
|
90
|
+
throw new Error(`AtlasProvider: failed to open ${failures.length} connection(s) — ` +
|
|
91
|
+
`'${first.name}' failed: ${String(first.error)}` +
|
|
92
|
+
(others ? ` (also: ${others})` : ""));
|
|
93
|
+
}
|
|
94
|
+
for (const { name, conn } of successes) {
|
|
95
|
+
this.#connections.set(name, conn);
|
|
96
|
+
this.app.container.singleton(`db:${name}`, () => conn);
|
|
97
|
+
}
|
|
98
|
+
// Expose the default under the short aliases `db` and `db.connection`.
|
|
99
|
+
const defaultConn = this.#connections.get(defaultName);
|
|
100
|
+
if (!defaultConn) {
|
|
101
|
+
throw new Error(`AtlasProvider: default connection '${defaultName}' is not defined in config.database.connections`);
|
|
102
|
+
}
|
|
103
|
+
this.app.container.singleton("db", () => defaultConn);
|
|
104
|
+
this.app.container.singleton("db.connection", () => defaultConn);
|
|
105
|
+
// Populate the `@c9up/atlas/services/db` proxy so apps can
|
|
106
|
+
// `import db from '@c9up/atlas/services/db'` from anywhere.
|
|
107
|
+
// Done inside the lazy-import to avoid pulling the services
|
|
108
|
+
// module at construction time when the provider is type-imported
|
|
109
|
+
// by `@c9up/ream`'s discovery scan.
|
|
110
|
+
const { setDb } = await import("./services/db.js");
|
|
111
|
+
setDb(defaultConn);
|
|
112
|
+
// The dialect set module-wide is the DEFAULT connection's dialect.
|
|
113
|
+
// Per-connection dialect (when a user hits a non-default) is read from
|
|
114
|
+
// the connection URL at query time by each call site that cares.
|
|
115
|
+
setAtlasDialect(dialectFromUrl(connections[defaultName]?.url));
|
|
116
|
+
if (config.migrations?.path) {
|
|
117
|
+
await this.#runMigrations(config.migrations.path, connections[defaultName]?.url, defaultConn, config.migrations.table);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
async shutdown() {
|
|
121
|
+
// Close every connection in parallel — same reasoning as boot. We use
|
|
122
|
+
// `allSettled` so a single driver failing to close doesn't prevent the
|
|
123
|
+
// rest from shutting down, BUT we surface the failures afterwards:
|
|
124
|
+
//
|
|
125
|
+
// - the map is cleared unconditionally (the process is shutting down
|
|
126
|
+
// and we don't want to hand out closed handles)
|
|
127
|
+
// - any rejection is aggregated into a single `AggregateError` thrown
|
|
128
|
+
// at the end so supervisors / health-checks see a non-zero exit
|
|
129
|
+
// signal instead of a silent "everything is fine" shutdown
|
|
130
|
+
const named = [...this.#connections.entries()];
|
|
131
|
+
const results = await Promise.allSettled(named.map(([, c]) => c.close()));
|
|
132
|
+
this.#connections.clear();
|
|
133
|
+
const errors = results
|
|
134
|
+
.map((r, i) => r.status === "rejected" ? { name: named[i][0], error: r.reason } : null)
|
|
135
|
+
.filter((x) => x !== null);
|
|
136
|
+
if (errors.length > 0) {
|
|
137
|
+
const summary = errors
|
|
138
|
+
.map((e) => `'${e.name}': ${String(e.error)}`)
|
|
139
|
+
.join("; ");
|
|
140
|
+
throw new AggregateError(errors.map((e) => e.error), `AtlasProvider: ${errors.length} connection(s) failed to close — ${summary}`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
async start() { }
|
|
144
|
+
async ready() { }
|
|
145
|
+
/** Normalize the config into a `{ name → ConnectionConfig }` map + default name. */
|
|
146
|
+
#resolveConnections(config) {
|
|
147
|
+
if (config.connections && Object.keys(config.connections).length > 0) {
|
|
148
|
+
return {
|
|
149
|
+
connections: config.connections,
|
|
150
|
+
defaultName: config.default ?? "primary",
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
// Legacy single-connection shape — promote to multi-connection under "primary".
|
|
154
|
+
return {
|
|
155
|
+
connections: {
|
|
156
|
+
primary: {
|
|
157
|
+
url: config.url,
|
|
158
|
+
poolMin: config.poolMin,
|
|
159
|
+
poolMax: config.poolMax,
|
|
160
|
+
pragmas: config.pragmas,
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
defaultName: "primary",
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
async #runMigrations(migrationsPath, url, db, tableName) {
|
|
167
|
+
const { existsSync } = await import("node:fs");
|
|
168
|
+
if (!existsSync(migrationsPath))
|
|
169
|
+
return;
|
|
170
|
+
const adapter = {
|
|
171
|
+
execute: async (sql, params) => {
|
|
172
|
+
await db.execute(sql, params);
|
|
173
|
+
},
|
|
174
|
+
query: (sql, params) => db.query(sql, params),
|
|
175
|
+
close: () => db.close(),
|
|
176
|
+
// Thread the transactional path through so MigrationRunner takes the
|
|
177
|
+
// atomic branch (a mid-migration failure rolls back both the SQL and the
|
|
178
|
+
// `_migrations` bookkeeping row together). Without this, the runner
|
|
179
|
+
// silently falls back to non-transactional execution.
|
|
180
|
+
runInTransaction: async (batch) => db.runInTransaction(batch),
|
|
181
|
+
};
|
|
182
|
+
const runner = new MigrationRunner(adapter, {
|
|
183
|
+
migrationsDir: migrationsPath,
|
|
184
|
+
dialect: dialectFromUrl(url),
|
|
185
|
+
tableName,
|
|
186
|
+
});
|
|
187
|
+
await runner.migrate();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=AtlasProvider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"AtlasProvider.js","sourceRoot":"","sources":["../src/AtlasProvider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,OAAO,EAEN,oBAAoB,GACpB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAEN,e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yE;YACzE,oEAAoE;YACpE,sDAAsD;YACtD,gBAAgB,EAAE,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,EAAE,CAAC,gBAAgB,CAAC,KAAK,CAAC;SAC7D,CAAC;QACF,MAAM,MAAM,GAAG,IAAI,eAAe,CAAC,OAAO,EAAE;YAC3C,aAAa,EAAE,cAAc;YAC7B,OAAO,EAAE,cAAc,CAAC,GAAG,CAAC;YAC5B,SAAS;SACT,CAAC,CAAC;QACH,MAAM,MAAM,CAAC,OAAO,EAAE,CAAC;IACxB,CAAC;CACD"}
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BaseEntity — base class for all Atlas entities.
|
|
3
|
+
*
|
|
4
|
+
* Provides:
|
|
5
|
+
* - Domain event accumulation (flushed post-commit through the event bus)
|
|
6
|
+
* - `$extras` bag for ad-hoc / computed columns (32.5)
|
|
7
|
+
* - `$original` snapshot + `$dirty` diff tracking (32.2)
|
|
8
|
+
* - Serialization layer hooks (`hidden` / `visible` / `@column` serializeAs) (32.4)
|
|
9
|
+
* - Computed-property collection (32.3)
|
|
10
|
+
*
|
|
11
|
+
* @implements FR29, FR35, stories 32.1 through 32.5
|
|
12
|
+
*/
|
|
13
|
+
export interface DomainEvent {
|
|
14
|
+
name: string;
|
|
15
|
+
data: Record<string, unknown>;
|
|
16
|
+
}
|
|
17
|
+
/** Symbol metadata key for the computed-property registry on an entity class. */
|
|
18
|
+
export declare const COMPUTED_KEY: unique symbol;
|
|
19
|
+
/** Symbol metadata key for the serialize-as / serializer overrides on columns. */
|
|
20
|
+
export declare const COLUMN_SERIALIZE_KEY: unique symbol;
|
|
21
|
+
/** Symbol property key used by entities to back-reference their hydrating repo. */
|
|
22
|
+
export declare const REPO_REF: unique symbol;
|
|
23
|
+
/** Minimal repo-back-reference interface used by `entity.refresh()` / `entity.fresh()` / `entity.loadCount()`. */
|
|
24
|
+
export interface EntityRepoRef {
|
|
25
|
+
refresh(entity: BaseEntity): Promise<void>;
|
|
26
|
+
fresh(entity: BaseEntity): Promise<BaseEntity>;
|
|
27
|
+
loadCount(entity: BaseEntity, relationName: string, alias?: string): Promise<void>;
|
|
28
|
+
loadAggregate(entity: BaseEntity, relationName: string, build: (q: unknown) => void): Promise<void>;
|
|
29
|
+
/** Lazy-load a relation onto `entity` — Story 31.10. */
|
|
30
|
+
loadRelation(entity: BaseEntity, relationName: string, callback?: (q: unknown) => void): Promise<void>;
|
|
31
|
+
/** Build a related-entity proxy for fluent create/save + pivot ops — Stories 31.5–31.9. */
|
|
32
|
+
relatedProxy(entity: BaseEntity, relationName: string): RelationProxy;
|
|
33
|
+
}
|
|
34
|
+
interface BaseRelationProxy {
|
|
35
|
+
create(data: Record<string, unknown>): Promise<BaseEntity>;
|
|
36
|
+
save(related: BaseEntity): Promise<void>;
|
|
37
|
+
/** Scoped query builder over the related table (Story 31.9). */
|
|
38
|
+
query(): unknown;
|
|
39
|
+
}
|
|
40
|
+
interface BulkRelationProxy extends BaseRelationProxy {
|
|
41
|
+
createMany(rows: Array<Record<string, unknown>>): Promise<BaseEntity[]>;
|
|
42
|
+
saveMany(related: BaseEntity[]): Promise<BaseEntity[]>;
|
|
43
|
+
}
|
|
44
|
+
/** `@HasOne` — single related row. `createMany`/`saveMany` are intentionally absent. */
|
|
45
|
+
export interface HasOneRelationProxy extends BaseRelationProxy {
|
|
46
|
+
readonly type: "hasOne";
|
|
47
|
+
/** Throws with a clear "not supported on @HasOne" — exposed as a typed no-op for symmetry. */
|
|
48
|
+
createMany(rows: Array<Record<string, unknown>>): Promise<never>;
|
|
49
|
+
saveMany(related: BaseEntity[]): Promise<never>;
|
|
50
|
+
}
|
|
51
|
+
/** `@HasMany` — zero or more related rows with bulk write support. */
|
|
52
|
+
export interface HasManyRelationProxy extends BulkRelationProxy {
|
|
53
|
+
readonly type: "hasMany";
|
|
54
|
+
}
|
|
55
|
+
/** `@BelongsTo` — set/clear the FK via `associate`/`dissociate`. */
|
|
56
|
+
export interface BelongsToRelationProxy extends BulkRelationProxy {
|
|
57
|
+
readonly type: "belongsTo";
|
|
58
|
+
/** Set `parent.<fk> = model.<ownerKey>` and save the parent. Rejects null/undefined. */
|
|
59
|
+
associate(model: BaseEntity): Promise<void>;
|
|
60
|
+
/** Clear the FK and save the parent. */
|
|
61
|
+
dissociate(): Promise<void>;
|
|
62
|
+
}
|
|
63
|
+
/** `@ManyToMany` — full Lucid pivot API. */
|
|
64
|
+
export interface ManyToManyRelationProxy extends BulkRelationProxy {
|
|
65
|
+
readonly type: "manyToMany";
|
|
66
|
+
/** Insert pivot rows. Accepts `id[]` or `{ id: extras }`. */
|
|
67
|
+
attach(ids: Array<string | number> | Record<string, Record<string, unknown>>): Promise<void>;
|
|
68
|
+
/** Delete pivot rows. No args = delete all for this parent. */
|
|
69
|
+
detach(ids?: Array<string | number>): Promise<void>;
|
|
70
|
+
/**
|
|
71
|
+
* Diff-compute the target set. `additive=false` (default) removes orphans;
|
|
72
|
+
* `additive=true` only inserts, never deletes.
|
|
73
|
+
*/
|
|
74
|
+
sync(target: Array<string | number> | Record<string, Record<string, unknown>>, additive?: boolean): Promise<void>;
|
|
75
|
+
}
|
|
76
|
+
export type RelationProxy = HasOneRelationProxy | HasManyRelationProxy | BelongsToRelationProxy | ManyToManyRelationProxy;
|
|
77
|
+
/** Per-column serialization config (populated by @Column options). */
|
|
78
|
+
export interface ColumnSerializeConfig {
|
|
79
|
+
/** Rename this column at toJSON time (e.g. `password` → `passwordHash`). Null = hidden. */
|
|
80
|
+
serializeAs?: string | null;
|
|
81
|
+
/** Transform function applied to the value at toJSON time. */
|
|
82
|
+
serialize?: (value: unknown) => unknown;
|
|
83
|
+
}
|
|
84
|
+
export declare class BaseEntity {
|
|
85
|
+
#private;
|
|
86
|
+
/** Index signature — entities have dynamic column properties set by hydrate/create. */
|
|
87
|
+
[key: string]: unknown;
|
|
88
|
+
/**
|
|
89
|
+
* `$extras` — bag for ad-hoc/computed values that are NOT declared as `@Column`.
|
|
90
|
+
* Used by `withCount`, pivot extras, and aggregate loaders. Kept separate from
|
|
91
|
+
* real columns so persistence (`#entityToRow`) never tries to write them back.
|
|
92
|
+
*
|
|
93
|
+
* @implements Story 32.5
|
|
94
|
+
*/
|
|
95
|
+
$extras: Record<string, unknown>;
|
|
96
|
+
/**
|
|
97
|
+
* Snapshot of the column values at the moment this entity was hydrated from
|
|
98
|
+
* the database. Used by dirty tracking (`isDirty`, `$dirty`). Populated by
|
|
99
|
+
* `BaseRepository.#hydrate` via `markAsPersisted` below; empty for entities
|
|
100
|
+
* built in memory with `new MyEntity()`.
|
|
101
|
+
*
|
|
102
|
+
* @implements Story 32.2
|
|
103
|
+
*/
|
|
104
|
+
$original: Record<string, unknown>;
|
|
105
|
+
/** Set a property dynamically (used by hydrate/create). */
|
|
106
|
+
setProp(key: string, value: unknown): void;
|
|
107
|
+
/** Set an `$extras` value (used by `withCount`, pivot extras, aggregate loaders). */
|
|
108
|
+
setExtra(key: string, value: unknown): void;
|
|
109
|
+
/** Get an `$extras` value with optional default. */
|
|
110
|
+
getExtra<T = unknown>(key: string, defaultValue?: T): T | undefined;
|
|
111
|
+
/**
|
|
112
|
+
* Freeze the current column values as the "persisted" snapshot. Called by
|
|
113
|
+
* `BaseRepository.#hydrate` after a SELECT and by `save()` after INSERT/UPDATE
|
|
114
|
+
* succeeds. From now on, `isDirty()` compares against this snapshot.
|
|
115
|
+
*/
|
|
116
|
+
/**
|
|
117
|
+
* Freeze the current column values as the persisted snapshot. Atlas uses
|
|
118
|
+
* **reference-based dirty tracking**: `$original` holds the SAME reference
|
|
119
|
+
* the hydrator produced, not a deep clone. A column is dirty iff
|
|
120
|
+
* `Object.is(current, original) === false`.
|
|
121
|
+
*
|
|
122
|
+
* **Contract (important)**: to mark an object/array column dirty, the user
|
|
123
|
+
* MUST reassign it — in-place mutation is undetectable by design:
|
|
124
|
+
*
|
|
125
|
+
* entity.settings = { ...entity.settings, theme: 'dark' } // ✅ dirty
|
|
126
|
+
* entity.settings.theme = 'dark' // ❌ NOT detected
|
|
127
|
+
*
|
|
128
|
+
* This matches Lucid's contract and gives us O(1) dirty checks + zero
|
|
129
|
+
* allocations on hydrate. The alternative (deep-equal with cloned snapshot)
|
|
130
|
+
* was correct but allocated a full copy of every column on every load and
|
|
131
|
+
* traversed nested JSON on every `save()` — unacceptable for hot paths.
|
|
132
|
+
*
|
|
133
|
+
* Rollback can only restore reassigned columns; in-place mutations are
|
|
134
|
+
* unrecoverable because the snapshot is the same reference as the current
|
|
135
|
+
* value. Use immutable update patterns if you rely on rollback.
|
|
136
|
+
*
|
|
137
|
+
* @implements Story 32.2
|
|
138
|
+
*/
|
|
139
|
+
markAsPersisted(): void;
|
|
140
|
+
/**
|
|
141
|
+
* Compute the set of columns whose current value differs from `$original`.
|
|
142
|
+
* Called on demand by `save()` (to emit UPDATEs that only touch dirty cols)
|
|
143
|
+
* and by lifecycle hooks (e.g. `beforeSave` only rehashes password if dirty).
|
|
144
|
+
*
|
|
145
|
+
* @implements Story 32.2
|
|
146
|
+
*/
|
|
147
|
+
get $dirty(): Record<string, unknown>;
|
|
148
|
+
/**
|
|
149
|
+
* Check whether a specific column is dirty, or whether any column is dirty
|
|
150
|
+
* when called without arguments.
|
|
151
|
+
*/
|
|
152
|
+
isDirty(field?: string): boolean;
|
|
153
|
+
/**
|
|
154
|
+
* Revert all dirty columns back to their `$original` values.
|
|
155
|
+
*
|
|
156
|
+
* Because dirty tracking is reference-based, `rollback` only restores
|
|
157
|
+
* reassigned columns to their persisted reference. In-place mutations on
|
|
158
|
+
* object/array columns are NOT recoverable — the snapshot holds the same
|
|
159
|
+
* reference the user mutated. If you rely on rollback, use immutable
|
|
160
|
+
* update patterns (`entity.field = { ...entity.field, x: y }`).
|
|
161
|
+
*/
|
|
162
|
+
rollback(): void;
|
|
163
|
+
/**
|
|
164
|
+
* Repository back-pointer set by `BaseRepository.#hydrate` so instances can
|
|
165
|
+
* self-refresh / lazy-load. Not serialized (symbol key).
|
|
166
|
+
*
|
|
167
|
+
* @implements Story 32.6
|
|
168
|
+
*/
|
|
169
|
+
[REPO_REF]?: EntityRepoRef;
|
|
170
|
+
/**
|
|
171
|
+
* Re-read this entity's row from the database and mutate THIS instance
|
|
172
|
+
* with the latest values. Throws if the row no longer exists.
|
|
173
|
+
*/
|
|
174
|
+
refresh(): Promise<this>;
|
|
175
|
+
/**
|
|
176
|
+
* Re-read this entity's row from the database and return a NEW instance.
|
|
177
|
+
* `this` is NOT mutated. The returned object has the same runtime class
|
|
178
|
+
* because the repository that produced it is the same one we back-reference.
|
|
179
|
+
*/
|
|
180
|
+
fresh(): Promise<BaseEntity>;
|
|
181
|
+
/**
|
|
182
|
+
* Lazy-load a relation count into `this.$extras[alias ?? `${relationName}_count`]`.
|
|
183
|
+
* Issues a single `SELECT COUNT(*) FROM related WHERE <fk> = ?` for this entity.
|
|
184
|
+
*
|
|
185
|
+
* @implements Story 29.2
|
|
186
|
+
*/
|
|
187
|
+
loadCount(relationName: string, alias?: string): Promise<this>;
|
|
188
|
+
/**
|
|
189
|
+
* Lazy-load a relation aggregate. The builder callback must set the aggregate
|
|
190
|
+
* via `.sum('col')` / `.avg(...)` / `.min(...)` / `.max(...)` / `.count()` and
|
|
191
|
+
* an alias via `.as('name')`. The result lands on `this.$extras[alias]`.
|
|
192
|
+
*
|
|
193
|
+
* await user.loadAggregate('posts', q => q.sum('views').as('total_views'))
|
|
194
|
+
*
|
|
195
|
+
* @implements Story 29.2
|
|
196
|
+
*/
|
|
197
|
+
loadAggregate(relationName: string, build: (q: unknown) => void): Promise<this>;
|
|
198
|
+
/**
|
|
199
|
+
* Lazy-load a relation onto this entity after it was initially fetched.
|
|
200
|
+
*
|
|
201
|
+
* @implements Story 31.10
|
|
202
|
+
*/
|
|
203
|
+
load(relationName: string, callback?: (q: unknown) => void): Promise<this>;
|
|
204
|
+
/**
|
|
205
|
+
* Return a relation proxy bound to this instance. The proxy exposes
|
|
206
|
+
* `create` / `createMany` / `save` / `saveMany` that auto-set the FK.
|
|
207
|
+
*
|
|
208
|
+
* @implements Story 31.5
|
|
209
|
+
*/
|
|
210
|
+
related(relationName: string): ReturnType<EntityRepoRef["relatedProxy"]>;
|
|
211
|
+
/**
|
|
212
|
+
* Mass-assign columns from a plain payload. Only columns that are in the
|
|
213
|
+
* class's `static fillable` allowlist (or absent from `static guarded` when
|
|
214
|
+
* no fillable is declared) are assigned. Columns not in the payload are
|
|
215
|
+
* reset to undefined so the entity reflects exactly what was filled.
|
|
216
|
+
*
|
|
217
|
+
* @implements Story 30.7
|
|
218
|
+
*/
|
|
219
|
+
fill(payload: Record<string, unknown>): this;
|
|
220
|
+
/**
|
|
221
|
+
* Patch the entity with a payload, only touching the provided keys. Same
|
|
222
|
+
* allowlist/blocklist rules as `fill` but preserves fields not present in
|
|
223
|
+
* the payload.
|
|
224
|
+
*/
|
|
225
|
+
merge(payload: Record<string, unknown>): this;
|
|
226
|
+
/** Add a domain event to be dispatched after save. */
|
|
227
|
+
addDomainEvent(name: string, data: Record<string, unknown>): void;
|
|
228
|
+
/** Get accumulated domain events (non-destructive read). */
|
|
229
|
+
getDomainEvents(): readonly DomainEvent[];
|
|
230
|
+
/** Clear accumulated domain events. */
|
|
231
|
+
clearDomainEvents(): void;
|
|
232
|
+
/** Get and clear accumulated domain events atomically. */
|
|
233
|
+
flushDomainEvents(): DomainEvent[];
|
|
234
|
+
/** Check if entity has pending domain events. */
|
|
235
|
+
hasDomainEvents(): boolean;
|
|
236
|
+
/**
|
|
237
|
+
* Serialize to JSON — honors class-level `hidden`/`visible` allowlists,
|
|
238
|
+
* per-column `serializeAs` / `serialize` overrides, and `@computed` getters.
|
|
239
|
+
* `$extras` is merged on top so callers see `withCount` / pivot extras next
|
|
240
|
+
* to regular columns. `#private` fields are excluded automatically by ES.
|
|
241
|
+
*
|
|
242
|
+
* @implements Story 32.4
|
|
243
|
+
*/
|
|
244
|
+
toJSON(): Record<string, unknown>;
|
|
245
|
+
/**
|
|
246
|
+
* Pick / limit the fields returned by `toJSON()` for a single call.
|
|
247
|
+
*
|
|
248
|
+
* entity.serialize({ fields: ['id', 'title'] })
|
|
249
|
+
*/
|
|
250
|
+
serialize(options?: {
|
|
251
|
+
fields?: readonly string[];
|
|
252
|
+
}): Record<string, unknown>;
|
|
253
|
+
}
|
|
254
|
+
export {};
|
|
255
|
+
//# sourceMappingURL=BaseEntity.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"BaseEntity.d.ts","sourceRoot":"","sources":["../src/BaseEntity.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAC9B;AAED,iFAAiF;AACjF,eAAO,MAAM,YAAY,eAA+B,CAAC;AAEzD,kFAAkF;AAClF,eAAO,MAAM,oBAAoB,eAAsC,CAAC;AAExE,mFAAmF;AACnF,eAAO,MAAM,QAAQ,eAA8B,CAAC;AAEpD,kHAAkH;AAClH,MAAM,WAAW,aAAa;IAC7B,OAAO,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,KAAK,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;IAC/C,SAAS,CACR,MAAM,EAAE,UAAU,EAClB,YAAY,EAAE,MAAM,EACpB,KAAK,CAAC,EAAE,MAAM,GACZ,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,aAAa,CACZ,MAAM,EAAE,UAAU,EAClB,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,IAAI,GACzB,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,wDAAwD;IACxD,YAAY,CACX,MAAM,EAAE,UAAU,EAClB,YAAY,EAAE,MAAM,EACpB,QAAQ,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,KAA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