From 71a0284689f5892be75a25642861811e20948892 Mon Sep 17 00:00:00 2001 From: Dmytro Shyryaiev Date: Thu, 23 May 2024 18:51:21 +0300 Subject: [PATCH] Fixed an error when creating a structure file for 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. --- lib/dbms.js | 5 ++++- lib/pg.js | 8 ++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/lib/dbms.js b/lib/dbms.js index 9bf7085..9be501d 100644 --- a/lib/dbms.js +++ b/lib/dbms.js @@ -51,6 +51,8 @@ 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 script = []; const ins = []; const upd = []; @@ -58,13 +60,14 @@ const create = async (modelPath, outputPath = modelPath) => { for (const name of model.order) { const entity = model.entities.get(name); if (metaschema.KIND_STORED.includes(entity.kind)) { - script.push(createEntity(model, name), ''); + script.push(createEntity(model, name, modelRemain), ''); if (model.entities.get('Identifier')) { const { inserts, updates } = registerEntity(model, name); ins.push(inserts); upd.push(updates); } } + delete modelRemain[name]; } if (ins.length) script.push(...ins, '', ...upd, ''); const dbPath = path.join(outputPath, 'database.sql'); diff --git a/lib/pg.js b/lib/pg.js index 2af7051..707fd81 100644 --- a/lib/pg.js +++ b/lib/pg.js @@ -138,7 +138,7 @@ const flatFields = (fields) => { return flat; }; -const createEntity = (model, name) => { +const createEntity = (model, name, modelRemain = {}) => { const entity = model.entities.get(name); const sql = []; const idx = []; @@ -183,7 +183,10 @@ const createEntity = (model, name) => { const ref = model.entities.get(def.type); if (!ref) throw new Error(`Unknown schema: ${def.type}`); const refId = ref.kind === 'registry'; - idx.push(foreignKey(name, field, def, refId)); + const fKey = foreignKey(name, field, def, refId); + if (def.type in modelRemain && def.type !== name) { + modelRemain[def.type] = fKey; + } else idx.push(fKey); } } } @@ -201,6 +204,7 @@ const createEntity = (model, name) => { } sql[sql.length - 1] = sql[sql.length - 1].slice(0, -1); sql.push(');'); + if (modelRemain[name]) idx.push(modelRemain[name]); return sql.join('\n') + '\n\n' + idx.join('\n'); };