Skip to content

Commit

Permalink
Fixed an error when creating a structure file for
Browse files Browse the repository at this point in the history
Fixed an error when creating structure.sql file for a database, when it is necessary to create a relation for tables that refer to each other.
Fixed ussues Metasql metarhia#291
  • Loading branch information
turone committed May 24, 2024
1 parent 71a0284 commit c5fd5f8
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
10 changes: 6 additions & 4 deletions lib/dbms.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,23 +51,25 @@ const getPreviousVersion = async (modelPath) => {
const create = async (modelPath, outputPath = modelPath) => {
console.log('Generating SQL DDL script ' + shorten(outputPath));
const model = await loadModel(modelPath);
const modelRemain = {};
model.order.forEach((value) => (modelRemain[value] = null));
const delayedKeys = {};
for (const key of model.order) {
delayedKeys[key] = null;
}
const script = [];
const ins = [];
const upd = [];
const { createEntity, registerEntity } = dbms[model.database.driver];
for (const name of model.order) {
const entity = model.entities.get(name);
if (metaschema.KIND_STORED.includes(entity.kind)) {
script.push(createEntity(model, name, modelRemain), '');
script.push(createEntity(model, name, delayedKeys), '');
if (model.entities.get('Identifier')) {
const { inserts, updates } = registerEntity(model, name);
ins.push(inserts);
upd.push(updates);
}
}
delete modelRemain[name];
delete delayedKeys[name];
}
if (ins.length) script.push(...ins, '', ...upd, '');
const dbPath = path.join(outputPath, 'database.sql');
Expand Down
12 changes: 7 additions & 5 deletions lib/pg.js
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ const flatFields = (fields) => {
return flat;
};

const createEntity = (model, name, modelRemain = {}) => {
const createEntity = (model, name, delayedKeys = {}) => {
const entity = model.entities.get(name);
const sql = [];
const idx = [];
Expand Down Expand Up @@ -184,9 +184,11 @@ const createEntity = (model, name, modelRemain = {}) => {
if (!ref) throw new Error(`Unknown schema: ${def.type}`);
const refId = ref.kind === 'registry';
const fKey = foreignKey(name, field, def, refId);
if (def.type in modelRemain && def.type !== name) {
modelRemain[def.type] = fKey;
} else idx.push(fKey);
if (def.type in delayedKeys && def.type !== name) {
delayedKeys[def.type] = fKey;
} else {
idx.push(fKey);
}
}
}
}
Expand All @@ -204,7 +206,7 @@ const createEntity = (model, name, modelRemain = {}) => {
}
sql[sql.length - 1] = sql[sql.length - 1].slice(0, -1);
sql.push(');');
if (modelRemain[name]) idx.push(modelRemain[name]);
if (delayedKeys[name]) idx.push(delayedKeys[name]);
return sql.join('\n') + '\n\n' + idx.join('\n');
};

Expand Down

0 comments on commit c5fd5f8

Please sign in to comment.