@c9up/atlas 0.1.3
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/LICENSE +21 -0
- package/README.md +35 -0
- 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/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 +69 -0
- package/scripts/copy-napi.mjs +86 -0
- package/src/AtlasProvider.ts +297 -0
- package/src/BaseEntity.ts +585 -0
- package/src/BaseRepository.ts +1694 -0
- package/src/ModelQuery.ts +2293 -0
- package/src/Transaction.ts +83 -0
- package/src/adapters/NapiDbAdapter.ts +178 -0
- package/src/config.ts +7 -0
- package/src/configure.ts +37 -0
- package/src/decorators/entity.ts +532 -0
- package/src/decorators/hooks.ts +169 -0
- package/src/decorators/scope.ts +44 -0
- package/src/errors.ts +111 -0
- package/src/index.ts +114 -0
- package/src/naming/NamingStrategy.ts +106 -0
- package/src/query/QueryBuilder.ts +422 -0
- package/src/query/native.ts +74 -0
- package/src/schema/Migration.ts +81 -0
- package/src/schema/MigrationRunner.ts +532 -0
- package/src/schema/Schema.ts +78 -0
- package/src/schema/SchemaBuilder.ts +14 -0
- package/src/schema/Seeder.ts +132 -0
- package/src/schema/TableBuilder.ts +238 -0
- package/src/schema/types.ts +51 -0
- package/src/services/db.ts +45 -0
- package/src/testing/DatabaseCleanup.ts +49 -0
- package/src/testing/Factory.ts +164 -0
- package/src/testing/TestDatabase.ts +81 -0
- package/src/testing/index.ts +3 -0
- package/src/utils/casing.ts +11 -0
- package/src/utils/dialectFromUrl.ts +16 -0
- package/src/utils/identifier.ts +35 -0
- package/src/utils/safePath.ts +59 -0
- package/src/utils/transactionBrand.ts +10 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 C9up
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
# @c9up/atlas
|
|
2
|
+
|
|
3
|
+
Data Mapper ORM for Node.js. Entity decorators, fluent QueryBuilder, domain events.
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
```typescript
|
|
8
|
+
import { Entity, Column, PrimaryKey, BaseEntity, QueryBuilder } from '@c9up/atlas'
|
|
9
|
+
|
|
10
|
+
@Entity('orders')
|
|
11
|
+
class Order extends BaseEntity {
|
|
12
|
+
@PrimaryKey({ generated: 'uuid' }) declare id: string
|
|
13
|
+
@Column() declare status: string
|
|
14
|
+
@Column({ type: 'decimal' }) declare total: number
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const { sql, params } = new QueryBuilder('orders')
|
|
18
|
+
.where('status', 'active')
|
|
19
|
+
.orderBy('createdAt', 'desc')
|
|
20
|
+
.paginate(1, 20)
|
|
21
|
+
.toSQL()
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Features
|
|
25
|
+
|
|
26
|
+
- `@Entity`, `@Column`, `@PrimaryKey`, `@BelongsTo`, `@HasMany`, `@ManyToMany`
|
|
27
|
+
- Fluent QueryBuilder with parameterized SQL (injection-safe)
|
|
28
|
+
- CTE (`.with()`), UNION, WHERE EXISTS, GROUP BY, HAVING, DISTINCT
|
|
29
|
+
- `RawSql` tagged template for edge cases
|
|
30
|
+
- Domain events accumulated on entities, dispatched after save
|
|
31
|
+
- BaseRepository with query builder access
|
|
32
|
+
|
|
33
|
+
## License
|
|
34
|
+
|
|
35
|
+
MIT
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@c9up/atlas",
|
|
3
|
+
"version": "0.1.3",
|
|
4
|
+
"description": "Atlas — Data Mapper ORM for the Ream framework",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"AUDIT-migration-templates.md",
|
|
11
|
+
"LICENSE",
|
|
12
|
+
"README.md",
|
|
13
|
+
"db.*.node",
|
|
14
|
+
"dist",
|
|
15
|
+
"index.*.node",
|
|
16
|
+
"scripts",
|
|
17
|
+
"src"
|
|
18
|
+
],
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./provider": {
|
|
25
|
+
"types": "./dist/AtlasProvider.d.ts",
|
|
26
|
+
"import": "./dist/AtlasProvider.js"
|
|
27
|
+
},
|
|
28
|
+
"./services/db": {
|
|
29
|
+
"types": "./dist/services/db.d.ts",
|
|
30
|
+
"import": "./dist/services/db.js"
|
|
31
|
+
},
|
|
32
|
+
"./configure": {
|
|
33
|
+
"types": "./dist/configure.d.ts",
|
|
34
|
+
"import": "./dist/configure.js"
|
|
35
|
+
},
|
|
36
|
+
"./testing": {
|
|
37
|
+
"types": "./dist/testing/index.d.ts",
|
|
38
|
+
"import": "./dist/testing/index.js"
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
"dependencies": {
|
|
42
|
+
"reflect-metadata": "^0.2"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"typescript": "^6.0.2",
|
|
46
|
+
"vitest": "^4.1.2",
|
|
47
|
+
"@types/node": "^22"
|
|
48
|
+
},
|
|
49
|
+
"engines": {
|
|
50
|
+
"node": ">=22.0.0"
|
|
51
|
+
},
|
|
52
|
+
"publishConfig": {
|
|
53
|
+
"access": "public"
|
|
54
|
+
},
|
|
55
|
+
"repository": {
|
|
56
|
+
"type": "git",
|
|
57
|
+
"url": "git+https://github.com/C9up/atlas.git"
|
|
58
|
+
},
|
|
59
|
+
"scripts": {
|
|
60
|
+
"build": "tsc -p tsconfig.build.json",
|
|
61
|
+
"build:rust": "cargo build --release -p atlas-query-napi && cargo build --release -p atlas-db-napi",
|
|
62
|
+
"build:napi": "pnpm build:rust && node scripts/copy-napi.mjs && node scripts/copy-napi.mjs --basename db",
|
|
63
|
+
"test": "vitest run",
|
|
64
|
+
"test:rust": "cargo test -p atlas-query",
|
|
65
|
+
"lint": "biome check src/",
|
|
66
|
+
"test:coverage": "vitest run --coverage",
|
|
67
|
+
"typecheck": "tsc --noEmit"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Atlas ships TWO NAPI artefacts:
|
|
2
|
+
// - atlas-query-napi → index.<suffix>.node (default)
|
|
3
|
+
// - atlas-db-napi → db.<suffix>.node (--basename db)
|
|
4
|
+
//
|
|
5
|
+
// Usage:
|
|
6
|
+
// node scripts/copy-napi.mjs # query → index.<suffix>.node
|
|
7
|
+
// node scripts/copy-napi.mjs --basename db # db → db.<suffix>.node
|
|
8
|
+
|
|
9
|
+
import { copyFileSync, existsSync } from 'node:fs'
|
|
10
|
+
import { dirname, join } from 'node:path'
|
|
11
|
+
import { argv, arch, env, platform } from 'node:process'
|
|
12
|
+
import { fileURLToPath } from 'node:url'
|
|
13
|
+
|
|
14
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
15
|
+
const root = join(here, '..')
|
|
16
|
+
|
|
17
|
+
// Cross-compile aware: set CARGO_BUILD_TARGET (e.g. x86_64-apple-darwin on an
|
|
18
|
+
// arm64 runner so we don't depend on the scarce macos-13 Intel runners) and we
|
|
19
|
+
// read target/<triple>/release. Unset = host platform / target/release.
|
|
20
|
+
const tripleMap = {
|
|
21
|
+
'x86_64-unknown-linux-gnu': { suffix: 'linux-x64-gnu', os: 'linux' },
|
|
22
|
+
'aarch64-unknown-linux-gnu': { suffix: 'linux-arm64-gnu', os: 'linux' },
|
|
23
|
+
'x86_64-apple-darwin': { suffix: 'darwin-x64', os: 'darwin' },
|
|
24
|
+
'aarch64-apple-darwin': { suffix: 'darwin-arm64', os: 'darwin' },
|
|
25
|
+
'x86_64-pc-windows-msvc': { suffix: 'win32-x64-msvc', os: 'win32' },
|
|
26
|
+
}
|
|
27
|
+
const hostSuffixMap = {
|
|
28
|
+
'linux-x64': 'linux-x64-gnu',
|
|
29
|
+
'linux-arm64': 'linux-arm64-gnu',
|
|
30
|
+
'darwin-x64': 'darwin-x64',
|
|
31
|
+
'darwin-arm64': 'darwin-arm64',
|
|
32
|
+
'win32-x64': 'win32-x64-msvc',
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const basenameIdx = argv.indexOf('--basename')
|
|
36
|
+
const basename = basenameIdx >= 0 ? argv[basenameIdx + 1] : 'index'
|
|
37
|
+
if (!basename || basename.startsWith('-')) {
|
|
38
|
+
throw new Error(`[atlas:napi] --basename requires a value (got: ${basename ?? '<missing>'})`)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const crateMap = {
|
|
42
|
+
index: 'atlas_query_napi',
|
|
43
|
+
db: 'atlas_db_napi',
|
|
44
|
+
}
|
|
45
|
+
const crate = crateMap[basename]
|
|
46
|
+
if (!crate) {
|
|
47
|
+
throw new Error(`[atlas:napi] unknown basename '${basename}'. Expected one of: ${Object.keys(crateMap).join(', ')}`)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const triple = env.CARGO_BUILD_TARGET ?? ''
|
|
51
|
+
let suffix
|
|
52
|
+
let os
|
|
53
|
+
let releaseDir
|
|
54
|
+
if (triple) {
|
|
55
|
+
const entry = tripleMap[triple]
|
|
56
|
+
if (!entry) {
|
|
57
|
+
throw new Error(`[atlas:napi] unsupported CARGO_BUILD_TARGET: ${triple}`)
|
|
58
|
+
}
|
|
59
|
+
suffix = entry.suffix
|
|
60
|
+
os = entry.os
|
|
61
|
+
releaseDir = join(root, 'target', triple, 'release')
|
|
62
|
+
} else {
|
|
63
|
+
suffix = hostSuffixMap[`${platform}-${arch}`]
|
|
64
|
+
os = platform
|
|
65
|
+
releaseDir = join(root, 'target', 'release')
|
|
66
|
+
if (!suffix) {
|
|
67
|
+
throw new Error(`[atlas:napi] unsupported platform/arch: ${platform}-${arch}`)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const candidates = os === 'win32'
|
|
72
|
+
? [join(releaseDir, `${crate}.dll`), join(releaseDir, `lib${crate}.dll`)]
|
|
73
|
+
: os === 'darwin'
|
|
74
|
+
? [join(releaseDir, `lib${crate}.dylib`)]
|
|
75
|
+
: [join(releaseDir, `lib${crate}.so`)]
|
|
76
|
+
|
|
77
|
+
const source = candidates.find((candidate) => existsSync(candidate))
|
|
78
|
+
if (!source) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`[atlas:napi] native library not found. Looked for:\n${candidates.map((p) => `- ${p}`).join('\n')}`,
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const target = join(root, `${basename}.${suffix}.node`)
|
|
85
|
+
copyFileSync(source, target)
|
|
86
|
+
console.log(`[atlas:napi] copied ${source} -> ${target}`)
|
|
@@ -0,0 +1,297 @@
|
|
|
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
|
+
import {
|
|
25
|
+
type AsyncDatabaseConnection,
|
|
26
|
+
createNapiConnection,
|
|
27
|
+
} from "./adapters/NapiDbAdapter.js";
|
|
28
|
+
import { setAtlasDialect } from "./query/native.js";
|
|
29
|
+
import {
|
|
30
|
+
type DatabaseAdapter,
|
|
31
|
+
MigrationRunner,
|
|
32
|
+
} from "./schema/MigrationRunner.js";
|
|
33
|
+
import { dialectFromUrl } from "./utils/dialectFromUrl.js";
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Structural slice of the host framework's app context — only the surface
|
|
37
|
+
* AtlasProvider actually uses. Declared locally so atlas does NOT import
|
|
38
|
+
* `@c9up/ream`; any framework whose context exposes a `config.get(key)`
|
|
39
|
+
* reader and a `container.singleton(token, factory)` binder satisfies this
|
|
40
|
+
* contract via TypeScript structural compatibility.
|
|
41
|
+
*
|
|
42
|
+
* The `token` type mirrors ream's `ServiceToken` union (`string | symbol |
|
|
43
|
+
* ctor`) so AtlasProvider can grow into class-as-token / Symbol-keyed
|
|
44
|
+
* bindings without re-coupling to `@c9up/ream`. AtlasProvider itself only
|
|
45
|
+
* uses `string` tokens today.
|
|
46
|
+
*/
|
|
47
|
+
export interface AtlasAppContext {
|
|
48
|
+
container: {
|
|
49
|
+
singleton(
|
|
50
|
+
token: string | symbol | (new (...args: never[]) => unknown),
|
|
51
|
+
factory: () => unknown,
|
|
52
|
+
): void;
|
|
53
|
+
};
|
|
54
|
+
config: { get<T = unknown>(key: string): T | undefined };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Canonical sqlite production pragma recipe.
|
|
59
|
+
*
|
|
60
|
+
* journal_mode = WAL // writes go to a side-log, readers don't block
|
|
61
|
+
* synchronous = NORMAL // one fsync per commit (on the WAL); recovery
|
|
62
|
+
* // still rebuilds a consistent DB after crash
|
|
63
|
+
*
|
|
64
|
+
* Drops INSERT latency by ~5–10x vs sqlite's default
|
|
65
|
+
* (`journal_mode=delete` + `synchronous=FULL`) without sacrificing
|
|
66
|
+
* durability. Spread the constant into `pragmas` so app-specific overrides
|
|
67
|
+
* stay literal:
|
|
68
|
+
*
|
|
69
|
+
* pragmas: { ...SQLITE_PROD_PRAGMAS, foreign_keys: "ON" }
|
|
70
|
+
*/
|
|
71
|
+
export const SQLITE_PROD_PRAGMAS = Object.freeze({
|
|
72
|
+
journal_mode: "WAL",
|
|
73
|
+
synchronous: "NORMAL",
|
|
74
|
+
} as const);
|
|
75
|
+
|
|
76
|
+
/** One connection's settings. */
|
|
77
|
+
export interface ConnectionConfig {
|
|
78
|
+
/** Connection URL: "sqlite:data/app.db", "postgres://...", "mysql://..." */
|
|
79
|
+
url: string;
|
|
80
|
+
/** Minimum pool connections (default: 1) */
|
|
81
|
+
poolMin?: number;
|
|
82
|
+
/** Maximum pool connections (default: 10) */
|
|
83
|
+
poolMax?: number;
|
|
84
|
+
/**
|
|
85
|
+
* Connection-level pragmas (sqlite only). Each entry becomes a
|
|
86
|
+
* `PRAGMA <key> = <value>;` issued before the first query.
|
|
87
|
+
*
|
|
88
|
+
* Most apps want `{ journal_mode: "WAL", synchronous: "NORMAL" }` —
|
|
89
|
+
* disk-backed, durable, and ~5–10x faster than the default
|
|
90
|
+
* `journal_mode=delete` + `synchronous=FULL` (two fsyncs per
|
|
91
|
+
* commit). Ignored for postgres / mysql URLs.
|
|
92
|
+
*/
|
|
93
|
+
pragmas?: Record<string, string | number>;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Full database config — single-connection (legacy) OR multi-connection. */
|
|
97
|
+
export interface AtlasDatabaseConfig extends ConnectionConfig {
|
|
98
|
+
/** Name of the default connection when `connections` is set. Defaults to `"primary"`. */
|
|
99
|
+
default?: string;
|
|
100
|
+
/** Named connections. When present, top-level `url` is treated as `connections[default].url`. */
|
|
101
|
+
connections?: Record<string, ConnectionConfig>;
|
|
102
|
+
migrations?: {
|
|
103
|
+
path?: string;
|
|
104
|
+
/**
|
|
105
|
+
* Custom name for the migrations tracking table. Defaults to `"_migrations"`.
|
|
106
|
+
* Must match `/^[A-Za-z_][A-Za-z0-9_]*$/` — the `MigrationRunner` constructor
|
|
107
|
+
* throws `AtlasError("MIGRATION_INVALID_TABLE_NAME")` otherwise.
|
|
108
|
+
*/
|
|
109
|
+
table?: string;
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export default class AtlasProvider {
|
|
114
|
+
/** Map of connection name → open connection. Populated at boot. */
|
|
115
|
+
#connections = new Map<string, AsyncDatabaseConnection>();
|
|
116
|
+
#defaultName = "primary";
|
|
117
|
+
|
|
118
|
+
constructor(protected app: AtlasAppContext) {}
|
|
119
|
+
|
|
120
|
+
register() {}
|
|
121
|
+
|
|
122
|
+
async boot() {
|
|
123
|
+
const config = this.app.config.get<AtlasDatabaseConfig>("database");
|
|
124
|
+
if (!config) return;
|
|
125
|
+
|
|
126
|
+
// Normalize: if `connections` is not set, build a single-entry map from top-level config.
|
|
127
|
+
const { connections, defaultName } = this.#resolveConnections(config);
|
|
128
|
+
this.#defaultName = defaultName;
|
|
129
|
+
|
|
130
|
+
// Open every connection in parallel — multi-database apps with slow-to-
|
|
131
|
+
// handshake drivers (Postgres over TLS, RDS proxies) previously paid the
|
|
132
|
+
// sum of the round-trip times on boot; now it's the max.
|
|
133
|
+
//
|
|
134
|
+
// `Promise.allSettled` lets us distinguish successes from failures without
|
|
135
|
+
// losing the already-opened connections. If any connection rejected, we
|
|
136
|
+
// close every successful one before rethrowing so a partial boot never
|
|
137
|
+
// leaks pools/sockets.
|
|
138
|
+
const entries = Object.entries(connections);
|
|
139
|
+
const results = await Promise.allSettled(
|
|
140
|
+
entries.map(([, settings]) =>
|
|
141
|
+
createNapiConnection(
|
|
142
|
+
settings.url,
|
|
143
|
+
settings.poolMin ?? 1,
|
|
144
|
+
settings.poolMax ?? 10,
|
|
145
|
+
settings.pragmas,
|
|
146
|
+
),
|
|
147
|
+
),
|
|
148
|
+
);
|
|
149
|
+
const failures: Array<{ name: string; error: unknown }> = [];
|
|
150
|
+
const successes: Array<{ name: string; conn: AsyncDatabaseConnection }> =
|
|
151
|
+
[];
|
|
152
|
+
results.forEach((r, i) => {
|
|
153
|
+
const [name] = entries[i];
|
|
154
|
+
if (r.status === "fulfilled") successes.push({ name, conn: r.value });
|
|
155
|
+
else failures.push({ name, error: r.reason });
|
|
156
|
+
});
|
|
157
|
+
if (failures.length > 0) {
|
|
158
|
+
// Tear down the successes so we don't leak any pool that the runtime
|
|
159
|
+
// has already opened. Closures run in parallel with allSettled so a
|
|
160
|
+
// stuck close doesn't block the rollback path.
|
|
161
|
+
await Promise.allSettled(successes.map((s) => s.conn.close()));
|
|
162
|
+
const first = failures[0];
|
|
163
|
+
const others = failures
|
|
164
|
+
.slice(1)
|
|
165
|
+
.map((f) => `${f.name}: ${String(f.error)}`)
|
|
166
|
+
.join("; ");
|
|
167
|
+
throw new Error(
|
|
168
|
+
`AtlasProvider: failed to open ${failures.length} connection(s) — ` +
|
|
169
|
+
`'${first.name}' failed: ${String(first.error)}` +
|
|
170
|
+
(others ? ` (also: ${others})` : ""),
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
for (const { name, conn } of successes) {
|
|
174
|
+
this.#connections.set(name, conn);
|
|
175
|
+
this.app.container.singleton(`db:${name}`, () => conn);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Expose the default under the short aliases `db` and `db.connection`.
|
|
179
|
+
const defaultConn = this.#connections.get(defaultName);
|
|
180
|
+
if (!defaultConn) {
|
|
181
|
+
throw new Error(
|
|
182
|
+
`AtlasProvider: default connection '${defaultName}' is not defined in config.database.connections`,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
this.app.container.singleton("db", () => defaultConn);
|
|
186
|
+
this.app.container.singleton("db.connection", () => defaultConn);
|
|
187
|
+
|
|
188
|
+
// Populate the `@c9up/atlas/services/db` proxy so apps can
|
|
189
|
+
// `import db from '@c9up/atlas/services/db'` from anywhere.
|
|
190
|
+
// Done inside the lazy-import to avoid pulling the services
|
|
191
|
+
// module at construction time when the provider is type-imported
|
|
192
|
+
// by `@c9up/ream`'s discovery scan.
|
|
193
|
+
const { setDb } = await import("./services/db.js");
|
|
194
|
+
setDb(defaultConn);
|
|
195
|
+
|
|
196
|
+
// The dialect set module-wide is the DEFAULT connection's dialect.
|
|
197
|
+
// Per-connection dialect (when a user hits a non-default) is read from
|
|
198
|
+
// the connection URL at query time by each call site that cares.
|
|
199
|
+
setAtlasDialect(dialectFromUrl(connections[defaultName]?.url));
|
|
200
|
+
|
|
201
|
+
if (config.migrations?.path) {
|
|
202
|
+
await this.#runMigrations(
|
|
203
|
+
config.migrations.path,
|
|
204
|
+
connections[defaultName]?.url,
|
|
205
|
+
defaultConn,
|
|
206
|
+
config.migrations.table,
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
async shutdown() {
|
|
212
|
+
// Close every connection in parallel — same reasoning as boot. We use
|
|
213
|
+
// `allSettled` so a single driver failing to close doesn't prevent the
|
|
214
|
+
// rest from shutting down, BUT we surface the failures afterwards:
|
|
215
|
+
//
|
|
216
|
+
// - the map is cleared unconditionally (the process is shutting down
|
|
217
|
+
// and we don't want to hand out closed handles)
|
|
218
|
+
// - any rejection is aggregated into a single `AggregateError` thrown
|
|
219
|
+
// at the end so supervisors / health-checks see a non-zero exit
|
|
220
|
+
// signal instead of a silent "everything is fine" shutdown
|
|
221
|
+
const named = [...this.#connections.entries()];
|
|
222
|
+
const results = await Promise.allSettled(named.map(([, c]) => c.close()));
|
|
223
|
+
this.#connections.clear();
|
|
224
|
+
const errors = results
|
|
225
|
+
.map((r, i) =>
|
|
226
|
+
r.status === "rejected" ? { name: named[i][0], error: r.reason } : null,
|
|
227
|
+
)
|
|
228
|
+
.filter((x): x is { name: string; error: unknown } => x !== null);
|
|
229
|
+
if (errors.length > 0) {
|
|
230
|
+
const summary = errors
|
|
231
|
+
.map((e) => `'${e.name}': ${String(e.error)}`)
|
|
232
|
+
.join("; ");
|
|
233
|
+
throw new AggregateError(
|
|
234
|
+
errors.map((e) => e.error),
|
|
235
|
+
`AtlasProvider: ${errors.length} connection(s) failed to close — ${summary}`,
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async start() {}
|
|
241
|
+
async ready() {}
|
|
242
|
+
|
|
243
|
+
/** Normalize the config into a `{ name → ConnectionConfig }` map + default name. */
|
|
244
|
+
#resolveConnections(config: AtlasDatabaseConfig): {
|
|
245
|
+
connections: Record<string, ConnectionConfig>;
|
|
246
|
+
defaultName: string;
|
|
247
|
+
} {
|
|
248
|
+
if (config.connections && Object.keys(config.connections).length > 0) {
|
|
249
|
+
return {
|
|
250
|
+
connections: config.connections,
|
|
251
|
+
defaultName: config.default ?? "primary",
|
|
252
|
+
};
|
|
253
|
+
}
|
|
254
|
+
// Legacy single-connection shape — promote to multi-connection under "primary".
|
|
255
|
+
return {
|
|
256
|
+
connections: {
|
|
257
|
+
primary: {
|
|
258
|
+
url: config.url,
|
|
259
|
+
poolMin: config.poolMin,
|
|
260
|
+
poolMax: config.poolMax,
|
|
261
|
+
pragmas: config.pragmas,
|
|
262
|
+
},
|
|
263
|
+
},
|
|
264
|
+
defaultName: "primary",
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async #runMigrations(
|
|
269
|
+
migrationsPath: string,
|
|
270
|
+
url: string,
|
|
271
|
+
db: AsyncDatabaseConnection,
|
|
272
|
+
tableName: string | undefined,
|
|
273
|
+
): Promise<void> {
|
|
274
|
+
const { existsSync } = await import("node:fs");
|
|
275
|
+
if (!existsSync(migrationsPath)) return;
|
|
276
|
+
|
|
277
|
+
const adapter: DatabaseAdapter = {
|
|
278
|
+
execute: async (sql, params) => {
|
|
279
|
+
await db.execute(sql, params);
|
|
280
|
+
},
|
|
281
|
+
query: <T>(sql: string, params?: unknown[]) =>
|
|
282
|
+
db.query(sql, params) as Promise<T[]>,
|
|
283
|
+
close: () => db.close(),
|
|
284
|
+
// Thread the transactional path through so MigrationRunner takes the
|
|
285
|
+
// atomic branch (a mid-migration failure rolls back both the SQL and the
|
|
286
|
+
// `_migrations` bookkeeping row together). Without this, the runner
|
|
287
|
+
// silently falls back to non-transactional execution.
|
|
288
|
+
runInTransaction: async (batch) => db.runInTransaction(batch),
|
|
289
|
+
};
|
|
290
|
+
const runner = new MigrationRunner(adapter, {
|
|
291
|
+
migrationsDir: migrationsPath,
|
|
292
|
+
dialect: dialectFromUrl(url),
|
|
293
|
+
tableName,
|
|
294
|
+
});
|
|
295
|
+
await runner.migrate();
|
|
296
|
+
}
|
|
297
|
+
}
|