Skip to content

Commit

Permalink
feat: custom primary key generation
Browse files Browse the repository at this point in the history
  • Loading branch information
tshemsedinov committed Oct 9, 2020
1 parent ca0dd04 commit 996f728
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
2 changes: 1 addition & 1 deletion application/schemas/CompanyCity.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@
company: 'Company',
city: 'City',

companyCity: { primary: ['Company', 'City'] },
companyCity: { primary: ['company', 'city'] },
});
15 changes: 12 additions & 3 deletions lib/schema-pg.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,17 @@ const foreignKey = (entityName, def) => {
);
};

const primaryKey = entityName => {
const fieldName = toLowerCamel(entityName) + 'Id';
const constraint = `"pk${entityName}" PRIMARY KEY ("${fieldName}")`;
const primaryCustom = (entityName, fields) => {
const fieldNames = `"${fields.map(name => name + 'Id').join('", "')}"`;
const constraint = `"pk${entityName}" PRIMARY KEY (${fieldNames})`;
return `ALTER TABLE "${entityName}" ADD CONSTRAINT ${constraint};`;
};

const primaryKey = entityName => {
const fieldName = toLowerCamel(entityName);
return primaryCustom(entityName, [fieldName]);
};

class PgSchema extends DatabaseSchema {
async preprocessEntity(name) {
const { entity } = this.entities.get(name);
Expand Down Expand Up @@ -128,6 +133,10 @@ class PgSchema extends DatabaseSchema {
if (kind === DB_RELATION) idx.push(foreignKey(name, def));
}
if (def.unique || def.index) idx.push(createIndex(name, def));
if (def.primary) {
idx[0] = primaryCustom(name, def.primary);
sql.splice(1, 1);
}
}
sql[sql.length - 1] = sql[sql.length - 1].slice(0, -1);
sql.push(');');
Expand Down

0 comments on commit 996f728

Please sign in to comment.