Skip to content

Commit

Permalink
fix: complex custom promary key generation
Browse files Browse the repository at this point in the history
Refs: #52

PR-URL: #56
  • Loading branch information
tshemsedinov committed Oct 9, 2020
1 parent d366680 commit 0e26b47
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions lib/schema-pg.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,20 @@ const foreignKey = (entityName, def) => {
);
};

const primaryCustom = (entityName, fields) => {
const fieldNames = `"${fields.map(name => name + 'Id').join('", "')}"`;
const primaryCustom = (entityName, fields, entity) => {
const idx = [...fields];
if (entity) {
for (let i = 0; i < idx.length; i++) {
const field = idx[i];
const def = entity[field];
if (!def) continue;
const { type } = def;
if (!type) continue;
const ref = isUpperCamel(type);
idx[i] = ref ? field + 'Id' : field;
}
}
const fieldNames = `"${idx.join('", "')}"`;
const constraint = `"pk${entityName}" PRIMARY KEY (${fieldNames})`;
return `ALTER TABLE "${entityName}" ADD CONSTRAINT ${constraint};`;
};
Expand Down Expand Up @@ -147,7 +159,7 @@ class PgSchema extends DatabaseSchema {
}
if (def.unique || def.index) idx.push(createIndex(name, def));
if (def.primary) {
idx[0] = primaryCustom(name, def.primary);
idx[0] = primaryCustom(name, def.primary, entity);
sql.splice(1, 1);
}
if (def.many) idx.push(await createMany(name, def, this));
Expand Down

0 comments on commit 0e26b47

Please sign in to comment.