Add feature to add multiple unique constraints to db tables + remove trailing commas

This commit is contained in:
AbegaM
2024-02-13 17:44:17 +03:00
parent 12656b3d7a
commit 3fa13e6d5b
3 changed files with 28 additions and 19 deletions

View File

@@ -52,7 +52,7 @@ module.exports = {
}, },
{ {
name: 'tableName', name: 'table_name',
type: 'TEXT', type: 'TEXT',
primaryKey: false, primaryKey: false,
notNull: true, notNull: true,

View File

@@ -18,16 +18,22 @@ const createDefaultTables = async () => {
tableService.createTable('_users', dbTables.userSchema); tableService.createTable('_users', dbTables.userSchema);
} }
if (!usersRolesTable) {
tableService.createTable('_users_roles', dbTables.usersRoleSchema);
}
if (!rolesPermissionTable) { if (!rolesPermissionTable) {
tableService.createTable( tableService.createTable(
'_roles_permissions', '_roles_permissions',
dbTables.rolePermissionSchema, dbTables.rolePermissionSchema,
{
multipleUniqueConstraints: {
name: 'unique_role_table',
fields: ['role_id', 'table_name'],
},
},
); );
} }
if (!usersRolesTable) {
tableService.createTable('_users_roles', dbTables.usersRoleSchema);
}
}; };
module.exports = { createDefaultTables }; module.exports = { createDefaultTables };

View File

@@ -1,11 +1,12 @@
module.exports = (db) => { module.exports = (db) => {
return { return {
createTable( createTable(tableName, schema, options = {}) {
tableName, const {
schema, autoAddCreatedAt = true,
autoAddCreatedAt = true, autoAddUpdatedAt = true,
autoAddUpdatedAt = true, multipleUniqueConstraints,
) { } = options;
let indices = []; let indices = [];
let schemaString = schema let schemaString = schema
@@ -45,17 +46,19 @@ module.exports = (db) => {
// add created at and updated at // add created at and updated at
if (autoAddCreatedAt) { if (autoAddCreatedAt) {
schemaString = ` schemaString = `${schemaString}, createdAt DATETIME DEFAULT CURRENT_TIMESTAMP`;
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
${schemaString}
`;
} }
if (autoAddUpdatedAt) { if (autoAddUpdatedAt) {
schemaString = ` schemaString = `${schemaString}, updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP`;
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP, }
${schemaString}
`; if (multipleUniqueConstraints) {
schemaString = `${schemaString}, CONSTRAINT ${
multipleUniqueConstraints.name
} UNIQUE (${multipleUniqueConstraints.fields
.map((field) => field)
.join(' ,')})`;
} }
let indicesString = indices let indicesString = indices