soma-core 1.1.1 → 1.3.1

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 (40) hide show
  1. package/bin/soma-db.cjs +13 -0
  2. package/core/build/db/cli.ts +10 -0
  3. package/core/build/db/emit-entities.ts +45 -0
  4. package/core/build/db/emit-mappers.ts +175 -0
  5. package/core/build/db/emit-prisma-schema.ts +92 -0
  6. package/core/build/db/generate.ts +166 -0
  7. package/core/build/db/ir.ts +75 -0
  8. package/core/build/db/load-db-yaml.ts +241 -0
  9. package/core/server/index.ts +15 -0
  10. package/core/server/infra/db/errors.ts +11 -0
  11. package/core/server/infra/db/mapper/PrismaSomaMapper.ts +313 -0
  12. package/core/server/infra/db/mapper/SomaBaseMapper.ts +23 -0
  13. package/core/server/infra/db/mapper/SomaMapperHooks.ts +13 -0
  14. package/core/server/infra/db/query/SomaQuery.ts +149 -0
  15. package/core/server/infra/db/service/SomaDbService.ts +64 -0
  16. package/core/server/infra/db/soma-db.ts +56 -6
  17. package/core/server/infra/db/types.ts +21 -0
  18. package/core/server/mock/node/cli.mjs +4 -2
  19. package/dist/cli/soma.js +20 -1
  20. package/dist/types/build/db/cli.d.ts +2 -0
  21. package/dist/types/build/db/emit-entities.d.ts +5 -0
  22. package/dist/types/build/db/emit-mappers.d.ts +15 -0
  23. package/dist/types/build/db/emit-prisma-schema.d.ts +2 -0
  24. package/dist/types/build/db/generate.d.ts +7 -0
  25. package/dist/types/build/db/ir.d.ts +58 -0
  26. package/dist/types/build/db/load-db-yaml.d.ts +14 -0
  27. package/dist/types/server/index.d.ts +8 -1
  28. package/dist/types/server/infra/db/errors.d.ts +5 -0
  29. package/dist/types/server/infra/db/mapper/PrismaSomaMapper.d.ts +77 -0
  30. package/dist/types/server/infra/db/mapper/SomaBaseMapper.d.ts +20 -0
  31. package/dist/types/server/infra/db/mapper/SomaMapperHooks.d.ts +12 -0
  32. package/dist/types/server/infra/db/query/SomaQuery.d.ts +42 -0
  33. package/dist/types/server/infra/db/service/SomaDbService.d.ts +24 -0
  34. package/dist/types/server/infra/db/soma-db.d.ts +15 -1
  35. package/dist/types/server/infra/db/types.d.ts +18 -0
  36. package/next.config.js +22 -1
  37. package/package.json +6 -3
  38. package/docs//345/256/242/346/210/267/347/253/257/346/234/215/345/212/241/347/253/257/351/232/224/347/246/273/346/226/271/346/241/210.md +0 -399
  39. package/docs//351/232/224/347/246/273/346/216/245/345/205/245/345/217/230/346/233/264/346/226/271/346/241/210.md +0 -250
  40. package/docs//351/241/265/351/235/242JSON/346/250/241/345/274/217/346/216/245/345/205/245/346/214/207/345/215/227.md +0 -141
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Chainable query builder (MyBatis-Plus QueryWrapper style).
3
+ * Compiles to a Prisma-compatible where / orderBy / select shape.
4
+ */
5
+ import 'server-only';
6
+
7
+ import type { SomaFieldPath } from '../types';
8
+
9
+ type WhereLeaf = Record<string, unknown>;
10
+
11
+ export class SomaQuery<T = Record<string, unknown>> {
12
+ private readonly conditions: WhereLeaf[] = [];
13
+ private readonly orGroups: WhereLeaf[][] = [];
14
+ private readonly order: Array<Record<string, 'asc' | 'desc'>> = [];
15
+ private selectFields: string[] | null = null;
16
+ private includeDeletedFlag = false;
17
+
18
+ eq(field: SomaFieldPath<T>, value: unknown): this {
19
+ this.conditions.push({ [field]: value });
20
+ return this;
21
+ }
22
+
23
+ ne(field: SomaFieldPath<T>, value: unknown): this {
24
+ this.conditions.push({ [field]: { not: value } });
25
+ return this;
26
+ }
27
+
28
+ in(field: SomaFieldPath<T>, values: unknown[]): this {
29
+ this.conditions.push({ [field]: { in: values } });
30
+ return this;
31
+ }
32
+
33
+ notIn(field: SomaFieldPath<T>, values: unknown[]): this {
34
+ this.conditions.push({ [field]: { notIn: values } });
35
+ return this;
36
+ }
37
+
38
+ like(field: SomaFieldPath<T>, value: string): this {
39
+ this.conditions.push({ [field]: { contains: value } });
40
+ return this;
41
+ }
42
+
43
+ gt(field: SomaFieldPath<T>, value: unknown): this {
44
+ this.conditions.push({ [field]: { gt: value } });
45
+ return this;
46
+ }
47
+
48
+ ge(field: SomaFieldPath<T>, value: unknown): this {
49
+ this.conditions.push({ [field]: { gte: value } });
50
+ return this;
51
+ }
52
+
53
+ lt(field: SomaFieldPath<T>, value: unknown): this {
54
+ this.conditions.push({ [field]: { lt: value } });
55
+ return this;
56
+ }
57
+
58
+ le(field: SomaFieldPath<T>, value: unknown): this {
59
+ this.conditions.push({ [field]: { lte: value } });
60
+ return this;
61
+ }
62
+
63
+ between(field: SomaFieldPath<T>, start: unknown, end: unknown): this {
64
+ this.conditions.push({ [field]: { gte: start, lte: end } });
65
+ return this;
66
+ }
67
+
68
+ isNull(field: SomaFieldPath<T>): this {
69
+ this.conditions.push({ [field]: null });
70
+ return this;
71
+ }
72
+
73
+ isNotNull(field: SomaFieldPath<T>): this {
74
+ this.conditions.push({ [field]: { not: null } });
75
+ return this;
76
+ }
77
+
78
+ /** Nested AND group: q.and(sub => sub.eq(...).eq(...)) */
79
+ and(builder: (q: SomaQuery<T>) => void): this {
80
+ const nested = new SomaQuery<T>();
81
+ builder(nested);
82
+ const where = nested.toPrismaWhere();
83
+ if (where) this.conditions.push(where);
84
+ return this;
85
+ }
86
+
87
+ /** Nested OR group: q.or(sub => sub.eq(...).eq(...)) — OR among conditions in the subgroup */
88
+ or(builder: (q: SomaQuery<T>) => void): this {
89
+ const nested = new SomaQuery<T>();
90
+ builder(nested);
91
+ if (nested.conditions.length > 0) {
92
+ this.orGroups.push([...nested.conditions]);
93
+ }
94
+ return this;
95
+ }
96
+
97
+ orderByAsc(field: SomaFieldPath<T>): this {
98
+ this.order.push({ [field]: 'asc' });
99
+ return this;
100
+ }
101
+
102
+ orderByDesc(field: SomaFieldPath<T>): this {
103
+ this.order.push({ [field]: 'desc' });
104
+ return this;
105
+ }
106
+
107
+ select(...fields: Array<SomaFieldPath<T>>): this {
108
+ this.selectFields = fields.map(String);
109
+ return this;
110
+ }
111
+
112
+ /** Include soft-deleted rows when mapper has logicDelete configured */
113
+ includeDeleted(flag = true): this {
114
+ this.includeDeletedFlag = flag;
115
+ return this;
116
+ }
117
+
118
+ /** @internal */
119
+ shouldIncludeDeleted(): boolean {
120
+ return this.includeDeletedFlag;
121
+ }
122
+
123
+ /** @internal Prisma where */
124
+ toPrismaWhere(): Record<string, unknown> | undefined {
125
+ const parts: WhereLeaf[] = [...this.conditions];
126
+ for (const group of this.orGroups) {
127
+ if (group.length === 1) parts.push(group[0]!);
128
+ else if (group.length > 1) parts.push({ OR: group });
129
+ }
130
+ if (parts.length === 0) return undefined;
131
+ if (parts.length === 1) return parts[0];
132
+ return { AND: parts };
133
+ }
134
+
135
+ /** @internal Prisma orderBy */
136
+ toPrismaOrderBy(): Array<Record<string, 'asc' | 'desc'>> | undefined {
137
+ return this.order.length > 0 ? this.order : undefined;
138
+ }
139
+
140
+ /** @internal Prisma select object */
141
+ toPrismaSelect(): Record<string, true> | undefined {
142
+ if (!this.selectFields || this.selectFields.length === 0) return undefined;
143
+ const select: Record<string, true> = {};
144
+ for (const field of this.selectFields) {
145
+ select[field] = true;
146
+ }
147
+ return select;
148
+ }
149
+ }
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Service layer over SomaBaseMapper (MyBatis-Plus IService style).
3
+ */
4
+ import 'server-only';
5
+
6
+ import type { SomaBaseMapper } from '../mapper/SomaBaseMapper';
7
+ import type { SomaQuery } from '../query/SomaQuery';
8
+ import type { PageRequest, PageResult } from '../types';
9
+
10
+ export class SomaDbService<T extends object, ID = string> {
11
+ constructor(protected readonly baseMapper: SomaBaseMapper<T, ID>) {}
12
+
13
+ getMapper(): SomaBaseMapper<T, ID> {
14
+ return this.baseMapper;
15
+ }
16
+
17
+ selectById(id: ID): Promise<T | null> {
18
+ return this.baseMapper.selectById(id);
19
+ }
20
+
21
+ selectBatchIds(ids: ID[]): Promise<T[]> {
22
+ return this.baseMapper.selectBatchIds(ids);
23
+ }
24
+
25
+ selectOne(query?: SomaQuery<T>): Promise<T | null> {
26
+ return this.baseMapper.selectOne(query);
27
+ }
28
+
29
+ selectList(query?: SomaQuery<T>): Promise<T[]> {
30
+ return this.baseMapper.selectList(query);
31
+ }
32
+
33
+ selectCount(query?: SomaQuery<T>): Promise<number> {
34
+ return this.baseMapper.selectCount(query);
35
+ }
36
+
37
+ selectPage(page: PageRequest, query?: SomaQuery<T>): Promise<PageResult<T>> {
38
+ return this.baseMapper.selectPage(page, query);
39
+ }
40
+
41
+ save(entity: Partial<T>): Promise<T> {
42
+ return this.baseMapper.insert(entity);
43
+ }
44
+
45
+ saveBatch(entities: Partial<T>[]): Promise<T[]> {
46
+ return this.baseMapper.insertBatch(entities);
47
+ }
48
+
49
+ updateById(id: ID, patch: Partial<T>): Promise<T> {
50
+ return this.baseMapper.updateById(id, patch);
51
+ }
52
+
53
+ update(query: SomaQuery<T>, patch: Partial<T>): Promise<number> {
54
+ return this.baseMapper.update(query, patch);
55
+ }
56
+
57
+ removeById(id: ID): Promise<boolean> {
58
+ return this.baseMapper.deleteById(id);
59
+ }
60
+
61
+ remove(query: SomaQuery<T>): Promise<number> {
62
+ return this.baseMapper.delete(query);
63
+ }
64
+ }
@@ -1,16 +1,24 @@
1
1
  /**
2
2
  * Server-only DB capability for Host `api/service`.
3
3
  *
4
- * Framework provides registration / singleton helpers only.
4
+ * Framework provides registration / singleton / provider lifecycle.
5
5
  * Host owns Prisma (or other) client, schema, and queries.
6
6
  * Never import from Domain / `'use client'` code.
7
7
  */
8
8
  import 'server-only';
9
9
 
10
10
  const STATE_KEY = Symbol.for('soma.server.db');
11
+ const PROVIDER_KEY = Symbol.for('soma.server.db.provider');
12
+ const SINGLETON_KEY = Symbol.for('soma.server.db.singleton');
13
+
14
+ export interface ISomaDbProvider<TClient = unknown> {
15
+ getClient(): TClient;
16
+ disconnect?(): Promise<void> | void;
17
+ }
11
18
 
12
19
  interface SomaDbState {
13
20
  client: unknown;
21
+ provider?: ISomaDbProvider;
14
22
  }
15
23
 
16
24
  function getState(): SomaDbState {
@@ -30,6 +38,16 @@ export function setSomaDb<T>(client: T): T {
30
38
  return client;
31
39
  }
32
40
 
41
+ /**
42
+ * Register a provider (client + optional disconnect).
43
+ */
44
+ export function registerSomaDbProvider<T>(provider: ISomaDbProvider<T>): T {
45
+ const record = globalThis as unknown as Record<PropertyKey, ISomaDbProvider | undefined>;
46
+ record[PROVIDER_KEY] = provider as ISomaDbProvider;
47
+ getState().provider = provider as ISomaDbProvider;
48
+ return setSomaDb(provider.getClient());
49
+ }
50
+
33
51
  /**
34
52
  * Read the registered DB client.
35
53
  * Throws if `setSomaDb` / `createSomaDbSingleton` has not run yet.
@@ -45,9 +63,29 @@ export function getSomaDb<T = unknown>(): T {
45
63
  return client as T;
46
64
  }
47
65
 
66
+ /** Disconnect provider if registered, then clear state. */
67
+ export async function disconnectSomaDb(): Promise<void> {
68
+ const state = getState();
69
+ const provider = state.provider;
70
+ if (provider?.disconnect) {
71
+ await provider.disconnect();
72
+ } else {
73
+ const client = state.client as { $disconnect?: () => Promise<void> } | undefined;
74
+ if (client && typeof client.$disconnect === 'function') {
75
+ await client.$disconnect();
76
+ }
77
+ }
78
+ resetSomaDb();
79
+ }
80
+
48
81
  /** Test / hot-reload helper. */
49
82
  export function resetSomaDb(): void {
50
- getState().client = undefined;
83
+ const state = getState();
84
+ state.client = undefined;
85
+ state.provider = undefined;
86
+ const record = globalThis as unknown as Record<PropertyKey, unknown>;
87
+ delete record[PROVIDER_KEY];
88
+ delete record[SINGLETON_KEY];
51
89
  }
52
90
 
53
91
  /**
@@ -62,9 +100,21 @@ export function resetSomaDb(): void {
62
100
  */
63
101
  export function createSomaDbSingleton<T>(factory: () => T): T {
64
102
  const record = globalThis as unknown as Record<PropertyKey, T | undefined>;
65
- const singletonKey = Symbol.for('soma.server.db.singleton');
66
- if (record[singletonKey] === undefined) {
67
- record[singletonKey] = factory();
103
+ if (record[SINGLETON_KEY] === undefined) {
104
+ record[SINGLETON_KEY] = factory();
105
+ }
106
+ return setSomaDb(record[SINGLETON_KEY] as T);
107
+ }
108
+
109
+ /**
110
+ * Scoped client for tests: set for duration of fn, then restore previous.
111
+ */
112
+ export async function withSomaDb<T, R>(client: T, fn: () => Promise<R> | R): Promise<R> {
113
+ const previous = getState().client;
114
+ setSomaDb(client);
115
+ try {
116
+ return await fn();
117
+ } finally {
118
+ getState().client = previous;
68
119
  }
69
- return setSomaDb(record[singletonKey] as T);
70
120
  }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Shared DB paging types (MyBatis-Plus style).
3
+ * Server-only; never import from Domain / client code.
4
+ */
5
+ import 'server-only';
6
+
7
+ export interface PageRequest {
8
+ /** 1-based page index */
9
+ page: number;
10
+ /** page size */
11
+ size: number;
12
+ }
13
+
14
+ export interface PageResult<T> {
15
+ records: T[];
16
+ total: number;
17
+ page: number;
18
+ size: number;
19
+ }
20
+
21
+ export type SomaFieldPath<T> = Extract<keyof T, string> | (string & {});
@@ -10,8 +10,10 @@ import {
10
10
  import { filterMockEnvironment } from './environment-policy.mjs';
11
11
 
12
12
  const MOCK_COMMANDS = new Set(['dev', 'build', 'start']);
13
- const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
14
- const DEFAULT_PRELOAD_URL = pathToFileURL(path.join(PACKAGE_ROOT, 'core', 'mock', 'node', 'preload.mjs')).href;
13
+ const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
14
+ const DEFAULT_PRELOAD_URL = pathToFileURL(
15
+ path.join(path.dirname(fileURLToPath(import.meta.url)), 'preload.mjs'),
16
+ ).href;
15
17
 
16
18
  export { SomaMockCliError, terminateMockChild };
17
19
 
package/dist/cli/soma.js CHANGED
@@ -11,6 +11,10 @@ const args = process.argv.slice(2);
11
11
  const command = args[0] || 'dev';
12
12
  const delegated = ['doctor', 'sync', 'lsp', 'codegen', 'init', 'package-vscode'];
13
13
  const packageRoot = node_path_1.default.resolve(__dirname, '../..');
14
+ if (command === 'db') {
15
+ const child = (0, node_child_process_1.spawnSync)(process.execPath, [node_path_1.default.join(packageRoot, 'bin', 'soma-db.cjs'), ...args.slice(1)], { cwd: process.cwd(), stdio: 'inherit', env: process.env });
16
+ process.exit(child.status === null ? 1 : child.status);
17
+ }
14
18
  function lstatIfPresent(filePath) {
15
19
  try {
16
20
  return node_fs_1.default.lstatSync(filePath);
@@ -371,6 +375,20 @@ function resolveNextWorkspaceDir(hostDir) {
371
375
  assertReusableWorkspaceDir(workspaceDir);
372
376
  return workspaceDir;
373
377
  }
378
+ /** Mount Host `public/` into the Next workspace so files are served at `/…`. */
379
+ function ensureHostPublicAssets(hostDir, workspaceDir) {
380
+ const hostPublic = node_path_1.default.join(hostDir, 'public');
381
+ const workspacePublic = node_path_1.default.join(workspaceDir, 'public');
382
+ const hostPublicStat = lstatIfPresent(hostPublic);
383
+ if (hostPublicStat?.isDirectory()) {
384
+ linkOrCopy(hostPublic, workspacePublic, 'dir');
385
+ return;
386
+ }
387
+ const existing = lstatIfPresent(workspacePublic);
388
+ if (existing) {
389
+ node_fs_1.default.rmSync(workspacePublic, { recursive: true, force: true });
390
+ }
391
+ }
374
392
  function ensureNextWorkspace(hostDir) {
375
393
  const workspaceDir = resolveNextWorkspaceDir(hostDir);
376
394
  node_fs_1.default.mkdirSync(workspaceDir, { recursive: true });
@@ -381,6 +399,7 @@ function ensureNextWorkspace(hostDir) {
381
399
  linkOrCopy(node_path_1.default.join(packageRoot, 'postcss.config.js'), node_path_1.default.join(workspaceDir, 'postcss.config.js'), 'file');
382
400
  linkOrCopy(node_path_1.default.join(packageRoot, 'tailwind.config.ts'), node_path_1.default.join(workspaceDir, 'tailwind.config.ts'), 'file');
383
401
  linkOrCopy(node_path_1.default.join(packageRoot, 'global.d.ts'), node_path_1.default.join(workspaceDir, 'global.d.ts'), 'file');
402
+ ensureHostPublicAssets(hostDir, workspaceDir);
384
403
  const hasWorkspaceNodeModules = ensureWorkspaceNodeModules(workspaceDir);
385
404
  writeFileIfChanged(node_path_1.default.join(workspaceDir, 'next.config.js'), `module.exports = require(${JSON.stringify(node_path_1.default.join(packageRoot, 'next.config.js'))});\n`);
386
405
  writeFileIfChanged(node_path_1.default.join(workspaceDir, 'tsconfig.json'), buildNextWorkspaceTsconfig(workspaceDir, hasWorkspaceNodeModules));
@@ -396,7 +415,7 @@ if (delegated.includes(command)) {
396
415
  process.exit(child.status === null ? 1 : child.status);
397
416
  }
398
417
  if (!['dev', 'build', 'start'].includes(command)) {
399
- console.error(`Usage: soma <dev|build|start|${delegated.join('|')}> [...args]`);
418
+ console.error(`Usage: soma <dev|build|start|db|${delegated.join('|')}> [...args]`);
400
419
  process.exit(1);
401
420
  }
402
421
  const nextBin = resolveNextBin();
@@ -0,0 +1,2 @@
1
+ export { runSomaDbCli, generateSomaDb } from './generate';
2
+ export declare function main(argv?: string[], hostDir?: string): never;
@@ -0,0 +1,5 @@
1
+ import type { DbSchemaIr } from './ir';
2
+ export declare function emitEntities(schema: DbSchemaIr): Array<{
3
+ fileName: string;
4
+ content: string;
5
+ }>;
@@ -0,0 +1,15 @@
1
+ import type { DbSchemaIr } from './ir';
2
+ export declare function emitMappers(schema: DbSchemaIr): Array<{
3
+ fileName: string;
4
+ content: string;
5
+ }>;
6
+ export declare function emitServices(schema: DbSchemaIr): Array<{
7
+ fileName: string;
8
+ content: string;
9
+ }>;
10
+ export declare function emitRepositoryIndex(schema: DbSchemaIr): string;
11
+ /** CRUD Route Handler under api/service/db/{Model}.ts → /api/db/{model} */
12
+ export declare function emitApiServices(schema: DbSchemaIr): Array<{
13
+ fileName: string;
14
+ content: string;
15
+ }>;
@@ -0,0 +1,2 @@
1
+ import type { DbSchemaIr } from './ir';
2
+ export declare function emitPrismaSchema(schema: DbSchemaIr): string;
@@ -0,0 +1,7 @@
1
+ import type { DbGenerateOptions, DbSchemaIr } from './ir';
2
+ export interface DbGenerateResult {
3
+ schema: DbSchemaIr;
4
+ written: string[];
5
+ }
6
+ export declare function generateSomaDb(options: DbGenerateOptions): DbGenerateResult;
7
+ export declare function runSomaDbCli(argv: string[], hostDir?: string): number;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Schema IR for Host config/db.yaml → Prisma + repository codegen.
3
+ * MySQL only.
4
+ */
5
+ export type DbFieldType = 'string' | 'int' | 'bigint' | 'float' | 'decimal' | 'boolean' | 'datetime' | 'json' | 'text';
6
+ export type DbFieldDefault = 'cuid' | 'uuid' | 'now' | 'autoincrement' | string | number | boolean;
7
+ export interface DbFieldIr {
8
+ name: string;
9
+ type: DbFieldType;
10
+ id?: boolean;
11
+ optional?: boolean;
12
+ unique?: boolean;
13
+ default?: DbFieldDefault;
14
+ precision?: number;
15
+ scale?: number;
16
+ /** Soft-delete column (TableLogic) */
17
+ logicDelete?: boolean;
18
+ /** Auto-fill on insert */
19
+ fillOnInsert?: boolean;
20
+ /** Auto-fill on update (and insert if also fillOnInsert or createdAt pattern) */
21
+ fillOnUpdate?: boolean;
22
+ }
23
+ export type DbRelationKind = 'hasMany' | 'belongsTo';
24
+ export interface DbRelationIr {
25
+ name: string;
26
+ kind: DbRelationKind;
27
+ model: string;
28
+ fields?: string[];
29
+ references?: string[];
30
+ optional?: boolean;
31
+ }
32
+ export interface DbModelIr {
33
+ name: string;
34
+ table: string;
35
+ idField: string;
36
+ fields: DbFieldIr[];
37
+ relations: DbRelationIr[];
38
+ logicDeleteField?: string;
39
+ createdAtField?: string;
40
+ updatedAtField?: string;
41
+ }
42
+ export interface DbSchemaIr {
43
+ provider: 'mysql';
44
+ datasourceUrlEnv: string;
45
+ models: DbModelIr[];
46
+ /** When true, also emit api/service/db/* CRUD scaffolds */
47
+ generateApiService: boolean;
48
+ }
49
+ export interface DbGenerateOptions {
50
+ hostDir: string;
51
+ dbYamlPath?: string;
52
+ appConfigPath?: string;
53
+ repositoryDir?: string;
54
+ prismaSchemaPath?: string;
55
+ scaffoldLibDb?: boolean;
56
+ /** Override yaml generateApiService */
57
+ generateApiService?: boolean;
58
+ }
@@ -0,0 +1,14 @@
1
+ import type { DbModelIr, DbSchemaIr } from './ir';
2
+ export declare function parseDbYaml(source: string): {
3
+ models: DbModelIr[];
4
+ generateApiService: boolean;
5
+ };
6
+ export declare function readDatasourceFromAppConfig(appConfigYaml: string): {
7
+ provider: 'mysql';
8
+ datasourceUrlEnv: string;
9
+ };
10
+ export declare function loadDbSchemaIr(options: {
11
+ dbYamlPath: string;
12
+ appConfigPath: string | null;
13
+ }): DbSchemaIr;
14
+ export declare function resolveDefaultDbYamlPath(hostDir: string): string;
@@ -16,4 +16,11 @@ export { resolveServiceFilePath, toPascalCase } from './api/service-path';
16
16
  export { invokeHostRequestHook } from './host/invoke-host-request-hook';
17
17
  export { resolveHostRequestHook, type SomaHostRequestContext, type SomaHostRequestKind, type SomaRequestHook, } from './host/resolve-host-request-hook';
18
18
  export { loadSomaServerPageAssets, SomaPageAssetError, type SomaServerPageAssets, type SomaPageAssetLoadProfile, } from './host/server-page-assets';
19
- export { setSomaDb, getSomaDb, resetSomaDb, createSomaDbSingleton, } from './infra/db/soma-db';
19
+ export { setSomaDb, getSomaDb, resetSomaDb, createSomaDbSingleton, registerSomaDbProvider, disconnectSomaDb, withSomaDb, type ISomaDbProvider, } from './infra/db/soma-db';
20
+ export { SomaQuery } from './infra/db/query/SomaQuery';
21
+ export type { SomaBaseMapper } from './infra/db/mapper/SomaBaseMapper';
22
+ export type { SomaMapperHooks } from './infra/db/mapper/SomaMapperHooks';
23
+ export { PrismaSomaMapper, type PrismaSomaMapperOptions, type PrismaDelegate, } from './infra/db/mapper/PrismaSomaMapper';
24
+ export { SomaDbService } from './infra/db/service/SomaDbService';
25
+ export type { PageRequest, PageResult, SomaFieldPath } from './infra/db/types';
26
+ export { SomaDbError } from './infra/db/errors';
@@ -0,0 +1,5 @@
1
+ import 'server-only';
2
+ export declare class SomaDbError extends Error {
3
+ readonly code: string;
4
+ constructor(code: string, message: string);
5
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Prisma-backed SomaBaseMapper (MySQL).
3
+ * Supports logic delete, auto-fill timestamps, and lifecycle hooks.
4
+ */
5
+ import 'server-only';
6
+ import { SomaQuery } from '../query/SomaQuery';
7
+ import type { SomaBaseMapper } from './SomaBaseMapper';
8
+ import type { SomaMapperHooks } from './SomaMapperHooks';
9
+ import type { PageRequest, PageResult } from '../types';
10
+ export interface PrismaDelegate {
11
+ findUnique(args: Record<string, unknown>): Promise<unknown>;
12
+ findFirst(args: Record<string, unknown>): Promise<unknown>;
13
+ findMany(args: Record<string, unknown>): Promise<unknown[]>;
14
+ count(args: Record<string, unknown>): Promise<number>;
15
+ create(args: Record<string, unknown>): Promise<unknown>;
16
+ createMany?(args: Record<string, unknown>): Promise<{
17
+ count: number;
18
+ }>;
19
+ update(args: Record<string, unknown>): Promise<unknown>;
20
+ updateMany(args: Record<string, unknown>): Promise<{
21
+ count: number;
22
+ }>;
23
+ delete(args: Record<string, unknown>): Promise<unknown>;
24
+ deleteMany(args: Record<string, unknown>): Promise<{
25
+ count: number;
26
+ }>;
27
+ }
28
+ export interface PrismaSomaMapperOptions {
29
+ /** Prisma client model key, e.g. "order" for model Order */
30
+ model: string;
31
+ /** Primary key field name, default "id" */
32
+ idField?: string;
33
+ /**
34
+ * Soft-delete field. If set:
35
+ * - selects filter `field IS NULL` unless query.includeDeleted()
36
+ * - delete* sets field to Date (or logicDeleteValue) instead of hard delete
37
+ */
38
+ logicDeleteField?: string;
39
+ /** Value written on soft delete; default `new Date()` */
40
+ logicDeleteValue?: unknown | (() => unknown);
41
+ /** Auto-set on insert when missing */
42
+ createdAtField?: string;
43
+ /** Auto-set on insert/update */
44
+ updatedAtField?: string;
45
+ hooks?: SomaMapperHooks;
46
+ }
47
+ export declare class PrismaSomaMapper<T extends object = Record<string, unknown>, ID = string> implements SomaBaseMapper<T, ID> {
48
+ protected readonly model: string;
49
+ protected readonly idField: string;
50
+ protected readonly logicDeleteField?: string;
51
+ protected readonly logicDeleteValue?: unknown | (() => unknown);
52
+ protected readonly createdAtField?: string;
53
+ protected readonly updatedAtField?: string;
54
+ protected readonly hooks: SomaMapperHooks<T>;
55
+ constructor(options: PrismaSomaMapperOptions);
56
+ protected delegate(): PrismaDelegate;
57
+ protected softDeleteMarker(): unknown;
58
+ protected notDeletedWhere(): Record<string, unknown> | undefined;
59
+ protected applyLogicDeleteFilter(query: SomaQuery<T> | undefined, where: Record<string, unknown> | undefined): Record<string, unknown> | undefined;
60
+ protected buildArgs(query?: SomaQuery<T>): Record<string, unknown>;
61
+ protected applyInsertFill(entity: Partial<T>): Partial<T>;
62
+ protected applyUpdateFill(patch: Partial<T>): Partial<T>;
63
+ selectById(id: ID): Promise<T | null>;
64
+ selectBatchIds(ids: ID[]): Promise<T[]>;
65
+ selectOne(query?: SomaQuery<T>): Promise<T | null>;
66
+ selectList(query?: SomaQuery<T>): Promise<T[]>;
67
+ selectCount(query?: SomaQuery<T>): Promise<number>;
68
+ selectPage(page: PageRequest, query?: SomaQuery<T>): Promise<PageResult<T>>;
69
+ insert(entity: Partial<T>): Promise<T>;
70
+ insertBatch(entities: Partial<T>[]): Promise<T[]>;
71
+ updateById(id: ID, patch: Partial<T>): Promise<T>;
72
+ update(query: SomaQuery<T>, patch: Partial<T>): Promise<number>;
73
+ deleteById(id: ID): Promise<boolean>;
74
+ delete(query: SomaQuery<T>): Promise<number>;
75
+ /** Force physical delete even when logicDeleteField is set */
76
+ forceDeleteById(id: ID): Promise<boolean>;
77
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * MyBatis-Plus BaseMapper-style contract for Host repository mappers.
3
+ */
4
+ import 'server-only';
5
+ import type { SomaQuery } from '../query/SomaQuery';
6
+ import type { PageRequest, PageResult } from '../types';
7
+ export interface SomaBaseMapper<T, ID = string> {
8
+ selectById(id: ID): Promise<T | null>;
9
+ selectBatchIds(ids: ID[]): Promise<T[]>;
10
+ selectOne(query?: SomaQuery<T>): Promise<T | null>;
11
+ selectList(query?: SomaQuery<T>): Promise<T[]>;
12
+ selectCount(query?: SomaQuery<T>): Promise<number>;
13
+ selectPage(page: PageRequest, query?: SomaQuery<T>): Promise<PageResult<T>>;
14
+ insert(entity: Partial<T>): Promise<T>;
15
+ insertBatch(entities: Partial<T>[]): Promise<T[]>;
16
+ updateById(id: ID, patch: Partial<T>): Promise<T>;
17
+ update(query: SomaQuery<T>, patch: Partial<T>): Promise<number>;
18
+ deleteById(id: ID): Promise<boolean>;
19
+ delete(query: SomaQuery<T>): Promise<number>;
20
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Mapper lifecycle hooks (MyBatis-Plus interceptor style, simplified).
3
+ */
4
+ import 'server-only';
5
+ export interface SomaMapperHooks<T extends object = Record<string, unknown>> {
6
+ beforeInsert?(entity: Partial<T>): Partial<T> | void | Promise<Partial<T> | void>;
7
+ afterInsert?(entity: T): void | Promise<void>;
8
+ beforeUpdate?(patch: Partial<T>): Partial<T> | void | Promise<Partial<T> | void>;
9
+ afterUpdate?(entity: T): void | Promise<void>;
10
+ beforeDelete?(idOrQuery: unknown): void | Promise<void>;
11
+ afterDelete?(result: unknown): void | Promise<void>;
12
+ }