Skip to content

Commit 2c2f9db

Browse files
committed
fix: rewrite model generation
generate model from ground up and diff later
1 parent 7d3997c commit 2c2f9db

File tree

5 files changed

+570
-207
lines changed

5 files changed

+570
-207
lines changed

packages/cli/src/actions/db.ts

Lines changed: 22 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
1+
import type { Model } from '@zenstackhq/language/ast';
12
import { ZModelCodeGenerator } from '@zenstackhq/sdk';
23
import fs from 'node:fs';
34
import path from 'node:path';
45
import { execPackage } from '../utils/exec-utils';
56
import { generateTempPrismaSchema, getSchemaFile, handleSubProcessError, loadSchemaDocumentWithServices } from './action-utils';
67
import { syncEnums, syncRelation, syncTable, type Relation } from './pull';
78
import { providers } from './pull/provider';
8-
import { getDatasource, getDbName } from './pull/utils';
9+
import { getDatasource } from './pull/utils';
910

1011
type PushOptions = {
1112
schema?: string;
@@ -84,31 +85,35 @@ async function runPull(options: PullOptions) {
8485

8586
const { enums, tables } = await provider.introspect(datasource.url)
8687

87-
syncEnums({ dbEnums: enums, model, services })
88+
const newModel: Model = {
89+
$type: 'Model',
90+
$container: undefined,
91+
$containerProperty: undefined,
92+
$containerIndex: undefined,
93+
declarations: [...model.declarations.filter(d => ["DataSource"].includes(d.$type))],
94+
imports: [],
95+
};
96+
97+
98+
syncEnums({ dbEnums: enums, model: newModel, services })
8899

89-
const resolveRelations: Relation[] = []
90-
for (const table of tables) {
91-
const relations = syncTable({ table, model, provider, services })
92-
resolveRelations.push(...relations)
93-
}
94100

95-
for (const relation of resolveRelations) {
96-
syncRelation({ model, relation, services });
101+
102+
const resolvedRelations: Relation[] = []
103+
for (const table of tables) {
104+
const relations = syncTable({ table, model: newModel, provider, services })
105+
resolvedRelations.push(...relations)
97106
}
98107

99-
for (const d of model.declarations) {
100-
if (d.$type !== 'DataModel') continue
101-
const found = tables.find((t) => getDbName(d) === t.name)
102-
if (!found) {
103-
delete (d.$container as any)[d.$containerProperty!][d.$containerIndex!]
104-
}
108+
for (const relation of resolvedRelations) {
109+
syncRelation({ model: newModel, relation, services });
105110
}
106111

107-
model.declarations = model.declarations.filter((d) => d !== undefined)
112+
//TODO: diff models and apply changes only
108113

109114
const generator = await new ZModelCodeGenerator();
110115

111-
const zmodelSchema = await generator.generate(model)
116+
const zmodelSchema = await generator.generate(newModel)
112117

113118
console.log(options.out ? `Writing to ${options.out}` : schemaFile);
114119

0 commit comments

Comments
 (0)